From fe2fe549d4a9da2d5bbe3c919ebe92aa15ee745f Mon Sep 17 00:00:00 2001 From: garrytan Date: Thu, 8 Oct 2026 06:14:56 +0000 Subject: [PATCH 1/5] ci: refresh GitHub Actions SHA pins (setup-buildx 4.4.1, build-push 7.4.0, attest 4.2.2, setup-node 7.0.0) Rewrite of dependabot #2988. Every bumped `uses:` stays pinned to the full commit SHA (verified against the upstream tags) and now carries its exact version comment, including the lines that had none. setup-node 6.5.0 -> 7.0.0 is a major bump; its notes list an ESM migration, cache outputs and removal of a dummy NODE_AUTH_TOKEN export, none of which affect our node-version-only use. actionlint 1.7.11 (CI image) and 1.7.12 are clean. Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- .github/workflows/cso-runtime-images.yml | 12 ++++++------ .github/workflows/cso-runtime-promote.yml | 2 +- .github/workflows/cso-scanner-images.yml | 8 ++++---- .github/workflows/evals-marathon.yml | 4 ++-- .github/workflows/evals-periodic.yml | 4 ++-- .github/workflows/evals.yml | 4 ++-- .github/workflows/native-qualification.yml | 6 +++--- .github/workflows/windows-free-tests.yml | 4 ++-- 8 files changed, 22 insertions(+), 22 deletions(-) diff --git a/.github/workflows/cso-runtime-images.yml b/.github/workflows/cso-runtime-images.yml index 2e83097e8..601d0c8c4 100644 --- a/.github/workflows/cso-runtime-images.yml +++ b/.github/workflows/cso-runtime-images.yml @@ -70,7 +70,7 @@ jobs: - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 with: bun-version: 1.4.2 - - uses: docker/setup-buildx-action@37fe631027851001ddb9b187196cc803df7f5f0e + - uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 - name: Require native Docker and verify reviewed source manifests env: CSO_ARCH: ${{ matrix.arch }} @@ -98,7 +98,7 @@ jobs: --no-compile-autoload-package-json \ lib/cso/preparation-container.ts --outfile lib/cso/images/gstack-cso-preparation - name: Build the reviewed runtime without publishing - uses: docker/build-push-action@53b7df96c91f9c12dcc8a07bcb9ccacbed38856a + uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0 with: context: lib/cso/images file: lib/cso/images/${{ matrix.stack }}.Dockerfile @@ -155,7 +155,7 @@ jobs: *) echo 'Native architecture mismatch; emulation cannot qualify a runtime.' >&2; exit 1 ;; esac docker --host unix:///var/run/docker.sock info - - uses: docker/setup-buildx-action@37fe631027851001ddb9b187196cc803df7f5f0e # v4 + - uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 - uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4 with: registry: ghcr.io @@ -192,7 +192,7 @@ jobs: printf 'tag=%s:%s-%s\n' "$image" "$GITHUB_SHA" "$GITHUB_RUN_ID" >> "$GITHUB_OUTPUT" - name: Build native staging image with SBOM and provenance id: build - uses: docker/build-push-action@53b7df96c91f9c12dcc8a07bcb9ccacbed38856a # v7 + uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0 with: context: lib/cso/images file: lib/cso/images/${{ matrix.stack }}.Dockerfile @@ -213,13 +213,13 @@ jobs: jq -c -f scripts/cso-sbom-packages.jq sbom.full.spdx.json > sbom.spdx.json jq -e -f scripts/cso-sbom-packages-check.jq sbom.spdx.json >/dev/null - name: Sign build provenance - uses: actions/attest@f7c74d28b9d84cb8768d0b8ca14a4bac6ef463e6 # v4.2.0 + uses: actions/attest@1e69f48acb82d1966a394da916b4c1698aa569d6 # v4.2.2 with: subject-name: ${{ steps.image.outputs.name }} subject-digest: ${{ steps.build.outputs.digest }} push-to-registry: true - name: Sign the image SBOM - uses: actions/attest@f7c74d28b9d84cb8768d0b8ca14a4bac6ef463e6 # v4.2.0 + uses: actions/attest@1e69f48acb82d1966a394da916b4c1698aa569d6 # v4.2.2 with: subject-name: ${{ steps.image.outputs.name }} subject-digest: ${{ steps.build.outputs.digest }} diff --git a/.github/workflows/cso-runtime-promote.yml b/.github/workflows/cso-runtime-promote.yml index 63972ccdd..e3575309f 100644 --- a/.github/workflows/cso-runtime-promote.yml +++ b/.github/workflows/cso-runtime-promote.yml @@ -102,7 +102,7 @@ jobs: --output "public-image-evidence/$runtime_id.json" --remove-after done - name: Attest the exact review candidate - uses: actions/attest@f7c74d28b9d84cb8768d0b8ca14a4bac6ef463e6 + uses: actions/attest@1e69f48acb82d1966a394da916b4c1698aa569d6 # v4.2.2 with: subject-path: runtime-catalog.candidate.json - name: Verify and record the exact candidate attestation diff --git a/.github/workflows/cso-scanner-images.yml b/.github/workflows/cso-scanner-images.yml index 90804b9e2..655b00f2a 100644 --- a/.github/workflows/cso-scanner-images.yml +++ b/.github/workflows/cso-scanner-images.yml @@ -75,7 +75,7 @@ jobs: *) echo 'Native architecture mismatch; emulation cannot qualify a scanner.' >&2; exit 1 ;; esac docker --host unix:///var/run/docker.sock info - - uses: docker/setup-buildx-action@37fe631027851001ddb9b187196cc803df7f5f0e # v4 + - uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 - uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4 with: registry: ghcr.io @@ -128,7 +128,7 @@ jobs: printf 'tag=%s:%s-%s\n' "$name" "$GITHUB_SHA" "$GITHUB_RUN_ID" >> "$GITHUB_OUTPUT" - name: Build native scanner wrapper with SBOM and provenance id: build - uses: docker/build-push-action@53b7df96c91f9c12dcc8a07bcb9ccacbed38856a # v7 + uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0 with: context: lib/cso file: lib/cso/scanner-images/scanner.Dockerfile @@ -149,13 +149,13 @@ jobs: jq -c -f scripts/cso-sbom-packages.jq sbom.full.spdx.json > sbom.spdx.json jq -e -f scripts/cso-sbom-packages-check.jq sbom.spdx.json >/dev/null - name: Sign build provenance - uses: actions/attest@f7c74d28b9d84cb8768d0b8ca14a4bac6ef463e6 # v4.2.0 + uses: actions/attest@1e69f48acb82d1966a394da916b4c1698aa569d6 # v4.2.2 with: subject-name: ${{ steps.image.outputs.name }} subject-digest: ${{ steps.build.outputs.digest }} push-to-registry: true - name: Sign the image SBOM - uses: actions/attest@f7c74d28b9d84cb8768d0b8ca14a4bac6ef463e6 # v4.2.0 + uses: actions/attest@1e69f48acb82d1966a394da916b4c1698aa569d6 # v4.2.2 with: subject-name: ${{ steps.image.outputs.name }} subject-digest: ${{ steps.build.outputs.digest }} diff --git a/.github/workflows/evals-marathon.yml b/.github/workflows/evals-marathon.yml index 565c32d77..81cc72bc8 100644 --- a/.github/workflows/evals-marathon.yml +++ b/.github/workflows/evals-marathon.yml @@ -63,10 +63,10 @@ jobs: # Registry cache export needs a docker-container builder — the default # `docker` driver hard-errors on cache-to. - if: steps.check.outputs.exists == 'false' - uses: docker/setup-buildx-action@37fe631027851001ddb9b187196cc803df7f5f0e # v4 + uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 - if: steps.check.outputs.exists == 'false' - uses: docker/build-push-action@53b7df96c91f9c12dcc8a07bcb9ccacbed38856a # v7 + uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0 with: context: .github/docker file: .github/docker/Dockerfile.ci diff --git a/.github/workflows/evals-periodic.yml b/.github/workflows/evals-periodic.yml index e4bc8fe86..eaa185d18 100644 --- a/.github/workflows/evals-periodic.yml +++ b/.github/workflows/evals-periodic.yml @@ -99,10 +99,10 @@ jobs: # Registry cache export needs a docker-container builder — the default # `docker` driver hard-errors on cache-to. - if: steps.check.outputs.exists == 'false' - uses: docker/setup-buildx-action@37fe631027851001ddb9b187196cc803df7f5f0e # v4 + uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 - if: steps.check.outputs.exists == 'false' - uses: docker/build-push-action@53b7df96c91f9c12dcc8a07bcb9ccacbed38856a # v7 + uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0 with: context: .github/docker file: .github/docker/Dockerfile.ci diff --git a/.github/workflows/evals.yml b/.github/workflows/evals.yml index 9263e39ab..484cda7f5 100644 --- a/.github/workflows/evals.yml +++ b/.github/workflows/evals.yml @@ -95,10 +95,10 @@ jobs: # Registry cache export needs a docker-container builder — the default # `docker` driver hard-errors on cache-to (first live run of the trio). - if: steps.check.outputs.exists == 'false' - uses: docker/setup-buildx-action@37fe631027851001ddb9b187196cc803df7f5f0e # v4 + uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 - if: steps.check.outputs.exists == 'false' - uses: docker/build-push-action@53b7df96c91f9c12dcc8a07bcb9ccacbed38856a # v7 + uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0 with: context: .github/docker file: .github/docker/Dockerfile.ci diff --git a/.github/workflows/native-qualification.yml b/.github/workflows/native-qualification.yml index 23c63ef36..176e881e5 100644 --- a/.github/workflows/native-qualification.yml +++ b/.github/workflows/native-qualification.yml @@ -42,7 +42,7 @@ jobs: - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 with: bun-version: 1.4.2 - - uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 + - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 with: node-version: 24.18.0 - name: Install pinned dependencies @@ -71,7 +71,7 @@ jobs: - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 with: bun-version: 1.4.2 - - uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 + - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 with: node-version: 24.18.0 - name: Configure git identity (required by tests that init temp repos) @@ -118,7 +118,7 @@ jobs: - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 with: bun-version: 1.4.2 - - uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 + - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 if: inputs.mode == 'dia-launch-comparison' with: node-version: 24.18.0 diff --git a/.github/workflows/windows-free-tests.yml b/.github/workflows/windows-free-tests.yml index 0b8adec1d..8420a7dd3 100644 --- a/.github/workflows/windows-free-tests.yml +++ b/.github/workflows/windows-free-tests.yml @@ -84,7 +84,7 @@ jobs: with: bun-version: 1.4.2 - - uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 + - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 with: node-version: 24.18.0 @@ -214,7 +214,7 @@ jobs: - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 with: bun-version: 1.4.2 - - uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 + - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 with: node-version: 24.18.0 - name: Prepare the same inputs as a Windows shard From 2ec5275db5d8612133f454119e1215bb209047fc Mon Sep 17 00:00:00 2001 From: garrytan Date: Thu, 8 Oct 2026 06:17:04 +0000 Subject: [PATCH 2/5] fix(ci): install Bun from the SHA-256-verified release archive in GitLab CI and Ubicloud setup Rewrite of #1713. .gitlab-ci.yml's .setup-bun anchor and scripts/ubicloud/setup-free-suite.sh still piped https://bun.sh/install into bash. Both now download the bun-v$BUN_VERSION linux-x64 release zip, check it against the same SHA-256 Dockerfile.ci uses (#1706) before unzipping, install it to ~/.bun/bin and assert `bun --version`. test/ci-image-cli-pin.test.ts runs curlPipedToShell over both files and binds their hash and BUN_VERSION to Dockerfile.ci's amd64 arm and package.json's engines floor, so a Bun bump has to move all of them together. Verified by running the GitLab anchor in debian:stable-slim (bash and sh) and the Ubicloud block in a temp HOME. Co-authored-by: Zee Zheng <228040220+spacegeologist@users.noreply.github.com> Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- .gitlab-ci.yml | 14 +++++++++++-- scripts/ubicloud/setup-free-suite.sh | 11 +++++++++- test/ci-image-cli-pin.test.ts | 31 ++++++++++++++++++++++++++++ 3 files changed, 53 insertions(+), 3 deletions(-) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index eb7735ac0..7b337726e 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -9,9 +9,19 @@ variables: BUN_VERSION: "1.4.2" .setup-bun: &setup-bun - - apt-get update -qq && apt-get install -qq -y curl jq git - - curl -fsSL https://bun.sh/install | bash -s "bun-v$BUN_VERSION" + - apt-get update -qq && apt-get install -qq -y curl jq git unzip + # The exact release archive, verified by SHA-256 before it is unpacked, as + # in .github/docker/Dockerfile.ci. test/ci-image-cli-pin.test.ts keeps the + # hash and BUN_VERSION equal to that file's linux-x64 arm. + - | + curl --retry 5 --retry-delay 5 --retry-connrefused -fsSL \ + "https://github.com/oven-sh/bun/releases/download/bun-v$BUN_VERSION/bun-linux-x64.zip" -o /tmp/bun.zip + echo "36368faef7527875d5ffa52e53cd48021741f2a83eb6208a8dd64068d422a913 /tmp/bun.zip" | sha256sum -c - + unzip -q /tmp/bun.zip -d /tmp/bun + install -D -m 0755 /tmp/bun/bun-linux-x64/bun "$HOME/.bun/bin/bun" + rm -rf /tmp/bun /tmp/bun.zip - export PATH="$HOME/.bun/bin:$PATH" + - test "$(bun --version)" = "$BUN_VERSION" version-gate: stage: check diff --git a/scripts/ubicloud/setup-free-suite.sh b/scripts/ubicloud/setup-free-suite.sh index ed8d09253..af8029543 100755 --- a/scripts/ubicloud/setup-free-suite.sh +++ b/scripts/ubicloud/setup-free-suite.sh @@ -22,11 +22,20 @@ if ! command -v node >/dev/null; then | sudo tar -xJ -C /usr/local --strip-components=1 fi +# The exact release archive, verified by SHA-256 before it is unpacked, as in +# .github/docker/Dockerfile.ci (test/ci-image-cli-pin.test.ts keeps them equal). if [ ! -x "$HOME/.bun/bin/bun" ]; then - curl -fsSL https://bun.sh/install | bash -s "bun-v$BUN_VERSION" >/dev/null + bun_tmp=$(mktemp -d) + curl --retry 5 --retry-delay 5 --retry-connrefused -fsSL \ + "https://github.com/oven-sh/bun/releases/download/bun-v$BUN_VERSION/bun-linux-x64.zip" -o "$bun_tmp/bun.zip" + echo "36368faef7527875d5ffa52e53cd48021741f2a83eb6208a8dd64068d422a913 $bun_tmp/bun.zip" | sha256sum -c - >/dev/null + unzip -q "$bun_tmp/bun.zip" -d "$bun_tmp" + install -D -m 0755 "$bun_tmp/bun-linux-x64/bun" "$HOME/.bun/bin/bun" + rm -rf "$bun_tmp" fi grep -q '.bun/bin' "$HOME/.profile" || echo 'export PATH="$HOME/.bun/bin:$PATH"' >>"$HOME/.profile" export PATH="$HOME/.bun/bin:$PATH" +test "$(bun --version)" = "$BUN_VERSION" git config --global user.email "free-tests@gstack.test" git config --global user.name "Free Tests" diff --git a/test/ci-image-cli-pin.test.ts b/test/ci-image-cli-pin.test.ts index a04ce197c..805858c21 100644 --- a/test/ci-image-cli-pin.test.ts +++ b/test/ci-image-cli-pin.test.ts @@ -180,3 +180,34 @@ describe('ci image codex authentication', () => { } }); }); + +describe('other CI Bun installs match the image (#1713, #1706)', () => { + const docker = fs.readFileSync(DOCKERFILE, 'utf-8'); + const imageSha = bunArchiveArms(docker).get('amd64'); + const imageVersion = docker.match(/^ARG BUN_VERSION=(\S+)$/m)?.[1]; + const engines = JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf-8')).engines.bun; + + for (const rel of ['.gitlab-ci.yml', 'scripts/ubicloud/setup-free-suite.sh']) { + const source = fs.readFileSync(path.join(ROOT, rel), 'utf-8'); + + test(`${rel} downloads the verified linux-x64 archive instead of piping an installer into a shell`, () => { + expect(curlPipedToShell(source)).toEqual([]); + const download = source.indexOf('/releases/download/bun-v$BUN_VERSION/bun-linux-x64.zip'); + const verify = source.indexOf('sha256sum -c'); + const unpack = source.indexOf('unzip -q'); + expect(download).toBeGreaterThan(-1); + expect(verify).toBeGreaterThan(download); + expect(unpack).toBeGreaterThan(verify); + expect(source).toContain('test "$(bun --version)" = "$BUN_VERSION"'); + }); + + test(`${rel} pins the same Bun version and SHA-256 as Dockerfile.ci`, () => { + expect(imageSha).toMatch(/^[0-9a-f]{64}$/); + const hashes = [...source.matchAll(/echo "([0-9a-f]{64}) /g)].map((m) => m[1]); + expect(hashes).toEqual([imageSha!]); + const version = source.match(/^\s*BUN_VERSION[=:]\s*"?([\d.]+)"?\s*$/m)?.[1]; + expect(version).toBe(imageVersion!); + expect(engines).toBe(`>=${imageVersion}`); + }); + } +}); From f629bd560db75aaa05952da7f51bf7e7e367bdf7 Mon Sep 17 00:00:00 2001 From: garrytan Date: Thu, 8 Oct 2026 06:23:53 +0000 Subject: [PATCH 3/5] fix(hook-check): cover skill frontmatter hooks, sourced helpers, conflict markers and the caller's tsconfig Rewrite of #3066. bin/gstack-hook-check only listed setup's hooks plus /autoplan's by name, so the /careful and /freeze PreToolUse checks (also run by /guard and /investigate), /plan-ceo-review's hand-off hook and the helpers they source were never parse-checked before Claude Code ran them. - The hook list is setup's _hook_command_path arguments plus every gstack path on a `command:` line in a generated */SKILL.md frontmatter (9 hooks, up from 6). The generated files are read rather than the .tmpl sources because the /autoplan and /plan-ceo-review commands come from resolvers. - Each shell hook's gstack-tree helpers (`.`/`source` lines, assignments and shellcheck source= directives, followed transitively) are parsed too: careful/bin/hook-extract.sh and bin/gstack-state-root.sh for /careful and /freeze. - The shim, its helpers, each TypeScript entry and every local module the bundle used (bun build --metafile; entry only when bun lacks it) are scanned for conflict-marker lines, which still parse inside heredocs, strings and template literals. - bun build runs from the gstack root, so the caller's broken tsconfig.json or bunfig.toml no longer fails every TypeScript hook. Lists are newline separated, so a root with spaces works. Tests in test/setup-hook-syntax-gate.test.ts cover each case; the gstack-doctor fixture now copies autoplan/SKILL.md, whose frontmatter registers the hook its hooks-row test breaks. docs/troubleshooting.md describes the wider check. Co-authored-by: Benjamin D. Smith <7134745+BenjaminDSmithy@users.noreply.github.com> Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- bin/gstack-hook-check | 96 ++++++++++++++++++++++++++--- docs/troubleshooting.md | 25 +++++--- test/gstack-doctor.test.ts | 1 + test/setup-hook-syntax-gate.test.ts | 78 +++++++++++++++++++++-- 4 files changed, 178 insertions(+), 22 deletions(-) diff --git a/bin/gstack-hook-check b/bin/gstack-hook-check index 3601e8d47..ca9727f12 100755 --- a/bin/gstack-hook-check +++ b/bin/gstack-hook-check @@ -13,14 +13,21 @@ # # The hook list comes from the registration code: every # `_hook_command_path ` argument in /setup (or the setup named by -# --setup, when another tree's setup registers 's hooks), plus the autoplan -# phase-publication hook (registered by its skill frontmatter). -# test/setup-hook-syntax-gate.test.ts keeps the two equal. +# --setup, when another tree's setup registers 's hooks), plus every +# gstack path on a `command:` line in a skill's frontmatter (/*/SKILL.md: +# /autoplan, /careful, /freeze, /guard, /investigate, /plan-ceo-review). Claude +# Code runs those while the skill is active, and a broken PreToolUse one blocks +# the tool call. test/setup-hook-syntax-gate.test.ts keeps the lists equal. # -# Each shim is parsed by the interpreter its shebang names (bash -n, sh -n). -# Each TypeScript entry the shim runs (a `.ts` beside it) is bundled with -# its local imports into a temp directory, packages external, so a broken or -# missing local import fails; a missing entry fails. +# Each shim is parsed by the interpreter its shebang names (bash -n, sh -n), +# and so is every gstack shell file it sources, transitively. Each TypeScript +# entry the shim runs (a `.ts` beside it) is bundled with its local +# imports into a temp directory, packages external, so a broken or missing +# local import fails; a missing entry fails. Bundles run from , so the +# caller's tsconfig.json and bunfig.toml are never read. The shim, its sourced +# helpers, each entry and every local module the entry bundles are scanned for +# merge conflict marker lines, which still parse inside a heredoc, a string, a +# comment or a template literal. # # Output, one line per hook: # ok @@ -44,11 +51,18 @@ if [ -z "$ROOT" ] || [ ! -d "$ROOT" ]; then echo "usage: gstack-hook-check [--setup ] [--list] " >&2 exit 2 fi +case "$ROOT" in /*) ;; *) ROOT="$PWD/$ROOT" ;; esac +[ "$ROOT" = / ] || ROOT=${ROOT%/} SETUP_FILE="${SETUP_FILE:-$ROOT/setup}" +# Frontmatter is the block between a SKILL.md's first two `---` lines. hook_list() { sed -n 's/.*\$(_hook_command_path \([A-Za-z0-9._/-]*\).*/\1/p' "$SETUP_FILE" 2>/dev/null - echo autoplan/bin/phase-publication-hook + for skill in "$ROOT"/*/SKILL.md; do + [ -f "$skill" ] || continue + tr -d '\r' < "$skill" | awk 'NR == 1 && !/^---/ { exit } NR > 1 && /^---/ { exit } /^[[:space:]]*command:/' \ + | grep -oE 'skills/gstack/[A-Za-z0-9._/-]+' | sed 's|^skills/gstack/||' + done } HOOKS=$(hook_list | awk '!seen[$0]++') @@ -79,9 +93,50 @@ first_message() { printf '%s\n' "$_msg" } +# Lists below are newline-separated, so a root with spaces stays one word. +NL=' +' +IFS=$NL FAILED=0 fail() { echo "fail $1 $2: $3"; FAILED=1; } +# sourced_by — the gstack files sources: each `*.sh` path on a +# `.`/`source` line, in a variable assignment, or in a `# shellcheck source=` +# directive. A path resolves from , then beside , then beside +# without its first segment (a `$DIR/` prefix); only files inside +# count. +sourced_by() { + _sdir=$(dirname "$1") + grep -E '^[[:space:]]*#[[:space:]]*shellcheck[[:space:]].*source=|(^|[;&|({[:space:]])(\.|source)[[:space:]]|^[[:space:]]*(local |export |readonly )?[A-Za-z_][A-Za-z0-9_]*=' "$1" \ + | grep -oE '[A-Za-z0-9._/-]*\.sh([^A-Za-z0-9_]|$)' | sed -E 's/\.sh.*$/.sh/' | awk '!seen[$0]++' | while IFS= read -r _tok; do + for _cand in "$ROOT/$_tok" "$_sdir/$_tok" "$_sdir/${_tok#*/}"; do + [ -f "$_cand" ] || continue + _cand="$(cd "$(dirname "$_cand")" && pwd)/$(basename "$_cand")" + case "$_cand" in "$ROOT"/*) [ "$_cand" != "$1" ] && echo "$_cand"; break ;; esac + done + done +} + +# helpers_of — sourced_by, followed transitively. +helpers_of() { + _seen="$NL$1$NL" _queue=$1 + while [ -n "$_queue" ]; do + _next="" + for _f in $_queue; do + for _c in $(sourced_by "$_f"); do + case "$_seen" in *"$NL$_c$NL"*) continue ;; esac + _seen="$_seen$_c$NL" + echo "$_c" + _next="$_next$_c$NL" + done + done + _queue=$_next + done +} + +META=0 +"$BUN" build --help 2>/dev/null | grep -q -- '--metafile' && META=1 + for hook in $HOOKS; do shim="$ROOT/$hook" if [ ! -f "$shim" ]; then echo "missing $hook"; continue; fi @@ -100,6 +155,14 @@ for hook in $HOOKS; do fail "$hook" "$(first_location "$shim" "$err")" "$(first_message "$err")" hook_ok=0 fi + scan="$shim" + for helper in $(helpers_of "$shim"); do + if ! err=$("$interp" -n "$helper" 2>&1); then + fail "$hook" "$(first_location "$helper" "$err")" "$(first_message "$err")" + hook_ok=0 + fi + scan="$scan$NL$helper" + done dir=$(dirname "$shim") for entry in $(grep -v '^[[:space:]]*#' "$shim" | grep -oE '[A-Za-z0-9._-]+\.ts([^A-Za-z0-9_]|$)' | sed -E 's/\.ts.*$/.ts/' | awk '!seen[$0]++'); do if [ ! -f "$dir/$entry" ]; then @@ -107,10 +170,25 @@ for hook in $HOOKS; do hook_ok=0 continue fi - if ! err=$("$BUN" build --target=bun --packages=external --outdir "$TMP_OUT/$(basename "$hook")" "$dir/$entry" 2>&1 >/dev/null); then + meta="$TMP_OUT/meta.json" metaflag="" + rm -f "$meta" + [ "$META" -eq 1 ] && metaflag="--metafile=$meta" + if ! err=$(cd "$ROOT" && "$BUN" build --target=bun --packages=external --outdir "$TMP_OUT/$(basename "$hook")" \ + ${metaflag:+"$metaflag"} "$dir/$entry" 2>&1 >/dev/null); then fail "$hook" "$(first_location "$dir/$entry" "$err")" "$(first_message "$err")" hook_ok=0 fi + scan="$scan$NL$dir/$entry" + [ -f "$meta" ] || continue + for rel in $(cd "$ROOT" && "$BUN" -e 'for (const f of Object.keys(JSON.parse(await Bun.file(process.argv[1]).text()).inputs)) console.log(f)' "$meta" 2>/dev/null); do + case "$rel" in /*|../*) ;; *) scan="$scan$NL$ROOT/$rel" ;; esac + done + done + for file in $(printf '%s\n' "$scan" | awk '!seen[$0]++'); do + marker=$(grep -nE '^(<<<<<<<|=======|>>>>>>>)( |$)' "$file" 2>/dev/null | head -1 | cut -d: -f1) + [ -n "$marker" ] || continue + fail "$hook" "$file:$marker" "unresolved merge conflict marker" + hook_ok=0 done [ "$hook_ok" -eq 1 ] && echo "ok $hook" done diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index 6aa2ceac9..8453983fb 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -615,13 +615,21 @@ Bun first. **Meaning.** Claude Code runs gstack's hook shims through `/bin/sh`, and a hook that does not parse exits 2, which blocks the tool call it guards in every -session. Setup parse-checks every hook it registers (the shim, and the -TypeScript it runs with its local imports). It registers the hooks that parse, -skips the ones listed, finishes the rest of the install, and exits non-zero. -Claude Code runs hooks straight from `~/.claude/skills/gstack`, so a skipped -hook that an earlier setup registered keeps running the broken file until it -is fixed. This is a gstack bug, or a half-applied edit or merge in your -checkout: report the printed `:`. +session. Setup parse-checks every hook it registers and every hook a skill's +frontmatter runs (`/autoplan`, `/careful`, `/freeze`, `/guard`, `/investigate` +and `/plan-ceo-review`): the shim, the gstack shell helpers it sources (such as +`careful/bin/hook-extract.sh` and `bin/gstack-state-root.sh`), and the +TypeScript it runs with its local imports. A merge conflict marker line in any +of those files fails as `unresolved merge conflict marker`, even when the file +still parses (markers inside a heredoc, a string or a template literal do). +The TypeScript is bundled from the gstack checkout, so the `tsconfig.json` or +`bunfig.toml` of the project you run it from is never read. It registers the +hooks that parse, skips the ones listed, finishes the rest of the install, and +exits non-zero. Claude Code runs hooks straight from `~/.claude/skills/gstack`, +so a skipped hook that an earlier setup registered, or that a skill runs, +keeps running the broken file until it is fixed. This is a gstack bug, or a +half-applied edit or merge in your checkout: report the printed +`:`. **Fix.** @@ -637,7 +645,8 @@ cd ~/.claude/skills/gstack && ./setup ### `gstack auto-update: update held (hook-does-not-parse: :: ); nothing was installed or changed, and your current hooks keep running. ...` **Meaning.** Team-mode auto-update fetched a release with a hook that does not -parse. It checked the incoming revision before moving your checkout, so your +parse or still holds a merge conflict marker (the same check setup runs). It +checked the incoming revision before moving your checkout, so your checkout, installed skills and registered hooks stay at the current revision. gstack checks again at the next update check and installs the first release whose hooks parse. This is a gstack bug: report the printed `:`. diff --git a/test/gstack-doctor.test.ts b/test/gstack-doctor.test.ts index cd19a717f..970f0a638 100644 --- a/test/gstack-doctor.test.ts +++ b/test/gstack-doctor.test.ts @@ -22,6 +22,7 @@ const COPIED = [ 'setup', 'VERSION', 'bin/gstack-doctor', 'bin/gstack-codex-status.sh', 'bin/gstack-state-root.sh', 'bin/gstack-install-registry.sh', 'bin/gstack-render-claude.sh', 'bin/gstack-bun-version.sh', 'bin/gstack-hook-check', 'bin/gstack-config', + 'autoplan/SKILL.md', // its frontmatter registers the autoplan hook the hooks-row test breaks ]; const bases: string[] = []; afterEach(() => { for (const b of bases.splice(0)) fs.rmSync(b, { recursive: true, force: true }); }); diff --git a/test/setup-hook-syntax-gate.test.ts b/test/setup-hook-syntax-gate.test.ts index 4ab686509..cc9d88139 100644 --- a/test/setup-hook-syntax-gate.test.ts +++ b/test/setup-hook-syntax-gate.test.ts @@ -47,7 +47,13 @@ afterEach(() => { for (const b of bases.splice(0)) fs.rmSync(b, { recursive: tru const HOOKS = listHooks(ROOT); -/** A gstack tree with the real hook shims and trivial TypeScript entries. */ +/** Skills whose frontmatter registers a hook command. */ +const SKILLS_WITH_HOOKS = fs.readdirSync(ROOT).filter((dir) => { + const skill = path.join(ROOT, dir, 'SKILL.md'); + return fs.existsSync(skill) && /^---\n[\s\S]*?^\s*command:[\s\S]*?\n---/m.test(fs.readFileSync(skill, 'utf8')); +}); + +/** A gstack tree with the real hook shims and skill frontmatter, sourced helpers, and trivial TypeScript entries. */ function fixtureTree(root: string) { for (const hook of HOOKS) { fs.mkdirSync(path.dirname(path.join(root, hook)), { recursive: true }); @@ -55,6 +61,14 @@ function fixtureTree(root: string) { fs.chmodSync(path.join(root, hook), 0o755); if (fs.existsSync(path.join(ROOT, `${hook}.ts`))) fs.writeFileSync(path.join(root, `${hook}.ts`), 'export const ok = 1;\n'); } + for (const dir of SKILLS_WITH_HOOKS) { + fs.mkdirSync(path.join(root, dir), { recursive: true }); + fs.copyFileSync(path.join(ROOT, dir, 'SKILL.md'), path.join(root, dir, 'SKILL.md')); + } + for (const helper of ['careful/bin/hook-extract.sh', 'bin/gstack-state-root.sh']) { + fs.mkdirSync(path.dirname(path.join(root, helper)), { recursive: true }); + fs.copyFileSync(path.join(ROOT, helper), path.join(root, helper)); + } fs.copyFileSync(path.join(ROOT, 'setup'), path.join(root, 'setup')); } @@ -70,13 +84,19 @@ function check(root: string) { } describe('gstack-hook-check: the hook list is the registration code', () => { - test('equals every hook setup resolves for registration plus the frontmatter-registered autoplan hook', () => { + test('equals every hook setup resolves for registration plus every gstack path a skill frontmatter command runs', () => { const registered = [...SETUP.matchAll(/_hook_command_path (\S+)/g)].map(m => m[1]!.replace(/\W+$/, '')); - const frontmatter = [...fs.readFileSync(path.join(ROOT, 'autoplan', 'SKILL.md'), 'utf8') - .matchAll(/skills\/gstack\/(autoplan\/bin\/[a-z-]+-hook)\b/g)].map(m => m[1]!); + const frontmatter = fs.readdirSync(ROOT).flatMap((dir) => { + const skill = path.join(ROOT, dir, 'SKILL.md'); + if (!fs.existsSync(skill)) return []; + const front = fs.readFileSync(skill, 'utf8').match(/^---\n([\s\S]*?)\n---/)?.[1] ?? ''; + return front.split('\n').filter(line => /^\s*command:/.test(line)) + .flatMap(line => [...line.matchAll(/skills\/gstack\/([\w./-]+)/g)].map(m => m[1]!)); + }); const expected = [...new Set([...registered, ...frontmatter])].sort(); expect(registered.length).toBeGreaterThanOrEqual(5); - expect(frontmatter.length).toBeGreaterThan(0); + for (const hook of ['autoplan/bin/phase-publication-hook', 'careful/bin/check-careful.sh', + 'freeze/bin/check-freeze.sh', 'plan-ceo-review/bin/mode-handoff-hook']) expect(frontmatter).toContain(hook); expect([...HOOKS].sort()).toEqual(expected); }); @@ -147,6 +167,54 @@ describe('gstack-hook-check: what fails', () => { expect(r.out).toContain(`fail hosts/claude/hooks/auq-error-fallback-hook ${entry}:1: missing TypeScript entry`); }); + test('a sourced helper that does not parse fails at the helper', () => { + const root = tmpBase(); + fixtureTree(root); + const helper = path.join(root, 'careful/bin/hook-extract.sh'); + fs.appendFileSync(helper, 'if then\n'); + const r = check(root); + expect(r.code).toBe(1); + expect(r.out).toMatch(new RegExp(`^fail careful/bin/check-careful.sh ${helper}:\\d+: syntax error`, 'm')); + expect(r.out).toMatch(new RegExp(`^fail freeze/bin/check-freeze.sh ${helper}:\\d+: syntax error`, 'm')); + }); + + test('a conflict marker inside a heredoc of a transitively sourced helper still parses, and fails', () => { + const root = tmpBase(); + fixtureTree(root); + const helper = path.join(root, 'bin/gstack-state-root.sh'); + const lines = fs.readFileSync(helper, 'utf8').split('\n').length; + fs.appendFileSync(helper, ": <<'EOF'\n<<<<<<< HEAD\nours\n=======\ntheirs\n>>>>>>> branch\nEOF\n"); + expect(spawnSync('bash', ['-n', helper], { timeout: 10_000 }).status).toBe(0); + const r = check(root); + expect(r.code).toBe(1); + expect(r.out).toContain(`fail careful/bin/check-careful.sh ${helper}:${lines + 1}: unresolved merge conflict marker`); + expect(r.out).toContain(`fail bin/gstack-session-update ${helper}:${lines + 1}: unresolved merge conflict marker`); + }); + + test('a conflict marker in a module the TypeScript entry imports fails, even inside a template literal', () => { + const root = tmpBase(); + fixtureTree(root); + const dir = path.join(root, 'hosts/claude/hooks'); + fs.writeFileSync(path.join(dir, 'question-log-hook.ts'), "import { msg } from './hook-msg';\nconsole.log(msg);\n"); + fs.writeFileSync(path.join(dir, 'hook-msg.ts'), 'export const msg = `\n<<<<<<< HEAD\na\n=======\nb\n>>>>>>> other\n`;\n'); + const r = check(root); + expect(r.code).toBe(1); + expect(r.out).toContain(`fail hosts/claude/hooks/question-log-hook ${path.join(dir, 'hook-msg.ts')}:2: unresolved merge conflict marker`); + }); + + test("the caller's tsconfig.json and bunfig.toml are not read, and a root with spaces works", () => { + const base = tmpBase(); + const root = path.join(base, 'gstack root'); + fixtureTree(root); + const caller = path.join(base, 'project'); + fs.mkdirSync(caller); + fs.writeFileSync(path.join(caller, 'tsconfig.json'), '{ "compilerOptions": { ,,, '); + fs.writeFileSync(path.join(caller, 'bunfig.toml'), '[[[ not toml'); + const r = spawnSync('bash', [CHECK, root], { cwd: caller, encoding: 'utf8', timeout: 30_000 }); + expect(`${r.stdout}${r.stderr}`).not.toContain('fail '); + expect(r.status).toBe(0); + }); + test('a missing shim is reported as missing, not failed (setup already skips registering it)', () => { const root = tmpBase(); fixtureTree(root); From 6f1b4cad0f380c3d766e2e05b0dc61234a054b53 Mon Sep 17 00:00:00 2001 From: garrytan Date: Thu, 8 Oct 2026 06:29:09 +0000 Subject: [PATCH 4/5] fix(team-init): make the required-mode hook shell-neutral (node CommonJS, no shell variables) Rewrite of #2217. Required team mode wrote a bash check-gstack.sh and registered it as "$CLAUDE_PROJECT_DIR/.claude/hooks/check-gstack.sh", which only works when the hook runner is a POSIX shell. Under cmd.exe or PowerShell (Windows, Copilot CLI) the variable is not expanded and the .sh cannot run, so an intended allow or deny became a hook error. - The hook is now .claude/hooks/check-gstack.cjs: the same root search (GSTACK_ROOT, every host's global root, the migrated repo), with the home directory from HOME, then USERPROFILE, then os.homedir(). It prints {} when gstack resolves and the PreToolUse deny JSON with exit 2 when not. - The registered command is `node -e "require(require('path').resolve( process.env.CLAUDE_PROJECT_DIR || '.', '.claude', 'hooks', 'check-gstack.cjs'))"`: no `$` or `%`, so sh, cmd.exe and PowerShell all pass it through unchanged. - An existing check-gstack registration (matcher Skill or Skill|skill) is replaced in place; duplicates are dropped and unrelated hooks in the same entry kept. The legacy .sh is deleted only after the settings write succeeds (a tracked one joins the suggested git add), and is kept when bun is missing or the write fails, which now reports instead of claiming success. Tests: team-mode and the hook-schema test run the command as registered; test/team-init-hook-shell-neutral.test.ts runs it through the platform's default shell (cmd.exe on the Windows lane, which curates it in) and through PowerShell when installed (verified here in the pwsh 7 container). The routing-probe check for the bash `_GSTACK_ROOT` gate now pins the same contract in the .cjs: every host root probed, block only when none resolves. Co-authored-by: neallee2012 <1499497+neallee2012@users.noreply.github.com> Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- bin/gstack-team-init | 122 +++++++++++++--------- test/gstack-team-init-hook-schema.test.ts | 14 ++- test/routing-probe.test.ts | 14 ++- test/team-init-hook-shell-neutral.test.ts | 82 +++++++++++++++ test/team-mode.test.ts | 89 +++++++++++++++- 5 files changed, 264 insertions(+), 57 deletions(-) create mode 100644 test/team-init-hook-shell-neutral.test.ts diff --git a/bin/gstack-team-init b/bin/gstack-team-init index 2c92c82b4..5bba62a07 100755 --- a/bin/gstack-team-init +++ b/bin/gstack-team-init @@ -124,24 +124,38 @@ if [ "$MODE" = "required" ]; then HOOKS_DIR="$REPO_ROOT/.claude/hooks" SETTINGS="$REPO_ROOT/.claude/settings.json" - # Create enforcement hook script + # Create the enforcement hook. Claude Code and Copilot CLI may run hook + # commands through sh, cmd.exe or PowerShell, so the hook is CommonJS run by + # node, and the registered command holds no shell variable syntax: it reads + # CLAUDE_PROJECT_DIR through process.env. `.cjs` keeps a project's + # package.json "type" from changing how node loads it. mkdir -p "$HOOKS_DIR" - cat > "$HOOKS_DIR/check-gstack.sh" << 'HOOK_EOF' -#!/bin/bash -# Block skill usage when gstack is not installed globally. -# -# Resolve the install root the way gstack skill preambles do: the GSTACK_ROOT -# env var first, then every host's global install location, then the migrated -# repo location. Block only when NONE exist (#2500 — hardcoding -# ~/.claude/skills/gstack false-blocked Codex-host and migrated-repo installs). -_GSTACK_ROOT="" -for _D in "${GSTACK_ROOT:-}" "$HOME/.claude/skills/gstack" "$HOME/.codex/skills/gstack" "$HOME/.factory/skills/gstack" "$HOME/.kiro/skills/gstack" "$HOME/.config/opencode/skills/gstack" "$HOME/.slate/skills/gstack" "$HOME/.cursor/skills/gstack" "$HOME/.openclaw/skills/gstack" "$HOME/.hermes/skills/gstack" "$HOME/.gbrain/skills/gstack" "$HOME/.copilot/skills/gstack" "$HOME/.gstack/repos/gstack"; do - [ -z "$_GSTACK_ROOT" ] && [ -n "$_D" ] && [ -d "$_D/bin" ] && _GSTACK_ROOT="$_D" -done + cat > "$HOOKS_DIR/check-gstack.cjs" << 'HOOK_EOF' +'use strict'; +// Block skill usage when gstack is not installed globally. +// +// Resolve the install root the way gstack skill preambles do: the GSTACK_ROOT +// env var first, then every host's global install location, then the migrated +// repo location. Block only when NONE exist (#2500 — hardcoding +// ~/.claude/skills/gstack false-blocked Codex-host and migrated-repo installs). +const fs = require('fs'); +const os = require('os'); +const path = require('path'); -if [ -z "$_GSTACK_ROOT" ]; then - cat >&2 <<'MSG' -BLOCKED: gstack is not installed globally. +const home = process.env.HOME || process.env.USERPROFILE || os.homedir(); +const roots = [process.env.GSTACK_ROOT || ''].concat([ + '.claude/skills/gstack', '.codex/skills/gstack', '.factory/skills/gstack', '.kiro/skills/gstack', + '.config/opencode/skills/gstack', '.slate/skills/gstack', '.cursor/skills/gstack', '.openclaw/skills/gstack', + '.hermes/skills/gstack', '.gbrain/skills/gstack', '.copilot/skills/gstack', '.gstack/repos/gstack', +].map((rel) => path.join(home, rel))); +const gstackRoot = roots.find((root) => { + try { return root !== '' && fs.statSync(path.join(root, 'bin')).isDirectory(); } catch { return false; } +}); + +if (gstackRoot) { + process.stdout.write('{}\n'); +} else { + process.stderr.write(`BLOCKED: gstack is not installed globally. gstack is required for AI-assisted work in this repo. @@ -150,24 +164,27 @@ Install it: cd ~/.claude/skills/gstack && ./setup --team Then restart your AI coding tool. -MSG - # Exit 2 denies on Claude Code (#2413) and on Copilot CLI, which treats a - # preToolUse exit 2 as deny (#2229). - echo '{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny","permissionDecisionReason":"gstack is required but not installed. See stderr for install instructions."}}' - exit 2 -fi - -echo '{}' +`); + // Exit 2 denies on Claude Code (#2413) and on Copilot CLI, which treats a + // preToolUse exit 2 as deny (#2229). + process.stdout.write(JSON.stringify({ hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny', + permissionDecisionReason: 'gstack is required but not installed. See stderr for install instructions.' } }) + '\n'); + process.exitCode = 2; +} HOOK_EOF - chmod +x "$HOOKS_DIR/check-gstack.sh" - GENERATED+=(".claude/hooks/check-gstack.sh") - echo " + .claude/hooks/check-gstack.sh — enforcement hook" + chmod +x "$HOOKS_DIR/check-gstack.cjs" + GENERATED+=(".claude/hooks/check-gstack.cjs") + echo " + .claude/hooks/check-gstack.cjs — enforcement hook" # Add hook to project-level settings.json - if command -v bun >/dev/null 2>&1; then - GSTACK_SETTINGS_PATH="$SETTINGS" bun -e " + HOOK_COMMAND="node -e \"require(require('path').resolve(process.env.CLAUDE_PROJECT_DIR || '.', '.claude', 'hooks', 'check-gstack.cjs'))\"" + if ! command -v bun >/dev/null 2>&1; then + echo " ! bun not found — manually add this PreToolUse hook (matcher Skill|skill) to .claude/settings.json:" + echo " $HOOK_COMMAND" + elif GSTACK_SETTINGS_PATH="$SETTINGS" GSTACK_HOOK_COMMAND="$HOOK_COMMAND" bun -e " const fs = require('fs'); const settingsPath = process.env.GSTACK_SETTINGS_PATH; + const command = process.env.GSTACK_HOOK_COMMAND; let settings = {}; try { settings = JSON.parse(fs.readFileSync(settingsPath, 'utf8')); } catch {} @@ -177,32 +194,43 @@ HOOK_EOF // Claude Code's skill tool is Skill; Copilot CLI's is skill, which no // Claude tool name maps to, so a bare 'Skill' never fired there (#2229). - // An entry an older team-init wrote is upgraded in place, never duplicated. + // A registration an older team-init wrote (the .sh hook, matcher Skill) + // is replaced in place: exactly one check-gstack handler remains, and + // unrelated hooks in the same entry are kept. const MATCHER = 'Skill|skill'; - const ours = settings.hooks.PreToolUse.filter(entry => - (entry.matcher === 'Skill' || entry.matcher === MATCHER) && - entry.hooks && entry.hooks.some(h => h.command && h.command.includes('check-gstack')) - ); - for (const entry of ours) entry.matcher = MATCHER; - - if (ours.length === 0) { - settings.hooks.PreToolUse.push({ - matcher: MATCHER, - hooks: [{ - type: 'command', - command: '\"\$CLAUDE_PROJECT_DIR/.claude/hooks/check-gstack.sh\"' - }] - }); - } + const isOurs = h => h && typeof h.command === 'string' && h.command.includes('check-gstack'); + let placed = false; + settings.hooks.PreToolUse = settings.hooks.PreToolUse.filter(entry => { + if (entry.matcher !== 'Skill' && entry.matcher !== MATCHER) return true; + if (!Array.isArray(entry.hooks) || !entry.hooks.some(isOurs)) return true; + entry.matcher = MATCHER; + const kept = []; + for (const h of entry.hooks) { + if (!isOurs(h)) kept.push(h); + else if (!placed) { kept.push({ type: 'command', command }); placed = true; } + } + entry.hooks = kept; + return kept.length > 0; + }); + if (!placed) settings.hooks.PreToolUse.push({ matcher: MATCHER, hooks: [{ type: 'command', command }] }); const tmp = settingsPath + '.tmp'; fs.writeFileSync(tmp, JSON.stringify(settings, null, 2) + '\n'); fs.renameSync(tmp, settingsPath); - " 2>/dev/null + "; then GENERATED+=(".claude/settings.json") echo " + .claude/settings.json — PreToolUse hook registered" + # The bash hook an older team-init wrote goes only once its replacement is + # registered; a tracked one is staged as a deletion by the git add below. + if [ -e "$HOOKS_DIR/check-gstack.sh" ]; then + rm -f "$HOOKS_DIR/check-gstack.sh" + git -C "$REPO_ROOT" ls-files --error-unmatch -- .claude/hooks/check-gstack.sh >/dev/null 2>&1 \ + && GENERATED+=(".claude/hooks/check-gstack.sh") + echo " - .claude/hooks/check-gstack.sh — replaced by check-gstack.cjs" + fi else - echo " ! bun not found — manually add the PreToolUse hook to .claude/settings.json" + echo " ! could not update .claude/settings.json — add this PreToolUse hook (matcher Skill|skill) manually:" + echo " $HOOK_COMMAND" fi fi diff --git a/test/gstack-team-init-hook-schema.test.ts b/test/gstack-team-init-hook-schema.test.ts index f5ff08a4f..ee8cef78e 100644 --- a/test/gstack-team-init-hook-schema.test.ts +++ b/test/gstack-team-init-hook-schema.test.ts @@ -36,11 +36,14 @@ describe('gstack-team-init required: PreToolUse hook schema (#2413)', () => { fs.rmSync(fakeHomePresent, { recursive: true, force: true }); }); + // Run the command exactly as registered in settings.json, the way a hook + // runner does: through a shell, with CLAUDE_PROJECT_DIR set. function runHook(home: string): { status: number; stdout: string; stderr: string } { - const hookPath = path.join(repoDir, '.claude', 'hooks', 'check-gstack.sh'); + const settings = JSON.parse(fs.readFileSync(path.join(repoDir, '.claude', 'settings.json'), 'utf-8')); + const command = settings.hooks.PreToolUse[0].hooks[0].command; try { - const stdout = execSync(`bash "${hookPath}"`, { - env: { ...process.env, HOME: home }, + const stdout = execSync(command, { + env: { ...process.env, HOME: home, CLAUDE_PROJECT_DIR: repoDir, GSTACK_ROOT: '' }, encoding: 'utf-8', timeout: 30_000, }); @@ -52,11 +55,12 @@ describe('gstack-team-init required: PreToolUse hook schema (#2413)', () => { } test('generates the hook and registers it in settings.json', () => { - expect(fs.existsSync(path.join(repoDir, '.claude', 'hooks', 'check-gstack.sh'))).toBe(true); + expect(fs.existsSync(path.join(repoDir, '.claude', 'hooks', 'check-gstack.cjs'))).toBe(true); const settings = JSON.parse( fs.readFileSync(path.join(repoDir, '.claude', 'settings.json'), 'utf-8'), ); - expect(JSON.stringify(settings)).toContain('check-gstack.sh'); + expect(JSON.stringify(settings)).toContain('check-gstack.cjs'); + expect(settings.hooks.PreToolUse[0].hooks[0].command).not.toContain('$'); }); test('gstack absent: exits 2 (blocking) with schema-valid deny JSON', () => { diff --git a/test/routing-probe.test.ts b/test/routing-probe.test.ts index 6fb15f131..e71e83458 100644 --- a/test/routing-probe.test.ts +++ b/test/routing-probe.test.ts @@ -8,7 +8,7 @@ * HAS_ROUTING: no and got nagged to create CLAUDE.md. * * 2. gstack-team-init's required-mode enforcement (the CLAUDE.md - * verification snippet and the generated check-gstack.sh hook) must + * verification snippet and the generated check-gstack.cjs hook) must * resolve the install root across GSTACK_ROOT + every host's global * install location, never hardcode ~/.claude/skills/gstack. The drift * test pins the probe list against the hosts registry so a new host @@ -118,8 +118,14 @@ describe('team-init resolves GSTACK_ROOT across every host (#2500)', () => { }); test('generated hook blocks only when NO install root resolves', () => { - // The hook's block branch must gate on the resolved root being empty, - // not on any single hardcoded directory. - expect(teamInit).toContain('if [ -z "$_GSTACK_ROOT" ]; then'); + // The hook (CommonJS, so it runs under any hook shell) probes GSTACK_ROOT + // and every host's global root, and its block branch gates on none + // resolving, not on any single hardcoded directory. + const hook = teamInit.slice(teamInit.indexOf("cat > \"$HOOKS_DIR/check-gstack.cjs\""), teamInit.indexOf('\nHOOK_EOF\n')); + expect(hook).toContain('process.env.GSTACK_ROOT'); + for (const config of ALL_HOST_CONFIGS) expect(hook).toContain(`'${config.globalRoot}'`); + expect(hook).toContain("'.gstack/repos/gstack'"); + expect(hook).toContain('const gstackRoot = roots.find('); + expect(hook).toContain('if (gstackRoot) {'); }); }); diff --git a/test/team-init-hook-shell-neutral.test.ts b/test/team-init-hook-shell-neutral.test.ts new file mode 100644 index 000000000..385c4003d --- /dev/null +++ b/test/team-init-hook-shell-neutral.test.ts @@ -0,0 +1,82 @@ +/** + * Required team mode registers its PreToolUse hook as a command string that + * the hook runner hands to whatever shell it uses: sh on macOS and Linux, + * cmd.exe or PowerShell on Windows and under Copilot CLI. The old + * `"$CLAUDE_PROJECT_DIR/.claude/hooks/check-gstack.sh"` only worked in a POSIX + * shell, so on Windows an intended allow or deny became a hook error (#2217). + * + * This reads the hook source and the registered command straight out of + * bin/gstack-team-init (no bash needed) and runs the command through the + * platform's default shell (`shell: true`: /bin/sh here, cmd.exe on Windows), + * plus PowerShell when one is installed, from a project path with a space. + */ +import { afterAll, describe, expect, test } from 'bun:test'; +import { spawnSync } from 'node:child_process'; +import * as fs from 'node:fs'; +import * as os from 'node:os'; +import * as path from 'node:path'; + +const TEAM_INIT = fs.readFileSync(new URL('../bin/gstack-team-init', import.meta.url), 'utf-8'); + +const HOOK_START = 'cat > "$HOOKS_DIR/check-gstack.cjs" << \'HOOK_EOF\'\n'; +const hookSource = TEAM_INIT.slice(TEAM_INIT.indexOf(HOOK_START) + HOOK_START.length, TEAM_INIT.indexOf('\nHOOK_EOF\n')); +const commandLiteral = TEAM_INIT.match(/^\s*HOOK_COMMAND="((?:[^"\\]|\\.)*)"$/m)?.[1] ?? ''; +const command = commandLiteral.replace(/\\(["\\$`])/g, '$1'); + +const base = fs.mkdtempSync(path.join(os.tmpdir(), 'team-hook-neutral-')); +afterAll(() => fs.rmSync(base, { recursive: true, force: true })); +const project = path.join(base, 'my project'); +fs.mkdirSync(path.join(project, '.claude', 'hooks'), { recursive: true }); +fs.writeFileSync(path.join(project, '.claude', 'hooks', 'check-gstack.cjs'), hookSource); +const elsewhere = path.join(base, 'elsewhere'); +fs.mkdirSync(elsewhere); + +function hookEnv(home: Record): NodeJS.ProcessEnv { + const env: NodeJS.ProcessEnv = { ...process.env, CLAUDE_PROJECT_DIR: project, ...home }; + delete env.GSTACK_ROOT; + if (!('HOME' in home)) delete env.HOME; + return env; +} + +type Runner = (env: NodeJS.ProcessEnv) => { status: number | null; stdout: string; stderr: string }; +const viaDefaultShell: Runner = (env) => spawnSync(command, { shell: true, cwd: elsewhere, env, encoding: 'utf-8', timeout: 20_000 }); +const powershell = process.platform === 'win32' ? 'powershell' : Bun.which('pwsh'); +const viaPowerShell: Runner = (env) => + spawnSync(powershell!, ['-NoProfile', '-NonInteractive', '-Command', command], { cwd: elsewhere, env, encoding: 'utf-8', timeout: 30_000 }); + +describe('required team hook: shell-neutral registration', () => { + test('the extracted command is a node launcher with no shell variable syntax', () => { + expect(hookSource).toContain("'use strict';"); + expect(command).toStartWith('node -e "'); + expect(command).toContain('process.env.CLAUDE_PROJECT_DIR'); + expect(commandLiteral).not.toContain('$'); + expect(command).not.toContain('%'); + }); + + // `powershell -Command` reports a failing native command as exit 1, so only + // the default shell sees the hook's own exit 2; the deny JSON is the same. + for (const [name, runner, enabled, denyStatus] of [ + ['the default shell', viaDefaultShell, true, 2], + ['PowerShell', viaPowerShell, Boolean(powershell), 1], + ] as const) { + test.skipIf(!enabled)(`through ${name}: deny with exit 2 when no install resolves, {} when one does`, () => { + const home = path.join(base, `home-${name.replace(/\W+/g, '-')}`); + fs.mkdirSync(home, { recursive: true }); + + const denied = runner(hookEnv({ HOME: home, USERPROFILE: home })); + expect(denied.status).toBe(denyStatus); + expect(JSON.parse(denied.stdout.trim()).hookSpecificOutput).toMatchObject({ hookEventName: 'PreToolUse', permissionDecision: 'deny' }); + expect(denied.stderr).toContain('BLOCKED: gstack is not installed globally.'); + + fs.mkdirSync(path.join(home, '.claude/skills/gstack/bin'), { recursive: true }); + const allowed = runner(hookEnv({ HOME: home, USERPROFILE: home })); + expect(allowed.stderr).toBe(''); + expect(allowed.stdout.trim()).toBe('{}'); + expect(allowed.status).toBe(0); + + const viaProfile = runner(hookEnv({ USERPROFILE: home })); + expect(viaProfile.stdout.trim()).toBe('{}'); + expect(viaProfile.status).toBe(0); + }); + } +}); diff --git a/test/team-mode.test.ts b/test/team-mode.test.ts index cee5b095a..a7fe7b817 100644 --- a/test/team-mode.test.ts +++ b/test/team-mode.test.ts @@ -233,7 +233,7 @@ describe('gstack-team-init', () => { test('required: creates enforcement hook', () => { run(`${TEAM_INIT} required`, { cwd: tmpDir }); - const hookPath = path.join(tmpDir, '.claude', 'hooks', 'check-gstack.sh'); + const hookPath = path.join(tmpDir, '.claude', 'hooks', 'check-gstack.cjs'); expect(fs.existsSync(hookPath)).toBe(true); const hook = fs.readFileSync(hookPath, 'utf-8'); expect(hook).toContain('BLOCKED: gstack is not installed'); @@ -267,6 +267,93 @@ describe('gstack-team-init', () => { expect(pre.map((e: { matcher: string }) => e.matcher)).toEqual(['Bash', 'Skill|skill']); }); + const registeredCommand = () => { + const pre = JSON.parse(fs.readFileSync(path.join(tmpDir, '.claude', 'settings.json'), 'utf-8')).hooks.PreToolUse; + return pre.flatMap((e: { hooks: { command: string }[] }) => e.hooks.map(h => h.command)).find((c: string) => c.includes('check-gstack')); + }; + + test('required: the registered command is shell-neutral (no shell variable syntax, node reads CLAUDE_PROJECT_DIR)', () => { + run(`${TEAM_INIT} required`, { cwd: tmpDir }); + const command = registeredCommand(); + expect(command).toStartWith('node -e "'); + expect(command).toContain('process.env.CLAUDE_PROJECT_DIR'); + expect(command).toContain('check-gstack.cjs'); + expect(command).not.toContain('$'); + expect(command).not.toContain('%'); + expect(command).not.toContain('.sh'); + }); + + test('required: the registered command, run from another directory, allows when gstack resolves and denies when not', () => { + run(`${TEAM_INIT} required`, { cwd: tmpDir }); + const command = registeredCommand(); + const home = mkTmpDir(); + const elsewhere = mkTmpDir(); + const hook = (env: Record) => { + const r = Bun.spawnSync(['sh', '-c', command], { cwd: elsewhere, env: { PATH: process.env.PATH!, CLAUDE_PROJECT_DIR: tmpDir, ...env }, timeout: 10_000 }); + return { code: r.exitCode, out: r.stdout.toString().trim(), err: r.stderr.toString() }; + }; + try { + const denied = hook({ HOME: home }); + expect(denied.code).toBe(2); + expect(JSON.parse(denied.out).hookSpecificOutput.permissionDecision).toBe('deny'); + expect(denied.err).toContain('BLOCKED: gstack is not installed globally.'); + + expect(hook({ HOME: home, GSTACK_ROOT: path.join(ROOT) })).toEqual({ code: 0, out: '{}', err: '' }); + fs.mkdirSync(path.join(home, '.codex', 'skills', 'gstack', 'bin'), { recursive: true }); + expect(hook({ HOME: home })).toEqual({ code: 0, out: '{}', err: '' }); + // No HOME (a Windows hook runner): USERPROFILE is next. + expect(hook({ USERPROFILE: home })).toEqual({ code: 0, out: '{}', err: '' }); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + fs.rmSync(elsewhere, { recursive: true, force: true }); + } + }); + + test('required: re-running over a legacy .sh registration leaves exactly one handler and removes the tracked .sh', () => { + const hooksDir = path.join(tmpDir, '.claude', 'hooks'); + fs.mkdirSync(hooksDir, { recursive: true }); + fs.writeFileSync(path.join(hooksDir, 'check-gstack.sh'), '#!/bin/bash\necho "{}"\n', { mode: 0o755 }); + const legacy = { type: 'command', command: '"$CLAUDE_PROJECT_DIR/.claude/hooks/check-gstack.sh"' }; + fs.writeFileSync(path.join(tmpDir, '.claude', 'settings.json'), JSON.stringify({ hooks: { PreToolUse: [ + { matcher: 'Skill', hooks: [{ type: 'command', command: 'team-audit' }, legacy] }, + { matcher: 'Skill|skill', hooks: [legacy] }, + { matcher: 'Bash', hooks: [{ type: 'command', command: 'my-own-hook' }] }, + ] } })); + execSync('git add .claude && git commit -q -m legacy', { cwd: tmpDir, timeout: 30_000 }); + + const first = run(`${TEAM_INIT} required`, { cwd: tmpDir }); + expect(first.exitCode).toBe(0); + expect(fs.existsSync(path.join(hooksDir, 'check-gstack.sh'))).toBe(false); + expect(first.stdout).toMatch(/git add .*\.claude\/hooks\/check-gstack\.sh/); + run(`${TEAM_INIT} required`, { cwd: tmpDir }); + + const pre = JSON.parse(fs.readFileSync(path.join(tmpDir, '.claude', 'settings.json'), 'utf-8')).hooks.PreToolUse; + expect(pre).toEqual([ + { matcher: 'Skill|skill', hooks: [{ type: 'command', command: 'team-audit' }, { type: 'command', command: registeredCommand() }] }, + { matcher: 'Bash', hooks: [{ type: 'command', command: 'my-own-hook' }] }, + ]); + expect(registeredCommand()).not.toContain('$'); + }); + + test('required: without bun the legacy .sh stays, since nothing re-registers its replacement', () => { + const hooksDir = path.join(tmpDir, '.claude', 'hooks'); + fs.mkdirSync(hooksDir, { recursive: true }); + fs.writeFileSync(path.join(hooksDir, 'check-gstack.sh'), '#!/bin/bash\necho "{}"\n', { mode: 0o755 }); + const bin = mkTmpDir(); + try { + for (const tool of ['git', 'bash', 'cat', 'mkdir', 'chmod', 'grep', 'dirname', 'rm']) { + const real = execSync(`command -v ${tool}`, { encoding: 'utf-8', shell: '/bin/bash' }).trim(); + fs.symlinkSync(real, path.join(bin, tool)); + } + const r = run(`${bin}/bash ${TEAM_INIT} required`, { cwd: tmpDir, env: { PATH: bin } }); + expect(r.exitCode).toBe(0); + expect(r.stdout).toContain('bun not found'); + expect(fs.existsSync(path.join(hooksDir, 'check-gstack.sh'))).toBe(true); + } finally { + fs.rmSync(bin, { recursive: true, force: true }); + } + }); + test('idempotent: running twice does not duplicate CLAUDE.md section', () => { run(`${TEAM_INIT} optional`, { cwd: tmpDir }); run(`${TEAM_INIT} optional`, { cwd: tmpDir }); From 652b5d3558825f9804e9b32f9bbef88bd455a403 Mon Sep 17 00:00:00 2001 From: garrytan Date: Thu, 8 Oct 2026 06:32:56 +0000 Subject: [PATCH 5/5] fix(setup-gbrain): register the gbrain MCP through bun.exe on Windows so no console window opens Rewrite of #2007, folding #1963's MCP notes. On Windows the local stdio registration stored the bun `gbrain` binstub; gbrain.exe starts bun in a new console, so every Claude Code session opened a visible terminal for the MCP (the contributor's process trees show it; bun.exe launched directly attaches to Claude Code's headless ConPTY). Under MINGW/MSYS/Cygwin the skill now resolves BUN_ROOT from BUN_INSTALL or ~/.bun and registers `$BUN_ROOT/bin/bun.exe serve`. That path also covers a `bun link`ed clone, whose global node_modules entry links to it; gstack-gbrain-install records no other clone location. When bun.exe or the entry is missing it registers `$BUN_ROOT/bin/gbrain.exe` by its full name, because Claude Code does not apply PATHEXT to a stored path (#1963). POSIX keeps the binstub line. The skill also notes that `claude mcp list` can show "Failed to connect" while a live session holds a local PGLite brain's single-writer lock (#1963). test/setup-gbrain-windows-mcp.test.ts runs the generated fence under bash with stub uname/claude and a temp HOME for MINGW64, MSYS with BUN_INSTALL, a missing entry, and Linux. It is listed as Windows-incompatible (POSIX stubs); the console behavior needs a manual Windows check. Co-authored-by: Max Hogan Co-authored-by: maxpetrusenkoagent <280464918+maxpetrusenkoagent@users.noreply.github.com> Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- scripts/lib/windows-curation.ts | 4 ++ setup-gbrain/SKILL.md | 26 +++++++++- setup-gbrain/SKILL.md.tmpl | 26 +++++++++- test/setup-gbrain-windows-mcp.test.ts | 75 +++++++++++++++++++++++++++ 4 files changed, 129 insertions(+), 2 deletions(-) create mode 100644 test/setup-gbrain-windows-mcp.test.ts diff --git a/scripts/lib/windows-curation.ts b/scripts/lib/windows-curation.ts index 1694a0f2a..5a8c7d3dc 100644 --- a/scripts/lib/windows-curation.ts +++ b/scripts/lib/windows-curation.ts @@ -75,6 +75,10 @@ export const KNOWN_WINDOWS_INCOMPATIBLE: Array<{ file: string; reason: string }> file: 'test/setup-gbrain-fixture.test.ts', reason: 'the fixture invokes real POSIX detector/verifier helpers through executable shebang wrappers', }, + { + file: 'test/setup-gbrain-windows-mcp.test.ts', + reason: 'drives the Windows MCP registration branch on POSIX by putting uname/claude shebang stubs on a colon-separated PATH and comparing POSIX path spellings; the console behavior it guards needs a manual Windows check', + }, { file: 'test/hermetic-skills-seeding.test.ts', reason: 'seeds the POSIX PTY skill runtime, whose embedded shell paths require a POSIX temporary root', diff --git a/setup-gbrain/SKILL.md b/setup-gbrain/SKILL.md index d79a2220c..66e6942fe 100644 --- a/setup-gbrain/SKILL.md +++ b/setup-gbrain/SKILL.md @@ -611,15 +611,39 @@ binary. User scope makes the MCP available in every Claude Code session on this machine, not just the current workspace. Absolute path avoids PATH resolution issues when Claude Code spawns `gbrain serve` as a subprocess. +On Windows (Git Bash/MSYS) the `gbrain.exe` binstub starts bun in a new +console, so every Claude Code session would open a visible terminal for the +MCP. Register `bun.exe` with gbrain's entry instead, which attaches to Claude +Code's hidden console. Without them, register `gbrain.exe` by its full name, +because Claude Code does not add `.exe` to a stored path. + ```bash GBRAIN_BIN=$(command -v gbrain) [ -z "$GBRAIN_BIN" ] && GBRAIN_BIN="$HOME/.bun/bin/gbrain" claude mcp remove gbrain -s user 2>/dev/null || true claude mcp remove gbrain 2>/dev/null || true -claude mcp add --scope user gbrain -- "$GBRAIN_BIN" serve +case "$(uname -s)" in + MINGW*|MSYS*|CYGWIN*) + BUN_ROOT="${BUN_INSTALL:-$HOME/.bun}" + GBRAIN_ENTRY="$BUN_ROOT/install/global/node_modules/gbrain/src/cli.ts" + if [ -f "$BUN_ROOT/bin/bun.exe" ] && [ -f "$GBRAIN_ENTRY" ]; then + claude mcp add --scope user gbrain -- "$BUN_ROOT/bin/bun.exe" "$GBRAIN_ENTRY" serve + else + claude mcp add --scope user gbrain -- "$BUN_ROOT/bin/gbrain.exe" serve + fi + ;; + *) + claude mcp add --scope user gbrain -- "$GBRAIN_BIN" serve + ;; +esac claude mcp list | grep gbrain # verify: should show "✓ Connected" ``` +On a local PGLite brain, `claude mcp list` can show `Failed to connect` +while an open Claude Code session's gbrain holds the database's single-writer +lock. If `mcp__gbrain__*` tools work in that session, the registration is +fine. + ### Both paths If `claude` is not on PATH: emit "MCP registration skipped — this skill is diff --git a/setup-gbrain/SKILL.md.tmpl b/setup-gbrain/SKILL.md.tmpl index 22e846b86..3af5f03be 100644 --- a/setup-gbrain/SKILL.md.tmpl +++ b/setup-gbrain/SKILL.md.tmpl @@ -275,15 +275,39 @@ binary. User scope makes the MCP available in every Claude Code session on this machine, not just the current workspace. Absolute path avoids PATH resolution issues when Claude Code spawns `gbrain serve` as a subprocess. +On Windows (Git Bash/MSYS) the `gbrain.exe` binstub starts bun in a new +console, so every Claude Code session would open a visible terminal for the +MCP. Register `bun.exe` with gbrain's entry instead, which attaches to Claude +Code's hidden console. Without them, register `gbrain.exe` by its full name, +because Claude Code does not add `.exe` to a stored path. + ```bash GBRAIN_BIN=$(command -v gbrain) [ -z "$GBRAIN_BIN" ] && GBRAIN_BIN="$HOME/.bun/bin/gbrain" claude mcp remove gbrain -s user 2>/dev/null || true claude mcp remove gbrain 2>/dev/null || true -claude mcp add --scope user gbrain -- "$GBRAIN_BIN" serve +case "$(uname -s)" in + MINGW*|MSYS*|CYGWIN*) + BUN_ROOT="${BUN_INSTALL:-$HOME/.bun}" + GBRAIN_ENTRY="$BUN_ROOT/install/global/node_modules/gbrain/src/cli.ts" + if [ -f "$BUN_ROOT/bin/bun.exe" ] && [ -f "$GBRAIN_ENTRY" ]; then + claude mcp add --scope user gbrain -- "$BUN_ROOT/bin/bun.exe" "$GBRAIN_ENTRY" serve + else + claude mcp add --scope user gbrain -- "$BUN_ROOT/bin/gbrain.exe" serve + fi + ;; + *) + claude mcp add --scope user gbrain -- "$GBRAIN_BIN" serve + ;; +esac claude mcp list | grep gbrain # verify: should show "✓ Connected" ``` +On a local PGLite brain, `claude mcp list` can show `Failed to connect` +while an open Claude Code session's gbrain holds the database's single-writer +lock. If `mcp__gbrain__*` tools work in that session, the registration is +fine. + ### Both paths If `claude` is not on PATH: emit "MCP registration skipped — this skill is diff --git a/test/setup-gbrain-windows-mcp.test.ts b/test/setup-gbrain-windows-mcp.test.ts new file mode 100644 index 000000000..302ffb865 --- /dev/null +++ b/test/setup-gbrain-windows-mcp.test.ts @@ -0,0 +1,75 @@ +/** + * /setup-gbrain's local stdio MCP registration (#2007, #1963). On Windows the + * bun `gbrain.exe` binstub starts bun in a new console, so registering it made + * every Claude Code session open a visible terminal; the skill registers + * `bun.exe serve` instead, and `gbrain.exe` by its full name + * when bun.exe or the entry is missing. POSIX keeps the binstub. + * + * Runs the generated fence under bash with stub `uname` and `claude` and a + * temp HOME. The console behavior itself needs a real Windows machine. + */ +import { afterAll, describe, expect, test } from 'bun:test'; +import { spawnSync } from 'node:child_process'; +import * as fs from 'node:fs'; +import * as os from 'node:os'; +import * as path from 'node:path'; + +const ROOT = path.resolve(import.meta.dir, '..'); +const SKILL = fs.readFileSync(path.join(ROOT, 'setup-gbrain', 'SKILL.md'), 'utf-8'); + +function localStdioFence(): string { + const section = SKILL.indexOf('### Paths 1, 2a, 2b, 3 (Local stdio)\n\nRegister at **user scope**'); + expect(section).toBeGreaterThan(-1); + const start = SKILL.indexOf('```bash\n', section) + '```bash\n'.length; + return SKILL.slice(start, SKILL.indexOf('\n```', start)); +} + +const base = fs.mkdtempSync(path.join(os.tmpdir(), 'setup-gbrain-mcp-')); +afterAll(() => fs.rmSync(base, { recursive: true, force: true })); + +function register(uname: string, files: string[], env: (home: string) => Record = () => ({})) { + const dir = fs.mkdtempSync(path.join(base, 'case-')); + const home = path.join(dir, 'home'); + const stubs = path.join(dir, 'stubs'); + const log = path.join(dir, 'claude-argv'); + fs.mkdirSync(stubs, { recursive: true }); + for (const rel of files) { + fs.mkdirSync(path.dirname(path.join(home, rel)), { recursive: true }); + fs.writeFileSync(path.join(home, rel), ''); + } + fs.writeFileSync(path.join(stubs, 'uname'), `#!/bin/bash\necho ${uname}\n`, { mode: 0o755 }); + fs.writeFileSync(path.join(stubs, 'claude'), `#!/bin/bash\ncase "$2" in add) printf '%s\\n' "$@" > "${log}" ;; list) echo 'gbrain: stub - ✓ Connected' ;; esac\nexit 0\n`, { mode: 0o755 }); + const r = spawnSync('bash', ['-c', localStdioFence()], { + env: { PATH: `${stubs}:/usr/bin:/bin`, HOME: home, ...env(home) }, + encoding: 'utf-8', + timeout: 20_000, + }); + expect(r.status).toBe(0); + return { home, argv: fs.readFileSync(log, 'utf-8').trim().split('\n') }; +} + +const BUN_EXE = '.bun/bin/bun.exe'; +const ENTRY = '.bun/install/global/node_modules/gbrain/src/cli.ts'; + +describe('setup-gbrain local stdio MCP registration', () => { + test('Windows (MINGW64): registers bun.exe with the gbrain entry, not the binstub', () => { + const { home, argv } = register('MINGW64_NT-10.0-26100', [BUN_EXE, ENTRY]); + expect(argv).toEqual(['mcp', 'add', '--scope', 'user', 'gbrain', '--', path.join(home, BUN_EXE), path.join(home, ENTRY), 'serve']); + }); + + test('Windows honors BUN_INSTALL', () => { + const files = ['custom-bun/bin/bun.exe', 'custom-bun/install/global/node_modules/gbrain/src/cli.ts']; + const { home, argv } = register('MSYS_NT-10.0', files, (h) => ({ BUN_INSTALL: path.join(h, 'custom-bun') })); + expect(argv).toEqual(['mcp', 'add', '--scope', 'user', 'gbrain', '--', ...files.map((f) => path.join(home, f)), 'serve']); + }); + + test('Windows without the entry: registers gbrain.exe by its full name', () => { + const { home, argv } = register('MINGW64_NT-10.0', [BUN_EXE]); + expect(argv).toEqual(['mcp', 'add', '--scope', 'user', 'gbrain', '--', path.join(home, '.bun/bin/gbrain.exe'), 'serve']); + }); + + test('Linux keeps the binstub registration', () => { + const { home, argv } = register('Linux', [BUN_EXE, ENTRY]); + expect(argv).toEqual(['mcp', 'add', '--scope', 'user', 'gbrain', '--', path.join(home, '.bun/bin/gbrain'), 'serve']); + }); +});