Skip to content

Use Garry Tan's exact Claude Code setup: 23 opinionated tools that serve as CEO, Designer, Eng Manager, Release Manager, Doc Engineer, and QA

TypeScript

v1.67.0.0 fix: the tracker wave — XProtect self-heal, complete installs, brain-sync integrity, 31 community PRs credited (#2604)

Garry Tanae8914af7eda
diff --git a/.gitattributes b/.gitattributes
index e67042f0a..10a4ff7fd 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -8,6 +8,7 @@
*.yaml text eol=lf
*.json text eol=lf
*.toml text eol=lf
+*.txt text eol=lf
# Bash scripts must always use LF — CRLF in bash scripts produces bizarre
# "Bad interpreter" / "command not found" errors on Linux runners.
diff --git a/.github/docker/Dockerfile.ci b/.github/docker/Dockerfile.ci
index fed221005..550c90d3a 100644
--- a/.github/docker/Dockerfile.ci
+++ b/.github/docker/Dockerfile.ci
@@ -104,7 +104,12 @@ RUN for i in 1 2 3; do \
# resolution. Without bun.lock here, bun install resolved transitive deps
# differently in CI vs local (observed on v1.28.0.0: socks landed but
# smart-buffer + ip-address didn't make it into the cached node_modules).
+# patches/ rides along: bun.lock's patchedDependencies (playwright-core
+# windowsHide, v1.67) makes install fail without the patch files present —
+# and the workflows' image-tag hash includes patches/** so editing a patch
+# rebuilds this layer.
COPY package.json bun.lock /workspace/
+COPY patches /workspace/patches
WORKDIR /workspace
RUN bun install --frozen-lockfile && rm -rf /tmp/*
diff --git a/.github/workflows/actionlint.yml b/.github/workflows/actionlint.yml
index a6e203ee3..544f694fd 100644
--- a/.github/workflows/actionlint.yml
+++ b/.github/workflows/actionlint.yml
@@ -22,7 +22,7 @@ jobs:
actionlint:
runs-on: ubicloud-standard-2
steps:
- - uses: actions/checkout@v4
+ - uses: actions/checkout@v7
with:
persist-credentials: false
# Pull the prebuilt image instead of rhysd/[email protected] (a Docker
diff --git a/.github/workflows/ci-image.yml b/.github/workflows/ci-image.yml
index 2cb916063..4cb1dccc2 100644
--- a/.github/workflows/ci-image.yml
+++ b/.github/workflows/ci-image.yml
@@ -20,18 +20,18 @@ jobs:
contents: read
packages: write
steps:
- - uses: actions/checkout@v4
+ - uses: actions/checkout@v7
# Copy lockfile + package.json into Docker build context
- - run: cp package.json bun.lock .github/docker/
+ - run: cp package.json bun.lock .github/docker/ && cp -R patches .github/docker/patches
# Same content-hash tag expression as evals.yml / evals-periodic.yml.
# This is the tag the eval matrix looks up first — without pushing it
# here, the weekly/main prebuild never warms the cache that matters.
- id: meta
- run: echo "tag=ghcr.io/${{ github.repository }}/ci:${{ hashFiles('.github/docker/Dockerfile.ci', 'bun.lock') }}" >> "$GITHUB_OUTPUT"
+ run: echo "tag=ghcr.io/${{ github.repository }}/ci:${{ hashFiles('.github/docker/Dockerfile.ci', 'bun.lock', 'patches/**') }}" >> "$GITHUB_OUTPUT"
- - uses: docker/login-action@v3
+ - uses: docker/login-action@v4
with:
registry: ghcr.io
username: ${{ github.actor }}
@@ -39,9 +39,9 @@ jobs:
# Registry cache export needs a docker-container builder — the default
# `docker` driver hard-errors on cache-to.
- - uses: docker/setup-buildx-action@v3
+ - uses: docker/setup-buildx-action@v4
- - uses: docker/build-push-action@v6
+ - uses: docker/build-push-action@v7
with:
context: .github/docker
file: .github/docker/Dockerfile.ci
diff --git a/.github/workflows/dependency-review.yml b/.github/workflows/dependency-review.yml
index c69dad8d1..b600ada81 100644
--- a/.github/workflows/dependency-review.yml
+++ b/.github/workflows/dependency-review.yml
@@ -24,8 +24,8 @@ jobs:
contents: read
pull-requests: write
steps:
- - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
- - uses: actions/dependency-review-action@2031cfc080254a8a887f58cffee85186f0e49e48 # v4.9.0
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v4
+ - uses: actions/dependency-review-action@a1d282b36b6f3519aa1f3fc636f609c47dddb294 # v5.0.0
with:
fail-on-severity: high
fail-on-scopes: runtime, development
diff --git a/.github/workflows/evals-periodic.yml b/.github/workflows/evals-periodic.yml
index 2bbfb5bf9..b1493bc3f 100644
--- a/.github/workflows/evals-periodic.yml
+++ b/.github/workflows/evals-periodic.yml
@@ -22,14 +22,14 @@ jobs:
outputs:
image-tag: ${{ steps.meta.outputs.tag }}
steps:
- - uses: actions/checkout@v4
+ - uses: actions/checkout@v7
- id: meta
# Keep in sync with evals.yml — key on Dockerfile + lockfile only
# (package.json's version field would bust the key on every ship).
- run: echo "tag=${{ env.IMAGE }}:${{ hashFiles('.github/docker/Dockerfile.ci', 'bun.lock') }}" >> "$GITHUB_OUTPUT"
+ run: echo "tag=${{ env.IMAGE }}:${{ hashFiles('.github/docker/Dockerfile.ci', 'bun.lock', 'patches/**') }}" >> "$GITHUB_OUTPUT"
- - uses: docker/login-action@v3
+ - uses: docker/login-action@v4
with:
registry: ghcr.io
username: ${{ github.actor }}
@@ -45,15 +45,15 @@ jobs:
fi
- if: steps.check.outputs.exists == 'false'
- run: cp package.json bun.lock .github/docker/
+ run: cp package.json bun.lock .github/docker/ && cp -R patches .github/docker/patches
# 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@v3
+ uses: docker/setup-buildx-action@v4
- if: steps.check.outputs.exists == 'false'
- uses: docker/build-push-action@v6
+ uses: docker/build-push-action@v7
with:
context: .github/docker
file: .github/docker/Dockerfile.ci
@@ -103,7 +103,7 @@ jobs:
- name: e2e-gemini
file: test/gemini-e2e.test.ts
steps:
- - uses: actions/checkout@v4
+ - uses: actions/checkout@v7
with:
fetch-depth: 0
@@ -141,7 +141,7 @@ jobs:
- name: Upload eval results
if: always()
- uses: actions/upload-artifact@v4
+ uses: actions/upload-artifact@v7
with:
name: eval-periodic-${{ matrix.suite.name }}
path: ~/.gstack-dev/evals/*.json
diff --git a/.github/workflows/evals.yml b/.github/workflows/evals.yml
index 5400b19d4..fffb6cda1 100644
--- a/.github/workflows/evals.yml
+++ b/.github/workflows/evals.yml
@@ -28,7 +28,7 @@ jobs:
outputs:
image-tag: ${{ steps.meta.outputs.tag }}
steps:
- - uses: actions/checkout@v4
+ - uses: actions/checkout@v7
- id: meta
# Key on Dockerfile + lockfile only. package.json is deliberately NOT
@@ -36,9 +36,9 @@ jobs:
# which rebuilt the image each time for a dependency set that only
# bun.lock determines. A stale baked package.json is harmless — checkout
# overwrites /workspace and node_modules comes from the lockfile.
- run: echo "tag=${{ env.IMAGE }}:${{ hashFiles('.github/docker/Dockerfile.ci', 'bun.lock') }}" >> "$GITHUB_OUTPUT"
+ run: echo "tag=${{ env.IMAGE }}:${{ hashFiles('.github/docker/Dockerfile.ci', 'bun.lock', 'patches/**') }}" >> "$GITHUB_OUTPUT"
- - uses: docker/login-action@v3
+ - uses: docker/login-action@v4
with:
registry: ghcr.io
username: ${{ github.actor }}
@@ -54,7 +54,7 @@ jobs:
fi
- if: steps.check.outputs.exists == 'false'
- run: cp package.json bun.lock .github/docker/
+ run: cp package.json bun.lock .github/docker/ && cp -R patches .github/docker/patches
# A fork PR's GITHUB_TOKEN only has `packages: read`, so pushing fails.
# Still BUILD (validates Dockerfile.ci changes), just don't publish. This
@@ -63,10 +63,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@v3
+ uses: docker/setup-buildx-action@v4
- if: steps.check.outputs.exists == 'false'
- uses: docker/build-push-action@v6
+ uses: docker/build-push-action@v7
with:
context: .github/docker
file: .github/docker/Dockerfile.ci
@@ -158,7 +158,7 @@ jobs:
# row keeps --retry 1.
retries: 2
steps:
- - uses: actions/checkout@v4
+ - uses: actions/checkout@v7
with:
fetch-depth: 0
@@ -320,7 +320,7 @@ jobs:
- name: Upload eval results
if: always()
- uses: actions/upload-artifact@v4
+ uses: actions/upload-artifact@v7
with:
name: eval-${{ matrix.suite.name }}
path: ~/.gstack-dev/evals/*.json
@@ -341,12 +341,12 @@ jobs:
# early and never hit it, which is why this stayed hidden). See #1802 CI fix.
issues: write
steps:
- - uses: actions/checkout@v4
+ - uses: actions/checkout@v7
with:
fetch-depth: 1
- name: Download all eval artifacts
- uses: actions/download-artifact@v4
+ uses: actions/download-artifact@v8
with:
pattern: eval-*
path: /tmp/eval-results
diff --git a/.github/workflows/free-tests.yml b/.github/workflows/free-tests.yml
index 9296e3928..782727772 100644
--- a/.github/workflows/free-tests.yml
+++ b/.github/workflows/free-tests.yml
@@ -48,7 +48,7 @@ jobs:
runs-on: ubicloud-standard-8
timeout-minutes: 20
steps:
- - uses: actions/checkout@v4
+ - uses: actions/checkout@v7
with:
persist-credentials: false
@@ -56,7 +56,7 @@ jobs:
with:
bun-version: 1.3.13
- - uses: actions/cache@v4
+ - uses: actions/cache@v6
with:
path: ~/.bun/install/cache
key: linux-bun-${{ hashFiles('bun.lock') }}
@@ -67,7 +67,7 @@ jobs:
- name: Install dependencies
run: bun install --frozen-lockfile
- - uses: actions/cache@v4
+ - uses: actions/cache@v6
with:
path: ~/.cache/ms-playwright
key: linux-playwright-${{ hashFiles('bun.lock') }}
@@ -118,7 +118,7 @@ jobs:
# need a local re-run, which fork contributors can't do on this image.
- name: Upload shard logs on failure
if: failure()
- uses: actions/upload-artifact@v4
+ uses: actions/upload-artifact@v7
with:
name: free-test-shard-logs
path: /tmp/gstack-free-test-*.log
diff --git a/.github/workflows/make-pdf-gate.yml b/.github/workflows/make-pdf-gate.yml
index ec52e6996..fa9808276 100644
--- a/.github/workflows/make-pdf-gate.yml
+++ b/.github/workflows/make-pdf-gate.yml
@@ -40,7 +40,7 @@ jobs:
runs-on: ${{ matrix.os }}
steps:
- - uses: actions/checkout@v4
+ - uses: actions/checkout@v7
- uses: oven-sh/setup-bun@v2
with:
diff --git a/.github/workflows/osv-scanner.yml b/.github/workflows/osv-scanner.yml
index 22b8ae6eb..a5f4131ff 100644
--- a/.github/workflows/osv-scanner.yml
+++ b/.github/workflows/osv-scanner.yml
@@ -18,7 +18,7 @@ jobs:
actions: read
contents: read
security-events: write
- uses: google/osv-scanner-action/.github/workflows/osv-scanner-reusable.yml@3adb4b14a2b0623876d18d863a498b785fb3752d # v2.3.8
+ uses: google/osv-scanner-action/.github/workflows/osv-scanner-reusable.yml@f4cfcc01edc9c8b756a9b873b7a623ca674da51e # v2.3.8
with:
scan-args: |-
--include-git-root
diff --git a/.github/workflows/pr-title-sync.yml b/.github/workflows/pr-title-sync.yml
index 9534e4277..5a01ae275 100644
--- a/.github/workflows/pr-title-sync.yml
+++ b/.github/workflows/pr-title-sync.yml
@@ -39,7 +39,7 @@ jobs:
steps:
# Base repo only — trusted infra (the rewrite helper). No PR-head checkout.
- name: Checkout base repo (trusted)
- uses: actions/checkout@v4
+ uses: actions/checkout@v7
with:
fetch-depth: 1
diff --git a/.github/workflows/quality-gate.yml b/.github/workflows/quality-gate.yml
index af1c6fb12..5760d1a6b 100644
--- a/.github/workflows/quality-gate.yml
+++ b/.github/workflows/quality-gate.yml
@@ -31,7 +31,7 @@ jobs:
runs-on: ubicloud-standard-8
timeout-minutes: 20
steps:
- - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v4
with:
fetch-depth: 0
- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2
diff --git a/.github/workflows/skill-docs.yml b/.github/workflows/skill-docs.yml
index f9833426f..47ba5f36b 100644
--- a/.github/workflows/skill-docs.yml
+++ b/.github/workflows/skill-docs.yml
@@ -17,7 +17,7 @@ jobs:
check-freshness:
runs-on: ubicloud-standard-2
steps:
- - uses: actions/checkout@v4
+ - uses: actions/checkout@v7
- uses: oven-sh/setup-bun@v2
- run: bun install
# One generation pass for ALL 10 hosts. gen-skill-docs --host all
diff --git a/.github/workflows/version-gate.yml b/.github/workflows/version-gate.yml
index 0e42a2dc9..00a2e25ec 100644
--- a/.github/workflows/version-gate.yml
+++ b/.github/workflows/version-gate.yml
@@ -20,7 +20,7 @@ jobs:
pull-requests: read
steps:
- name: Checkout PR head
- uses: actions/checkout@v4
+ uses: actions/checkout@v7
with:
fetch-depth: 0
ref: ${{ github.event.pull_request.head.sha }}
diff --git a/.github/workflows/windows-free-tests.yml b/.github/workflows/windows-free-tests.yml
index 3ac871e5d..67e5cd0b8 100644
--- a/.github/workflows/windows-free-tests.yml
+++ b/.github/workflows/windows-free-tests.yml
@@ -39,16 +39,16 @@ jobs:
timeout-minutes: 15
steps:
- - uses: actions/checkout@v4
+ - uses: actions/checkout@v7
- - uses: oven-sh/setup-bun@v1
+ - uses: oven-sh/setup-bun@v2
with:
bun-version: 1.3.13
# bun install was 35s of a 55s job, all network. Cache keyed on the
# lockfile; bun's install cache lives under ~/.bun/install/cache on
# every platform.
- - uses: actions/cache@v4
+ - uses: actions/cache@v6
with:
path: ~/.bun/install/cache
key: windows-bun-${{ hashFiles('bun.lock') }}
@@ -119,9 +119,12 @@ jobs:
# Same diagnosability contract as free-tests.yml: a red lane must
# carry the WHY (the runner's quiet console names files, not causes).
+ # (#2561 was written against the old hand-listed subset; its two new
+ # test files are pure-TS and flow into the --windows-only curation
+ # automatically, so no per-file entry is needed here.)
- name: Upload shard logs on failure
if: failure()
- uses: actions/upload-artifact@v4
+ uses: actions/upload-artifact@v7
with:
name: windows-free-test-shard-logs
path: ${{ runner.temp }}/gstack-free-test-*.log
diff --git a/.github/workflows/windows-setup-e2e.yml b/.github/workflows/windows-setup-e2e.yml
index 90bb6f0b2..7d2014a2f 100644
--- a/.github/workflows/windows-setup-e2e.yml
+++ b/.github/workflows/windows-setup-e2e.yml
@@ -35,15 +35,15 @@ jobs:
timeout-minutes: 15
steps:
- - uses: actions/checkout@v4
+ - uses: actions/checkout@v7
- - uses: oven-sh/setup-bun@v1
+ - uses: oven-sh/setup-bun@v2
with:
bun-version: 1.3.13
# Same lockfile-keyed install cache as windows-free-tests.yml (install
# was 45s of a 64s job, all network).
- - uses: actions/cache@v4
+ - uses: actions/cache@v6
with:
path: ~/.bun/install/cache
key: windows-bun-${{ hashFiles('bun.lock') }}
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md
index 1856f0ad7..cad068f5f 100644
--- a/ARCHITECTURE.md
+++ b/ARCHITECTURE.md
@@ -69,11 +69,11 @@ The server writes `.gstack/browse.json` (atomic write via tmp + rename, mode 0o6
{ "pid": 12345, "port": 34567, "token": "uuid-v4", "startedAt": "...", "binaryVersion": "abc123" }
```
-The CLI reads this file to find the server. If the file is missing or the server fails an HTTP health check, the CLI spawns a new server. On Windows, PID-based process detection is unreliable in Bun binaries, so the health check (GET /health) is the primary liveness signal on all platforms.
+The CLI reads this file to find the server. If the file is missing or the daemon process is dead, the CLI spawns a new server. A process that is alive but not answering `/health` is busy, not dead: the CLI probes for a bounded ~8s, then reports busy with a nonzero exit — only an explicit `--force-restart` kills a live daemon. Process liveness uses signal-0 (`isProcessAlive`, EPERM counts as alive) on every platform, with the health check (GET /health) as the responsiveness signal. Daemon stdout/stderr persists to `<project>/.gstack/browse-daemon.log`.
### Port selection
-Random port between 10000-60000 (retry up to 5 on collision). This means 10 Conductor workspaces can each run their own browse daemon with zero configuration and zero port conflicts. The old approach (scanning 9400-9409) broke constantly in multi-workspace setups.
+Random port between 10000-49151 (retry up to 5 on collision), allocated through the shared `browse/src/port-allocator.ts` so every long-lived gstack listener draws from the same range. The range ends at 49151 on purpose: 49152-65535 is the macOS ephemeral pool, and allocating inside it meant the OS could hand the same port to another process moments later. This means 10 Conductor workspaces can each run their own browse daemon with zero configuration and zero port conflicts. The old approach (scanning 9400-9409) broke constantly in multi-workspace setups.
### Version auto-restart
@@ -176,19 +176,19 @@ The Chrome sidebar agent has tools (Bash, Read, Glob, Grep, WebFetch) and reads
1. **L1-L3 content security (`browse/src/content-security.ts`).** Runs on every page-content command and every tool output: datamarking, hidden-element strip, ARIA regex, URL blocklist, and a trust-boundary envelope wrapper. Applied at both the server and the agent.
-2. **L4 ML classifier — TestSavantAI (`browse/src/security-classifier.ts`).** A 22MB BERT-small ONNX model (int8 quantized) bundled with the agent. Runs locally, no network. Scans every user message and every Read/Glob/Grep/WebFetch tool output before Claude sees it. Opt-in 721MB DeBERTa-v3 ensemble via `GSTACK_SECURITY_ENSEMBLE=deberta`.
+2. **L4 ML classifier — TestSavantAI (`browse/src/security-classifier.ts`).** A 22MB BERT-small ONNX model (int8 quantized) running in the security sidecar subprocess. Runs locally, no network. Scans page-derived content on the inject-scan path before the agent sees it.
-3. **L4b transcript classifier.** A Claude Haiku pass that looks at the full conversation shape (user message, tool calls, tool output), not just text. Gated by `LOG_ONLY: 0.40` so most clean traffic skips the paid call.
+3. **L4b transcript classifier (removed).** A Claude Haiku conversation-shape pass existed until the chat-path agent that invoked it was ripped; it was deleted as dead code (zero production callers), along with the opt-in DeBERTa ensemble. Do not re-document either as live.
-4. **L5 canary token (`browse/src/security.ts`).** A random token injected into the system prompt at session start. Rolling-buffer detection across `text_delta` and `input_json_delta` streams catches the token if it shows up anywhere in Claude's output, tool arguments, URLs, or file writes. Deterministic BLOCK — if the token leaks, the attacker convinced Claude to reveal the system prompt, and the session ends.
+4. **L5 canary token (`browse/src/security.ts`).** Generate/inject/detect utilities for a random system-prompt token whose leak means the attacker convinced the model to reveal the system prompt. Canary leak BLOCKs deterministically. The utilities are pure and tested; the chat prompt-builder that injected the canary was ripped, so no production path injects it today.
5. **L6 ensemble combiner (`combineVerdict`).** BLOCK requires agreement from two ML classifiers at >= `WARN` (0.75), not a single confident hit. This is the Stack Overflow instruction-writing false-positive mitigation. On tool-output scans, single-layer high confidence BLOCKs directly — the content wasn't user-authored, so the FP concern doesn't apply.
-**Critical constraint:** `security-classifier.ts` runs only in the sidebar-agent process, never in the compiled browse binary. `@huggingface/transformers` v4 requires `onnxruntime-node`, which fails `dlopen` from Bun compile's temp extract directory. Only the pure-string pieces (canary inject/check, verdict combiner, attack log, status) are in `security.ts`, which is safe to import from `server.ts`.
+**Critical constraint:** `security-classifier.ts` runs only in the security sidecar subprocess (`security-sidecar-entry.ts`), never in the compiled browse binary. `@huggingface/transformers` v4 requires `onnxruntime-node`, which fails `dlopen` from Bun compile's temp extract directory. Only the pure-string pieces (canary inject/check, verdict combiner) are in `security.ts`, which is safe to import from `server.ts`. (The attack log lives in `tunnel-denial-log.ts`; the session-state/status surface was removed in #2557.)
-**Env knobs:** `GSTACK_SECURITY_OFF=1` is a real kill switch (skips ML scan, canary still injects). Model cache at `~/.gstack/models/testsavant-small/` (112MB, first run) and `~/.gstack/models/deberta-v3-injection/` (721MB, opt-in only). Attack log at `~/.gstack/security/attempts.jsonl` (salted sha256 + domain, rotates at 10MB, 5 generations). Per-device salt at `~/.gstack/security/device-salt` (0600), cached in-process to survive FS-unwritable environments.
+**Env knobs:** `GSTACK_SECURITY_OFF=1` is a real kill switch (classifier stays off even if warmed; the L1-L3 filters keep running). Model cache at `~/.gstack/models/testsavant-small/` (112MB, first run). Attack log at `~/.gstack/security/attempts.jsonl` (salted sha256 + domain, rotates at 10MB, 5 generations). Per-device salt at `~/.gstack/security/device-salt` (0600), cached in-process to survive FS-unwritable environments.
-**Visibility.** The sidebar header shows a shield icon (green/amber/red) polled via `/sidebar-chat`. A centered banner appears on canary leak or BLOCK verdict with the exact layer scores. `bin/gstack-security-dashboard` aggregates local attempts; `supabase/functions/community-pulse` aggregates opt-in community telemetry across users.
+**Visibility.** A centered banner appears on canary leak or BLOCK verdict with the exact layer scores. `bin/gstack-security-dashboard` aggregates local attempts; `supabase/functions/community-pulse` aggregates opt-in community telemetry across users. (The sidebar header's SEC shield icon and the `/health` `security` field were removed in #2557: their only data source — `~/.gstack/security/session-state.json` — lost its only writer when the chat-path agent was ripped, so the shield reported stale or empty state. The live defenses report through their own call sites.)
## The ref system
diff --git a/BROWSER.md b/BROWSER.md
index 1ab7a1e60..dfd4774bf 100644
--- a/BROWSER.md
+++ b/BROWSER.md
@@ -168,8 +168,18 @@ for the full design + decision trail.
1. **First call.** CLI checks `<project>/.gstack/browse.json` for a running
server. None found — it spawns `bun run browse/src/server.ts` in the
background. Daemon launches headless Chromium via Playwright, picks a
- random port (10000–60000), generates a bearer token, writes the state
- file (chmod 600), starts accepting requests. ~3 seconds.
+ random port (10000–49151, deliberately below the macOS ephemeral pool
+ 49152-65535 so the OS never hands a colliding port to another process),
+ generates a bearer token, writes the state file (chmod 600), starts
+ accepting requests. ~3 seconds. One launch-time exception to fail-fast:
+ when a macOS XProtect definition update SIGKILLs the pinned Chromium at
+ spawn, the daemon classifies the kill signature, clears the quarantine
+ flag on the Playwright cache, reinstalls the pinned revision from the
+ gstack install root (bounded ~120s), and retries once — at most once per
+ daemon process. If the heal can't complete, the original launch error
+ plus manual `bunx playwright install chromium` guidance lands on daemon
+ stderr (see `browse-daemon.log`). Wired at all three launch sites in
+ `browser-manager.ts` via `browse/src/xprotect-heal.ts`.
2. **Subsequent calls.** CLI reads the state file, sends an HTTP POST with
the bearer token, prints the response. ~100-200ms round trip.
3. **Idle shutdown.** After 30 minutes of no commands, daemon shuts down and
@@ -177,6 +187,13 @@ for the full design + decision trail.
4. **Crash recovery.** If Chromium crashes, the daemon exits immediately —
no self-healing, don't hide failure. CLI detects the dead daemon on the
next call and starts a fresh one.
+5. **Busy vs dead.** A daemon that stops answering HTTP while its process is
+ alive is busy, not dead. The CLI gives `/health` a bounded ~8s to recover,
+ then reports busy with a nonzero exit — it never kills an alive pid.
+ Only an explicit `--force-restart` replaces a live-but-unresponsive
+ daemon (tabs, cookies, and logins are lost). `browse stop` against a
+ daemon that already died is success: the desired end state holds, so it
+ cleans the stale state file instead of booting a daemon just to stop it.
### Multi-workspace isolation
@@ -186,8 +203,8 @@ collisions. State at `<project>/.gstack/browse.json`.
| Workspace | State file | Port |
|-----------|-----------|------|
-| `/code/project-a` | `/code/project-a/.gstack/browse.json` | random (10000–60000) |
-| `/code/project-b` | `/code/project-b/.gstack/browse.json` | random (10000–60000) |
+| `/code/project-a` | `/code/project-a/.gstack/browse.json` | random (10000–49151) |
+| `/code/project-b` | `/code/project-b/.gstack/browse.json` | random (10000–49151) |
---
@@ -311,7 +328,7 @@ from `snapshot`, or `@c` refs from `snapshot -C`. Full table:
| Command | Description |
|---------|-------------|
| `status` | Daemon health + mode (headless / headed / cdp) |
-| `stop` | Shut down daemon |
+| `stop` | Shut down daemon (succeeds even if the daemon already died — never boots one just to stop it) |
| `restart` | Restart daemon |
| `connect` | Launch headed GStack Browser with Side Panel extension |
| `disconnect` | Close headed Chrome, return to headless |
@@ -319,6 +336,12 @@ from `snapshot`, or `@c` refs from `snapshot -C`. Full table:
| `state save\|load <name>` | Save or load browser state (cookies + URLs) |
| `memory [--json]` | Snapshot Bun heap + per-tab JS heap + Chromium process tree + bounded buffer sizes. Use `--json` for programmatic consumers; text mode renders sorted top-10 tabs with "and N more" tail. |
+The daemon's own stdout/stderr persists to `<project>/.gstack/browse-daemon.log`
+(append mode, rotated to `.log.1` at the size cap, single generation), with
+tokens and unsanitized page content kept out — check it when a daemon dies
+without an obvious cause. A live-but-unresponsive daemon is never auto-killed;
+pass `--force-restart` to replace it explicitly (see "Daemon lifecycle" above).
+
### Handoff
| Command | Description |
@@ -880,10 +903,11 @@ sidebar chat pipeline that hosted them. **Canary leak always BLOCKs
- Attack log: `~/.gstack/security/attempts.jsonl` (salted SHA-256 + domain
only, rotates at 10MB, 5 generations).
- Per-device salt: `~/.gstack/security/device-salt` (0600).
-- Session state: `~/.gstack/security/session-state.json` (cross-process,
- atomic).
-A shield icon in the sidebar header shows the live status. See
+There is no security status indicator in the sidebar and no `security`
+field on `/health` (#2557): the session-state file that fed them lost its
+only writer when the chat-path agent was removed, so they reported stale or
+empty data. The live defenses report through their own call sites. See
ARCHITECTURE.md § "Prompt injection defense" for the full threat model.
---
@@ -1209,8 +1233,8 @@ collisions.
| Workspace | State file | Port |
|-----------|-----------|------|
-| `/code/project-a` | `/code/project-a/.gstack/browse.json` | random (10000–60000) |
-| `/code/project-b` | `/code/project-b/.gstack/browse.json` | random (10000–60000) |
+| `/code/project-a` | `/code/project-a/.gstack/browse.json` | random (10000–49151) |
+| `/code/project-b` | `/code/project-b/.gstack/browse.json` | random (10000–49151) |
Browser-skills three-tier lookup walks project → global → bundled, so a
project-tier skill at `/code/project-a/.gstack/browser-skills/foo/` shadows
@@ -1222,7 +1246,7 @@ the global `~/.gstack/browser-skills/foo/` only inside project-a.
| Variable | Default | Description |
|----------|---------|-------------|
-| `BROWSE_PORT` | 0 (random 10000–60000) | Fixed port for the HTTP server (debug override) |
+| `BROWSE_PORT` | 0 (random 10000–49151) | Fixed port for the HTTP server (debug override) |
| `BROWSE_IDLE_TIMEOUT` | 1800000 (30 min) | Idle shutdown timeout in ms |
| `BROWSE_STATE_FILE` | `.gstack/browse.json` | Path to state file |
| `BROWSE_SERVER_SCRIPT` | auto-detected | Path to `server.ts` |
@@ -1249,6 +1273,8 @@ browse/
│ ├── cli.ts # Thin client — reads state, sends HTTP, prints
│ ├── server.ts # Bun HTTP daemon — routes commands, dual-listener
│ ├── browser-manager.ts # Chromium lifecycle, tabs, ref map, crash detection
+│ ├── port-allocator.ts # Fixed 10000-49151 scan range for every long-lived listener (never port:0)
+│ ├── xprotect-heal.ts # macOS XProtect launch-kill classify + quarantine-clear + bounded reinstall
│ ├── socks-bridge.ts # Local 127.0.0.1 SOCKS5 bridge that handles auth handshakes Chromium can't speak
│ ├── proxy-config.ts # --proxy URL parsing + cred resolution (URL vs env, fail-fast on both)
│ ├── proxy-redact.ts # Cred-redaction helper for any proxy URL surfaced to logs/errors
@@ -1281,6 +1307,8 @@ browse/
│ ├── content-security.ts # L1-L3: datamarking, hidden strip, ARIA, URL blocklist, envelopes
│ ├── security.ts # L5 canary + L6 verdict combiner + thresholds
│ ├── security-classifier.ts # L4 ML classifier (TestSavantAI, runs in the security sidecar)
+│ ├── security-sidecar-entry.ts # Sidecar subprocess entrypoint hosting the ONNX classifier
+│ ├── security-sidecar-client.ts # server.ts-side client that drives the sidecar
│ ├── terminal-agent.ts # Side Panel Claude PTY manager (auth + lifecycle)
│ ├── sidebar-utils.ts # Sidebar URL sanitization + helpers
│ ├── cookie-import-browser.ts # Decrypt + import cookies from real Chromium browsers
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3e0bc893e..0787a6dfe 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,197 @@
# Changelog
+## [1.67.0.0] - 2026-08-16
+
+**The tracker wave: browse survives macOS, installs are complete,**
+**memory sync never drops a record. 30 contributors landed.**
+
+This release mines the full issue tracker and community PR queue. Browse now
+classifies a macOS XProtect kill at Chromium launch and heals itself. It
+clears the quarantine flag, reinstalls the pinned browser revision from the
+right install root, and retries, all bounded and logged. Fresh installs link
+every runtime asset a skill references, so /review and friends work on a
+clean machine the first time. Brain-sync's queue is drained with a classified
+disposition. Privacy-held records are retained and labeled, a failed push
+keeps its commit and re-delivers it on the next run, and the retry only ever
+publishes commits it authored itself. Twenty-five community PRs landed with
+credit, and roughly thirty-five issues close on merge.
+
+### The numbers that matter
+
+From the wave's gate eval run (`bun run eval:bg:gate`, log in
+`~/.gstack-dev/eval-runs/`) and the free suite (`bun run test`) at HEAD.
+
+| Metric | Before | After | Δ |
+|---|---|---|---|
+| Browse launch on macOS 26 (XProtect kill) | manual reinstall | classified + self-healed | automatic |
+| Skill runtime assets on a fresh install | SKILL.md + sections only | every referenced asset | /review works day one |
+| Brain-sync queue at a push failure | truncated | retained + re-delivered | no data loss |
+| Detector push with an interleaved user commit | published it | refuses | author boundary holds |
+| Gate evals | 41/43 | 43/43 | both reds root-caused |
+| Free suite | — | ~7,000 tests, ~90-100s | green at HEAD |
+
+The brain-sync row is the one to internalize: the queue is only ever rewritten
+by subtracting the exact records that were staged, against a live re-read, so
+a record enqueued mid-drain survives to the next boundary.
+
+### What this means for gstack users
+
+Upgrade and the three most-reported failure classes disappear: browse comes
+back on macOS without touching a terminal, a teammate's first `./setup`
+produces working skills, and your cross-machine memory stops silently thinning
+under flaky networks. If you filed one of the ~35 issues this closes, your
+repro is now a regression test with your name on the commit.
+
+### Itemized changes
+
+#### Fixed — the three P0s
+
+- **Browse dead on macOS (#2554).** Playwright pinned to 1.62.1 (split from
+ dependabot #2582), plus an XProtect kill-signature classifier with positive
+ AND negative fixtures, a one-shot quarantine-clear + bounded (~120s,
+ process-group-killed) reinstall from the gstack install root that pins the
+ matching Chromium revision, structured heal logging, and an upgrade-time
+ quarantine-clear + reinstall in `setup` for already-poisoned caches. The
+ heal resolves the install
+ root via `os.homedir()` and keeps its manual-remediation guidance even when
+ the post-heal retry fails.
+- **Fresh installs missing runtime assets (#2317, #2454).** `setup` links
+ every runtime asset with an explicit exclusion list (node_modules, dist,
+ *.tmpl, test, hidden), pinned by a two-class referenced-paths test:
+ alias-relative references must exist under the installed alias, repo-anchored
+ ones in the tree modulo a reasoned dist/ allowlist.
+- **Brain-sync data loss (#2549).** Queue records are classified at drain
+ time: skip-filtered and nonexistent drop WITH counts (full paths in a 0600
+ sidecar), privacy-held records are retained and labeled instead of being
+ wiped as "no allowlisted changes", unparseable lines are preserved, and the
+ rewrite subtracts the staged set from a LIVE re-read so concurrent enqueues
+ survive. A failed push keeps its commit; a run-start detector re-delivers it
+ — receipted, locked, throttled to one attempt per 10 minutes, bounded by
+ git's low-speed limits (portable to stock macOS), and gated to fire only
+ when EVERY unpushed commit is its own, so an interleaved manual commit in
+ ~/.gstack is never auto-published. The sync lock releases on every exit
+ path, including interrupts mid-push.
+
+#### Fixed — browse & daemon lifecycle
+
+- A healthy daemon is never killed by `browse start` (the #2219 iron rule):
+ a total-budget health probe answers in ~8s, busy daemons get "retry or
+ --force-restart" plus a nonzero exit, and only an explicit `--force-restart`
+ ever kills an alive pid — pinned by a regression test. `browse stop` on a
+ dead daemon short-circuits to success (#2254); `/gstack-upgrade` defers to a
+ busy daemon and prints the escape hatch (#2551).
+- Chromium no longer dies with the terminal: signal handling moved off
+ Playwright's defaults at all three launch sites with a SIGHUP handler
+ routing through the real shutdown path, and a tripwire pinning the count.
+- The terminal-agent allocates from the same fixed port range as the daemon
+ (#2314) — and that range now ends at 49151, actually below the macOS
+ ephemeral pool it exists to avoid; boot retries a raced bind instead of
+ dying. Windows terminal-agent leaks fixed via `process.kill(pid, 0)`
+ liveness (#1952) and the error-handling helpers. Contributed by @SYKhayyat
+ (#2414).
+- Daemon crash logs persist without tokens or unsanitized page content
+ (needle-tested). Contributed by @phuttimatebenchanakatkul (#2461).
+- The dead security-shield surface was removed end to end (−272 net lines) while
+ the live L4 sidecar path keeps its status endpoint — docs updated in the
+ same commit. Contributed by @frederik-kaster-noygear (#2557, with the
+ pipe-capture core from #2559). CDP `Emulation.setEmulatedMedia` joins the
+ allowlist — contributed by @meshailabs (#2419). Windows gbrain probe
+ timeout — contributed by @vaston-viji (#2450). `browse/dist` mkdir —
+ contributed by @guyua9 (#2542).
+- First `patchedDependencies` entry: playwright-core's two Windows spawn
+ sites carry `windowsHide` (#2160, #1989), statically pinned and
+ independently revertable.
+
+#### Fixed — install & setup correctness
+
+- Root-alias skills install as rewritten copies, never symlinks whose edits
+ would corrupt generated sources (#2511, #2201). Windows re-runs refresh
+ real-directory installs (#2444), and uninstall deletes only directories
+ that pass BOTH the inventory match and the generated-banner provenance gate,
+ listing (never deleting) anything else (#2563).
+- `--host cursor` gets the full install slice — contributed by @szsunyuan
+ (#2547). Settings-hook dedup includes the command (#2382) — contributed by
+ @gregario (#2431). `:user` renders route through `--out-dir` (#2569) with a
+ migration that cleans legacy in-place render dirt. setup-gbrain invocation
+ paths fixed (#2250) — contributed by @SomSamantray (#2409). Office-hours
+ installs into codex/factory/opencode runtime roots (#2449).
+- The redact pre-push hook stays opt-in but its fail-open gaps are closed,
+ with a one-time consent prompt (#1946). Skills-timeline Stop hook ships
+ fail-open (always exit 0, 2s budget) with setup registration (#2553).
+- iOS QA: DebugBridgeTouch compiles out of Release builds — contributed by
+ @Bastea (#2585); front-most bridge ordering — contributed by @IDSTUK
+ (#2397); compat preflight docs — contributed by @itstimwhite (#2581).
+
+#### Fixed — memory & gbrain
+
+- Windows slug resolution and the decisions.jsonl allowlist (#2396) —
+ contributed by @source-utsho (#2561). Brain-sync arithmetic-injection
+ guard — contributed by @sneakygriff (#2588). Windows bash routing for
+ brain-sync/gbrain — contributed by @ShahriarLak (#2510), extended to every
+ gbrain-sources spawn (#2471). `--full` walks the full tree — contributed by
+ @ShahriarLak (#2406). Honest "missing" from brain-cache — contributed by
+ @sneakygriff (#2587). Memory-ingest parses both codex rollout shapes and
+ stages outside GSTACK_HOME (#2105, #2104).
+- gbrain detection: engine-locked is a healthy status (#2456), bearer-token
+ thin clients are recognized (#2520), GBRAIN_HOME gets its .gbrain segment
+ (#2521), project-scoped MCP registrations are honored (#2499). Source pins
+ respected — contributed by @exGeni (#2417); `--dry-run` works offline
+ (#2536) — contributed by @CarringtonCreative (#2540); bun-on-npm PATH
+ guidance (#2487); dream-stage classifier anchored (#2341).
+
+#### Fixed — version tooling, diff-scope, redaction
+
+- VERSION stays the 4-digit source of truth; package.json carries the
+ npm-valid 3-digit translation, lockfiles sync only when they already exist,
+ and drift is judged on translated forms. Built on re-derived work
+ contributed by @YiftahR (#2501), @ortonom (#2568), and
+ @CarringtonCreative (#2531, #2545). Pinned repos compare base and current
+ against the SAME file (#2462). JSON version-paths get honest per-file
+ recovery messages. The path pins (`.gstack/version-path`,
+ `.gstack/package-json-path`) cannot escape the repository — absolute paths,
+ `..` traversal, and symlink escapes are all refused, and a lockfile
+ symlinked outside the repo is skipped with a warning.
+- Diff-scope covers api/*, migrations/*, and db/data, with a no-match exit
+ code and uncommitted-work handling (#2526, #2455, #2299). Redact scans the
+ merge-base range and knows parcel IDs are not phone numbers — contributed
+ by @Two-Six-Alpha-1115 (#2592, #2591); rebased force-pushes are scanned
+ correctly, proven by test (#2573).
+- The codex model probe caches its verdicts both ways: a working model for an
+ hour, a deterministic model-400 for 15 minutes (editing config.toml
+ re-probes immediately) — so the affected account stops paying a 30s round
+ trip per review section (#2477). Its timeout wrapper now enforces the
+ deadline with a bash-native watchdog on stock macOS, where no timeout
+ binary exists.
+
+#### Fixed — templates & everything else
+
+- Skills running under Codex skip the nested codex specialist with a printed
+ notice (#2519). Codex web-search flag unified behind one resolver constant
+ across 19 sites (#2525). Slugs are sanitized in every path position
+ (#2550) — with groundwork contributed by @harjothkhara (#1851). AGENTS.md
+ routing probe — contributed by @gamerey43 (#2500); empty-find fallthrough
+ killed — contributed by @tranthanhnhatkhoa (#2483); cygpath MSYS builds —
+ contributed by @chiragborse1 (#2452). /ship's review army loops until clean
+ (#2391). Question-registry path is absolute (#2489). Retro glob (#2552),
+ capability-check temp file (#2503), repo-mode stat order (#2195), hover doc
+ note (#2445), make-pdf boolean flags — including `--strict` and
+ `--confidential` — no longer swallow the input file, with a guard test that
+ derives the flag set from the source (#2514).
+
+#### For contributors
+
+- Test/generator infra hardened first: host-config golden isolation (#2532),
+ hermetic-wiring tripwire and YAML ellipsis quoting — contributed by
+ @sneakygriff (#2586, #2589); prepush PATH separator — contributed by
+ @luckywenapere (#2544); gen-skill-docs throws on duplicate preamble tokens.
+- Dependency hygiene: puppeteer-core removed outright (zero consumers),
+ adm-zip CVE closed via lock override — contributed by @anupamme (#2485);
+ transformers/marked/socks bumped with the ONNX sidecar smoke green;
+ .gitattributes LF pin — contributed by @mlaniak (#2527); GitHub Actions
+ bumps — contributed by @dependabot (#2594).
+- The wave's own adversarial reviews (Codex + Claude, 28 findings) landed as
+ fixes in-branch; verified residuals are filed in TODOS.md with rationale.
+
## [1.66.1.0] - 2026-08-16
**Every claim gstack makes now binds to the content it was made on.**
diff --git a/CLAUDE.md b/CLAUDE.md
index 316f60bcc..cd76565aa 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -166,11 +166,12 @@ gstack/
│ ├── test/ # Integration tests
│ └── dist/ # Compiled binary
├── extension/ # Chrome extension (side panel + activity feed + CSS inspector)
-├── lib/ # Shared libraries (worktree.ts, egress-receipt.ts, context-bill.ts, redact-engine.ts, tracker-guard.ts, code-intelligence/)
+├── lib/ # Shared libraries (worktree.ts, egress-receipt.ts, context-bill.ts, redact-engine.ts, tracker-guard.ts, version-source.ts, code-intelligence/)
+├── patches/ # bun `patchedDependencies` patches (playwright-core windowsHide)
├── docs/designs/ # Design documents
├── setup-deploy/ # /setup-deploy skill (one-time deploy config)
├── .github/ # CI workflows + Docker image
-│ ├── workflows/ # evals.yml (E2E on Ubicloud), quality-gate.yml (secret scan), dependency-review.yml, osv-scanner.yml, skill-docs.yml, actionlint.yml, and 7 more (windows, periodic evals, release gates, ci-image)
+│ ├── workflows/ # evals.yml (E2E on Ubicloud), quality-gate.yml (secret scan), dependency-review.yml, osv-scanner.yml, skill-docs.yml, actionlint.yml, and 8 more (windows, periodic evals, release gates, ci-image)
│ └── docker/ # Dockerfile.ci (pre-baked toolchain + Playwright/Chromium)
├── contrib/ # Contributor-only tools (never installed for users)
│ └── add-host/ # /gstack-contrib-add-host skill
@@ -429,9 +430,16 @@ leak always BLOCKs (deterministic).
- Classifier model cache: `~/.gstack/models/testsavant-small/` (112MB, first run only)
- Attack log: `~/.gstack/security/attempts.jsonl` — written by
`tunnel-denial-log.ts` (tunnel-surface rejections; rotates at 10MB, 5 generations)
-- Session state: `~/.gstack/security/session-state.json` (cross-process, atomic;
- NOTE: classifierStatus currently has no live writer — shield status derives
- from what's on disk)
+
+History note (#2557): the cross-process session state
+(`~/.gstack/security/session-state.json`), `getStatus()`, the `/health`
+`security` field, and the sidepanel SEC shield were all removed — the state
+file lost its only writer when sidebar-agent.ts was ripped, so the shield
+reported a permanent 'inactive' or a stale false-green 'protected' from
+leftover disk state. The live defenses (L1-L3 filters, L4 sidecar on the
+inject-scan path) report through their own call sites, never through
+/health. `browse/test/server-security-surface.test.ts` pins both the
+removal and the live L4 wiring. Do not re-document these as live.
## Dev symlink awareness
@@ -448,8 +456,11 @@ symlink or a real copy. If it's a symlink to your working directory, be aware th
global install at `~/.claude/skills/gstack/` is used instead
**Prefix setting:** Setup creates real directories (not symlinks) at the top level
-with a SKILL.md symlink inside (e.g., `qa/SKILL.md -> gstack/qa/SKILL.md`). This
-ensures Claude discovers them as top-level skills, not nested under `gstack/`.
+with a SKILL.md symlink inside (e.g., `qa/SKILL.md -> gstack/qa/SKILL.md`), plus
+links to each skill's runtime assets (sections/, templates, checklists — everything
+except SKILL.md, tests, build output, and `.tmpl` sources). Alias skills
+(`_gstack-command`, `connect-chrome`) install as rewritten copies, never symlinks.
+This ensures Claude discovers them as top-level skills, not nested under `gstack/`.
Names are either short (`qa`) or namespaced (`gstack-qa`), controlled by
`skill_prefix` in `~/.gstack/config.yaml`. Pass `--no-prefix` or `--prefix` to
skip the interactive prompt.
@@ -653,6 +664,17 @@ claims v1.7.0.0 as a MINOR and branch B is also a MINOR, B lands at v1.8.0.0
`bin/gstack-next-version` advances within the chosen bump level rather than
repicking the level when collisions happen.
+**package.json carries the npm-valid translation, not VERSION verbatim.**
+VERSION stays the 4-digit source of truth (e.g. `1.67.0.0`); package.json and
+any subdirectory manifests with a `version` field get the 3-digit npm-valid
+translation (`1.67.0`), and lockfile `version` fields sync only when the
+lockfile already exists. `bin/gstack-version-bump` (via `lib/version-source.ts`)
+owns the translation and judges drift on translated forms — do NOT "fix" the
+apparent mismatch by hand, and do not write a 4-digit version into
+package.json (npm rejects it). Rationale and translation rules live in the
+`lib/version-source.ts` header; `test/gstack-version-bump.test.ts` pins the
+contract.
+
**Scale-aware bumps — use common sense.** When the diff is big, bump MINOR (or
MAJOR), not PATCH. PATCH is for bug fixes and small additions; MINOR is for
substantial new capability or substantial reduction; MAJOR is for breaking
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index e7da57eea..d69b538fc 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -42,8 +42,10 @@ No setup needed. Learnings are logged automatically. View them with `/learn`.
ln -sfn /path/to/your/gstack-fork .claude/skills/gstack
cd .claude/skills/gstack && bun install && bun run build && ./setup
```
- Setup creates per-skill directories with SKILL.md symlinks inside (`qa/SKILL.md -> gstack/qa/SKILL.md`)
- and asks your prefix preference. Pass `--no-prefix` to skip the prompt and use short names.
+ Setup creates per-skill directories with SKILL.md symlinks inside (`qa/SKILL.md -> gstack/qa/SKILL.md`),
+ links each skill's runtime assets alongside (sections/, templates, checklists — everything except
+ SKILL.md, tests, build output, and `.tmpl` sources), and asks your prefix preference.
+ Pass `--no-prefix` to skip the prompt and use short names.
5. **Fix the issue** — your changes are live immediately in this project
6. **Test by actually using gstack** — do the thing that annoyed you, verify it's fixed
7. **Open a PR from your fork**
@@ -82,7 +84,10 @@ gstack/ <- your working tree
```
Setup creates real directories (not symlinks) at the top level with a SKILL.md
-symlink inside. This ensures Claude discovers them as top-level skills, not nested
+symlink inside, plus links to each skill's runtime assets (sections/, templates,
+checklists). Alias skills (`_gstack-command`, `connect-chrome`) install as
+rewritten copies, never symlinks — editing a symlinked alias would corrupt the
+generated source. This ensures Claude discovers them as top-level skills, not nested
under `gstack/`. Names depend on your prefix setting (`~/.gstack/config.yaml`).
Short names (`/review`, `/ship`) are the default. Run `./setup --prefix` if you
prefer namespaced names (`/gstack-review`, `/gstack-ship`).
@@ -118,9 +123,11 @@ passes `GSTACK_SKIP_GBRAIN_REGEN=1` inline to the nested `./setup` (so it never
dirties tracked source) and runs `gen:skill-docs:user --out-dir .claude/gstack-rendered`,
which rewrites only the section-base paths to point at the render. `bin/dev-teardown`
removes the render. To make the blocks live across your *other* projects' Claude
-sessions, run `gstack-config gbrain-refresh`, which renders them into the global
-install (`~/.claude/skills/gstack`), guarded so it never touches a symlinked or
-non-gstack directory.
+sessions, run `gstack-config gbrain-refresh`, which renders them to a user render
+dir (`${GSTACK_USER_RENDER_DIR:-~/.gstack/render/claude}`, swapped in only on a
+successful render) and repoints the installed skills at it via `gstack-relink` —
+the global install checkout stays git-clean, and the refresh is guarded so it
+never touches a symlinked or non-gstack directory.
## Testing & evals
diff --git a/README.md b/README.md
index 26ad1bfbb..e2cdf193f 100644
--- a/README.md
+++ b/README.md
@@ -254,6 +254,13 @@ Beyond the slash-command skills, gstack ships standalone CLIs for workflows that
| `gstack-ios-qa-mint` | **iOS allowlist manager** — owner-grant CLI for the tailnet allowlist. `grant`/`revoke`/`list` against `~/.gstack/ios-qa-allowlist.json` (mode 0600). Remote agents never auto-allowlist; this is the explicit-intent path. |
| `gstack-ios-qa-regen` | **iOS bridge regenerator** — deterministically installs the canonical DebugBridge package, generates typed state accessors, and records the installed gstack version. Safe to rerun after source changes or upgrades. |
+`./setup` also registers one default-on Stop hook in `~/.claude/settings.json`:
+`gstack-timeline-stop` (closes dangling session-timeline entries when a session
+is interrupted; fail-open — 2s internal budget, always exits 0, can never block
+a session). Skip it with `./setup --no-team`, remove it with
+`gstack-settings-hook remove-source --source gstack-timeline-stop`;
+`gstack-uninstall` removes it too.
+
### Continuous checkpoint mode (opt-in, local by default)
Set `gstack-config set checkpoint_mode continuous` and skills auto-commit your work as you go with a `WIP:` prefix plus a structured `[gstack-context]` body (decisions, remaining work, failed approaches). Survives crashes and context switches. `/context-restore` reads those commits to reconstruct session state. `/ship` filter-squashes WIP commits before the PR (preserving non-WIP commits) so bisect stays clean. Push is opt-in via `checkpoint_push=true` — default is local-only so you don't trigger CI on every WIP commit.
@@ -297,7 +304,7 @@ gstack works well with one sprint. It gets interesting with ten running at once.
**Personal automation.** The sidebar agent isn't just for dev workflows. Example: "Browse my kid's school parent portal and add all the other parents' names, phone numbers, and photos to my Google Contacts." Two ways to get authenticated: (1) log in once in the headed browser, your session persists, or (2) click the "cookies" button in the sidebar footer to import cookies from your real Chrome. Once authenticated, Claude navigates the directory, extracts the data, and creates the contacts.
-**Prompt injection defense.** Hostile web pages try to hijack your sidebar agent. gstack ships a layered defense: a 22MB ML classifier bundled with the browser scans every page and tool output locally, a Claude Haiku transcript check votes on the full conversation shape, a random canary token in the system prompt catches session exfil attempts across text, tool args, URLs, and file writes, and a verdict combiner requires two classifiers to agree before blocking (prevents single-model false positives on Stack Overflow-style instruction pages). A shield icon in the sidebar header shows status (green/amber/red). Opt in to a 721MB DeBERTa-v3 ensemble via `GSTACK_SECURITY_ENSEMBLE=deberta` for 2-of-3 agreement. Emergency kill switch: `GSTACK_SECURITY_OFF=1`. See [ARCHITECTURE.md](ARCHITECTURE.md#prompt-injection-defense-sidebar-agent) for the full stack.
+**Prompt injection defense.** Hostile web pages try to hijack your sidebar agent. gstack ships a layered defense: content filters (datamarking, hidden-element stripping, ARIA scrubbing, URL blocklist) on every page read, plus a 22MB ML classifier running locally in a sidecar subprocess that scans page-derived content before the agent sees it, with a verdict combiner that requires classifier agreement before blocking (prevents single-model false positives on Stack Overflow-style instruction pages). Everything runs on your machine, no network calls. Emergency kill switch: `GSTACK_SECURITY_OFF=1`. See [ARCHITECTURE.md](ARCHITECTURE.md#prompt-injection-defense-sidebar-agent) for the full stack.
**Browser handoff when the AI gets stuck.** Hit a CAPTCHA, auth wall, or MFA prompt? `$B handoff` opens a visible Chrome at the exact same page with all your cookies and tabs intact. Solve the problem, tell Claude you're done, `$B resume` picks up right where it left off. The agent even suggests it automatically after 3 consecutive failures.
@@ -344,6 +351,7 @@ If you don't have the repo cloned (e.g. you installed via a Claude Code paste an
pkill -f "gstack.*browse" 2>/dev/null || true
# 2. Remove per-skill directories whose SKILL.md points into gstack/
+# (rm -rf, not rmdir — installed dirs also contain runtime-asset links)
find ~/.claude/skills -mindepth 1 -maxdepth 1 -type d ! -name gstack 2>/dev/null |
while IFS= read -r dir; do
link="$dir/SKILL.md"
@@ -351,11 +359,12 @@ while IFS= read -r dir; do
target=$(readlink "$link" 2>/dev/null) || continue
case "$target" in
gstack/*|*/gstack/*)
- rm -f "$link"
- rmdir "$dir" 2>/dev/null || true
+ rm -rf "$dir"
;;
esac
done
+# Alias skills install as copies (no symlink to detect) — remove by name
+rm -rf ~/.claude/skills/_gstack-command ~/.claude/skills/connect-chrome 2>/dev/null
# 3. Remove gstack
rm -rf ~/.claude/skills/gstack
@@ -368,6 +377,8 @@ rm -rf ~/.codex/skills/gstack* 2>/dev/null
rm -rf ~/.factory/skills/gstack* 2>/dev/null
rm -rf ~/.kiro/skills/gstack* 2>/dev/null
rm -rf ~/.openclaw/skills/gstack* 2>/dev/null
+rm -rf ~/.cursor/skills/gstack* 2>/dev/null
+rm -rf ~/.config/opencode/skills/gstack* 2>/dev/null
# 6. Remove temp files
rm -f /tmp/gstack-* 2>/dev/null
@@ -377,6 +388,10 @@ rm -rf .gstack .gstack-worktrees .claude/skills/gstack 2>/dev/null
rm -rf .agents/skills/gstack* .factory/skills/gstack* 2>/dev/null
```
+Manual removal leaves the gstack Stop hook entry behind in `~/.claude/settings.json`
+(the uninstall script removes it for you). Edit that file and delete the hook whose
+command path ends in `hosts/claude/hooks/timeline-stop-hook`.
+
### Clean up CLAUDE.md
The uninstall script does not edit CLAUDE.md. In each project where gstack was added, remove the `## gstack` and `## Skill routing` sections.
diff --git a/SKILL.md b/SKILL.md
index b7f170567..9069bbb1b 100644
--- a/SKILL.md
+++ b/SKILL.md
@@ -106,9 +106,11 @@ else
fi
~/.claude/skills/gstack/bin/gstack-timeline-log '{"skill":"gstack","event":"started","branch":"'"$_BRANCH"'","session":"'"$_SESSION_ID"'"}' 2>/dev/null &
_HAS_ROUTING="no"
-if [ -f CLAUDE.md ] && grep -q "## Skill routing" CLAUDE.md 2>/dev/null; then
- _HAS_ROUTING="yes"
-fi
+for _RF in CLAUDE.md AGENTS.md; do
+ if [ -f "$_RF" ] && grep -q "## Skill routing" "$_RF" 2>/dev/null; then
+ _HAS_ROUTING="yes"
+ fi
+done
_ROUTING_DECLINED=$(~/.claude/skills/gstack/bin/gstack-config get routing_declined 2>/dev/null || echo "false")
echo "HAS_ROUTING: $_HAS_ROUTING"
echo "ROUTING_DECLINED: $_ROUTING_DECLINED"
@@ -377,10 +379,13 @@ _BRAIN_SYNC_MODE=$("$_BRAIN_CONFIG_BIN" get artifacts_sync_mode 2>/dev/null || e
# Detect remote-MCP mode (Path 4 of /setup-gbrain). Local artifacts sync is
# a no-op in remote mode; the brain server pulls from GitHub/GitLab on its
# own cadence. Read claude.json directly to keep this preamble fast (no
-# subprocess to claude CLI on every skill start).
+# subprocess to claude CLI on every skill start). Both registration scopes
+# are read (#2499): user scope, then the nearest-ancestor project scope.
_GBRAIN_MCP_MODE="none"
+_GBRAIN_MCP_ENTRY=""
if command -v jq >/dev/null 2>&1 && [ -f "$HOME/.claude.json" ]; then
- _GBRAIN_MCP_TYPE=$(jq -r '.mcpServers.gbrain.type // .mcpServers.gbrain.transport // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_ENTRY=$(jq -c --arg cwd "$PWD" '.mcpServers.gbrain // ((.projects // {}) | to_entries | map(select((.key as $k | $cwd == $k or ($cwd | startswith($k + "/"))) and ((try .value.mcpServers.gbrain catch null) != null))) | sort_by(.key | length) | last | .value.mcpServers.gbrain) // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_TYPE=$(printf '%s' "$_GBRAIN_MCP_ENTRY" | jq -r '.type // .transport // empty' 2>/dev/null)
case "$_GBRAIN_MCP_TYPE" in
url|http|sse) _GBRAIN_MCP_MODE="remote-http" ;;
stdio) _GBRAIN_MCP_MODE="local-stdio" ;;
@@ -401,6 +406,7 @@ if [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_DO_PULL=1
if [ -f "$_BRAIN_LAST_PULL_FILE" ]; then
_BRAIN_LAST=$(cat "$_BRAIN_LAST_PULL_FILE" 2>/dev/null || echo 0)
+ case "$_BRAIN_LAST" in ''|*[!0-9]*) _BRAIN_LAST=0 ;; esac
_BRAIN_AGE=$(( _BRAIN_NOW - _BRAIN_LAST ))
[ "$_BRAIN_AGE" -lt 86400 ] && _BRAIN_DO_PULL=0
fi
@@ -414,7 +420,7 @@ fi
if [ "$_GBRAIN_MCP_MODE" = "remote-http" ]; then
# Remote-MCP mode: local artifacts sync is a no-op (brain admin's server
# pulls from GitHub/GitLab). Show the user this is by design, not broken.
- _GBRAIN_HOST=$(jq -r '.mcpServers.gbrain.url // empty' "$HOME/.claude.json" 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|')
+ _GBRAIN_HOST=$(printf '%s' "${_GBRAIN_MCP_ENTRY:-}" | jq -r '.url // empty' 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|' | head -1 | tr -cd 'A-Za-z0-9._-')
echo "ARTIFACTS_SYNC: remote-mode (managed by brain server ${_GBRAIN_HOST:-remote})"
elif [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_QUEUE_DEPTH=0
diff --git a/TODOS.md b/TODOS.md
index a081bb1a3..38f69c9de 100644
--- a/TODOS.md
+++ b/TODOS.md
@@ -2,6 +2,166 @@
## NEXT PRIORITY
+### P1: ZeroEntropy sunset — gbrain's default embedding provider dies Sept 4, 2026 (#2365)
+
+**What:** ZeroEntropy (acquired by Notion) shuts down September 4, 2026. gbrain's
+default embedding provider needs a migration path before then; gstack's
+setup-gbrain flow should stop recommending it and detect/warn existing installs.
+
+**Why:** Hard external deadline. After Sept 4, fresh setup-gbrain runs against the
+default provider fail, and existing brains stop embedding new pages silently.
+
+**Effort:** M (human ~2d, CC ~1h — mostly gbrain-side; gstack side is detect+warn).
+**Priority:** P1 (calendar-driven). **Depends on:** gbrain upstream provider support.
+
+### P2: v1.67 fix-wave deferrals — next-wave queue
+
+Filed at v1.67.0.0 implementation time (see the wave plan's "Cut from this
+wave"). Each was explicitly deferred with rationale, not dropped:
+
+- **#2522 Windows omnibus mining** — the targeted Windows fixes landed in
+ v1.67 (#2414/#2510/#2561/#2542/#2452-half); the omnibus PR still carries a
+ doctor/migration surface worth extracting. Effort M→S with CC.
+- **#2443 AskUserQuestion numbering redesign** — real mismatch (brief letters
+ vs host-rendered numbers), but a prompt-behavior redesign that shifts eval
+ baselines; needs its own PR with baseline refresh. Effort S.
+- **#2447 typecheck infra** — tsconfig + repo-wide typecheck script + latent
+ type fixes. High-value, repo-wide blast radius, own PR with bake time.
+ Effort M. Re-derive on current main (several of its fixes landed since).
+- **#2492 per-project Chromium profile** — needs an on-disk migration story
+ for the machine-wide profile default and SingletonLock scoping. Effort M.
+- **#2286 `triggers:` frontmatter** — the Claude Code router never reads the
+ key; folding voice-triggers into description costs catalog tokens. Needs a
+ maintainer token-budget decision (catalog cap is enforced). Effort S.
+- **#2378 release-tag upgrade semantics** — update-check gates on
+ main:VERSION while upgrade installs main HEAD; installs sit between
+ releases. Design decision: tag-pinned installs vs HEAD. Effort M.
+- **Feature-PR triage queue** — #2564 (/deck), #2497 (browse record — best of
+ the batch), #2476 (a11y review, unblocked by the CDP media-emulation entry
+ landed in v1.67), #2446 (Cua), #2448 (tiered outside voice), #2412 (lens
+ layer), #2241 (/grok), #2507 (pi host), #2298 (Kimi host), #2438+#2436
+ (gbrain doc-sync pair, ordered), #2442 (portable skill roots), #2534
+ (gbrain MCP routing), #2535 (outside voice for /investigate,/cso,/devex),
+ #2576 (fast-ship rework — re-evaluate against v1.66's CI speedup),
+ #2580 (land-and-deploy CI tiers — human-gate UX needs maintainer call).
+
+### P2: v1.67 adversarial-review residuals (verified, deferred with rationale)
+
+Filed at v1.67 ship time from the Codex + Claude adversarial passes. Each was
+verified real but needs design input or device access the wave lacked:
+
+- **brain-sync enqueue lock** — the drain's surgical rewrite closes the reader
+ side, but a lockless producer appending between the live re-read and the
+ tmp+mv can still orphan one record. Needs a shared enqueue/drain lock
+ (mkdir-style, like the drain's). Effort S.
+- **iOS tap routing across windows** — Bridges template's frontmostWindow can
+ swallow taps when a keyboard/menu/transparent overlay window is topmost but
+ doesn't handle the coordinate. Needs hit-test-aware routing + real-device
+ verification. Effort M. (Related: the multi-window rewrite has no static
+ pins — see the test-gap backlog below.)
+- **pair-agent implicit --force-restart** — pair-agent auto-kills a healthy
+ headless daemon (tabs/cookies) with no consent, contradicting the #2219
+ iron rule it now sits beside. Needs a consent prompt or explicit-flag
+ requirement; UX call. Effort S.
+- **bin-context slugFromEnvironment walk-up parity (win32)** — the native
+ fallback slugs the INNERMOST repo while bash gstack-slug walks to the
+ outermost canonical remote; nested/vendored repos split stores. Effort S.
+- **hasRemoteOnlyGbrainMcp is machine-global** — one project's remote gbrain
+ registration reclassifies broken local engines as thin-client everywhere;
+ also confirm Claude Code's user-vs-project MCP precedence against
+ brain-cache's user-first assumption. Effort S.
+- **next-version git-fallback breadth** — the degraded path counts every
+ remote-tracking ref on every remote (stale experiment branches inflate the
+ allocation) and a failed 3-digit base read flips width to 4. Warned today;
+ tighten to origin + width-pin. Effort S.
+- **Stop-hook registration pins the setup-time absolute path** — registering
+ from a dev worktree bakes that path into settings.json; deleting the
+ worktree leaves a dead hook erroring on every session stop until removed.
+ Register the global-install path or re-point on upgrade. Effort S.
+- **Accepted threat-model notes (documented, no action planned):**
+ redact-prepush treats content pushed to ANY private remote as already-left
+ (accident-only threat model); a parcel-shaped twin within 400 chars can
+ suppress phone redaction (WARN-tier pattern, attacker-influence accepted);
+ codex-probe's 400-signature grep can misread a transient proxy 400 as
+ MODEL_UNUSABLE (bounded by the 15-min negative-cache TTL).
+
+### P2: v1.67 coverage-audit test-gap backlog (5-agent sweep, ranked)
+
+The wave's Step-7 coverage audit (5 subsystem agents, ~700 changed paths,
+~84% covered) ranked these residual gaps. None block v1.67 (the behaviors
+shipped verified by hand or adjacent tests); each is a cheap pin against
+silent regression:
+
+- **setup Playwright bootstrap block** — `_clear_playwright_quarantine`,
+ `_PW_LOCK` stale-holder reclaim, `_kill_tree`/`_wait_with_deadline`, Ubuntu
+ 26.04 platform override: zero test references. The P0 #2554 heal's shell
+ half. Effort S each.
+- **redact-prepush `scanAddedLines` slicing** — the >1MiB catch-up-diff chunk
+ path (the reason the function exists) is unexercised; a regression
+ reintroduces blocking-while-unscanned. Effort S.
+- **supabase telemetry-ingest edge function** — zero tests; producer caps at
+ 200 chars vs ingest's 500 (dead server cap); no column↔migration pin.
+- **gbrain-repo-policy-client** — no direct test file; the spawn-failed vs
+ unreadable split (its raison d'être) and win32 bash-wrapping unpinned.
+- **extension client half of token bootstrap** — `POST /extension-token` 403
+ → disconnected path untested (server half is exhaustively pinned); also
+ pin manifest `key` ↔ `GSTACK_EXTENSION_ID` via extension-id.ts. Effort S.
+- **`assertJsOriginAllowed`** — this wave made the js/eval origin gate
+ mandatory; the gate itself has zero direct tests. Effort S.
+- **`runBoundedChromiumReinstall`** — every heal test stubs it; the 120s
+ deadline + process-group SIGKILL + spawn-error branch never execute.
+- **CI three-way image-tag drift** — ci-image.yml + evals.yml +
+ evals-periodic.yml each carry the hashFiles tag expression, synced by
+ comment only. One test reading all three. Effort S.
+- **evals.yml matrix census** — the silent-never-ran class (see the two
+ files this wave had to re-add) has no membership test.
+- **design-doc-discovery resolver** — new anti-drift block, zero tests for
+ the -nt freshness rule or cross-render identity.
+- **Bridges.swift multi-window rewrite** — no static pins for
+ orderedWindows/searchRoots ordering; DebugBridgeTouch's `#if !defined(DEBUG)`
+ guard and Package.swift's `.define("DEBUG")` have no tripwire (Guideline
+ 2.5.1 exposure on revert); parity test runs periodic-lane only.
+- **Smaller pins:** gstack-egress `sanitizeForDisplay`; freeze-dir tilde
+ expansion; gstack-config `pair_agent` key + space-bearing values;
+ session-cookie-store tripwire scope (points at the wrapper, not the
+ factory); redact-patterns `/^pass(word)?$/i` placeholder loosening +
+ compact-timestamp negative; fs-atomic adoption tripwire; tracker-guard
+ `safeSource`; eval-watch `PARTIAL_PATH`; `killProcessGroup`;
+ make-pdf orchestrator `PAYLOAD_TMP_DIR` + CJK stack + smartypants NUL;
+ gbrain-guards `gbrainHome()`; gbrain-local-status `"timeout"` exclusion;
+ meta-commands state-load tripwire re-point; flushBuffers/audit 0600 census;
+ openclaw `version:` frontmatter drop (pre-wave, main-side — restore
+ extraFields or record as intentional); terse-build's stale "all 4" set
+ (main-side 5th terse-gated resolver).
+
+### P2: v1.67 review-fix-batch deferrals (post-wave review army findings)
+
+Filed at review-fix-batch time, deferred with rationale:
+
+- **setup host-function dedup** — four near-verbatim `create_*_runtime_root`
+ + `link_*_skill_dirs` copies (codex/factory/opencode/cursor) drift
+ independently (the #2142 ownership gate had to be patched at every site).
+ Parameterize on host name + skills dir. Effort S with CC.
+- **cmd.exe `%VAR%` expansion in gbrainInvocation quoting** — Windows-only,
+ contrived escalation (requires attacker-controlled env var names), but the
+ quoting is not cmd.exe-safe. Fix direction: route win32 spawns through
+ cross-spawn (dependency decision — bun-polyfill.cjs already carries it for
+ the browse daemon). Effort S.
+- **make-pdf flag registry metadata** — commands.ts flags are bare strings;
+ add a takes-value field and DERIVE cli.ts's BOOLEAN_FLAGS from the
+ registry (the structural `--no-*` test added in this batch covers only the
+ negation shape). Effort S.
+- **legacy host-glob uninstall provenance gating** — gstack-uninstall's
+ codex/factory/kiro `gstack*` globs still rm -rf without a provenance
+ check; bring them to parity with the cursor banner gate added in this
+ batch (v1.67 added cursor; the legacy three are inherited behavior).
+ Effort S.
+- **cursor auto-detect breadth** — `-d ~/.cursor` triggers a full extra
+ render + install for every Cursor-having dev on every ./setup (the dir
+ exists for anyone who ever launched the IDE). Product call on narrowing to
+ CLI detection (`command -v cursor`) or an opt-in flag. Effort S, needs a
+ maintainer decision on the detection contract.
+
### P2: Persona-fleet hostile-user harness (fork port wave 2 deferral)
**What:** Port the methodology behind time-attack/gstack's 87-hostile-user
@@ -3050,35 +3210,24 @@ rendering quirks"); or (c) move this test to periodic until (a)/(b) lands.
`test/helpers/claude-pty-runner.ts:308` (`isNumberedOptionListVisible`). Evidence:
`~/.gstack-dev/eval-runs/pdwu-verify-*.log`. **Effort:** M (human ~half day / CC ~30min).
-### P2: Follow-up fix waves from the 2026-08-14 tracker audit (v1.64.0.0)
-
-The full-tracker audit behind v1.64.0.0 verified every open PR/issue against
-main and consciously deferred four coherent fix waves. Audit records:
-`~/.gstack/projects/garrytan-gstack/` eng-review artifacts + the v1.64 PR body.
-
-**Wave A — browse-daemon lifecycle.** Watchdog kills headed handoff sessions
-(PRs 2565/2405/2346), macOS headed launch broken by the rebrand-invalidated
-Chromium signature + XProtect (issues 2554/2242/2138/1829/1379 — the three
-darwin-skipped handoff tests in browse/test/handoff.test.ts un-skip when this
-lands), busy-daemon kill (2219/2231), cosmetic SIGTERM ignore (2220),
-Playwright pin bump (PR 1761, #1703 — rebuilds the CI browser image).
-Start with the signature/re-sign question; everything else is small.
-
-**Wave B — install integrity.** connect-chrome alias shadowing (PR 2202,
-issues 2201/2511), Playwright bootstrap aborts/timeouts (PRs 2233/2359,
-issues 1902/2136), --host cursor/slate wiring (PRs 2547/2432, issue 2361),
-review checklist/specialists never copied (issues 2317/2518), Windows re-run
-refresh (#2444). Blast radius is `setup` — one focused PR.
-
-**Wave C — gbrain trust boundary.** Transcript trust/scope/source isolation
-(PR 2232, issue 2140), brain-sync queue truncation (#2549), worktree source
-pins (PR 2417, #2516), thin-client detection gaps (#2520/#2456), plus small
-absorbs (2371/2360/2406/2369/2368/2321). Needs never-double-store review.
-
-**Wave D — ship/version allocator.** Queue-down fallback (PRs 2545/2546),
-npm-invalid subdir manifest versions (PR 2531), versionless repos
-(2343/2334/2501, #1474), diff-scope specialist routing rewrite
-(#2526/#2299/#2455), /review token runaway (#2519).
-
-**Depends on:** v1.64.0.0 landing. Each wave is one bundled PR per the
-fix-wave pattern.
+### P3: Residuals from the 2026-08-14 tracker-audit waves (mostly shipped in v1.67.0.0)
+
+The four deferred waves (A: browse-daemon lifecycle, B: install integrity,
+C: gbrain trust boundary, D: ship/version allocator) LANDED in the v1.67.0.0
+fix wave: XProtect self-heal + Playwright bump + busy-daemon iron rule +
+signal policy (A); alias shadowing + cursor slice + runtime assets + Windows
+refresh (B); brain-sync disposition model + source pins + thin-client
+detection (C); version allocator end-state + subdir manifests + diff-scope
+globs (D). What remains, re-filed individually:
+
+- Watchdog kills headed handoff sessions (PRs 2565/2405/2346) and the three
+ darwin-skipped handoff tests in browse/test/handoff.test.ts — verify
+ whether the v1.67 XProtect + rebrand work un-blocks them, then un-skip or
+ fix. Effort S.
+- Transcript trust/scope/source isolation (PR 2232, issue 2140) — needs the
+ never-double-store review. Effort M.
+- Versionless-repo onboarding (#1474, issues 2343/2334) — the #2501 JSON
+ version-path half landed; the no-version-file-at-all flow did not.
+- Playwright bootstrap abort/timeout absorbs (PRs 2233/2359, issues
+ 1902/2136) — partially superseded by v1.67's bounded bootstrap; verify
+ and close or extract the remainder.
diff --git a/VERSION b/VERSION
index 4790d6fbd..20aa59f0d 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-1.66.1.0
+1.67.0.0
diff --git a/autoplan/SKILL.md b/autoplan/SKILL.md
index f24a1cdcb..6324f5e2b 100644
--- a/autoplan/SKILL.md
+++ b/autoplan/SKILL.md
@@ -116,9 +116,11 @@ else
fi
~/.claude/skills/gstack/bin/gstack-timeline-log '{"skill":"autoplan","event":"started","branch":"'"$_BRANCH"'","session":"'"$_SESSION_ID"'"}' 2>/dev/null &
_HAS_ROUTING="no"
-if [ -f CLAUDE.md ] && grep -q "## Skill routing" CLAUDE.md 2>/dev/null; then
- _HAS_ROUTING="yes"
-fi
+for _RF in CLAUDE.md AGENTS.md; do
+ if [ -f "$_RF" ] && grep -q "## Skill routing" "$_RF" 2>/dev/null; then
+ _HAS_ROUTING="yes"
+ fi
+done
_ROUTING_DECLINED=$(~/.claude/skills/gstack/bin/gstack-config get routing_declined 2>/dev/null || echo "false")
echo "HAS_ROUTING: $_HAS_ROUTING"
echo "ROUTING_DECLINED: $_ROUTING_DECLINED"
@@ -512,10 +514,13 @@ _BRAIN_SYNC_MODE=$("$_BRAIN_CONFIG_BIN" get artifacts_sync_mode 2>/dev/null || e
# Detect remote-MCP mode (Path 4 of /setup-gbrain). Local artifacts sync is
# a no-op in remote mode; the brain server pulls from GitHub/GitLab on its
# own cadence. Read claude.json directly to keep this preamble fast (no
-# subprocess to claude CLI on every skill start).
+# subprocess to claude CLI on every skill start). Both registration scopes
+# are read (#2499): user scope, then the nearest-ancestor project scope.
_GBRAIN_MCP_MODE="none"
+_GBRAIN_MCP_ENTRY=""
if command -v jq >/dev/null 2>&1 && [ -f "$HOME/.claude.json" ]; then
- _GBRAIN_MCP_TYPE=$(jq -r '.mcpServers.gbrain.type // .mcpServers.gbrain.transport // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_ENTRY=$(jq -c --arg cwd "$PWD" '.mcpServers.gbrain // ((.projects // {}) | to_entries | map(select((.key as $k | $cwd == $k or ($cwd | startswith($k + "/"))) and ((try .value.mcpServers.gbrain catch null) != null))) | sort_by(.key | length) | last | .value.mcpServers.gbrain) // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_TYPE=$(printf '%s' "$_GBRAIN_MCP_ENTRY" | jq -r '.type // .transport // empty' 2>/dev/null)
case "$_GBRAIN_MCP_TYPE" in
url|http|sse) _GBRAIN_MCP_MODE="remote-http" ;;
stdio) _GBRAIN_MCP_MODE="local-stdio" ;;
@@ -536,6 +541,7 @@ if [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_DO_PULL=1
if [ -f "$_BRAIN_LAST_PULL_FILE" ]; then
_BRAIN_LAST=$(cat "$_BRAIN_LAST_PULL_FILE" 2>/dev/null || echo 0)
+ case "$_BRAIN_LAST" in ''|*[!0-9]*) _BRAIN_LAST=0 ;; esac
_BRAIN_AGE=$(( _BRAIN_NOW - _BRAIN_LAST ))
[ "$_BRAIN_AGE" -lt 86400 ] && _BRAIN_DO_PULL=0
fi
@@ -549,7 +555,7 @@ fi
if [ "$_GBRAIN_MCP_MODE" = "remote-http" ]; then
# Remote-MCP mode: local artifacts sync is a no-op (brain admin's server
# pulls from GitHub/GitLab). Show the user this is by design, not broken.
- _GBRAIN_HOST=$(jq -r '.mcpServers.gbrain.url // empty' "$HOME/.claude.json" 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|')
+ _GBRAIN_HOST=$(printf '%s' "${_GBRAIN_MCP_ENTRY:-}" | jq -r '.url // empty' 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|' | head -1 | tr -cd 'A-Za-z0-9._-')
echo "ARTIFACTS_SYNC: remote-mode (managed by brain server ${_GBRAIN_HOST:-remote})"
elif [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_QUEUE_DEPTH=0
@@ -634,8 +640,8 @@ eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)"
_PROJ="${GSTACK_HOME:-$HOME/.gstack}/projects/${SLUG:-unknown}"
if [ -d "$_PROJ" ]; then
echo "--- RECENT ARTIFACTS ---"
- find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs ls -t 2>/dev/null | head -3
- [ -f "$_PROJ/${_BRANCH}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/${_BRANCH}-reviews.jsonl" | tr -d ' ') entries"
+ find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3
+ [ -f "$_PROJ/${BRANCH:-unknown}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/${BRANCH:-unknown}-reviews.jsonl" | tr -d ' ') entries"
[ -f "$_PROJ/timeline.jsonl" ] && tail -5 "$_PROJ/timeline.jsonl"
if [ -f "$_PROJ/timeline.jsonl" ]; then
_LAST=$(grep "\"branch\":\"${_BRANCH}\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -1)
@@ -643,7 +649,7 @@ if [ -d "$_PROJ" ]; then
_RECENT_SKILLS=$(grep "\"branch\":\"${_BRANCH}\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -3 | grep -o '"skill":"[^"]*"' | sed 's/"skill":"//;s/"//' | tr '\n' ',')
[ -n "$_RECENT_SKILLS" ] && echo "RECENT_PATTERN: $_RECENT_SKILLS"
fi
- _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs ls -t 2>/dev/null | head -1)
+ _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs -r ls -t 2>/dev/null | head -1)
[ -n "$_LATEST_CP" ] && echo "LATEST_CHECKPOINT: $_LATEST_CP"
if [ -f "$_PROJ/decisions.active.json" ]; then
echo "--- ACTIVE DECISIONS (recent, scope-relevant) ---"
@@ -719,7 +725,7 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST
## Question Tuning (skip entirely if `QUESTION_TUNING: false`)
-Before each AskUserQuestion, choose `question_id` from `scripts/question-registry.ts` or `{skill}-{slug}`, then run `printf '%s' "<question summary>" | ~/.claude/skills/gstack/bin/gstack-question-preference --check "<id>" --summary-stdin` (piped summary feeds the one-way keyword net, #2024). `AUTO_DECIDE` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." `ASK_NORMALLY` means ask.
+Before each AskUserQuestion, choose `question_id` from `~/.claude/skills/gstack/scripts/question-registry.ts` or `{skill}-{slug}`, then run `printf '%s' "<question summary>" | ~/.claude/skills/gstack/bin/gstack-question-preference --check "<id>" --summary-stdin` (piped summary feeds the one-way keyword net, #2024). `AUTO_DECIDE` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." `ASK_NORMALLY` means ask.
**Embed the question_id as a marker in the question text** so hooks can identify it deterministically (plan-tune cathedral T14 / D18 progressive markers). Append `<gstack-qid:{question_id}>` somewhere in the rendered question (the leading line or trailing line is fine; the marker doesn't render visibly to the user when wrapped in HTML-style angle brackets, but the hook strips it). Without the marker the PreToolUse enforcement hook treats the AUQ as observed-only and never auto-decides — so always include it when the question matches a registered `question_id`.
@@ -1151,6 +1157,12 @@ elif ! _gstack_codex_auth_probe >/dev/null; then
_gstack_codex_log_event "codex_auth_failed"
echo "[codex-unavailable: auth missing] — proceeding with Claude subagent only. Run \`codex login\` or set \$CODEX_API_KEY to enable dual-voice review."
_CODEX_AVAILABLE=false
+# Round-trip model probe (#2477): auth can pass while the account's configured
+# model is rejected with an HTTP 400 (stale `model =` pin in ~/.codex/config.toml).
+# ~10s on first run, cached 1h; timeouts fail open (probe returns 0).
+elif ! _gstack_codex_model_probe; then
+ echo "[codex-unavailable: configured model rejected] — proceeding with Claude subagent only. Fix the \`model =\` pin in ~/.codex/config.toml (see [notice.model_migrations] there for the replacement)."
+ _CODEX_AVAILABLE=false
else
_gstack_codex_version_check # non-blocking warn if known-bad
_CODEX_AVAILABLE=true
@@ -1195,7 +1207,7 @@ Override: every AskUserQuestion → auto-decide using the 6 principles.
What alternatives were dismissed too quickly? What competitive or market risks are
unaddressed? What scope decisions will look foolish in 6 months? Be adversarial.
No compliments. Just the strategic blind spots.
- File: <plan_path>" -C "$_REPO_ROOT" -s read-only --enable web_search_cached < /dev/null
+ File: <plan_path>" -C "$_REPO_ROOT" -s read-only -c 'web_search="cached"' < /dev/null
_CODEX_EXIT=$?
if [ "$_CODEX_EXIT" = "124" ]; then
_gstack_codex_log_event "codex_timeout" "600"
@@ -1318,7 +1330,7 @@ Override: every AskUserQuestion → auto-decide using the 6 principles.
accessibility requirements (keyboard nav, contrast, touch targets) specified or
aspirational? Does the plan describe specific UI decisions or generic patterns?
What design decisions will haunt the implementer if left ambiguous?
- Be opinionated. No hedging." -C "$_REPO_ROOT" -s read-only --enable web_search_cached < /dev/null
+ Be opinionated. No hedging." -C "$_REPO_ROOT" -s read-only -c 'web_search="cached"' < /dev/null
_CODEX_EXIT=$?
if [ "$_CODEX_EXIT" = "124" ]; then
_gstack_codex_log_event "codex_timeout" "600"
@@ -1394,7 +1406,7 @@ Override: every AskUserQuestion → auto-decide using the 6 principles.
CEO: <insert CEO consensus table summary — key concerns, DISAGREEs>
Design: <insert Design consensus table summary, or 'skipped, no UI scope'>
- File: <plan_path>" -C "$_REPO_ROOT" -s read-only --enable web_search_cached < /dev/null
+ File: <plan_path>" -C "$_REPO_ROOT" -s read-only -c 'web_search="cached"' < /dev/null
_CODEX_EXIT=$?
if [ "$_CODEX_EXIT" = "124" ]; then
_gstack_codex_log_event "codex_timeout" "600"
@@ -1520,7 +1532,7 @@ Log: "Phase 3.5 skipped — no developer-facing scope detected."
3. API/CLI design: are names guessable? Are defaults sensible? Is it consistent?
4. Docs: can a dev find what they need in under 2 minutes? Are examples copy-paste-complete?
5. Upgrade path: can devs upgrade without fear? Migration guides? Deprecation warnings?
- Be adversarial. Think like a developer who is evaluating this against 3 competitors." -C "$_REPO_ROOT" -s read-only --enable web_search_cached < /dev/null
+ Be adversarial. Think like a developer who is evaluating this against 3 competitors." -C "$_REPO_ROOT" -s read-only -c 'web_search="cached"' < /dev/null
_CODEX_EXIT=$?
if [ "$_CODEX_EXIT" = "124" ]; then
_gstack_codex_log_event "codex_timeout" "600"
diff --git a/autoplan/SKILL.md.tmpl b/autoplan/SKILL.md.tmpl
index 011bbacdd..08d7933e9 100644
--- a/autoplan/SKILL.md.tmpl
+++ b/autoplan/SKILL.md.tmpl
@@ -262,6 +262,12 @@ elif ! _gstack_codex_auth_probe >/dev/null; then
_gstack_codex_log_event "codex_auth_failed"
echo "[codex-unavailable: auth missing] — proceeding with Claude subagent only. Run \`codex login\` or set \$CODEX_API_KEY to enable dual-voice review."
_CODEX_AVAILABLE=false
+# Round-trip model probe (#2477): auth can pass while the account's configured
+# model is rejected with an HTTP 400 (stale `model =` pin in ~/.codex/config.toml).
+# ~10s on first run, cached 1h; timeouts fail open (probe returns 0).
+elif ! _gstack_codex_model_probe; then
+ echo "[codex-unavailable: configured model rejected] — proceeding with Claude subagent only. Fix the \`model =\` pin in ~/.codex/config.toml (see [notice.model_migrations] there for the replacement)."
+ _CODEX_AVAILABLE=false
else
_gstack_codex_version_check # non-blocking warn if known-bad
_CODEX_AVAILABLE=true
@@ -306,7 +312,7 @@ Override: every AskUserQuestion → auto-decide using the 6 principles.
What alternatives were dismissed too quickly? What competitive or market risks are
unaddressed? What scope decisions will look foolish in 6 months? Be adversarial.
No compliments. Just the strategic blind spots.
- File: <plan_path>" -C "$_REPO_ROOT" -s read-only --enable web_search_cached < /dev/null
+ File: <plan_path>" -C "$_REPO_ROOT" -s read-only {{CODEX_WEB_SEARCH_FLAG}} < /dev/null
_CODEX_EXIT=$?
if [ "$_CODEX_EXIT" = "124" ]; then
_gstack_codex_log_event "codex_timeout" "600"
@@ -429,7 +435,7 @@ Override: every AskUserQuestion → auto-decide using the 6 principles.
accessibility requirements (keyboard nav, contrast, touch targets) specified or
aspirational? Does the plan describe specific UI decisions or generic patterns?
What design decisions will haunt the implementer if left ambiguous?
- Be opinionated. No hedging." -C "$_REPO_ROOT" -s read-only --enable web_search_cached < /dev/null
+ Be opinionated. No hedging." -C "$_REPO_ROOT" -s read-only {{CODEX_WEB_SEARCH_FLAG}} < /dev/null
_CODEX_EXIT=$?
if [ "$_CODEX_EXIT" = "124" ]; then
_gstack_codex_log_event "codex_timeout" "600"
@@ -505,7 +511,7 @@ Override: every AskUserQuestion → auto-decide using the 6 principles.
CEO: <insert CEO consensus table summary — key concerns, DISAGREEs>
Design: <insert Design consensus table summary, or 'skipped, no UI scope'>
- File: <plan_path>" -C "$_REPO_ROOT" -s read-only --enable web_search_cached < /dev/null
+ File: <plan_path>" -C "$_REPO_ROOT" -s read-only {{CODEX_WEB_SEARCH_FLAG}} < /dev/null
_CODEX_EXIT=$?
if [ "$_CODEX_EXIT" = "124" ]; then
_gstack_codex_log_event "codex_timeout" "600"
@@ -631,7 +637,7 @@ Log: "Phase 3.5 skipped — no developer-facing scope detected."
3. API/CLI design: are names guessable? Are defaults sensible? Is it consistent?
4. Docs: can a dev find what they need in under 2 minutes? Are examples copy-paste-complete?
5. Upgrade path: can devs upgrade without fear? Migration guides? Deprecation warnings?
- Be adversarial. Think like a developer who is evaluating this against 3 competitors." -C "$_REPO_ROOT" -s read-only --enable web_search_cached < /dev/null
+ Be adversarial. Think like a developer who is evaluating this against 3 competitors." -C "$_REPO_ROOT" -s read-only {{CODEX_WEB_SEARCH_FLAG}} < /dev/null
_CODEX_EXIT=$?
if [ "$_CODEX_EXIT" = "124" ]; then
_gstack_codex_log_event "codex_timeout" "600"
diff --git a/benchmark-models/SKILL.md b/benchmark-models/SKILL.md
index 9519c73f6..80d32a6b7 100644
--- a/benchmark-models/SKILL.md
+++ b/benchmark-models/SKILL.md
@@ -110,9 +110,11 @@ else
fi
~/.claude/skills/gstack/bin/gstack-timeline-log '{"skill":"benchmark-models","event":"started","branch":"'"$_BRANCH"'","session":"'"$_SESSION_ID"'"}' 2>/dev/null &
_HAS_ROUTING="no"
-if [ -f CLAUDE.md ] && grep -q "## Skill routing" CLAUDE.md 2>/dev/null; then
- _HAS_ROUTING="yes"
-fi
+for _RF in CLAUDE.md AGENTS.md; do
+ if [ -f "$_RF" ] && grep -q "## Skill routing" "$_RF" 2>/dev/null; then
+ _HAS_ROUTING="yes"
+ fi
+done
_ROUTING_DECLINED=$(~/.claude/skills/gstack/bin/gstack-config get routing_declined 2>/dev/null || echo "false")
echo "HAS_ROUTING: $_HAS_ROUTING"
echo "ROUTING_DECLINED: $_ROUTING_DECLINED"
@@ -381,10 +383,13 @@ _BRAIN_SYNC_MODE=$("$_BRAIN_CONFIG_BIN" get artifacts_sync_mode 2>/dev/null || e
# Detect remote-MCP mode (Path 4 of /setup-gbrain). Local artifacts sync is
# a no-op in remote mode; the brain server pulls from GitHub/GitLab on its
# own cadence. Read claude.json directly to keep this preamble fast (no
-# subprocess to claude CLI on every skill start).
+# subprocess to claude CLI on every skill start). Both registration scopes
+# are read (#2499): user scope, then the nearest-ancestor project scope.
_GBRAIN_MCP_MODE="none"
+_GBRAIN_MCP_ENTRY=""
if command -v jq >/dev/null 2>&1 && [ -f "$HOME/.claude.json" ]; then
- _GBRAIN_MCP_TYPE=$(jq -r '.mcpServers.gbrain.type // .mcpServers.gbrain.transport // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_ENTRY=$(jq -c --arg cwd "$PWD" '.mcpServers.gbrain // ((.projects // {}) | to_entries | map(select((.key as $k | $cwd == $k or ($cwd | startswith($k + "/"))) and ((try .value.mcpServers.gbrain catch null) != null))) | sort_by(.key | length) | last | .value.mcpServers.gbrain) // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_TYPE=$(printf '%s' "$_GBRAIN_MCP_ENTRY" | jq -r '.type // .transport // empty' 2>/dev/null)
case "$_GBRAIN_MCP_TYPE" in
url|http|sse) _GBRAIN_MCP_MODE="remote-http" ;;
stdio) _GBRAIN_MCP_MODE="local-stdio" ;;
@@ -405,6 +410,7 @@ if [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_DO_PULL=1
if [ -f "$_BRAIN_LAST_PULL_FILE" ]; then
_BRAIN_LAST=$(cat "$_BRAIN_LAST_PULL_FILE" 2>/dev/null || echo 0)
+ case "$_BRAIN_LAST" in ''|*[!0-9]*) _BRAIN_LAST=0 ;; esac
_BRAIN_AGE=$(( _BRAIN_NOW - _BRAIN_LAST ))
[ "$_BRAIN_AGE" -lt 86400 ] && _BRAIN_DO_PULL=0
fi
@@ -418,7 +424,7 @@ fi
if [ "$_GBRAIN_MCP_MODE" = "remote-http" ]; then
# Remote-MCP mode: local artifacts sync is a no-op (brain admin's server
# pulls from GitHub/GitLab). Show the user this is by design, not broken.
- _GBRAIN_HOST=$(jq -r '.mcpServers.gbrain.url // empty' "$HOME/.claude.json" 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|')
+ _GBRAIN_HOST=$(printf '%s' "${_GBRAIN_MCP_ENTRY:-}" | jq -r '.url // empty' 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|' | head -1 | tr -cd 'A-Za-z0-9._-')
echo "ARTIFACTS_SYNC: remote-mode (managed by brain server ${_GBRAIN_HOST:-remote})"
elif [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_QUEUE_DEPTH=0
diff --git a/benchmark/SKILL.md b/benchmark/SKILL.md
index f0528c08f..8b1176b24 100644
--- a/benchmark/SKILL.md
+++ b/benchmark/SKILL.md
@@ -110,9 +110,11 @@ else
fi
~/.claude/skills/gstack/bin/gstack-timeline-log '{"skill":"benchmark","event":"started","branch":"'"$_BRANCH"'","session":"'"$_SESSION_ID"'"}' 2>/dev/null &
_HAS_ROUTING="no"
-if [ -f CLAUDE.md ] && grep -q "## Skill routing" CLAUDE.md 2>/dev/null; then
- _HAS_ROUTING="yes"
-fi
+for _RF in CLAUDE.md AGENTS.md; do
+ if [ -f "$_RF" ] && grep -q "## Skill routing" "$_RF" 2>/dev/null; then
+ _HAS_ROUTING="yes"
+ fi
+done
_ROUTING_DECLINED=$(~/.claude/skills/gstack/bin/gstack-config get routing_declined 2>/dev/null || echo "false")
echo "HAS_ROUTING: $_HAS_ROUTING"
echo "ROUTING_DECLINED: $_ROUTING_DECLINED"
@@ -381,10 +383,13 @@ _BRAIN_SYNC_MODE=$("$_BRAIN_CONFIG_BIN" get artifacts_sync_mode 2>/dev/null || e
# Detect remote-MCP mode (Path 4 of /setup-gbrain). Local artifacts sync is
# a no-op in remote mode; the brain server pulls from GitHub/GitLab on its
# own cadence. Read claude.json directly to keep this preamble fast (no
-# subprocess to claude CLI on every skill start).
+# subprocess to claude CLI on every skill start). Both registration scopes
+# are read (#2499): user scope, then the nearest-ancestor project scope.
_GBRAIN_MCP_MODE="none"
+_GBRAIN_MCP_ENTRY=""
if command -v jq >/dev/null 2>&1 && [ -f "$HOME/.claude.json" ]; then
- _GBRAIN_MCP_TYPE=$(jq -r '.mcpServers.gbrain.type // .mcpServers.gbrain.transport // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_ENTRY=$(jq -c --arg cwd "$PWD" '.mcpServers.gbrain // ((.projects // {}) | to_entries | map(select((.key as $k | $cwd == $k or ($cwd | startswith($k + "/"))) and ((try .value.mcpServers.gbrain catch null) != null))) | sort_by(.key | length) | last | .value.mcpServers.gbrain) // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_TYPE=$(printf '%s' "$_GBRAIN_MCP_ENTRY" | jq -r '.type // .transport // empty' 2>/dev/null)
case "$_GBRAIN_MCP_TYPE" in
url|http|sse) _GBRAIN_MCP_MODE="remote-http" ;;
stdio) _GBRAIN_MCP_MODE="local-stdio" ;;
@@ -405,6 +410,7 @@ if [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_DO_PULL=1
if [ -f "$_BRAIN_LAST_PULL_FILE" ]; then
_BRAIN_LAST=$(cat "$_BRAIN_LAST_PULL_FILE" 2>/dev/null || echo 0)
+ case "$_BRAIN_LAST" in ''|*[!0-9]*) _BRAIN_LAST=0 ;; esac
_BRAIN_AGE=$(( _BRAIN_NOW - _BRAIN_LAST ))
[ "$_BRAIN_AGE" -lt 86400 ] && _BRAIN_DO_PULL=0
fi
@@ -418,7 +424,7 @@ fi
if [ "$_GBRAIN_MCP_MODE" = "remote-http" ]; then
# Remote-MCP mode: local artifacts sync is a no-op (brain admin's server
# pulls from GitHub/GitLab). Show the user this is by design, not broken.
- _GBRAIN_HOST=$(jq -r '.mcpServers.gbrain.url // empty' "$HOME/.claude.json" 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|')
+ _GBRAIN_HOST=$(printf '%s' "${_GBRAIN_MCP_ENTRY:-}" | jq -r '.url // empty' 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|' | head -1 | tr -cd 'A-Za-z0-9._-')
echo "ARTIFACTS_SYNC: remote-mode (managed by brain server ${_GBRAIN_HOST:-remote})"
elif [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_QUEUE_DEPTH=0
diff --git a/bin/gstack-artifacts-init b/bin/gstack-artifacts-init
index f99c96591..9691c226e 100755
--- a/bin/gstack-artifacts-init
+++ b/bin/gstack-artifacts-init
@@ -291,6 +291,14 @@ projects/*/*-design-*.md
projects/*/*-test-plan-*.md
projects/*/*-eng-review-test-plan-*.md
projects/*/timeline.jsonl
+# The decision store. gstack-decision-log enqueues projects/<slug>/decisions.jsonl
+# after EVERY write, but no glob above matched it, so compute_paths_to_stage rejected
+# all of them at its "must match at least one allowlist glob" check -- a writer
+# enqueueing a path the syncer is guaranteed to drop. Without these the durable
+# decision ledger never leaves the machine, on any platform.
+projects/*/decisions.jsonl
+projects/*/decisions.active.json
+projects/*/decisions.archive.jsonl
retros/*.md
developer-profile.json
builder-journey.md
@@ -318,6 +326,9 @@ cat > "$GSTACK_HOME/.brain-privacy-map.json" <<'EOF'
{"pattern": "projects/*/*-design-*.md", "class": "artifact"},
{"pattern": "projects/*/*-test-plan-*.md", "class": "artifact"},
{"pattern": "projects/*/*-eng-review-test-plan-*.md", "class": "artifact"},
+ {"pattern": "projects/*/decisions.jsonl", "class": "artifact"},
+ {"pattern": "projects/*/decisions.active.json", "class": "artifact"},
+ {"pattern": "projects/*/decisions.archive.jsonl", "class": "artifact"},
{"pattern": "retros/*.md", "class": "artifact"},
{"pattern": "builder-journey.md", "class": "artifact"},
{"pattern": "projects/*/timeline.jsonl", "class": "behavioral"},
diff --git a/bin/gstack-brain-cache b/bin/gstack-brain-cache
index f7694f33f..abf45a013 100755
--- a/bin/gstack-brain-cache
+++ b/bin/gstack-brain-cache
@@ -126,13 +126,27 @@ function sha8(input: string): string {
* Detects the active brain endpoint (MCP URL or 'local') and returns its
* stable identity hash. Used to detect when the user switches brains
* (different endpoint → different cache).
+ *
+ * Reads BOTH registration scopes in ~/.claude.json (#2499): user scope
+ * (.mcpServers.gbrain) first, then project scope
+ * (.projects["/abs/path"].mcpServers.gbrain — what `claude mcp add`
+ * WITHOUT --scope user writes), preferring the nearest ancestor of cwd
+ * (longest matching project key) so nested repos resolve to their own
+ * brain. Before the project-scope read, two different project-scoped
+ * brains both hashed to 'local', so switching between them never
+ * invalidated the cache — the exact scenario this function exists to
+ * catch.
+ *
+ * Params exist for tests; production callers use the defaults.
*/
-export function detectEndpointHash(): string {
- const claudeJsonPath = join(homedir(), '.claude.json');
+export function detectEndpointHash(
+ claudeJsonPath: string = join(homedir(), '.claude.json'),
+ cwd: string = process.cwd(),
+): string {
if (existsSync(claudeJsonPath)) {
try {
const cfg = JSON.parse(readFileSync(claudeJsonPath, 'utf-8'));
- const gbrainServer = cfg?.mcpServers?.gbrain;
+ const gbrainServer = resolveGbrainMcpEntry(cfg, cwd);
const url = gbrainServer?.url || gbrainServer?.transport?.url;
if (typeof url === 'string' && url.length > 0) {
return sha8(url);
@@ -143,6 +157,40 @@ export function detectEndpointHash(): string {
return 'local';
}
+interface McpEntryish {
+ url?: unknown;
+ transport?: { url?: unknown };
+}
+
+/**
+ * User-scope gbrain entry, else the nearest-ancestor project-scope entry
+ * for cwd (#2499). Path-boundary-aware: /a/repo never matches /a/repo2.
+ * Both separators are accepted so Windows project keys resolve.
+ */
+function resolveGbrainMcpEntry(
+ cfg: unknown,
+ cwd: string,
+): McpEntryish | undefined {
+ const root = cfg as {
+ mcpServers?: Record<string, McpEntryish>;
+ projects?: Record<string, { mcpServers?: Record<string, McpEntryish> }>;
+ } | null;
+ if (root?.mcpServers?.gbrain) return root.mcpServers.gbrain;
+ const projects = root?.projects;
+ if (!projects || typeof projects !== 'object') return undefined;
+ let best: { key: string; entry: McpEntryish } | undefined;
+ for (const [key, val] of Object.entries(projects)) {
+ if (!val || typeof val !== 'object') continue;
+ const entry = val.mcpServers?.gbrain;
+ if (!entry || typeof entry !== 'object') continue;
+ const isAncestor =
+ cwd === key || cwd.startsWith(`${key}/`) || cwd.startsWith(`${key}\\`);
+ if (!isAncestor) continue;
+ if (!best || key.length > best.key.length) best = { key, entry };
+ }
+ return best?.entry;
+}
+
// ──────────────────────────────────────────────────────────────────────────
// Atomic write (tmp + rename)
// ──────────────────────────────────────────────────────────────────────────
@@ -521,6 +569,21 @@ function fetchRecentDecisions(projectSlug: string | null): string | null {
'--json',
]);
if (!result?.pages) {
+ // F10 bug fix: this branch used to return the hardcoded
+ // "_No prior skill runs recorded._" string here, which is indistinguishable
+ // from a genuine zero-rows result. That silently converted a gbrain-
+ // unreachable FAILURE into a "successful" cached digest — refreshEntity()
+ // would write it and stamp last_refresh, so the false negative survived
+ // every subsequent TTL cycle forever. Returning null instead lets cmdGet's
+ // existing missing/stale-fallback machinery report the true state, exactly
+ // like every sibling fetcher (fetchGoals, fetchSimplePage) already does on
+ // failure.
+ return null;
+ }
+ // A malformed payload ({pages: {}} etc.) must classify as failure, not crash
+ // refreshEntity mid-refresh — same honest-missing polarity as the F10 fix.
+ if (!Array.isArray(result.pages)) return null;
+ if (result.pages.length === 0) {
return `# Recent decisions (project: ${projectSlug})\n\n_No prior skill runs recorded._\n`;
}
const lines = result.pages.map((p) => `- ${p.title || p.slug}`);
@@ -576,7 +639,17 @@ function fetchSalience(projectSlug: string | null): string | null {
'--limit', '10',
'--json',
]);
- if (!result?.pages) return `# Recent salience\n\n_No salient pages in last 14d._\n`;
+ // F10 bug fix (sibling of fetchRecentDecisions above): a gbrain-unreachable
+ // failure used to render the identical hardcoded "no salient pages" string
+ // as a genuine empty result, which refreshEntity() then cached as if it
+ // were verified truth. Unlike recent-decisions there is no project-local
+ // fallback for salience — it is specifically gbrain's emotional-weight-
+ // ranked *brain* pages, not project decision/work data, and conflating the
+ // two would defeat the D9 privacy allowlist's purpose. So on failure we
+ // return null and let the cache report 'missing' (same as product.md,
+ // goals.md, etc. already do on this machine) instead of asserting a claim
+ // we have no way to verify.
+ if (!result?.pages) return null;
// D9 privacy gate: strip entries outside the allowlist BEFORE rendering.
// Sensitive personal content (family, therapy, reflection) is never written
diff --git a/bin/gstack-brain-sync b/bin/gstack-brain-sync
index 2fa696869..b3f460377 100755
--- a/bin/gstack-brain-sync
+++ b/bin/gstack-brain-sync
@@ -122,12 +122,23 @@ sys.exit(0)
# Compute matched allowlisted, privacy-filtered path set from queue.
# Output: newline-delimited relative paths that should be staged.
+#
+# #2549: every non-staged queue entry is CLASSIFIED, never silently discarded.
+# When $2 is given, a JSON classification lands there:
+# {"retained": [privacy/mode-held paths that stay queued],
+# "dropped": {"skipped": [...], "invalid": [...], "unmatched": [...], "missing": [...]}}
+# retained entries would sync if the user raises artifacts_sync_mode, so they
+# stay in the queue; dropped classes can never sync (explicit skip, escape
+# attempt, no allowlist glob, not on disk) and are removed WITH a counted
+# status — the old behavior truncated the whole queue and reported every one
+# of these, including privacy holds, as "no allowlisted changes".
compute_paths_to_stage() {
local mode="$1"
- python3 - "$GSTACK_HOME" "$QUEUE" "$ALLOWLIST" "$PRIVACY_MAP" "$SKIP_FILE" "$mode" <<'PYEOF'
+ local class_file="${2:-}"
+ python3 - "$GSTACK_HOME" "$QUEUE" "$ALLOWLIST" "$PRIVACY_MAP" "$SKIP_FILE" "$mode" "$class_file" <<'PYEOF'
import sys, json, os, fnmatch, glob
-gstack_home, queue, allowlist_path, privacy_path, skip_path, mode = sys.argv[1:7]
+gstack_home, queue, allowlist_path, privacy_path, skip_path, mode, class_file = sys.argv[1:8]
def load_lines(path):
try:
@@ -195,29 +206,135 @@ def mode_allows(cls, mode):
return True # full
final = []
+classified = {"retained": [], "dropped": {"skipped": [], "invalid": [], "unmatched": [], "missing": []}}
for p in sorted(queue_paths):
if p in skip_lines:
+ classified["dropped"]["skipped"].append(p)
continue
# Must be under GSTACK_HOME root. Reject absolute + reject ../ escape.
if p.startswith("/") or ".." in p.split("/"):
+ classified["dropped"]["invalid"].append(p)
continue
# Must match at least one allowlist glob.
if not path_matches_any(p, allowlist_globs):
+ classified["dropped"]["unmatched"].append(p)
continue
- # Must survive privacy mode filter.
+ # Must survive privacy mode filter — held entries STAY QUEUED (retained):
+ # they would sync under a higher artifacts_sync_mode, and reporting them
+ # as "no allowlisted changes" was #2549's misattribution.
cls = privacy_class(p, privacy_map)
if not mode_allows(cls, mode):
+ classified["retained"].append(p)
continue
# Must exist on disk — can't stage what isn't there.
if not os.path.exists(os.path.join(gstack_home, p)):
+ classified["dropped"]["missing"].append(p)
continue
final.append(p)
+if class_file:
+ with open(class_file, "w") as f:
+ json.dump(classified, f)
+
for p in final:
print(p)
PYEOF
}
+# #2549: surgical queue rewrite — replaces every whole-queue truncation
+# (`: > "$QUEUE"`). Re-reads the LIVE queue at rewrite time (a writer may have
+# enqueued while we were staging/pushing — those entries must survive; the old
+# truncation destroyed them) and keeps every line whose file is either
+# retained (privacy/mode-held) or not part of this drain at all. Atomic
+# tmp+mv in the same directory. Dropped-path detail goes to a 0600 sidecar so
+# the status line can stay content-free (counts only).
+rewrite_queue() {
+ local paths_file="$1" # staged (drained) paths, one per line
+ local class_file="$2" # classification JSON from compute_paths_to_stage
+ # Fail-open by design (a failed rewrite self-corrects next run: re-stage →
+ # nothing-to-commit), but say so — a silent failure here would let the
+ # subsequent "ok/idle" status claim a drain that did not happen.
+ python3 - "$QUEUE" "$paths_file" "$class_file" "$GSTACK_HOME/.brain-sync-drops.json" <<'PYEOF' || echo "BRAIN_SYNC: warning: queue rewrite failed — entries retained; next run re-drains" >&2
+import json, os, sys, time
+queue, paths_file, class_file, drops_file = sys.argv[1:5]
+
+def lines(path):
+ try:
+ with open(path) as f:
+ return [l.rstrip("\r\n") for l in f if l.strip()]
+ except FileNotFoundError:
+ return []
+
+staged = set(lines(paths_file))
+try:
+ with open(class_file) as f:
+ classified = json.load(f)
+except Exception:
+ classified = {"retained": [], "dropped": {}}
+retained = set(classified.get("retained", []))
+dropped = set()
+for group in (classified.get("dropped", {}) or {}).values():
+ dropped.update(group)
+processed = staged | dropped
+
+kept = []
+seen_lines = set()
+unparseable = 0
+# LIVE re-read narrows (not fully closes) the concurrent-append window: the
+# lockless enqueue can still land on the old inode between this read and the
+# os.replace below. Vastly better than the old whole-queue truncation.
+for line in lines(queue):
+ if line in seen_lines:
+ continue # identical duplicate lines collapse on rewrite
+ try:
+ p = json.loads(line).get("file")
+ except Exception:
+ unparseable += 1
+ kept.append(line) # unparseable line: keep, never destroy
+ seen_lines.add(line)
+ continue
+ if not isinstance(p, str) or p in retained or p not in processed:
+ kept.append(line)
+ seen_lines.add(line)
+if unparseable:
+ import sys as _sys
+ print(f"BRAIN_SYNC: {unparseable} unparseable queue line(s) held (inspect {queue})", file=_sys.stderr)
+
+tmp = queue + ".tmp." + str(os.getpid())
+with open(tmp, "w") as f:
+ for l in kept:
+ f.write(l + "\n")
+os.replace(tmp, queue)
+
+if dropped:
+ fd = os.open(drops_file, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
+ with os.fdopen(fd, "w") as f:
+ json.dump({"ts": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
+ "dropped": classified.get("dropped", {})}, f)
+PYEOF
+}
+
+# Human-readable classification counts for status messages.
+queue_summary() {
+ local class_file="$1"
+ python3 - "$class_file" <<'PYEOF' 2>/dev/null || echo ""
+import json, sys
+try:
+ with open(sys.argv[1]) as f:
+ c = json.load(f)
+except Exception:
+ print(""); sys.exit(0)
+d = c.get("dropped", {}) or {}
+parts = []
+r = len(c.get("retained", []))
+if r: parts.append(f"{r} privacy-held retained")
+for k in ("skipped", "unmatched", "missing", "invalid"):
+ n = len(d.get(k, []))
+ if n: parts.append(f"{n} {k} dropped")
+print("; ".join(parts))
+PYEOF
+}
+
subcmd_once() {
if ! sync_active; then
# Silent no-op when feature not initialized / disabled.
@@ -249,20 +366,90 @@ subcmd_once() {
fi
fi
echo "$$" > "$lock_dir/pid" 2>/dev/null || true
+ # Release the lock on EVERY exit from here on — including the empty-queue
+ # fast path and an INT during the detector's network push. Leaking it would
+ # rely on next-run stale-pid detection, which PID reuse can defeat (kill -0
+ # matching an unrelated live process wedges sync at every boundary). The
+ # mktemp block below re-traps with tempfile cleanup added; both traps keep
+ # the lock removal.
+ trap 'rm -rf "$lock_dir" 2>/dev/null || true' EXIT INT TERM
local mode
mode=$("$CONFIG_BIN" get artifacts_sync_mode 2>/dev/null || echo off)
- local paths_file
+ # #2549 unpushed-commit detector: a prior drain may have COMMITTED but
+ # failed to push (auth blip, offline). The data was never lost — it sits in
+ # a local commit — but nothing re-pushed it until NEW changes arrived.
+ # Retry the push up front, inside the lock. Receipted fail-closed like
+ # every other push; a receipt REFUSAL skips the retry without blocking the
+ # rest of the drain (local staging must not wedge on receipt problems).
+ # Guards: origin/<branch> may not exist yet (first sync, deleted remote).
+ #
+ # Throttled: the preamble runs --once at EVERY skill boundary, so an
+ # unthrottled retry would pay a full network push attempt per boundary in
+ # exactly the steady states this targets (offline, broken auth) — and a
+ # captive-portal push can block 30-75s against the header's "<1s when
+ # idle" promise. Attempts are recorded (success or fail) and retried at
+ # most every 10 minutes; the push itself never prompts for credentials and
+ # bounds stalled transfers via git's own low-speed limits (portable — stock
+ # macOS ships no `timeout` binary).
+ #
+ # Author-scoped — EXCLUSIVELY: `git push origin HEAD` publishes every
+ # unpushed commit, so the retry fires only when ALL unpushed commits are
+ # gstack-brain-sync's own. One interleaved user commit disables the
+ # auto-retry entirely (adversarial review: an existential check would
+ # silently auto-publish a user's manual ~/.gstack commit the moment a bot
+ # commit sat in front of it). User commits ride along when a REAL drain
+ # pushes, as before — the detector never publishes work it didn't create.
+ local det_branch det_unpushed det_total det_now det_last
+ det_branch=$(git -C "$GSTACK_HOME" rev-parse --abbrev-ref HEAD 2>/dev/null || echo "")
+ # Detached HEAD reads as the literal "HEAD" — origin/HEAD usually resolves,
+ # so without this exclusion the detector would retry a doomed push forever.
+ [ "$det_branch" = "HEAD" ] && det_branch=""
+ if [ -n "$det_branch" ] && git -C "$GSTACK_HOME" rev-parse --verify --quiet "origin/$det_branch" >/dev/null 2>&1; then
+ det_unpushed=$(git -C "$GSTACK_HOME" rev-list --count --author="gstack-brain-sync" "origin/$det_branch..HEAD" 2>/dev/null || echo 0)
+ det_total=$(git -C "$GSTACK_HOME" rev-list --count "origin/$det_branch..HEAD" 2>/dev/null || echo 0)
+ case "$det_unpushed" in ''|*[!0-9]*) det_unpushed=0 ;; esac
+ case "$det_total" in ''|*[!0-9]*) det_total=0 ;; esac
+ det_now=$(date +%s)
+ det_last=$(cat "$GSTACK_HOME/.brain-last-push-attempt" 2>/dev/null || echo 0)
+ case "$det_last" in ''|*[!0-9]*) det_last=0 ;; esac
+ if [ "$det_unpushed" -gt 0 ] && [ "$det_unpushed" -eq "$det_total" ] && [ $(( det_now - det_last )) -ge 600 ]; then
+ echo "$det_now" > "$GSTACK_HOME/.brain-last-push-attempt" 2>/dev/null || true
+ local det_host
+ det_host=$(remote_host)
+ if GSTACK_HOME="$GSTACK_HOME" _receipted_git closed brain-sync "$det_host" curated-memory-git-push "artifacts_sync_mode!=off" \
+ bash -c 'GIT_TERMINAL_PROMPT=0 git -c http.lowSpeedLimit=1024 -c http.lowSpeedTime=30 -C "$1" push origin HEAD 2>/dev/null' _ "$GSTACK_HOME"; then
+ date -u +%Y-%m-%dT%H:%M:%SZ > "$LAST_PUSH_FILE"
+ fi
+ fi
+ fi
+
+ # Empty-queue fast path: this is the steady state at every skill boundary.
+ # Skipping compute/rewrite here is safe — with zero queue lines there is
+ # nothing to classify, retain, or drop, and a concurrent append after this
+ # check simply waits for the next boundary. (The detector above already ran:
+ # its whole point is re-pushing stranded commits when the queue is empty.)
+ # The lock-release trap installed at acquisition covers this exit.
+ if [ ! -s "$QUEUE" ]; then
+ write_status "idle" "queue empty"
+ exit 0
+ fi
+
+ local paths_file class_file
paths_file=$(mktemp /tmp/brain-sync-paths.XXXXXX) || { rm -rf "$lock_dir" 2>/dev/null; write_status "error" "mktemp failed"; exit 1; }
- # Single trap covers both: lock cleanup AND tempfile cleanup.
- trap 'rm -f "$paths_file" 2>/dev/null; rm -rf "$lock_dir" 2>/dev/null || true' EXIT INT TERM
+ class_file=$(mktemp /tmp/brain-sync-class.XXXXXX) || { rm -f "$paths_file"; rm -rf "$lock_dir" 2>/dev/null; write_status "error" "mktemp failed"; exit 1; }
+ # Single trap covers all: lock cleanup AND tempfile cleanup.
+ trap 'rm -f "$paths_file" "$class_file" 2>/dev/null; rm -rf "$lock_dir" 2>/dev/null || true' EXIT INT TERM
- compute_paths_to_stage "$mode" > "$paths_file"
+ compute_paths_to_stage "$mode" "$class_file" > "$paths_file"
if [ ! -s "$paths_file" ]; then
- # Nothing to stage. Clear any stale queue entries and exit.
- : > "$QUEUE"
- write_status "idle" "no allowlisted changes in queue"
+ # Nothing stageable. Rewrite the queue (retained entries + concurrent
+ # appends survive; classified drops removed) instead of truncating it.
+ rewrite_queue "$paths_file" "$class_file"
+ local summary
+ summary=$(queue_summary "$class_file")
+ write_status "idle" "no stageable changes${summary:+ ($summary)}"
exit 0
fi
@@ -309,8 +496,9 @@ subcmd_once() {
local msg="sync: $n file(s) | $ts"
git -C "$GSTACK_HOME" -c user.email="gstack@localhost" -c user.name="gstack-brain-sync" \
commit -q -m "$msg" 2>/dev/null || {
- # Nothing to commit (e.g. all files already committed).
- : > "$QUEUE"
+ # Nothing to commit (e.g. all files already committed). The drained
+ # paths leave the queue; retained + concurrent entries survive (#2549).
+ rewrite_queue "$paths_file" "$class_file"
write_status "idle" "queue drained but no new changes to commit"
exit 0
}
@@ -322,10 +510,12 @@ subcmd_once() {
if echo "$push_err" | grep -qiE "auth|permission|403|401|forbidden"; then
local hint
hint=$(remote_auth_hint)
- write_status "push_failed" "push failed: auth error. fix: $hint"
+ write_status "push_failed" "push failed: auth error; commit retained locally, will retry next run. fix: $hint"
echo "BRAIN_SYNC: push failed: auth. fix: $hint" >&2
- # Queue cleared because the commit exists locally; next push will send it.
- : > "$QUEUE"
+ # Drained paths leave the queue — they live in the local commit, which
+ # the run-start detector re-pushes next time (#2549). Retained +
+ # concurrent entries survive the rewrite.
+ rewrite_queue "$paths_file" "$class_file"
exit 0
fi
@@ -339,20 +529,21 @@ subcmd_once() {
if git -C "$GSTACK_HOME" merge --no-edit "origin/$branch" >/dev/null 2>&1; then
if GSTACK_HOME="$GSTACK_HOME" _receipted_git closed brain-sync "$push_host" curated-memory-git-push "artifacts_sync_mode!=off" \
bash -c 'git -C "$1" push origin HEAD 2>/dev/null' _ "$GSTACK_HOME"; then
- : > "$QUEUE"
+ rewrite_queue "$paths_file" "$class_file"
date -u +%Y-%m-%dT%H:%M:%SZ > "$LAST_PUSH_FILE"
write_status "ok" "pushed $n file(s) after rebase"
exit 0
fi
fi
fi
- write_status "push_failed" "push failed: $(printf '%s' "$push_err" | head -1)"
- : > "$QUEUE"
+ # Commit exists locally; the run-start detector re-pushes it next time.
+ write_status "push_failed" "push failed: $(printf '%s' "$push_err" | head -1); commit retained locally, will retry next run"
+ rewrite_queue "$paths_file" "$class_file"
exit 0
}
- # Success: clear queue, update last-push.
- : > "$QUEUE"
+ # Success: drained paths leave the queue (retained + concurrent survive).
+ rewrite_queue "$paths_file" "$class_file"
date -u +%Y-%m-%dT%H:%M:%SZ > "$LAST_PUSH_FILE"
write_status "ok" "pushed $n file(s)"
exit 0
diff --git a/bin/gstack-codex-probe b/bin/gstack-codex-probe
index 940dacf84..2d151ef60 100755
--- a/bin/gstack-codex-probe
+++ b/bin/gstack-codex-probe
@@ -4,6 +4,7 @@
#
# Functions (all prefixed with _gstack_codex_ for namespace hygiene):
# _gstack_codex_auth_probe — multi-signal auth check (env + file)
+# _gstack_codex_model_probe — round-trip probe of the configured model (#2477)
# _gstack_codex_version_check — warn on known-bad Codex CLI versions
# _gstack_codex_timeout_wrapper — gtimeout -> timeout -> unwrapped fallback
# _gstack_codex_log_event — telemetry emission to ~/.gstack/analytics/
@@ -33,6 +34,92 @@ _gstack_codex_auth_probe() {
return 1
}
+# --- Model round-trip probe (#2477) ------------------------------------------
+
+_gstack_codex_model_probe() {
+ # Auth-exists is a weaker signal than the auth probe implies: a ChatGPT
+ # account with a stale `model = "..."` pin in ~/.codex/config.toml passes
+ # the auth probe, then EVERY invocation dies with an HTTP 400 ("The
+ # '<model>' model is not supported when using Codex with a ChatGPT
+ # account") and no guidance. A short real round trip with the configured
+ # model catches model rejection, entitlement changes, and stale pins in
+ # one shot (#2477).
+ #
+ # Contract:
+ # MODEL_OK (exit 0) — round trip succeeded; cached 1h.
+ # MODEL_UNUSABLE (exit 1) — deterministic model 400; hints printed.
+ # Cached 15 min: the 400 is config-driven, so re-probing every preflight
+ # charged the affected user a 30s round trip + real tokens per review
+ # section, forever. Editing config.toml (the fix) changes the cache
+ # signature and re-probes immediately; the short TTL covers server-side
+ # entitlement recovery the signature can't see.
+ # MODEL_PROBE_INCONCLUSIVE (exit 0) — timeout/transient; FAIL-OPEN so a
+ # slow network never wedges codex mode (the per-invocation Error
+ # Handling entry still covers a later 400). Never cached.
+ #
+ # Only call this AFTER _gstack_codex_auth_probe passes — probing without
+ # auth just measures the auth failure again.
+ local _codex_home="${CODEX_HOME:-$HOME/.codex}"
+ local _gstack_home="${GSTACK_HOME:-$HOME/.gstack}"
+ local _cache="$_gstack_home/.codex-model-probe"
+ # Cache signature: config.toml + auth.json mtimes. Editing the model pin
+ # or re-logging-in invalidates the cached MODEL_OK immediately.
+ # GNU-first stat order + numeric validation (the #2195 pattern): on GNU
+ # stat, `-f` means FILESYSTEM mode, so the BSD-first form emitted a
+ # multi-line filesystem block on Linux — the signature then never matched
+ # its own cache line and the cache missed on every read. BSD stat rejects
+ # `-c` cleanly, so GNU-first degrades correctly on macOS.
+ local _cfg_m _auth_m _sig
+ _cfg_m=$(stat -c %Y "$_codex_home/config.toml" 2>/dev/null || stat -f %m "$_codex_home/config.toml" 2>/dev/null || echo 0)
+ _auth_m=$(stat -c %Y "$_codex_home/auth.json" 2>/dev/null || stat -f %m "$_codex_home/auth.json" 2>/dev/null || echo 0)
+ case "$_cfg_m" in ''|*[!0-9]*) _cfg_m=0 ;; esac
+ case "$_auth_m" in ''|*[!0-9]*) _auth_m=0 ;; esac
+ _sig="${_cfg_m}-${_auth_m}"
+ local _now
+ _now=$(date +%s 2>/dev/null || echo 0)
+ if [ -f "$_cache" ]; then
+ local _c_line _c_status _c_ts _c_sig
+ _c_line=$(head -1 "$_cache" 2>/dev/null)
+ _c_status=$(printf '%s' "$_c_line" | cut -d' ' -f1)
+ _c_ts=$(printf '%s' "$_c_line" | cut -d' ' -f2)
+ _c_sig=$(printf '%s' "$_c_line" | cut -d' ' -f3)
+ case "$_c_ts" in ''|*[!0-9]*) _c_ts=0 ;; esac
+ if [ "$_c_status" = "MODEL_OK" ] && [ "$_c_sig" = "$_sig" ] && [ $((_now - _c_ts)) -lt 3600 ]; then
+ echo "MODEL_OK (cached)"
+ return 0
+ fi
+ if [ "$_c_status" = "MODEL_UNUSABLE" ] && [ "$_c_sig" = "$_sig" ] && [ $((_now - _c_ts)) -lt 900 ]; then
+ echo "MODEL_UNUSABLE (cached)"
+ echo "HINT: the rejected model comes from the 'model = ' line in $_codex_home/config.toml."
+ echo "HINT: check its [notice.model_migrations] table — Codex records the intended replacement there."
+ return 1
+ fi
+ fi
+ local _out _code
+ _out=$(_gstack_codex_timeout_wrapper 30 codex exec --skip-git-repo-check -s read-only "reply OK" </dev/null 2>&1)
+ _code=$?
+ if [ "$_code" -eq 0 ]; then
+ mkdir -p "$_gstack_home" 2>/dev/null || true
+ printf 'MODEL_OK %s %s\n' "$_now" "$_sig" > "$_cache" 2>/dev/null || true
+ echo "MODEL_OK"
+ return 0
+ fi
+ if printf '%s' "$_out" | grep -qiE 'model.{0,40}is not supported|"status":[[:space:]]*400'; then
+ mkdir -p "$_gstack_home" 2>/dev/null || true
+ printf 'MODEL_UNUSABLE %s %s\n' "$_now" "$_sig" > "$_cache" 2>/dev/null || true
+ echo "MODEL_UNUSABLE"
+ printf '%s\n' "$_out" | grep -i "model" | head -3
+ echo "HINT: the rejected model comes from the 'model = ' line in $_codex_home/config.toml."
+ echo "HINT: check its [notice.model_migrations] table — Codex records the intended replacement there."
+ _gstack_codex_log_event "codex_model_unusable" 2>/dev/null || true
+ return 1
+ fi
+ # Timeout (124) or transient failure: fail-open with a warning. The probe
+ # exists to catch the deterministic model 400, not to gate on network luck.
+ echo "MODEL_PROBE_INCONCLUSIVE (exit $_code) — proceeding; if invocations fail with a model 400, see the codex skill's Error Handling entry."
+ return 0
+}
+
# --- Version check ----------------------------------------------------------
_gstack_codex_version_check() {
@@ -53,8 +140,8 @@ _gstack_codex_version_check() {
_gstack_codex_timeout_wrapper() {
# Resolve wrapper binary: prefer gtimeout (Homebrew coreutils on macOS),
- # fall back to timeout (Linux), else run unwrapped. Arguments: $1 is the
- # duration in seconds; rest is the command to run.
+ # fall back to timeout (Linux), else a bash-native watchdog. Arguments:
+ # $1 is the duration in seconds; rest is the command to run.
local _duration="$1"
shift
local _to
@@ -62,7 +149,29 @@ _gstack_codex_timeout_wrapper() {
if [ -n "$_to" ]; then
"$_to" "$_duration" "$@"
else
- "$@"
+ # Stock macOS ships neither coreutils gtimeout nor timeout(1); running
+ # unwrapped let a hung `codex exec` block the probe — and the calling
+ # workflow — indefinitely. Emulate: background the command, TERM it at
+ # the deadline, mirror timeout(1)'s exit-124 contract. The watchdog's
+ # stdout is detached so an early finish never blocks a caller's $(...)
+ # capture on the orphaned sleep.
+ "$@" &
+ local _cmd_pid=$!
+ ( sleep "$_duration" && kill -TERM "$_cmd_pid" 2>/dev/null ) >/dev/null 2>&1 &
+ local _watch_pid=$!
+ local _rc
+ wait "$_cmd_pid"
+ _rc=$?
+ if kill -0 "$_watch_pid" 2>/dev/null; then
+ # Command finished before the deadline. Retiring the watchdog subshell
+ # also defuses its pending kill (the `&& kill` lives in the subshell);
+ # its detached sleep expires harmlessly.
+ kill "$_watch_pid" 2>/dev/null
+ wait "$_watch_pid" 2>/dev/null
+ elif [ "$_rc" -ge 128 ]; then
+ _rc=124 # killed by the watchdog: report timeout(1)'s code
+ fi
+ return "$_rc"
fi
}
@@ -72,7 +181,7 @@ _gstack_codex_log_event() {
# Emit a telemetry event to ~/.gstack/analytics/skill-usage.jsonl.
# Gated on $_TEL != "off" (caller sets this from gstack-config).
# Event types: codex_timeout, codex_auth_failed, codex_cli_missing,
- # codex_version_warning.
+ # codex_version_warning, codex_model_unusable.
# Payload schema: {skill, event, duration_s, ts}. NEVER includes prompt
# content, env var values, or auth tokens.
local _event="$1"
diff --git a/bin/gstack-config b/bin/gstack-config
index 575f93523..b8adf9c25 100755
--- a/bin/gstack-config
+++ b/bin/gstack-config
@@ -17,6 +17,21 @@ set -euo pipefail
STATE_DIR="${GSTACK_STATE_ROOT:-${GSTACK_HOME:-${GSTACK_STATE_DIR:-$HOME/.gstack}}}"
CONFIG_FILE="$STATE_DIR/config.yaml"
+# Swap a freshly-rendered tmp dir into the live render location (#2569
+# hardening). Installed skills SYMLINK into the live dir, so it is only ever
+# replaced AFTER a successful render — a failed render leaves the previous
+# render (and every link into it) fully intact. Keep in sync with setup's
+# _swap_in_render (same contract, both pinned by
+# test/user-render-out-dir-install.test.ts).
+_swap_in_render() {
+ local render_dir="$1" render_tmp="$2"
+ local render_old="$render_dir.old.$$"
+ rm -rf "$render_old"
+ if [ -e "$render_dir" ] || [ -L "$render_dir" ]; then mv "$render_dir" "$render_old"; fi
+ mv "$render_tmp" "$render_dir"
+ rm -rf "$render_old"
+}
+
# Annotated header for new config files. Written once on first `set`.
# Default semantics: DEFAULTS table below is the canonical source. Header text
# is documentation that must stay in sync with DEFAULTS.
@@ -434,33 +449,55 @@ case "${1:-}" in
fi
case "$STATUS" in
- ok|timeout|thin-client)
+ ok|timeout|thin-client|engine-locked)
# "timeout" = slow-but-healthy engine (#1964); "thin-client" =
- # remote-HTTP MCP brain, no local engine by design (#2051) — same
- # treatment as "ok", matching gstack-gbrain-detect --is-ok and
- # gen-skill-docs.
+ # remote-HTTP MCP brain, no local engine by design (#2051);
+ # "engine-locked" = same class (#2456): PGLite is single-writer, so a
+ # live `gbrain serve` (typically an MCP server) holds the embedded DB.
+ # gbrain is installed and healthy; a transient lock must not strip
+ # brain blocks out of every SKILL.md. All get the same treatment as
+ # "ok", matching gstack-gbrain-detect --is-ok and gen-skill-docs.
echo "Detected gbrain v$VERSION (local-status: $STATUS)."
- # Render brain-aware blocks INTO the global install so EVERY project's
- # Claude sessions get them (other projects read SKILL.md + sections from
- # ~/.claude/skills/gstack via absolute paths baked at gen time). Guards
- # (never mutate an arbitrary directory): the target must exist, not be a
- # symlink (a symlinked install points at a dev worktree — rendering there
- # would dirty tracked source), and look like a real gstack clone.
+ # Render brain-aware blocks into an UNTRACKED out-dir (#2569) and
+ # repoint the installed skills at it — the old in-place render wrote
+ # into TRACKED files of the global install checkout, so the checkout
+ # stayed permanently dirty and every upgrade grew a redundant stash.
+ # Guards (never mutate an arbitrary directory): the install must
+ # exist, not be a symlink (a symlinked install points at a dev
+ # worktree — bin/dev-setup owns that flow), and look like a real
+ # gstack clone.
INSTALL_DIR="$HOME/.claude/skills/gstack"
+ RENDER_DIR="${GSTACK_USER_RENDER_DIR:-${GSTACK_HOME:-$HOME/.gstack}/render/claude}"
if [ ! -d "$INSTALL_DIR" ]; then
echo "No global install at $INSTALL_DIR — nothing to render. (Dev workspaces get blocks via bin/dev-setup.)"
elif [ -L "$INSTALL_DIR" ]; then
- echo "Skip: $INSTALL_DIR is a symlink (likely a dev worktree). Rendering there would dirty tracked source — run bin/dev-setup in that worktree instead."
+ echo "Skip: $INSTALL_DIR is a symlink (likely a dev worktree). Run bin/dev-setup in that worktree instead."
elif [ ! -f "$INSTALL_DIR/VERSION" ] || [ ! -f "$INSTALL_DIR/package.json" ]; then
echo "Skip: $INSTALL_DIR doesn't look like a gstack clone (missing VERSION/package.json) — refusing to modify it."
elif ! command -v bun >/dev/null 2>&1; then
echo "Skip: bun not on PATH — can't render. Install bun, then re-run 'gstack-config gbrain-refresh'."
- elif ( cd "$INSTALL_DIR" && bun run gen:skill-docs:user --host claude >/dev/null 2>&1 ); then
- echo "Rendered brain-aware blocks into $INSTALL_DIR — now live across all your projects' Claude sessions."
- echo "Note: this dirties the install's git tree (generated blocks differ from main, by design)."
- echo " A 'git reset --hard origin/main' there reverts them; re-run 'gstack-config gbrain-refresh' to restore."
else
- echo "Warning: render failed. Run 'cd $INSTALL_DIR && bun run gen:skill-docs:user --host claude' manually to see the error."
+ # Render into a tmp dir and swap it in only on SUCCESS. Installed
+ # skills SYMLINK into $RENDER_DIR (gstack-relink prefers it), so
+ # wiping it before the render meant one transient failure (bun
+ # error, disk full, broken template) left every brain-aware
+ # SKILL.md link dangling — the whole skill set vanished from
+ # Claude Code until a successful re-render. A failed render now
+ # leaves the previous render fully intact.
+ RENDER_TMP="$RENDER_DIR.tmp.$$"
+ rm -rf "$RENDER_TMP"
+ if ( cd "$INSTALL_DIR" && bun run gen:skill-docs:user --host claude --out-dir "$RENDER_TMP" >/dev/null 2>&1 ); then
+ _swap_in_render "$RENDER_DIR" "$RENDER_TMP"
+ # Repoint installed skills at the render — gstack-relink prefers
+ # the render dir when present.
+ "$INSTALL_DIR/bin/gstack-relink" >/dev/null 2>&1 || true
+ echo "Rendered brain-aware blocks into $RENDER_DIR — now live across all your projects' Claude sessions."
+ echo "The install checkout stays clean: upgrades no longer stash generated render dirt (#2569)."
+ else
+ rm -rf "$RENDER_TMP"
+ echo "Warning: render failed — previous render (if any) left in place, links stay valid."
+ echo "Run 'cd $INSTALL_DIR && bun run gen:skill-docs:user --host claude --out-dir $RENDER_DIR' manually to see the error."
+ fi
fi
;;
*)
diff --git a/bin/gstack-diff-scope b/bin/gstack-diff-scope
index 38450e6b1..17da9c656 100755
--- a/bin/gstack-diff-scope
+++ b/bin/gstack-diff-scope
@@ -2,6 +2,24 @@
# gstack-diff-scope — categorize what changed in the diff against a base branch
# Usage: source <(gstack-diff-scope main) → sets SCOPE_FRONTEND=true SCOPE_BACKEND=false ...
# Or: gstack-diff-scope main → prints SCOPE_*=... lines
+#
+# Output contract (#2526 — all-false must be distinguishable from "we could
+# not look" and from "nothing matched"):
+# exit 0 changed-file set empty → all false, legitimately nothing
+# exit 0 changed files, >=1 category match → flags
+# exit 2 changed files, ZERO matches → flags + SCOPE_ERROR=unmatched
+# (+ the unmatched paths as comment lines, so a new top-level layout
+# trips loudly instead of silently disabling reviewers)
+# exit 2 base ref unresolvable → all false + SCOPE_ERROR=no_base
+# (shallow CI checkout / missing fetch — a green here would mean
+# "we could not look")
+# Every line is shell-safe for `source <(...)` consumers: assignments or
+# `#`-comments only.
+#
+# The changed-file set is the UNION of committed diff + working tree +
+# untracked files (#2299): /ship detects scope in Step 9, BEFORE it commits in
+# Step 15, so uncommitted work must be visible or every scope-gated reviewer
+# is skipped on the common start-work-then-ship flow.
set -euo pipefail
# Detect the repo's default branch when no arg is given (#703-class
@@ -14,22 +32,6 @@ _default_base() {
}
BASE="${1:-$(_default_base)}"
-# Get changed file list
-FILES=$(git diff "${BASE}...HEAD" --name-only 2>/dev/null || git diff "${BASE}" --name-only 2>/dev/null || echo "")
-
-if [ -z "$FILES" ]; then
- echo "SCOPE_FRONTEND=false"
- echo "SCOPE_BACKEND=false"
- echo "SCOPE_PROMPTS=false"
- echo "SCOPE_TESTS=false"
- echo "SCOPE_DOCS=false"
- echo "SCOPE_CONFIG=false"
- echo "SCOPE_MIGRATIONS=false"
- echo "SCOPE_API=false"
- echo "SCOPE_AUTH=false"
- exit 0
-fi
-
FRONTEND=false
BACKEND=false
PROMPTS=false
@@ -40,62 +42,162 @@ MIGRATIONS=false
API=false
AUTH=false
-while IFS= read -r f; do
+_print_flags() {
+ echo "SCOPE_FRONTEND=$FRONTEND"
+ echo "SCOPE_BACKEND=$BACKEND"
+ echo "SCOPE_PROMPTS=$PROMPTS"
+ echo "SCOPE_TESTS=$TESTS"
+ echo "SCOPE_DOCS=$DOCS"
+ echo "SCOPE_CONFIG=$CONFIG"
+ echo "SCOPE_MIGRATIONS=$MIGRATIONS"
+ echo "SCOPE_API=$API"
+ echo "SCOPE_AUTH=$AUTH"
+}
+
+# Base reachability (#2526): a shallow CI checkout or an unfetched ref makes
+# `git diff` return an empty list — all-false with exit 0, a green that means
+# "we could not look". Distinguish it before diffing.
+if ! git rev-parse --verify -q "${BASE}^{commit}" >/dev/null 2>&1; then
+ _print_flags
+ echo "SCOPE_ERROR=no_base"
+ echo "# base ref '${BASE}' is not resolvable — shallow checkout or missing fetch. Run: git fetch origin ${BASE}"
+ exit 2
+fi
+
+# Changed files, NUL-delimited (#2526 minor: `git diff --name-only` octal-quotes
+# non-ASCII paths, and the trailing quote defeats extension globs; -z avoids it).
+FILES_LIST=()
+_collect() {
+ local f
+ while IFS= read -r -d '' f; do
+ [ -n "$f" ] && FILES_LIST+=("$f")
+ done
+}
+# Committed diff vs base (merge-base form; two-dot fallback when no merge base).
+_collect < <(git diff -z "${BASE}...HEAD" --name-only 2>/dev/null || git diff -z "${BASE}" --name-only 2>/dev/null || true)
+# Working-tree changes (staged + unstaged). `git diff HEAD` fails on a repo
+# with no commits; tolerated.
+_collect < <(git diff -z HEAD --name-only 2>/dev/null || true)
+# Untracked files: a brand-new component/migration/test is exactly what a
+# reviewer should see, and /ship commits it in Step 15 regardless.
+_collect < <(git ls-files -z --others --exclude-standard 2>/dev/null || true)
+
+if [ "${#FILES_LIST[@]}" -eq 0 ]; then
+ _print_flags
+ exit 0
+fi
+
+UNMATCHED=()
+
+# Categories are INDEPENDENT booleans (#2299): a single first-match-wins case
+# made them mutually exclusive, so Button.test.jsx set FRONTEND but not TESTS
+# while util.test.ts set TESTS but not BACKEND — same intent, opposite result,
+# purely from arm ordering. Each category now gets its own case; only BACKEND
+# stays deliberately exclusive of frontend component/view files.
+for f in ${FILES_LIST[@]+"${FILES_LIST[@]}"}; do
+ m_frontend=false; m_prompts=false; m_tests=false; m_docs=false
+ m_config=false; m_migrations=false; m_api=false; m_auth=false; m_backend=false
+
+ # Frontend: CSS, views, components, templates
+ case "$f" in
+ *.css|*.scss|*.less|*.sass|*.pcss) m_frontend=true ;;
+ *.tsx|*.jsx|*.vue|*.svelte|*.astro) m_frontend=true ;;
+ *.erb|*.haml|*.slim|*.hbs|*.ejs) m_frontend=true ;;
+ *.html) m_frontend=true ;;
+ tailwind.config.*|postcss.config.*) m_frontend=true ;;
+ app/views/*|*/components/*|styles/*|css/*|app/assets/stylesheets/*) m_frontend=true ;;
+ esac
+
+ # Prompts: prompt builders, system prompts, generation services
case "$f" in
- # Frontend: CSS, views, components, templates
- *.css|*.scss|*.less|*.sass|*.pcss|*.module.css|*.module.scss) FRONTEND=true ;;
- *.tsx|*.jsx|*.vue|*.svelte|*.astro) FRONTEND=true ;;
- *.erb|*.haml|*.slim|*.hbs|*.ejs) FRONTEND=true ;;
- *.html) FRONTEND=true ;;
- tailwind.config.*|postcss.config.*) FRONTEND=true ;;
- app/views/*|*/components/*|styles/*|css/*|app/assets/stylesheets/*) FRONTEND=true ;;
-
- # Prompts: prompt builders, system prompts, generation services
- *prompt_builder*|*generation_service*|*writer_service*|*designer_service*) PROMPTS=true ;;
- *evaluator*|*scorer*|*classifier_service*|*analyzer*) PROMPTS=true ;;
- *voice*.rb|*writing*.rb|*prompt*.rb|*token*.rb) PROMPTS=true ;;
- app/services/chat_tools/*|app/services/x_thread_tools/*) PROMPTS=true ;;
- config/system_prompts/*) PROMPTS=true ;;
-
- # Tests
- *.test.*|*.spec.*|*_test.*|*_spec.*) TESTS=true ;;
- test/*|tests/*|spec/*|__tests__/*|cypress/*|e2e/*) TESTS=true ;;
-
- # Docs
- *.md) DOCS=true ;;
-
- # Config
- package.json|package-lock.json|yarn.lock|bun.lock|bun.lockb) CONFIG=true ;;
- Gemfile|Gemfile.lock) CONFIG=true ;;
- *.yml|*.yaml) CONFIG=true ;;
- .github/*) CONFIG=true ;;
- requirements.txt|pyproject.toml|go.mod|Cargo.toml|composer.json) CONFIG=true ;;
-
- # Migrations: database migration files
- db/migrate/*|*/migrations/*|alembic/*|prisma/migrations/*) MIGRATIONS=true ;;
-
- # API: routes, controllers, endpoints, GraphQL/OpenAPI schemas
- *controller*|*route*|*endpoint*|*/api/*) API=true ;;
- *.graphql|*.gql|openapi.*|swagger.*) API=true ;;
-
- # Auth: authentication, authorization, sessions, permissions
- *auth*|*session*|*jwt*|*oauth*|*permission*|*role*) AUTH=true ;;
-
- # Backend: everything else that's code (excluding views/components already matched)
- *.rb|*.py|*.go|*.rs|*.java|*.php|*.ex|*.exs) BACKEND=true ;;
- # Non-component TS/JS is backend. Include ESM/CJS (.mjs/.cjs) and
- # explicit-module TS (.mts/.cts) — #1810: these matched no category, so an
- # ESM/CJS-only PR skipped the backend reviewer entirely.
- *.ts|*.js|*.mjs|*.cjs|*.mts|*.cts) BACKEND=true ;;
+ *prompt_builder*|*generation_service*|*writer_service*|*designer_service*) m_prompts=true ;;
+ *evaluator*|*scorer*|*classifier_service*|*analyzer*) m_prompts=true ;;
+ *voice*.rb|*writing*.rb|*prompt*.rb|*token*.rb) m_prompts=true ;;
+ app/services/chat_tools/*|app/services/x_thread_tools/*) m_prompts=true ;;
+ config/system_prompts/*) m_prompts=true ;;
esac
-done <<< "$FILES"
-
-echo "SCOPE_FRONTEND=$FRONTEND"
-echo "SCOPE_BACKEND=$BACKEND"
-echo "SCOPE_PROMPTS=$PROMPTS"
-echo "SCOPE_TESTS=$TESTS"
-echo "SCOPE_DOCS=$DOCS"
-echo "SCOPE_CONFIG=$CONFIG"
-echo "SCOPE_MIGRATIONS=$MIGRATIONS"
-echo "SCOPE_API=$API"
-echo "SCOPE_AUTH=$AUTH"
+
+ # Tests
+ case "$f" in
+ *.test.*|*.spec.*|*_test.*|*_spec.*) m_tests=true ;;
+ test/*|tests/*|spec/*|__tests__/*|cypress/*|e2e/*) m_tests=true ;;
+ esac
+
+ # Docs
+ case "$f" in
+ *.md) m_docs=true ;;
+ esac
+
+ # Config
+ case "$f" in
+ package.json|package-lock.json|yarn.lock|bun.lock|bun.lockb) m_config=true ;;
+ Gemfile|Gemfile.lock) m_config=true ;;
+ *.yml|*.yaml) m_config=true ;;
+ .github/*) m_config=true ;;
+ requirements.txt|pyproject.toml|go.mod|Cargo.toml|composer.json) m_config=true ;;
+ esac
+
+ # Migrations: database migration files. Bare migrations/* covers a
+ # root-level migrations dir (#2526); db/data covers the Rails data_migrate
+ # gem's DATA migrations (#2455) — arbitrary Ruby run unattended against
+ # production data, strictly higher-risk than a schema migration (they also
+ # match BACKEND below via their extension, as ordinary app code should).
+ case "$f" in
+ db/migrate/*|migrations/*|*/migrations/*|alembic/*|prisma/migrations/*) m_migrations=true ;;
+ db/data/*|data_migrations/*|*/data_migrations/*) m_migrations=true ;;
+ esac
+
+ # API: routes, controllers, endpoints, GraphQL/OpenAPI schemas. Bare api/*
+ # covers root-level serverless layouts (Vercel functions, Next.js pages/api
+ # at root) that */api/* silently missed (#2526).
+ case "$f" in
+ api/*|*/api/*|*controller*|*route*|*endpoint*) m_api=true ;;
+ *.graphql|*.gql|openapi.*|swagger.*) m_api=true ;;
+ esac
+
+ # Auth: authentication, authorization, sessions, permissions
+ case "$f" in
+ *auth*|*session*|*jwt*|*oauth*|*permission*|*role*) m_auth=true ;;
+ esac
+
+ # Backend: code that isn't a frontend component/view file. Includes ESM/CJS
+ # (.mjs/.cjs) and explicit-module TS (.mts/.cts) — #1810: these matched no
+ # category, so an ESM/CJS-only PR skipped the backend reviewer entirely.
+ if [ "$m_frontend" = false ]; then
+ case "$f" in
+ *.rb|*.py|*.go|*.rs|*.java|*.php|*.ex|*.exs) m_backend=true ;;
+ *.ts|*.js|*.mjs|*.cjs|*.mts|*.cts) m_backend=true ;;
+ esac
+ fi
+
+ [ "$m_frontend" = true ] && FRONTEND=true
+ [ "$m_prompts" = true ] && PROMPTS=true
+ [ "$m_tests" = true ] && TESTS=true
+ [ "$m_docs" = true ] && DOCS=true
+ [ "$m_config" = true ] && CONFIG=true
+ [ "$m_migrations" = true ] && MIGRATIONS=true
+ [ "$m_api" = true ] && API=true
+ [ "$m_auth" = true ] && AUTH=true
+ [ "$m_backend" = true ] && BACKEND=true
+
+ if [ "$m_frontend" = false ] && [ "$m_prompts" = false ] && [ "$m_tests" = false ] \
+ && [ "$m_docs" = false ] && [ "$m_config" = false ] && [ "$m_migrations" = false ] \
+ && [ "$m_api" = false ] && [ "$m_auth" = false ] && [ "$m_backend" = false ]; then
+ UNMATCHED+=("$f")
+ fi
+done
+
+_print_flags
+
+# Changed files but ZERO category matches (#2526): a classifier bug, an
+# unrecognised layout, or a new top-level directory would otherwise present
+# as "no reviewers needed" with the skip invisible. Trip loudly instead.
+if [ "$FRONTEND" = false ] && [ "$BACKEND" = false ] && [ "$PROMPTS" = false ] \
+ && [ "$TESTS" = false ] && [ "$DOCS" = false ] && [ "$CONFIG" = false ] \
+ && [ "$MIGRATIONS" = false ] && [ "$API" = false ] && [ "$AUTH" = false ]; then
+ echo "SCOPE_ERROR=unmatched"
+ printf '%s\n' ${UNMATCHED[@]+"${UNMATCHED[@]}"} | sort -u | head -50 | while IFS= read -r u; do
+ [ -n "$u" ] && printf '# unmatched: %s\n' "$u"
+ done
+ exit 2
+fi
diff --git a/bin/gstack-gbrain-detect b/bin/gstack-gbrain-detect
index 19797a495..3774f6bac 100755
--- a/bin/gstack-gbrain-detect
+++ b/bin/gstack-gbrain-detect
@@ -43,18 +43,17 @@ import {
resolveGbrainBin,
readGbrainVersion,
} from "../lib/gbrain-local-status";
-import { isTransactionModePooler } from "../lib/gbrain-exec";
+import { gbrainConfigDir, isTransactionModePooler } from "../lib/gbrain-exec";
const STATE_DIR = process.env.GSTACK_HOME || join(userHome(), ".gstack");
const SCRIPT_DIR = __dirname;
const CONFIG_BIN = join(SCRIPT_DIR, "gstack-config");
-// Honors GBRAIN_HOME — must stay consistent with lib/gbrain-local-status's
-// config resolution, or the detect JSON reports gbrain_local_status "ok"
-// alongside gbrain_config_exists false for relocated-home users.
-const GBRAIN_CONFIG = join(
- process.env.GBRAIN_HOME || join(userHome(), ".gbrain"),
- "config.json",
-);
+// Honors GBRAIN_HOME with gbrain's own configDir() semantics (#2521:
+// GBRAIN_HOME is a parent dir, `.gbrain` is appended) — must stay consistent
+// with lib/gbrain-local-status's config resolution, or the detect JSON
+// reports gbrain_local_status "ok" alongside gbrain_config_exists false for
+// relocated-home users. Both route through gbrainConfigDir.
+const GBRAIN_CONFIG = join(gbrainConfigDir(), "config.json");
const CLAUDE_JSON = join(userHome(), ".claude.json");
function userHome(): string {
@@ -232,8 +231,7 @@ function detectMcpMode(): "local-stdio" | "remote-http" | "none" {
/** remote_mcp.mcp_url from gbrain's own config (thin-client marker, #2051). */
function readRemoteMcpUrl(): string {
- const gbrainHome = process.env.GBRAIN_HOME || join(userHome(), ".gbrain");
- const cfg = tryReadJSON(join(gbrainHome, "config.json")) as
+ const cfg = tryReadJSON(join(gbrainConfigDir(), "config.json")) as
| { remote_mcp?: { mcp_url?: string } }
| null;
return cfg?.remote_mcp?.mcp_url || "";
@@ -288,17 +286,23 @@ function main(): void {
}
// --is-ok: live engine-status gate. Exits 0 iff gbrain is usable ("ok";
-// "timeout" — a slow-but-healthy engine, #1964; or "thin-client" — remote-HTTP
-// MCP brain with no local engine by design, #2051 — neither slow nor remote
-// must silently suppress brain features), 1 otherwise. Runs detection live
-// (never reads the possibly-stale gbrain-detection.json), so callers — setup,
-// bin/dev-setup, and `gstack-config gbrain-refresh` — can decide whether to
-// render the gbrain :user variant without duplicating the JSON grep.
-// Prints nothing on stdout.
+// "timeout" — a slow-but-healthy engine, #1964; "thin-client" — remote-HTTP
+// MCP brain with no local engine by design, #2051; or "engine-locked" —
+// PGLite is single-writer, so a live `gbrain serve` (typically an MCP
+// server) holds the embedded DB, #2456 — gbrain is installed and healthy in
+// all four; none must silently suppress brain features), 1 otherwise. Runs
+// detection live (never reads the possibly-stale gbrain-detection.json), so
+// callers — setup, bin/dev-setup, and `gstack-config gbrain-refresh` — can
+// decide whether to render the gbrain :user variant without duplicating the
+// JSON grep. Prints nothing on stdout.
if (process.argv.includes("--is-ok")) {
const noCache = process.env.GSTACK_DETECT_NO_CACHE === "1";
const status = localEngineStatus({ noCache });
- process.exit(status === "ok" || status === "timeout" || status === "thin-client" ? 0 : 1);
+ process.exit(
+ status === "ok" || status === "timeout" || status === "thin-client" || status === "engine-locked"
+ ? 0
+ : 1,
+ );
}
main();
diff --git a/bin/gstack-gbrain-install b/bin/gstack-gbrain-install
index 60c8f86b6..84091c236 100755
--- a/bin/gstack-gbrain-install
+++ b/bin/gstack-gbrain-install
@@ -84,7 +84,14 @@ if ! $VALIDATE_ONLY; then
# GitHub reachability — fail fast if offline rather than hanging `git clone`.
# --max-time 10, --head (no body), quiet. Status code 200-4xx means we reached
# the server (even 404 is reachability proof).
- if ! curl -s --head --max-time 10 https://github.com >/dev/null 2>&1; then
+ #
+ # Skipped under --dry-run: a dry run prints a plan and exits without ever
+ # cloning, so requiring the network buys nothing and costs a real failure mode.
+ # It made `--dry-run` fail (exit 3, "cannot reach https://github.com") whenever
+ # the curl lost a race for sockets/DNS — reproducible at ~15% by running 60
+ # dry-runs concurrently, and the cause of intermittent red in the D5 tests,
+ # which call this exact path.
+ if ! $DRY_RUN && ! curl -s --head --max-time 10 https://github.com >/dev/null 2>&1; then
fail "cannot reach https://github.com. Check your network and try again."
fi
fi
@@ -168,6 +175,26 @@ if ! $VALIDATE_ONLY; then
( cd "$INSTALL_DIR" && bun link --silent )
fi
+# #2487: an npm-installed bun (`npm i -g bun`) puts a POSIX script + .cmd/.ps1
+# shims on %PATH% but never bun.exe — and the gbrain.exe shim that `bun link`
+# generates resolves bun.exe SPECIFICALLY. Link "succeeds", then every gbrain
+# call dies with bun's misleading "bun is not installed in %PATH%" (suggesting
+# a second parallel bun install). Detect the condition and name the real fix:
+# bun's own process.execPath IS the hidden bun.exe.
+_bun_exe_hint() {
+ [ "$IS_WINDOWS" -eq 1 ] || return 0
+ command -v bun.exe >/dev/null 2>&1 && return 0
+ local real_bun
+ real_bun=$(bun -e 'console.log(process.execPath)' 2>/dev/null | tr -d '\r' || true)
+ echo " detected: bun was installed via npm — bun.exe is NOT on %PATH%, and the gbrain.exe shim needs it." >&2
+ if [ -n "$real_bun" ]; then
+ echo " fix: add bun.exe's directory to PATH (persist it in your shell profile):" >&2
+ echo " export PATH=\"$(dirname "$real_bun"):\$PATH\"" >&2
+ else
+ echo " fix: install bun via the official installer (https://bun.sh) or add the directory containing bun.exe to %PATH%." >&2
+ fi
+}
+
# --- D19 PATH-shadowing validation ---
# Read the version from the install-dir's package.json; compare to
# `gbrain --version`. If they disagree, PATH is returning a DIFFERENT
@@ -178,11 +205,13 @@ if [ -z "$expected_version" ]; then
fi
if ! command -v gbrain >/dev/null 2>&1; then
+ _bun_exe_hint
fail "bun link completed but 'gbrain' is not on PATH. Ensure ~/.bun/bin is in your PATH."
fi
actual_version=$(gbrain --version 2>/dev/null | head -1 | awk '{print $NF}' | tr -d '[:space:]' || true)
if [ -z "$actual_version" ]; then
+ _bun_exe_hint
fail "gbrain is on PATH but 'gbrain --version' produced no output — the binary may be broken."
fi
@@ -235,7 +264,14 @@ fi
# a hard gate so a broken gbrain is caught at setup, not at data-loss time.
# Pre-init installs skip this (config not written yet); the full
# `/sync-gbrain --dry-run` self-test runs from /setup-gbrain after `gbrain init`.
-_GBRAIN_HOME_CHECK="${GBRAIN_HOME:-$HOME/.gbrain}"
+# #2521: GBRAIN_HOME is a PARENT dir per gbrain's configDir() contract —
+# gbrain appends `.gbrain` itself, so the config lives at
+# $GBRAIN_HOME/.gbrain/config.json (or ~/.gbrain/config.json when unset).
+if [ -n "${GBRAIN_HOME:-}" ]; then
+ _GBRAIN_HOME_CHECK="$GBRAIN_HOME/.gbrain"
+else
+ _GBRAIN_HOME_CHECK="$HOME/.gbrain"
+fi
if [ -f "$_GBRAIN_HOME_CHECK/config.json" ]; then
if ! gbrain doctor --fast >/dev/null 2>&1; then
echo "" >&2
diff --git a/bin/gstack-gbrain-sync.ts b/bin/gstack-gbrain-sync.ts
index 4cf6709df..4e3034b3a 100644
--- a/bin/gstack-gbrain-sync.ts
+++ b/bin/gstack-gbrain-sync.ts
@@ -29,7 +29,7 @@
* than building a gstack-side daemon.
*/
-import { existsSync, statSync, mkdirSync, writeFileSync, readFileSync, unlinkSync, renameSync } from "fs";
+import { existsSync, statSync, mkdirSync, writeFileSync, readFileSync, unlinkSync, renameSync, realpathSync } from "fs";
import { join, dirname } from "path";
import { execSync, spawnSync } from "child_process";
import { homedir, hostname } from "os";
@@ -41,7 +41,7 @@ import { ensureSourceRegistered, sourcePageCount, parseSourcesList, cycleComplet
import { detectAutopilot, decideSourceRemove, decideCodeSync } from "../lib/gbrain-guards";
import { writeReceipt } from "../lib/egress-receipt";
import { localEngineStatus, type LocalEngineStatus } from "../lib/gbrain-local-status";
-import { buildGbrainEnv, spawnGbrain, execGbrainJson, NEEDS_SHELL_ON_WINDOWS } from "../lib/gbrain-exec";
+import { buildGbrainEnv, spawnGbrain, execGbrainJson, NEEDS_SHELL_ON_WINDOWS, bashScriptInvocation } from "../lib/gbrain-exec";
import { repoPolicyTier as sharedRepoPolicyTier } from "../lib/gbrain-repo-policy-client";
import { checkOwnedStagingDir } from "../lib/staging-guard";
@@ -368,6 +368,42 @@ function deriveCodeSourceId(repoPath: string): string {
return constrainSourceId("gstack-code", `${base}-${hostPathHash}`);
}
+/**
+ * Reuse an explicit repo pin when it names a registered source for this exact
+ * checkout. The path check prevents a stale or copied dotfile from redirecting
+ * a code sync into another repo's source.
+ */
+function readPinnedSourceId(repoPath: string): string | null {
+ const pinPath = join(repoPath, ".gbrain-source");
+ if (!existsSync(pinPath)) return null;
+
+ try {
+ const sourceId = readFileSync(pinPath, "utf-8").trim();
+ return /^[a-z0-9](?:[a-z0-9-]{0,30}[a-z0-9])?$/.test(sourceId) ? sourceId : null;
+ } catch {
+ // A pin is advisory. A permission race or a directory at this path must
+ // not turn a sync preview into an unexpected crash.
+ return null;
+ }
+}
+
+export function existingPinnedSourceId(repoPath: string, env?: NodeJS.ProcessEnv): string | null {
+ const sourceId = readPinnedSourceId(repoPath);
+ if (!sourceId) return null;
+
+ const registeredPath = sourceLocalPath(sourceId, env);
+ if (!registeredPath) return null;
+ try {
+ return realpathSync(registeredPath) === realpathSync(repoPath) ? sourceId : null;
+ } catch {
+ return null;
+ }
+}
+
+function resolveCodeSourceId(repoPath: string, env?: NodeJS.ProcessEnv): string {
+ return existingPinnedSourceId(repoPath, env) ?? deriveCodeSourceId(repoPath);
+}
+
/**
* Pre-pathhash source id, kept for orphan detection only.
*
@@ -820,7 +856,13 @@ async function runCodeImport(args: CliArgs): Promise<StageResult> {
return { name: "code", ran: false, ok: true, duration_ms: 0, summary: "skipped (not in git repo)" };
}
- const sourceId = deriveCodeSourceId(root);
+ // A preview must not spawn gbrain. Trust a syntactically-valid local pin
+ // there; a real run confirms its registered path before using it.
+ const gbrainEnv = args.mode === "dry-run" ? undefined : buildGbrainEnv({ announce: !args.quiet });
+ const pinnedSourceId = args.mode === "dry-run"
+ ? readPinnedSourceId(root)
+ : existingPinnedSourceId(root, gbrainEnv);
+ const sourceId = pinnedSourceId ?? deriveCodeSourceId(root);
// Per-repo trust tier — checked BEFORE the dry-run branch so previews report
// the refusal honestly instead of claiming they would sync.
@@ -861,7 +903,9 @@ async function runCodeImport(args: CliArgs): Promise<StageResult> {
ran: false,
ok: true,
duration_ms: 0,
- summary: `would: gbrain sources add ${sourceId} --path ${root} --federated; gbrain sync --strategy code --source ${sourceId}; gbrain sources attach ${sourceId}`,
+ summary: pinnedSourceId
+ ? `would: gbrain sync --strategy code --source ${sourceId}; gbrain sources attach ${sourceId}`
+ : `would: gbrain sources add ${sourceId} --path ${root} --federated; gbrain sync --strategy code --source ${sourceId}; gbrain sources attach ${sourceId}`,
detail: { source_id: sourceId, source_path: root, status: "skipped" },
};
}
@@ -889,10 +933,9 @@ async function runCodeImport(args: CliArgs): Promise<StageResult> {
// gbrainEnv seeds DATABASE_URL from gbrain's config so this stage works
// inside Next.js / Prisma / Rails projects with their own .env.local
// (codex review #7 — bug fix is wider than #1508 as filed).
- const gbrainEnv = buildGbrainEnv({ announce: !args.quiet });
const legacyId = deriveLegacyCodeSourceId(root);
let legacyRemoved = false;
- if (legacyId !== sourceId) {
+ if (!pinnedSourceId && legacyId !== sourceId) {
// #1734: route through the data-loss guards (autopilot + source-safety).
const rm = safeSourcesRemove(legacyId, gbrainEnv);
if (rm.skipped && !args.quiet) {
@@ -908,7 +951,9 @@ async function runCodeImport(args: CliArgs): Promise<StageResult> {
// pages); fall back to register-new → sync-OK → remove-old. Path-drift
// (user moved the repo, etc.) skips migration with a warning.
const pathOnlyHashLegacyId = derivePathOnlyHashLegacyId(root);
- const migration = planHostnameFoldMigration(root, sourceId, pathOnlyHashLegacyId, gbrainEnv);
+ const migration = pinnedSourceId
+ ? { kind: "none", reason: "no-legacy-source" } as const
+ : planHostnameFoldMigration(root, sourceId, pathOnlyHashLegacyId, gbrainEnv);
if (migration.kind === "skipped-path-drift" && !args.quiet) {
console.error(
`[sync:code] hostname-fold migration skipped: legacy source ${migration.oldId} `
@@ -919,21 +964,24 @@ async function runCodeImport(args: CliArgs): Promise<StageResult> {
console.error(`[sync:code] hostname-fold migration: renamed ${migration.oldId} → ${migration.newId} (pages preserved)`);
}
- // Step 1: Ensure source registered (idempotent). Single source of truth in lib —
- // no synchronous duplicate here (per /codex review #12).
+ // Step 1: Ensure generated sources are registered. A confirmed explicit pin
+ // belongs to the user: its realpath was checked above, so never remove/add it
+ // merely because the registered spelling differs (e.g. a symlinked checkout).
let registered = false;
- try {
- const result = await ensureSourceRegistered(sourceId, root, { federated: true, env: gbrainEnv });
- registered = result.changed;
- } catch (err) {
- return {
- name: "code",
- ran: true,
- ok: false,
- duration_ms: Date.now() - t0,
- summary: `source registration failed: ${(err as Error).message}`,
- detail: { source_id: sourceId, source_path: root, status: "failed" },
- };
+ if (!pinnedSourceId) {
+ try {
+ const result = await ensureSourceRegistered(sourceId, root, { federated: true, env: gbrainEnv });
+ registered = result.changed;
+ } catch (err) {
+ return {
+ name: "code",
+ ran: true,
+ ok: false,
+ duration_ms: Date.now() - t0,
+ summary: `source registration failed: ${(err as Error).message}`,
+ detail: { source_id: sourceId, source_path: root, status: "failed" },
+ };
+ }
}
// Step 2: Always run the page-creating file walk first, then (for --full)
@@ -995,7 +1043,25 @@ async function runCodeImport(args: CliArgs): Promise<StageResult> {
};
}
- const walkResult = spawnGbrain(["sync", "--strategy", "code", "--source", sourceId], {
+ // `--full` must do a FULL walk, not a delta one.
+ //
+ // A bare `sync --strategy code` is incremental: it only revisits files that
+ // changed since the source's checkpoint. So a file missed at the ORIGINAL
+ // import is never revisited and stays invisible indefinitely — and the
+ // reindex-code pass below cannot rescue it, because it re-chunks pages that
+ // already exist and never walks the filesystem (the same property the comment
+ // above already relies on).
+ //
+ // The failure is silent: no error, no warning, and the verdict block still
+ // reports OK while `gbrain search` and `gbrain code-def` answer out of a
+ // partial index. It presents as "gbrain is weak at code questions" rather
+ // than "the index is incomplete", which is what makes it hard to spot.
+ //
+ // --yes because this is spawned non-interactively; a full walk otherwise
+ // prompts to confirm the import cost.
+ const walkArgs = ["sync", "--strategy", "code", "--source", sourceId];
+ if (args.mode === "full") walkArgs.push("--full", "--yes");
+ const walkResult = spawnGbrain(walkArgs, {
stdio: args.quiet ? ["ignore", "ignore", "ignore"] : ["ignore", "inherit", "inherit"],
timeout: codeTimeoutMs,
baseEnv: gbrainEnv,
@@ -1007,7 +1073,7 @@ async function runCodeImport(args: CliArgs): Promise<StageResult> {
ran: true,
ok: false,
duration_ms: Date.now() - t0,
- summary: `gbrain sync --strategy code --source ${sourceId} exited ${walkResult.status}`,
+ summary: `gbrain ${walkArgs.join(" ")} exited ${walkResult.status}`,
detail: { source_id: sourceId, source_path: root, status: "failed" },
};
}
@@ -1245,18 +1311,31 @@ function runBrainSyncPush(args: CliArgs): StageResult {
return { name: "brain-sync", ran: false, ok: true, duration_ms: 0, summary: "skipped (gstack-brain-sync not installed)" };
}
- // #1731: gstack-brain-sync is a bash shebang script; Windows can't spawn it
- // without a shell, which surfaced as "brain-sync exited undefined".
- spawnSync(brainSyncPath, ["--discover-new"], {
- stdio: args.quiet ? ["ignore", "ignore", "ignore"] : ["ignore", "inherit", "inherit"],
- timeout: 60 * 1000,
- shell: NEEDS_SHELL_ON_WINDOWS,
- });
- const result = spawnSync(brainSyncPath, ["--once"], {
- stdio: args.quiet ? ["ignore", "ignore", "ignore"] : ["ignore", "inherit", "inherit"],
- timeout: 60 * 1000,
- shell: NEEDS_SHELL_ON_WINDOWS,
- });
+ // gstack-brain-sync is a bash shebang script, so it needs an INTERPRETER, not
+ // a shell. #1731 gave it `shell: NEEDS_SHELL_ON_WINDOWS`, which is right for
+ // the gbrain.cmd shim and useless here: cmd.exe resolves .cmd/.bat via PATHEXT
+ // and rejects an extension-less shebang script outright ("is not recognized as
+ // an internal or external command"), so this stage failed on EVERY Windows run
+ // while looking like a single red line in an otherwise green report. See
+ // bashScriptInvocation.
+ const discover = bashScriptInvocation(brainSyncPath, ["--discover-new"]);
+ const once = bashScriptInvocation(brainSyncPath, ["--once"]);
+ if (!discover || !once) {
+ return {
+ name: "brain-sync",
+ ran: false,
+ ok: true,
+ duration_ms: Date.now() - t0,
+ summary: "skipped (no bash found; set GSTACK_BASH to your Git bash.exe)",
+ };
+ }
+
+ const stdio: "ignore"[] | ("ignore" | "inherit")[] = args.quiet
+ ? ["ignore", "ignore", "ignore"]
+ : ["ignore", "inherit", "inherit"];
+
+ spawnSync(discover.cmd, discover.argv, { stdio, timeout: 60 * 1000, shell: discover.shell });
+ const result = spawnSync(once.cmd, once.argv, { stdio, timeout: 60 * 1000, shell: once.shell });
return {
name: "brain-sync",
@@ -1305,7 +1384,7 @@ export async function runDream(args: CliArgs): Promise<StageResult> {
if (args.mode === "dry-run") {
const root = repoRoot();
- const sourceId = root ? deriveCodeSourceId(root) : null;
+ const sourceId = root ? readPinnedSourceId(root) ?? deriveCodeSourceId(root) : null;
return {
name: "dream",
ran: false,
@@ -1317,6 +1396,7 @@ export async function runDream(args: CliArgs): Promise<StageResult> {
};
}
+ const gbrainEnv = buildGbrainEnv({ announce: !args.quiet });
const localStatus = localEngineStatus({ noCache: false });
if (localStatus === "timeout") {
warnProbeTimeout("dream"); // #1964: slow-but-healthy — proceed
@@ -1352,7 +1432,7 @@ export async function runDream(args: CliArgs): Promise<StageResult> {
// code-callers/code-callees for this worktree. Falls back to plain `dream`
// only when we can't derive the source id (not in a git repo).
const root = repoRoot();
- const sourceId = root ? deriveCodeSourceId(root) : null;
+ const sourceId = root ? resolveCodeSourceId(root, gbrainEnv) : null;
const dreamArgs = sourceId ? ["dream", "--source", sourceId] : ["dream"];
// spawnGbrain seeds DATABASE_URL from gbrain's config via buildGbrainEnv.
@@ -1481,7 +1561,14 @@ export function parseResolvedEdges(out: string): number | null {
export function classifyDreamOutcome(out: string): string | null {
// The active schema pack doesn't declare the code-symbol extraction phase, so
// no symbols are extracted and resolve_symbol_edges has nothing to match.
- if (/does not declare this phase/i.test(out)) {
+ // #2341: anchor the match to a GRAPH phase. The bare phrase false-positived
+ // on every base-pack brain — gbrain's only emitters of "active pack does not
+ // declare this phase" are the CONTENT phases (extract_atoms,
+ // synthesize_concepts), which base packs legitimately skip while
+ // resolve_symbol_edges still runs and builds the graph. Matching the bare
+ // phrase sent users pack-churning ("switch schema packs") for nothing and
+ // masked real graph bugs behind a wrong diagnosis.
+ if (/(resolve_symbol_edges|extract_code_symbols)[^\n]*does not declare/i.test(out)) {
return (
"dream ran, but this source's schema pack does not extract code symbols, " +
"so the call graph stays empty. Switch this source to a code-aware schema " +
@@ -1644,7 +1731,8 @@ async function main(): Promise<void> {
let cycle: CycleStatus | null = null;
if (!args.dream && args.mode === "full" && !args.noDream && !args.noCode) {
const root = repoRoot();
- cycle = root ? cycleCompleted(deriveCodeSourceId(root), process.env) : "unknown";
+ const gbrainEnv = buildGbrainEnv({ announce: !args.quiet });
+ cycle = root ? cycleCompleted(resolveCodeSourceId(root, gbrainEnv), gbrainEnv) : "unknown";
}
if (shouldRunDream(args, cycle)) {
dreamStage = await runDream(args);
diff --git a/bin/gstack-memory-ingest.ts b/bin/gstack-memory-ingest.ts
index 4aeba0b69..5cbb535ba 100644
--- a/bin/gstack-memory-ingest.ts
+++ b/bin/gstack-memory-ingest.ts
@@ -543,7 +543,7 @@ interface ParsedSession {
partial: boolean;
}
-function parseTranscriptJsonl(path: string): ParsedSession | null {
+export function parseTranscriptJsonl(path: string): ParsedSession | null {
// Best-effort tolerant parser. Handles truncated last lines (D10 partial-flag).
let raw: string;
try {
@@ -619,7 +619,7 @@ function parseTranscriptJsonl(path: string): ParsedSession | null {
const tool = rec?.name || rec?.tool || rec?.tool_call?.name || "tool";
bodyParts.push(`### Tool call: ${tool}`);
} else if (isCodex && rec?.payload?.message) {
- // Codex shape: each record has payload.message
+ // Legacy Codex shape: each record has payload.message
const msg = rec.payload.message;
const role = msg.role || "user";
const content = extractContentText(msg);
@@ -627,6 +627,18 @@ function parseTranscriptJsonl(path: string): ParsedSession | null {
bodyParts.push(`## ${role.charAt(0).toUpperCase() + role.slice(1)}\n\n${content}`);
messageCount++;
}
+ } else if (isCodex && rec?.type === "response_item" && rec?.payload?.type === "message") {
+ // Current Codex rollout shape (#2105): records are
+ // { type: 'response_item', payload: { type: 'message', role, content: [...] } }.
+ // The legacy payload.message branch never fires on these, which rendered
+ // every Codex session as an empty shell (message_count: 0, 243/243 on
+ // the reporting machine). Flatten payload.content like the Claude branch.
+ const role = rec.payload.role || "user";
+ const content = extractContentText(rec.payload);
+ if (content) {
+ bodyParts.push(`## ${role.charAt(0).toUpperCase() + role.slice(1)}\n\n${content}`);
+ messageCount++;
+ }
}
}
diff --git a/bin/gstack-next-version b/bin/gstack-next-version
index 76879ddbd..e19781594 100755
--- a/bin/gstack-next-version
+++ b/bin/gstack-next-version
@@ -19,6 +19,13 @@
// committed so all collaborators benefit)
// 3. "VERSION" at the repo root (default, backward-compatible)
//
+// The pinned path may be a package.json (any depth) rather than a plain-text
+// VERSION file: a path ending in .json is read as JSON and its .version taken.
+// 3-digit semver is accepted as well as 4-digit, and stays 3-digit through
+// bumping. See lib/version-source.ts for why both mattered — each used to fail
+// closed, which silently disabled the queue-collision check this CLI exists to
+// provide (#2501).
+//
// Exit codes:
// 0 — emitted JSON successfully (may include "offline":true or "host":"unknown")
// 2 — invalid arguments
@@ -28,9 +35,18 @@ import { execFileSync, spawnSync } from "node:child_process";
import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
import { homedir } from "node:os";
import { join, resolve } from "node:path";
-
-type Bump = "major" | "minor" | "patch" | "micro";
-type Version = [number, number, number, number];
+import {
+ parseVersion,
+ versionWidth,
+ fmtVersion,
+ bumpVersion,
+ cmpVersion,
+ bumpWasCoerced,
+ extractVersion,
+ type Bump,
+ type Version,
+ type VersionWidth,
+} from "../lib/version-source";
type ClaimedPR = {
pr: number;
@@ -56,6 +72,7 @@ type Output = {
bump: Bump;
host: "github" | "gitlab" | "unknown";
offline: boolean;
+ fallback: "git" | null;
claimed: ClaimedPR[];
siblings: Sibling[];
active_siblings: Sibling[];
@@ -66,48 +83,20 @@ type Output = {
const ACTIVE_SIBLING_MAX_AGE_S = 24 * 60 * 60;
const GH_API_CONCURRENCY = 10;
-function parseVersion(s: string): Version | null {
- const m = s.trim().match(/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/);
- if (!m) return null;
- return [Number(m[1]), Number(m[2]), Number(m[3]), Number(m[4])];
-}
-
-function fmtVersion(v: Version): string {
- return v.join(".");
-}
-
-function bumpVersion(v: Version, level: Bump): Version {
- switch (level) {
- case "major":
- return [v[0] + 1, 0, 0, 0];
- case "minor":
- return [v[0], v[1] + 1, 0, 0];
- case "patch":
- return [v[0], v[1], v[2] + 1, 0];
- case "micro":
- return [v[0], v[1], v[2], v[3] + 1];
- }
-}
-
-function cmpVersion(a: Version, b: Version): number {
- for (let i = 0; i < 4; i++) {
- if (a[i] !== b[i]) return a[i] - b[i];
- }
- return 0;
-}
-
// Collision resolution: bump past the highest claimed within the same level.
// Semantics: if my bump is MINOR and the queue claims 1.7.0.0, I advance to
// 1.8.0.0 (still a MINOR relative to main). Preserves ship-time intent.
-function pickNextSlot(base: Version, claimed: Version[], level: Bump): { version: Version; reason: string } {
- let candidate = bumpVersion(base, level);
+// `width` keeps a 3-digit repo 3-digit (see lib/version-source.ts); it
+// defaults to 4 so existing callers and tests are unaffected.
+function pickNextSlot(base: Version, claimed: Version[], level: Bump, width: VersionWidth = 4): { version: Version; reason: string } {
+ let candidate = bumpVersion(base, level, width);
const sortedClaimed = [...claimed].sort(cmpVersion);
const highest = sortedClaimed[sortedClaimed.length - 1];
if (highest && cmpVersion(highest, base) > 0) {
// Queue already advanced past base; bump past the highest claim.
- const bumpedPastHighest = bumpVersion(highest, level);
+ const bumpedPastHighest = bumpVersion(highest, level, width);
if (cmpVersion(bumpedPastHighest, candidate) > 0) {
- return { version: bumpedPastHighest, reason: `bumped past claimed ${fmtVersion(highest)}` };
+ return { version: bumpedPastHighest, reason: `bumped past claimed ${fmtVersion(highest, width)}` };
}
}
return { version: candidate, reason: "no collision; clean bump from base" };
@@ -167,7 +156,12 @@ function readBaseVersion(base: string, versionPath: string, warnings: string[]):
warnings.push(`could not read ${versionPath} at origin/${base}; assuming 0.0.0.0`);
return "0.0.0.0";
}
- return r.stdout.trim();
+ const v = extractVersion(r.stdout, versionPath);
+ if (!v) {
+ warnings.push(`${versionPath} at origin/${base} has no readable version; assuming 0.0.0.0`);
+ return "0.0.0.0";
+ }
+ return v;
}
async function fetchGithubClaimed(base: string, versionPath: string, excludePR: number | null, warnings: string[]): Promise<{ claimed: ClaimedPR[]; offline: boolean }> {
@@ -233,7 +227,7 @@ async function fetchGithubClaimed(base: string, versionPath: string, excludePR:
}
let versionStr: string;
try {
- versionStr = Buffer.from(content.stdout.trim(), "base64").toString("utf8").trim();
+ versionStr = extractVersion(Buffer.from(content.stdout.trim(), "base64").toString("utf8"), versionPath);
} catch {
warnings.push(`PR #${pr.number}: VERSION is not valid base64`);
continue;
@@ -290,7 +284,7 @@ async function fetchGitlabClaimed(base: string, versionPath: string, excludePR:
}
try {
const j = JSON.parse(content.stdout);
- const versionStr = Buffer.from(j.content, "base64").toString("utf8").trim();
+ const versionStr = extractVersion(Buffer.from(j.content, "base64").toString("utf8"), versionPath);
if (!parseVersion(versionStr)) {
warnings.push(`MR !${mr.iid}: VERSION malformed (${versionStr})`);
continue;
@@ -349,7 +343,7 @@ function scanSiblings(root: string | null, versionPath: string, claimed: Claimed
if (!existsSync(versionFile)) continue;
let version: string;
try {
- version = readFileSync(versionFile, "utf8").trim();
+ version = extractVersion(readFileSync(versionFile, "utf8"), versionPath);
if (!parseVersion(version)) continue;
} catch {
continue;
@@ -452,6 +446,84 @@ function autoDetectExcludePR(): number | null {
return Number.isFinite(n) && n > 0 ? n : null;
}
+// ── git-only fallback (#2545) ────────────────────────────────────────────
+//
+// When the host query fails this util used to return `offline:true` with an
+// EMPTY claim set, and /ship's instruction was "fall back to local BUMP_LEVEL
+// arithmetic". Local arithmetic cannot see a sibling's claim, so the fallback
+// allocated a version another open PR already held.
+//
+// That is not hypothetical. On 2026-08-12 in a downstream repo, `gh pr list`
+// failed during a ship, this util reported offline, the bump fell back to
+// local arithmetic, and 0.1.57.0 was allocated to a second PR while an open
+// one already claimed it — both merged, and main carries two commits reading
+// v0.1.57.0. Auditing that repo's history found FOUR such pairs going back
+// three weeks, so the silent fallback had been mis-allocating for a while.
+//
+// Git already knows what the API was asked for. Remote-tracking refs carry
+// each branch's VERSION file, and the base's own history records every version
+// already shipped. Neither needs a token, a network round-trip, or a working
+// `gh`. So "offline" degrades the QUEUE VIEW (no PR numbers, no draft status)
+// without degrading the ALLOCATION.
+function fetchGitClaimed(
+ base: string,
+ versionPath: string,
+ warnings: string[],
+): ClaimedPR[] {
+ const claims: ClaimedPR[] = [];
+
+ // 1. Every remote-tracking branch's VERSION file. These are the open PRs'
+ // branches, whether or not the API can be reached to enumerate them.
+ // Read through extractVersion so a JSON version-path (#2501) resolves on
+ // remote refs too, and the branch's own width is preserved in the claim.
+ const refs = runCommand("git", [
+ "for-each-ref",
+ "--format=%(refname:short)",
+ "refs/remotes",
+ ]);
+ if (refs.ok) {
+ const baseShort = base.replace(/^origin\//, "");
+ for (const ref of refs.stdout.split("\n").map((r) => r.trim()).filter(Boolean)) {
+ if (ref.endsWith("/HEAD")) continue;
+ if (ref === base || ref.replace(/^origin\//, "") === baseShort) continue;
+ const show = runCommand("git", ["show", `${ref}:${versionPath}`]);
+ if (!show.ok) continue;
+ const raw = extractVersion(show.stdout, versionPath);
+ if (!raw || !parseVersion(raw)) continue;
+ claims.push({ pr: 0, branch: ref, version: raw });
+ }
+ } else {
+ warnings.push("git for-each-ref failed; branch claims unavailable");
+ }
+
+ // 2. Versions already shipped, read from the base's commit subjects. Catches
+ // the case the VERSION file cannot: a number that merged and was then
+ // re-picked. Bounded, and it says so rather than implying full history.
+ const SUBJECT_SCAN = 400;
+ const log = runCommand("git", ["log", `-n${SUBJECT_SCAN}`, "--format=%s", base]);
+ if (log.ok) {
+ for (const subject of log.stdout.split("\n")) {
+ const m = subject.trim().match(/^v(\d+\.\d+\.\d+(?:\.\d+)?)\b/);
+ if (!m) continue;
+ if (!parseVersion(m[1])) continue;
+ claims.push({ pr: 0, branch: `(shipped on ${base})`, version: m[1] });
+ }
+ // A cap that does not announce itself reads as "checked all history".
+ // Only fires when the log came back exactly full, which is the only
+ // observable signal that older commits went unread.
+ if (log.stdout.trim().split("\n").length >= SUBJECT_SCAN) {
+ warnings.push(
+ `shipped-version scan stopped at ${SUBJECT_SCAN} commits on ${base}; ` +
+ `a version shipped before that is not counted as claimed`,
+ );
+ }
+ } else {
+ warnings.push(`git log ${base} failed; shipped-version scan unavailable`);
+ }
+
+ return claims;
+}
+
async function main() {
const args = parseArgs(process.argv.slice(2));
if (args.help) {
@@ -469,6 +541,13 @@ async function main() {
console.error(`Error: could not parse base version '${baseVersion}'`);
process.exit(2);
}
+ // The repo's own width governs everything downstream: a 3-digit repo must
+ // not be handed a 4-digit slot, or /ship writes a version the repo's tooling
+ // can't read back (#2501).
+ const width = versionWidth(baseVersion);
+ if (bumpWasCoerced(args.bump, width)) {
+ warnings.push(`--bump micro has no component to move in a ${width}-digit version; treated as patch`);
+ }
const excludePR = args.excludePR ?? autoDetectExcludePR();
if (excludePR !== null && args.excludePR === null) {
@@ -485,6 +564,28 @@ async function main() {
warnings.push("host unknown; queue-awareness unavailable");
}
+ // Degraded host query → fall back to git, which needs no API. Additive: it
+ // only runs when the host told us nothing, so the online path is untouched.
+ let fallback: "git" | null = null;
+ if (offline || host === "unknown") {
+ const gitClaims = fetchGitClaimed(args.base, versionPath, warnings);
+ if (gitClaims.length) {
+ claimed = [...claimed, ...gitClaims];
+ fallback = "git";
+ warnings.push(
+ `host queue unavailable — allocated from git instead ` +
+ `(${gitClaims.length} claim(s) from remote refs + shipped subjects). ` +
+ `PR numbers and draft status are unavailable, but the version is safe.`,
+ );
+ } else {
+ warnings.push(
+ "host queue unavailable AND git found no claims — the pick rests on " +
+ "the base VERSION alone. Verify no sibling branch holds it before " +
+ "shipping.",
+ );
+ }
+ }
+
// Only count PRs that actually bumped VERSION past base as real "claims".
// A PR whose VERSION equals base's VERSION hasn't claimed anything.
const realClaims = claimed.filter((c) => {
@@ -495,7 +596,7 @@ async function main() {
.map((c) => parseVersion(c.version))
.filter((v): v is Version => v !== null);
- const { version: picked, reason } = pickNextSlot(baseParsed, claimedVersions, args.bump);
+ const { version: picked, reason } = pickNextSlot(baseParsed, claimedVersions, args.bump, width);
const workspaceRoot = resolveWorkspaceRoot(args.workspaceRoot);
const siblings = markActiveSiblings(scanSiblings(workspaceRoot, versionPath, claimed, warnings), baseParsed);
@@ -510,18 +611,19 @@ async function main() {
.filter((v) => cmpVersion(v, finalVersion) >= 0);
if (activeAhead.length) {
const highest = activeAhead.sort(cmpVersion)[activeAhead.length - 1];
- finalVersion = bumpVersion(highest, args.bump);
- finalReason = `bumped past active sibling ${fmtVersion(highest)}`;
+ finalVersion = bumpVersion(highest, args.bump, width);
+ finalReason = `bumped past active sibling ${fmtVersion(highest, width)}`;
}
const out: Output = {
- version: fmtVersion(finalVersion),
+ version: fmtVersion(finalVersion, width),
current_version: args.current || baseVersion,
base_version: baseVersion,
version_path: versionPath,
bump: args.bump,
host,
offline,
+ fallback,
claimed: realClaims,
siblings,
active_siblings: activeSiblings,
@@ -531,8 +633,11 @@ async function main() {
process.stdout.write(JSON.stringify(out, null, 2) + "\n");
}
-// Pure-function exports for testing
-export { parseVersion, fmtVersion, bumpVersion, cmpVersion, pickNextSlot, markActiveSiblings, resolveVersionPath };
+// Pure-function exports for testing. The version primitives are re-exported
+// from lib/version-source so existing importers of this module keep working
+// unchanged.
+export { parseVersion, fmtVersion, bumpVersion, cmpVersion, versionWidth, extractVersion };
+export { pickNextSlot, markActiveSiblings, resolveVersionPath, fetchGitClaimed };
// Only run main() when invoked as a script, not when imported by tests.
if (import.meta.main) {
diff --git a/bin/gstack-redact-prepush b/bin/gstack-redact-prepush
index d4fe45000..1dac0e94e 100755
--- a/bin/gstack-redact-prepush
+++ b/bin/gstack-redact-prepush
@@ -70,6 +70,33 @@ function objectExists(sha: string): boolean {
return r.status === 0;
}
+/**
+ * The remote-tracking exclusion used when narrowing to "commits new to the
+ * remote" (#2592 catch-up merges, #2573 rebased force-pushes).
+ *
+ * Narrowed to the PUSH TARGET's namespace (S1): a bare `--remotes` excludes
+ * commits reachable from ANY remote-tracking ref, so a secret that had only
+ * ever been fetched from (or pushed to) a private/local-path remote was never
+ * scanned when later pushed to a PUBLIC remote — "already left this machine"
+ * is not "already reached THIS remote". Git hands pre-push the push remote's
+ * name as $1 (and its URL as $2); the installed hook wrapper forwards "$@".
+ * Fallbacks keep the historical all-remotes behavior when the name is
+ * unavailable (stdin/CLI invocation) or is not a configured remote (URL
+ * pushes have no remote-tracking namespace) — falling back scans LESS than
+ * the narrowed form would, but never less than the hook historically did.
+ */
+let _remotesExclusion: string | undefined;
+function remotesExclusion(): string {
+ if (_remotesExclusion === undefined) {
+ const name = process.argv[2];
+ const configured = name
+ ? git(["remote"]).split("\n").map((s) => s.trim()).filter(Boolean).includes(name)
+ : false;
+ _remotesExclusion = configured ? `--remotes=${name}/*` : "--remotes";
+ }
+ return _remotesExclusion;
+}
+
function defaultRemoteBranch(): string {
// origin/HEAD → origin/main, fall back to main/master.
const sym = git(["symbolic-ref", "refs/remotes/origin/HEAD"]).trim();
@@ -104,12 +131,12 @@ function unknownRemoteTipBase(localSha: string): string | null {
// engine's byte cap, so `engine.input_too_large` blocks having scanned
// NOTHING — "scans more, never less" inverted into "scans nothing".
//
- // `--remotes` covers every remote, not just the push target: content
- // already published anywhere has already left this machine, so treating it
- // as pre-existing is deliberate. Git hands the remote name to pre-push in
- // argv, which this hook does not read; narrowing to it would only matter
- // for a repo that pushes secrets to one remote but not another.
- const newCommits = git(["rev-list", "--reverse", localSha, "--not", "--remotes"]).trim();
+ // The exclusion is scoped to the PUSH TARGET's tracking refs (see
+ // remotesExclusion): content on some OTHER remote has left this machine,
+ // but it has not reached the remote being pushed to — a secret that only
+ // ever hit a private remote must still be scanned on its way to a public
+ // one (S1).
+ const newCommits = git(["rev-list", "--reverse", localSha, "--not", remotesExclusion()]).trim();
if (newCommits) {
const oldest = newCommits.split("\n")[0];
const parent = git(["rev-parse", "--verify", `${oldest}^`]).trim();
@@ -122,8 +149,90 @@ function unknownRemoteTipBase(localSha: string): string | null {
return null;
}
+/**
+ * The commits this push actually adds — reachable from localSha and from NO
+ * remote-tracking ref.
+ *
+ * ⚠ WHY THIS EXISTS RATHER THAN A TWO-DOT RANGE.
+ *
+ * `remoteSha..localSha` is "everything new on this branch", which is NOT the
+ * same as "everything new to the remote". Merge origin/main into a feature
+ * branch and every commit main gained since the branch's last push becomes an
+ * added line — content that is already published, already scanned, and not
+ * this push's doing.
+ *
+ * Two things follow, and both were observed:
+ *
+ * · FALSE HIGH FINDINGS. A placeholder connection string in a test fixture,
+ * already merged to main by someone else, blocked an unrelated push as
+ * `db.url_with_password` — telling the operator to rotate a credential
+ * over a fixture they had never touched. A
+ * guard that cries wolf on catch-up merges is a guard people learn to
+ * bypass reflexively — which is exactly how a real secret gets through.
+ * · OVERSIZED SCANS. The comment on SCAN_CHUNK_BYTES below records a
+ * 1,146,782-byte diff from "a feature branch catching up to a busy main"
+ * blowing the engine's 1 MiB cap. Same root cause, treated there as a size
+ * problem and solved by slicing. Narrowing the range fixes the size too.
+ *
+ * A two-dot range cannot express this: after merging main, neither the remote
+ * tip nor the merge-base with main is an ancestor of the other, so no single
+ * base excludes both. `rev-list --not --remotes=<push-remote>/*` is the
+ * operation that does, and this file already reasons that way in
+ * `unknownRemoteTipBase` step 2. The exclusion is scoped to the push target's
+ * tracking namespace (see remotesExclusion): the upstream commits a catch-up
+ * merge brings in came from the SAME remote being pushed to, so scoping keeps
+ * the #2592 fix intact while a secret known only to some OTHER (private)
+ * remote is still scanned on its way to this one (S1).
+ *
+ * Each commit is diffed alone. `--cc` on a merge shows only the conflict
+ * RESOLUTION — content that exists in no parent — so a secret introduced while
+ * resolving a merge is still caught, while an ordinary merge contributes
+ * nothing. Returns null when the notion does not apply, so callers fall back.
+ */
+function addedLinesFromNewCommits(localSha: string, remoteSha: string): string | null {
+ // remoteSha is what git TELLS us the remote has, and it is authoritative in a
+ // way `--remotes` is not: remote-tracking refs can be absent (a fresh clone
+ // that never fetched, a push to a remote with no tracking ref) or stale. Drop
+ // it and a repo with no tracking refs excludes NOTHING — every commit ever
+ // made reads as "new", which re-introduces the false positives from the other
+ // direction. So it stays the base; `--remotes` only ADDS exclusions on top.
+ if (ZERO.test(remoteSha) || !objectExists(remoteSha)) return null;
+
+ const narrowed = git(["rev-list", localSha, "--not", remoteSha, remotesExclusion()]).trim();
+ if (!narrowed) return null;
+
+ // If excluding remote-tracking refs changes nothing, this push has no
+ // catch-up commits and the plain range already describes it exactly. Defer to
+ // it. That is not just an optimization: it keeps every push that ISN'T a
+ // catch-up merge on the original gitStrict diff path, so the fail-closed
+ // guarantee (#1946) and its regression test keep exercising the code they
+ // were written for. A narrowing that silently retired that test would be a
+ // worse trade than the false positives it set out to fix.
+ const plain = git(["rev-list", `${remoteSha}..${localSha}`]).trim();
+ const asSet = (s: string) => s.split("\n").filter(Boolean).sort().join("\n");
+ if (asSet(narrowed) === asSet(plain)) return null;
+
+ const shas = narrowed.split("\n").filter(Boolean);
+ // A rewrite of long history should fall back rather than shell out per commit.
+ if (shas.length > 500) return null;
+ const out: string[] = [];
+ for (const sha of shas) {
+ // gitStrict: a failed diff must never read as "nothing added" (#1946).
+ out.push(gitStrict([
+ "show", "--unified=0", "--no-color", "--no-ext-diff", "--no-textconv",
+ "--cc", "--format=", sha,
+ ]));
+ }
+ return out.join("\n");
+}
+
/** Return the added-line text for a ref update being pushed. */
function addedLinesFor(localSha: string, remoteSha: string): string {
+ // Preferred ONLY when this push carries catch-up commits: scanning them again
+ // is the bug. Every other shape falls through to the range logic below.
+ const fromNew = addedLinesFromNewCommits(localSha, remoteSha);
+ if (fromNew !== null) return collectAddedLines(fromNew);
+
let range: string;
if (ZERO.test(remoteSha) || !objectExists(remoteSha)) {
// Either a new branch (zero remote sha), or the remote tip object is absent
@@ -151,6 +260,14 @@ function addedLinesFor(localSha: string, remoteSha: string): string {
"diff", "--unified=0", "--no-color", "--no-ext-diff", "--no-textconv",
range,
]);
+ return collectAddedLines(diff);
+}
+
+/**
+ * Added-line text from a unified diff. Shared by both range strategies so the
+ * hunk-aware header handling below cannot drift between them.
+ */
+function collectAddedLines(diff: string): string {
const added: string[] = [];
// Hunk-aware header skip (#2498): `+++ ` is only a FILE HEADER outside a
// hunk. Inside a hunk, an added content line whose text begins with "++"
@@ -158,7 +275,11 @@ function addedLinesFor(localSha: string, remoteSha: string): string {
// silently dropped exactly those lines from the scan.
let inHunk = false;
for (const line of diff.split("\n")) {
- if (line.startsWith("diff --git")) { inHunk = false; continue; }
+ // `diff --` rather than `diff --git`: a merge scanned with --cc emits
+ // `diff --cc <path>`, so a --git-only reset left inHunk true across file
+ // boundaries and read the next file's `+++ b/...` header as content. Only
+ // noise (it over-scans, never under-scans), but the boundary is real.
+ if (line.startsWith("diff --")) { inHunk = false; continue; }
if (line.startsWith("@@")) { inHunk = true; continue; }
if (!inHunk && (line.startsWith("+++") || line.startsWith("---"))) continue;
if (line.startsWith("+")) added.push(line.slice(1));
diff --git a/bin/gstack-relink b/bin/gstack-relink
index dd2a681fa..e87bc3fac 100755
--- a/bin/gstack-relink
+++ b/bin/gstack-relink
@@ -36,6 +36,12 @@ SKILLS_DIR="${GSTACK_SKILLS_DIR:-$(dirname "$INSTALL_DIR")}"
# Read prefix setting
PREFIX=$("$GSTACK_CONFIG" get skill_prefix 2>/dev/null || echo "false")
+# #2569: rendered :user variants (brain-aware blocks) live in an UNTRACKED
+# out-dir instead of the tracked install checkout. When a render exists for a
+# skill, relink serves it — otherwise a config change would silently flip
+# every skill back to the canonical (blockless) source.
+RENDER_DIR="${GSTACK_USER_RENDER_DIR:-${GSTACK_HOME:-$HOME/.gstack}/render/claude}"
+
# Helper: remove old skill entry (symlink or real directory with symlinked SKILL.md)
_cleanup_skill_entry() {
local entry="$1"
@@ -52,7 +58,13 @@ _link_root_skill_alias() {
[ -f "$INSTALL_DIR/SKILL.md" ] || return 0
[ -L "$target" ] && rm -f "$target"
mkdir -p "$target"
- ln -snf "$INSTALL_DIR/SKILL.md" "$target/SKILL.md"
+ # Copy-then-rewrite, never a symlink (#2511): a symlinked alias re-serves
+ # the canonical `name: gstack`, Claude Code sees a duplicate skill name,
+ # and drops the ENTIRE personal-skills set. sed reads the source and writes
+ # a fresh copy — remove any prior symlink first so the redirect can never
+ # write through it into the generated source.
+ rm -f "$target/SKILL.md"
+ sed "1,/^---\$/ s/^name:[[:space:]].*/name: _gstack-command/" "$INSTALL_DIR/SKILL.md" > "$target/SKILL.md"
}
_link_root_skill_alias
@@ -61,6 +73,11 @@ _link_root_skill_alias
SKILL_COUNT=0
for skill_dir in "$INSTALL_DIR"/*/; do
[ -d "$skill_dir" ] || continue
+ # Skip symlinked skill dirs (connect-chrome → open-gstack-browser): linking
+ # one under the symlink's basename would duplicate the canonical frontmatter
+ # name and collide in Claude Code's skill registry (#2201). setup owns the
+ # rewritten-copy alias for those.
+ [ -L "${skill_dir%/}" ] && continue
skill=$(basename "$skill_dir")
# Skip non-skill directories
case "$skill" in bin|browse|design|docs|extension|lib|node_modules|scripts|test|.git|.github) continue ;; esac
@@ -87,7 +104,9 @@ for skill_dir in "$INSTALL_DIR"/*/; do
[ -L "$target" ] && rm -f "$target"
# Create real directory with symlinked SKILL.md (absolute path)
mkdir -p "$target"
- ln -snf "$INSTALL_DIR/$skill/SKILL.md" "$target/SKILL.md"
+ skill_md_src="$INSTALL_DIR/$skill/SKILL.md"
+ [ -f "$RENDER_DIR/$skill/SKILL.md" ] && skill_md_src="$RENDER_DIR/$skill/SKILL.md"
+ ln -snf "$skill_md_src" "$target/SKILL.md"
SKILL_COUNT=$((SKILL_COUNT + 1))
done
diff --git a/bin/gstack-repo-mode b/bin/gstack-repo-mode
index 0aabe378e..a5c5a6ba6 100755
--- a/bin/gstack-repo-mode
+++ b/bin/gstack-repo-mode
@@ -44,7 +44,15 @@ fi
CACHE_DIR="$HOME/.gstack/projects/$SLUG"
CACHE_FILE="$CACHE_DIR/repo-mode.json"
if [ -f "$CACHE_FILE" ]; then
- CACHE_AGE=$(( $(date +%s) - $(stat -f %m "$CACHE_FILE" 2>/dev/null || stat -c %Y "$CACHE_FILE" 2>/dev/null || echo 0) ))
+ # GNU first (#2195): on GNU coreutils `stat -f` SUCCEEDS with filesystem
+ # status (not a format string), so the BSD-first fallback chain never fell
+ # over — it fed multi-word filesystem output into the arithmetic below and
+ # crashed under set -u on Windows Git Bash. `stat -c` fails cleanly on
+ # BSD/macOS, making GNU-first the deterministic order. Numeric-validate
+ # before arithmetic as the last line of defense.
+ CACHE_MTIME=$(stat -c %Y "$CACHE_FILE" 2>/dev/null || stat -f %m "$CACHE_FILE" 2>/dev/null || echo 0)
+ case "$CACHE_MTIME" in ''|*[!0-9]*) CACHE_MTIME=0 ;; esac
+ CACHE_AGE=$(( $(date +%s) - CACHE_MTIME ))
if [ "$CACHE_AGE" -lt 604800 ]; then # 7 days in seconds
MODE=$(grep -o '"mode":"[^"]*"' "$CACHE_FILE" | head -1 | cut -d'"' -f4)
[ -n "$MODE" ] && echo "REPO_MODE=$(validate_mode "$MODE")" && exit 0
diff --git a/bin/gstack-settings-hook b/bin/gstack-settings-hook
index d5404c05d..463b3e4c5 100755
--- a/bin/gstack-settings-hook
+++ b/bin/gstack-settings-hook
@@ -171,8 +171,9 @@ case "$ACTION" in
const matchesEntry = (entry) => {
const sameMatcher = (entry.matcher || "") === matcher;
+ const sameCommand = entry.hooks && entry.hooks[0] && entry.hooks[0].command === cmd;
const sameSource = entry._gstack_source === source;
- return sameMatcher && sameSource;
+ return sameMatcher && (sameSource || sameCommand);
};
let existing = settings.hooks[event].find(matchesEntry);
@@ -184,6 +185,7 @@ case "$ACTION" in
if (existing) {
existing.hooks = [hookEntry];
+ existing._gstack_source = source;
} else {
const newEntry = { _gstack_source: source, hooks: [hookEntry] };
if (matcher) newEntry.matcher = matcher;
diff --git a/bin/gstack-slug b/bin/gstack-slug
index e9b2aaf02..924454722 100755
--- a/bin/gstack-slug
+++ b/bin/gstack-slug
@@ -27,7 +27,11 @@
# injection when consumed via source or eval.
set -euo pipefail
-CACHE_DIR="$HOME/.gstack/slug-cache"
+# GSTACK_HOME-aware, matching lib/bin-context.ts's native port (#2561): the
+# bash writer and the TS reader must key the SAME cache, and a test running
+# with GSTACK_HOME=<temp> must write its cache junk there, not into the real
+# home (observed: 2,528 stale temp-cwd entries accumulated in ~/.gstack).
+CACHE_DIR="${GSTACK_HOME:-$HOME/.gstack}/slug-cache"
PROJECT_DIR="$(pwd)"
# Encode absolute path as cache key: /Users/j/foo → _Users_j_foo
CACHE_KEY=$(printf '%s' "$PROJECT_DIR" | tr '/' '_')
@@ -37,8 +41,14 @@ SLUG=""
# 0. Explicit env override — wins over everything. Escape hatch for vendored
# sub-repos and other genuine "subdir IS its own project" edge cases.
+SLUG_FROM_ENV=0
if [[ -n "${GSTACK_PROJECT_SLUG:-}" ]]; then
SLUG=$(printf '%s' "$GSTACK_PROJECT_SLUG" | tr -cd 'a-zA-Z0-9._-')
+ # Per-invocation escape hatch, never a durable identity: persisting it
+ # would rebind THIS cwd's slug for every later env-less run (observed: a
+ # test exporting GSTACK_PROJECT_SLUG from the repo root rebound the whole
+ # repo's session state to the test's slug).
+ SLUG_FROM_ENV=1
fi
# 1. Walk up from pwd, tracking the OUTERMOST ancestor with a canonical
@@ -160,7 +170,7 @@ SLUG="${SLUG:-$(basename "$PROJECT_DIR" | tr -cd 'a-zA-Z0-9._-')}"
# injection, but the invariant should not depend on that reasoning).
SLUG=$(printf '%s' "$SLUG" | tr -cd 'a-zA-Z0-9._-')
-if [[ -n "$SLUG" ]]; then
+if [[ -n "$SLUG" && "$SLUG_FROM_ENV" -eq 0 ]]; then
CURRENT_CACHE=""
if [[ -f "$CACHE_FILE" ]]; then
CURRENT_CACHE=$(cat "$CACHE_FILE" 2>/dev/null || true)
diff --git a/bin/gstack-team-init b/bin/gstack-team-init
index fd6c1b7d9..99538425f 100755
--- a/bin/gstack-team-init
+++ b/bin/gstack-team-init
@@ -70,7 +70,11 @@ else
**Before doing ANY work, verify gstack is installed:**
```bash
-test -d ~/.claude/skills/gstack/bin && echo "GSTACK_OK" || echo "GSTACK_MISSING"
+_GS=""
+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/.gstack/repos/gstack"; do
+ [ -z "$_GS" ] && [ -n "$_D" ] && [ -d "$_D/bin" ] && _GS="$_D"
+done
+[ -n "$_GS" ] && echo "GSTACK_OK: $_GS" || echo "GSTACK_MISSING"
```
If GSTACK_MISSING: STOP. Do not proceed. Tell the user:
@@ -87,7 +91,8 @@ Do not skip skills, ignore gstack errors, or work around missing gstack.
Using gstack skills: After install, skills like /qa, /ship, /review, /investigate,
and /browse are available. Use /browse for all web browsing.
-Use ~/.claude/skills/gstack/... for gstack file paths (the global path).'
+Use the resolved install path above for gstack file paths
+(default: ~/.claude/skills/gstack).'
fi
# Check if CLAUDE.md already has a gstack section
@@ -114,8 +119,17 @@ if [ "$MODE" = "required" ]; then
cat > "$HOOKS_DIR/check-gstack.sh" << 'HOOK_EOF'
#!/bin/bash
# Block skill usage when gstack is not installed globally.
-
-if [ ! -d "$HOME/.claude/skills/gstack/bin" ]; then
+#
+# 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/.gstack/repos/gstack"; do
+ [ -z "$_GSTACK_ROOT" ] && [ -n "$_D" ] && [ -d "$_D/bin" ] && _GSTACK_ROOT="$_D"
+done
+
+if [ -z "$_GSTACK_ROOT" ]; then
cat >&2 <<'MSG'
BLOCKED: gstack is not installed globally.
diff --git a/bin/gstack-uninstall b/bin/gstack-uninstall
index 17d7d30bc..9f83386d7 100755
--- a/bin/gstack-uninstall
+++ b/bin/gstack-uninstall
@@ -12,12 +12,14 @@
# ~/.codex/skills/gstack* — Codex skill install + per-skill symlinks
# ~/.factory/skills/gstack* — Factory Droid skill install + per-skill symlinks
# ~/.kiro/skills/gstack* — Kiro skill install + per-skill symlinks
+# ~/.cursor/skills/gstack* — Cursor skill install + per-skill symlinks
# ~/.gstack/ — global state (config, analytics, sessions, projects,
# repos, installation-id, browse error logs)
# .claude/skills/gstack* — project-local skill install (--local installs)
# .gstack/ — per-project browse state (in current git repo)
# .gstack-worktrees/ — per-project test worktrees (in current git repo)
-# .agents/skills/gstack* — Codex/Gemini/Cursor sidecar (in current git repo)
+# .agents/skills/gstack* — Codex/Gemini sidecar (in current git repo)
+# .cursor/skills/gstack* — project-local Cursor skills (in current git repo)
# Running browse daemons — stopped via SIGTERM before cleanup
#
# What is NOT REMOVED:
@@ -66,6 +68,7 @@ if [ "$FORCE" -eq 0 ]; then
[ -d "$HOME/.codex/skills" ] && echo " ~/.codex/skills/gstack*"
[ -d "$HOME/.factory/skills" ] && echo " ~/.factory/skills/gstack*"
[ -d "$HOME/.kiro/skills" ] && echo " ~/.kiro/skills/gstack*"
+ [ -d "$HOME/.cursor/skills" ] && echo " ~/.cursor/skills/gstack*"
[ "$KEEP_STATE" -eq 0 ] && [ -d "$STATE_DIR" ] && echo " $STATE_DIR"
if [ -n "$_GIT_ROOT" ]; then
@@ -73,6 +76,7 @@ if [ "$FORCE" -eq 0 ]; then
[ -d "$_GIT_ROOT/.gstack" ] && echo " $_GIT_ROOT/.gstack/ (browse state + reports)"
[ -d "$_GIT_ROOT/.gstack-worktrees" ] && echo " $_GIT_ROOT/.gstack-worktrees/"
[ -d "$_GIT_ROOT/.agents/skills" ] && echo " $_GIT_ROOT/.agents/skills/gstack*"
+ [ -d "$_GIT_ROOT/.cursor/skills" ] && echo " $_GIT_ROOT/.cursor/skills/gstack*"
fi
# Preview running daemons
@@ -130,16 +134,76 @@ fi
# ─── Remove global Claude skills ────────────────────────────
CLAUDE_SKILLS="$HOME/.claude/skills"
+
+# Skill-name inventory (#2563 gate a): every name setup could have installed —
+# each source skill's directory name, its frontmatter name, their gstack-
+# prefixed variants, and the alias dirs. Built BEFORE the install root is
+# removed. A real directory in ~/.claude/skills is only deletable when its
+# name is in this inventory AND its SKILL.md carries the generated banner.
+# The seed names below are the alias dirs setup's _install_alias_skill_md
+# creates (setup: link_claude_root_skill_alias + the connect-chrome call
+# sites) — keep in sync with setup if an alias is added or renamed there.
+_INVENTORY=" _gstack-command connect-chrome gstack-connect-chrome "
+if [ -d "$GSTACK_DIR" ]; then
+ for _SRC in "$GSTACK_DIR"/*/; do
+ [ -f "$_SRC/SKILL.md" ] || continue
+ _SRC_NAME="$(basename "$_SRC")"
+ _FM_NAME=$(grep -m1 '^name:' "$_SRC/SKILL.md" 2>/dev/null | sed 's/^name:[[:space:]]*//' | tr -d '[:space:]' || true)
+ for _N in "$_SRC_NAME" "$_FM_NAME"; do
+ [ -n "$_N" ] || continue
+ case "$_INVENTORY" in *" $_N "*) ;; *) _INVENTORY="$_INVENTORY$_N gstack-$_N " ;; esac
+ done
+ done
+fi
+_in_skill_inventory() { case "$_INVENTORY" in *" $1 "*) return 0 ;; *) return 1 ;; esac; }
+
+_SKIPPED_DIRS=()
if [ -d "$CLAUDE_SKILLS/gstack" ] || [ -L "$CLAUDE_SKILLS/gstack" ]; then
- # Remove per-skill symlinks that point into gstack/
- for _LINK in "$CLAUDE_SKILLS"/*; do
- [ -L "$_LINK" ] || continue
- _NAME="$(basename "$_LINK")"
+ # Remove per-skill entries created by setup. Three install shapes exist:
+ # 1. symlink entry (oldest installs)
+ # 2. real dir + SYMLINKED SKILL.md (standard Unix install)
+ # 3. real dir + REAL-FILE SKILL.md (Windows copy install, #2563)
+ # Shape 3 was skipped entirely — gstack-uninstall exited 0 and reported
+ # success while leaving ~52 gstack-* directories behind on Windows.
+ for _ENTRY in "$CLAUDE_SKILLS"/*; do
+ _NAME="$(basename "$_ENTRY")"
[ "$_NAME" = "gstack" ] && continue
- _TARGET="$(readlink "$_LINK" 2>/dev/null || true)"
- case "$_TARGET" in
- gstack/*|*/gstack/*) rm -f "$_LINK"; REMOVED+=("claude/$_NAME") ;;
- esac
+ if [ -L "$_ENTRY" ]; then
+ _TARGET="$(readlink "$_ENTRY" 2>/dev/null || true)"
+ case "$_TARGET" in
+ gstack/*|*/gstack/*) rm -f "$_ENTRY"; REMOVED+=("claude/$_NAME") ;;
+ esac
+ elif [ -d "$_ENTRY" ] && { [ -f "$_ENTRY/SKILL.md" ] || [ -L "$_ENTRY/SKILL.md" ]; }; then
+ if [ -L "$_ENTRY/SKILL.md" ]; then
+ # Shape 2: provenance readable from the symlink target itself.
+ # Gate 1: the name must be in gstack's skill inventory (parity with
+ # shape 3). Gate 2: the target must contain "gstack" as an ANCHORED
+ # path segment (gstack/*|*/gstack/*, same pattern as shape 1) — a
+ # bare *gstack* substring match would wipe a user's own skill whose
+ # SKILL.md merely lives under e.g. ~/tools/gstack-fork/.
+ _TARGET="$(readlink "$_ENTRY/SKILL.md" 2>/dev/null || true)"
+ if _in_skill_inventory "$_NAME"; then
+ case "$_TARGET" in
+ gstack/*|*/gstack/*) rm -rf "$_ENTRY"; REMOVED+=("claude/$_NAME") ;;
+ *) _SKIPPED_DIRS+=("$_ENTRY") ;;
+ esac
+ else
+ _SKIPPED_DIRS+=("$_ENTRY")
+ fi
+ elif _in_skill_inventory "$_NAME" && grep -q '<!-- AUTO-GENERATED from' "$_ENTRY/SKILL.md" 2>/dev/null; then
+ # Shape 3: delete ONLY when BOTH gates pass (F8) — the name is in
+ # gstack's skill inventory AND the SKILL.md carries the existing
+ # generated banner. ENG-OV10: the banner IS the provenance marker —
+ # every pre-v1.67 copy already carries it; inventing a new marker
+ # would refuse to delete legitimate old installs, recreating #2563.
+ rm -rf "$_ENTRY"
+ REMOVED+=("claude/$_NAME")
+ else
+ # A real dir we cannot prove is gstack-managed (name collision with a
+ # user's own skill, or a hand-written SKILL.md): NEVER delete — list.
+ _SKIPPED_DIRS+=("$_ENTRY")
+ fi
+ fi
done
rm -rf "$CLAUDE_SKILLS/gstack"
@@ -191,6 +255,32 @@ if [ -d "$KIRO_SKILLS" ]; then
done
fi
+# ─── Remove Cursor skills ───────────────────────────────────
+# Cursor installs are rendered REAL directories, so a bare gstack* glob could
+# sweep a user's own dir that merely starts with "gstack" (e.g.
+# ~/.cursor/skills/gstack-fork-notes). Provenance gate: a real dir is only
+# deleted when its SKILL.md carries the generated banner; anything else is
+# listed, never deleted. Symlinks stay ungated — removing a link never
+# destroys user content.
+_cursor_item_is_gstack_managed() {
+ # Symlinks and plain files are safe to remove; real dirs need the banner.
+ if [ -L "$1" ] || [ ! -d "$1" ]; then return 0; fi
+ grep -q '<!-- AUTO-GENERATED from' "$1/SKILL.md" 2>/dev/null
+}
+
+CURSOR_SKILLS="$HOME/.cursor/skills"
+if [ -d "$CURSOR_SKILLS" ]; then
+ for _ITEM in "$CURSOR_SKILLS"/gstack*; do
+ [ -e "$_ITEM" ] || [ -L "$_ITEM" ] || continue
+ if _cursor_item_is_gstack_managed "$_ITEM"; then
+ rm -rf "$_ITEM"
+ REMOVED+=("cursor/$(basename "$_ITEM")")
+ else
+ _SKIPPED_DIRS+=("$_ITEM")
+ fi
+ done
+fi
+
# ─── Remove per-project .agents/ sidecar ─────────────────────
if [ -n "$_GIT_ROOT" ] && [ -d "$_GIT_ROOT/.agents/skills" ]; then
for _ITEM in "$_GIT_ROOT/.agents/skills"/gstack*; do
@@ -215,6 +305,23 @@ if [ -n "$_GIT_ROOT" ] && [ -d "$_GIT_ROOT/.factory/skills" ]; then
rmdir "$_GIT_ROOT/.factory" 2>/dev/null || true
fi
+# ─── Remove per-project .cursor/skills/gstack* ──────────────
+# Never rmdir .cursor itself — Cursor IDE stores rules and other user config there.
+# Same provenance gate as the global cursor block above.
+if [ -n "$_GIT_ROOT" ] && [ -d "$_GIT_ROOT/.cursor/skills" ]; then
+ for _ITEM in "$_GIT_ROOT/.cursor/skills"/gstack*; do
+ [ -e "$_ITEM" ] || [ -L "$_ITEM" ] || continue
+ if _cursor_item_is_gstack_managed "$_ITEM"; then
+ rm -rf "$_ITEM"
+ REMOVED+=("cursor/$(basename "$_ITEM")")
+ else
+ _SKIPPED_DIRS+=("$_ITEM")
+ fi
+ done
+
+ rmdir "$_GIT_ROOT/.cursor/skills" 2>/dev/null || true
+fi
+
# ─── Remove per-project state ───────────────────────────────
if [ -n "$_GIT_ROOT" ]; then
if [ -d "$_GIT_ROOT/.gstack" ]; then
@@ -236,6 +343,10 @@ if [ -x "$SETTINGS_HOOK" ]; then
if "$SETTINGS_HOOK" remove-source --source plan-tune-cathedral 2>/dev/null | grep -q "removed [1-9]"; then
REMOVED+=("plan-tune cathedral hooks")
fi
+ # Timeline Stop hook (#2553).
+ if "$SETTINGS_HOOK" remove-source --source gstack-timeline-stop 2>/dev/null | grep -q "removed [1-9]"; then
+ REMOVED+=("timeline Stop hook")
+ fi
fi
# ─── Remove global state ────────────────────────────────────
@@ -252,6 +363,16 @@ for _TMP in /tmp/gstack-latest-version /tmp/gstack-sketch-*.html /tmp/gstack-ske
fi
done
+# ─── Skipped-entry report ───────────────────────────────────
+# Everything any provenance gate refused to delete (Claude shapes 2/3,
+# cursor real dirs) — listed once, at the end, so nothing is silent.
+if [ ${#_SKIPPED_DIRS[@]} -gt 0 ]; then
+ echo "left in place (not provably gstack-managed — remove by hand if they are yours):" >&2
+ for _D in "${_SKIPPED_DIRS[@]}"; do
+ echo " $_D" >&2
+ done
+fi
+
# ─── Summary ────────────────────────────────────────────────
if [ ${#REMOVED[@]} -gt 0 ]; then
echo "Removed: ${REMOVED[*]}"
diff --git a/bin/gstack-version-bump b/bin/gstack-version-bump
index 298fab17d..cf756800e 100755
--- a/bin/gstack-version-bump
+++ b/bin/gstack-version-bump
@@ -30,15 +30,35 @@
// DRIFT_STALE_PKG path: sync package.json.version to the current VERSION
// file. No bump. Validates the VERSION pattern first.
//
-// Contract: classify NEVER writes. write/repair mutate VERSION + package.json
-// only. No git mutation, no network. Mirrors gstack-next-version's reader/writer
-// split so /ship composes them.
+// Contract: classify NEVER writes. write/repair mutate VERSION + the manifest
+// + npm lockfiles (package-lock.json / npm-shrinkwrap.json, when present)
+// only. No git mutation, no network. Mirrors gstack-next-version's
+// reader/writer split so /ship composes them.
+//
+// Manifest resolution (all three subcommands accept --package-json-path):
+// --package-json-path <p> → .gstack/package-json-path → ./package.json
+// A repo whose only Node package lives in a subdirectory (web/, app/,
+// frontend/) has no ROOT package.json. The tool used to report
+// pkgExists:false there and write VERSION alone, leaving the manifest to be
+// bumped by hand — the drift this tool exists to prevent, in the one layout
+// where it silently did nothing (#2531).
+//
+// npm semver (decision 11, v1.67 fix-wave plan): VERSION is the 4-digit
+// MAJOR.MINOR.PATCH.MICRO source of truth; npm rejects a fourth component,
+// so the manifest and its lockfiles carry the npm-valid 3-digit translation
+// (1.67.0.0 → 1.67.0). classify judges drift against the translated form
+// (accepting the pre-v1.67 1:1 mirror as in-sync until the next write).
-import { existsSync, readFileSync, writeFileSync } from "node:fs";
+import { existsSync, readFileSync, realpathSync, writeFileSync } from "node:fs";
import { execFileSync } from "node:child_process";
-import { join } from "node:path";
+import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
+import { extractVersion, isJsonVersionPath, npmVersion, setVersionInJson } from "../lib/version-source";
-const VERSION_RE = /^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$/;
+// 3- or 4-digit (#2501). gstack's own VERSION stays 4-digit MAJOR.MINOR.PATCH.
+// MICRO and stays the source of truth, but a repo whose pinned version source
+// is a package.json holds plain 3-digit semver, and rejecting it here meant
+// /ship could not write a version at all in such a repo. See lib/version-source.ts.
+const VERSION_RE = /^[0-9]+\.[0-9]+\.[0-9]+(\.[0-9]+)?$/;
const DEFAULT = "0.0.0.0";
type State = "FRESH" | "ALREADY_BUMPED" | "DRIFT_STALE_PKG" | "DRIFT_UNEXPECTED";
@@ -53,29 +73,109 @@ function argVal(args: string[], flag: string): string | undefined {
return i >= 0 && i + 1 < args.length ? args[i + 1] : undefined;
}
-/** Resolve the VERSION file path: --version-path, else .gstack/version-path, else "VERSION". */
-function resolveVersionPath(cwd: string, explicit?: string): string {
- if (explicit) return join(cwd, explicit);
+/**
+ * Containment guard: `.gstack/version-path` and `.gstack/package-json-path`
+ * are repo-controlled content. Without this, a cloned repo pinning
+ * `../../victim.json` — or an in-repo symlink pointing outside — turns a
+ * routine bump into an arbitrary file overwrite outside the repository.
+ * Rejects absolute paths, lexical `..` escapes, and symlink escapes (the
+ * deepest EXISTING ancestor is realpath'd, so a not-yet-created VERSION
+ * file is still checked through its parent directory).
+ */
+function assertRepoContained(cwd: string, rel: string, source: string): void {
+ const root = realpathSync(cwd);
+ const abs = resolve(root, rel);
+ const lex = relative(root, abs);
+ if (isAbsolute(rel) || lex === "" || lex.startsWith("..") || isAbsolute(lex)) {
+ fail(`${source} ('${rel}') resolves outside the repository. Refusing to read or write it.`, 2);
+ }
+ let probe = abs;
+ while (!existsSync(probe)) {
+ const parent = dirname(probe);
+ if (parent === probe) break;
+ probe = parent;
+ }
+ let real: string;
+ try {
+ real = realpathSync(probe);
+ } catch {
+ return; // vanished between existsSync and realpath — the read/write will fail honestly on its own
+ }
+ if (real !== root && !real.startsWith(root + sep)) {
+ fail(`${source} ('${rel}') resolves through a symlink to outside the repository. Refusing to read or write it.`, 2);
+ }
+}
+
+/**
+ * Resolve the version file's path RELATIVE to the repo root: --version-path,
+ * else .gstack/version-path, else "VERSION".
+ *
+ * The relative form is what matters — `git show origin/<base>:<rel>` needs it
+ * (an absolute path is unusable there). Callers used to
+ * derive versionRel from the CLI flag alone (#2462), so a repo using the
+ * .gstack/version-path pin had its local (pinned) version compared against
+ * the BASE's root VERSION file: two different files. On a repo with no root
+ * VERSION the base then always read 0.0.0.0, making every branch look FRESH —
+ * and the pinned-JSON handling never engaged without the explicit flag.
+ * Resolving once, here, keeps base and current reads in step.
+ */
+function resolveVersionRel(cwd: string, explicit?: string): string {
+ if (explicit) {
+ const rel = explicit.trim();
+ assertRepoContained(cwd, rel, "--version-path");
+ return rel;
+ }
const pin = join(cwd, ".gstack", "version-path");
if (existsSync(pin)) {
- const p = readFileSync(pin, "utf-8").trim();
- if (p) return join(cwd, p);
+ const p = readFileSync(pin, "utf-8").split("\n")[0]?.trim() ?? "";
+ if (p) {
+ assertRepoContained(cwd, p, ".gstack/version-path");
+ return p;
+ }
}
- return join(cwd, "VERSION");
+ return "VERSION";
}
-function readVersionFile(p: string): string {
+
+function readVersionFile(p: string, versionRel = "VERSION"): string {
try {
- const v = readFileSync(p, "utf-8").replace(/[\r\n\s]/g, "");
+ // extractVersion (#2501): a .json version-path is read as JSON (.version),
+ // not whitespace-stripped raw text that turns a package.json into garbage.
+ const v = extractVersion(readFileSync(p, "utf-8"), versionRel);
return v || DEFAULT;
} catch {
return DEFAULT;
}
}
+/**
+ * Resolve the manifest path: --package-json-path, else
+ * .gstack/package-json-path, else "package.json" (#2531, mirrors
+ * resolveVersionRel). A repo whose only Node package lives in a
+ * subdirectory (web/, app/, frontend/) has no ROOT package.json, so the
+ * old join(cwd, "package.json") reported pkgExists:false and every bump
+ * silently wrote VERSION alone — leaving the manifest to be edited by
+ * hand, which is exactly the drift this tool exists to prevent.
+ */
+function resolvePkgPath(cwd: string, explicit?: string): string {
+ if (explicit) {
+ const rel = explicit.trim();
+ assertRepoContained(cwd, rel, "--package-json-path");
+ return join(cwd, rel);
+ }
+ const pin = join(cwd, ".gstack", "package-json-path");
+ if (existsSync(pin)) {
+ const p = readFileSync(pin, "utf-8").split("\n")[0]?.trim() ?? "";
+ if (p) {
+ assertRepoContained(cwd, p, ".gstack/package-json-path");
+ return join(cwd, p);
+ }
+ }
+ return join(cwd, "package.json");
+}
+
/** package.json version + existence, parsed without spawning node. */
-function readPkgVersion(cwd: string): { exists: boolean; version: string } {
- const pkgPath = join(cwd, "package.json");
+function readPkgVersion(pkgPath: string): { exists: boolean; version: string } {
if (!existsSync(pkgPath)) return { exists: false, version: "" };
let raw: string;
try {
@@ -87,20 +187,65 @@ function readPkgVersion(cwd: string): { exists: boolean; version: string } {
try {
parsed = JSON.parse(raw);
} catch {
- fail("package.json is not valid JSON. Fix the file before re-running /ship.", 2);
+ fail(`${pkgPath} is not valid JSON. Fix the file before re-running /ship.`, 2);
}
const version = (parsed as { version?: unknown })?.version;
return { exists: true, version: typeof version === "string" ? version : "" };
}
-function writePkgVersion(cwd: string, version: string): void {
- const pkgPath = join(cwd, "package.json");
+function writePkgVersion(pkgPath: string, version: string): void {
const raw = readFileSync(pkgPath, "utf-8");
const parsed = JSON.parse(raw) as Record<string, unknown>;
parsed.version = version;
writeFileSync(pkgPath, JSON.stringify(parsed, null, 2) + "\n");
}
+/**
+ * npm records the package version twice in its lockfiles — top-level
+ * `version` and, in lockfileVersion >= 2, `packages[""].version` (the entry
+ * describing the root package itself) — and `npm install` keeps both in
+ * step. Nothing else in a release does, so a lockfile left behind drifts one
+ * field per bump until someone runs npm, dirtying the tree on the next
+ * `npm install` far from the cause (#2567). Pure JSON edit: no npm spawn,
+ * no dependency-tree churn.
+ *
+ * Synced ONLY when the file already exists — never created (gstack itself
+ * is bun-only; decision pinned in the v1.67 fix-wave plan).
+ * npm-shrinkwrap.json shares the format and, when present, is what npm
+ * actually honors, so both names are covered. Returns the names synced.
+ */
+const NPM_LOCKFILES = ["package-lock.json", "npm-shrinkwrap.json"];
+function syncNpmLockfiles(dir: string, version: string, root: string): string[] {
+ const synced: string[] = [];
+ for (const name of NPM_LOCKFILES) {
+ const lockPath = join(dir, name);
+ if (!existsSync(lockPath)) continue;
+ // A lockfile that is a symlink out of the repo would make this write an
+ // arbitrary-file overwrite (same class as the version-path pin escape).
+ // Skip with a warning — unlike the pins, a weird lockfile shouldn't
+ // brick the whole bump.
+ try {
+ const realRoot = realpathSync(root);
+ const realLock = realpathSync(lockPath);
+ if (realLock !== realRoot && !realLock.startsWith(realRoot + sep)) {
+ process.stderr.write(`WARNING: ${name} resolves outside the repository (symlink); not synced.\n`);
+ continue;
+ }
+ } catch {
+ continue;
+ }
+ const parsed = JSON.parse(readFileSync(lockPath, "utf-8")) as Record<string, unknown>;
+ parsed.version = version;
+ const packages = parsed.packages as Record<string, Record<string, unknown>> | undefined;
+ if (packages && typeof packages[""] === "object" && packages[""] !== null) {
+ packages[""].version = version;
+ }
+ writeFileSync(lockPath, JSON.stringify(parsed, null, 2) + "\n");
+ synced.push(name);
+ }
+ return synced;
+}
+
function baseVersion(cwd: string, base: string, versionRel: string): string {
// Verify the base ref resolves, mirroring the Step 12 guard.
try {
@@ -110,35 +255,64 @@ function baseVersion(cwd: string, base: string, versionRel: string): string {
}
try {
const out = execFileSync("git", ["show", `origin/${base}:${versionRel}`], { cwd }).toString();
- const v = out.replace(/[\r\n\s]/g, "");
- return v || DEFAULT;
+ return extractVersion(out, versionRel) || DEFAULT;
} catch {
// VERSION absent on base (new repo / new file) → treat as 0.0.0.0.
return DEFAULT;
}
}
-function classifyState(current: string, base: string, pkgExists: boolean, pkgVersion: string): State {
+/**
+ * `expectedPkg` is what the manifest SHOULD hold for the current VERSION —
+ * the npm-valid 3-digit translation (decision 11: npm rejects a fourth
+ * component, so a correctly-synced `1.67.0` must not read as drift against
+ * `1.67.0.0` forever). The historical 1:1 mirror (pre-v1.67 installs whose
+ * package.json still carries the 4-digit form) is also accepted as in-sync;
+ * write/repair migrate those to the translated form on the next release.
+ */
+function classifyState(
+ current: string,
+ base: string,
+ pkgExists: boolean,
+ pkgVersion: string,
+ expectedPkg: string = current,
+): State {
+ const pkgAgrees =
+ !pkgExists || !pkgVersion || pkgVersion === expectedPkg || pkgVersion === current;
if (current === base) {
// VERSION unchanged vs base. A diverging package.json means someone hand-edited
// package.json bypassing /ship — unsafe to guess which is authoritative.
- if (pkgExists && pkgVersion && pkgVersion !== current) return "DRIFT_UNEXPECTED";
+ if (!pkgAgrees) return "DRIFT_UNEXPECTED";
return "FRESH";
}
// VERSION already moved past base.
- if (pkgExists && pkgVersion && pkgVersion !== current) return "DRIFT_STALE_PKG";
+ if (!pkgAgrees) return "DRIFT_STALE_PKG";
return "ALREADY_BUMPED";
}
function cmdClassify(args: string[], cwd: string): void {
const base = argVal(args, "--base");
if (!base) fail("classify requires --base <branch>", 2);
- const versionPath = resolveVersionPath(cwd, argVal(args, "--version-path"));
- const versionRel = argVal(args, "--version-path") ?? "VERSION";
- const current = readVersionFile(versionPath);
+ const versionRel = resolveVersionRel(cwd, argVal(args, "--version-path"));
+ const versionPath = join(cwd, versionRel);
+ const current = readVersionFile(versionPath, versionRel);
const baseV = baseVersion(cwd, base!, versionRel);
- const pkg = readPkgVersion(cwd);
- const state = classifyState(current, baseV, pkg.exists, pkg.version);
+ // When the version-path IS a package.json (#2501), that file is the single
+ // source of truth and the "VERSION vs package.json" drift states cannot
+ // arise — they are the same file. Reporting it as its own pkg keeps DRIFT_*
+ // out of the classification instead of inventing a disagreement between a
+ // file and itself.
+ const jsonSource = isJsonVersionPath(versionRel);
+ const pkgPath = jsonSource ? versionPath : resolvePkgPath(cwd, argVal(args, "--package-json-path"));
+ const pkg = jsonSource
+ ? { exists: existsSync(versionPath), version: current === DEFAULT ? "" : current }
+ : readPkgVersion(pkgPath);
+ // Decision 11: the manifest carries the npm-valid 3-digit translation of
+ // the 4-digit VERSION; drift is judged against the translated form. A
+ // JSON version-path is its own source of truth, so its expected form is
+ // the version itself.
+ const expectedPkg = jsonSource ? current : npmVersion(current);
+ const state = classifyState(current, baseV, pkg.exists, pkg.version, expectedPkg);
process.stdout.write(
JSON.stringify({
state,
@@ -146,6 +320,8 @@ function cmdClassify(args: string[], cwd: string): void {
currentVersion: current,
pkgVersion: pkg.version || null,
pkgExists: pkg.exists,
+ pkgPath: pkg.exists ? relative(cwd, pkgPath) : null,
+ expectedPkgVersion: pkg.exists ? expectedPkg : null,
}) + "\n",
);
// DRIFT_UNEXPECTED is a real, decidable state — the caller stops on it, but the
@@ -157,43 +333,143 @@ function cmdWrite(args: string[], cwd: string): void {
const version = argVal(args, "--version");
if (!version) fail("write requires --version <X.Y.Z.W>", 2);
if (!VERSION_RE.test(version!)) {
- fail(`NEW_VERSION (${version}) does not match MAJOR.MINOR.PATCH.MICRO. Aborting.`, 2);
+ fail(`NEW_VERSION (${version}) does not match MAJOR.MINOR.PATCH[.MICRO]. Aborting.`, 2);
}
- const versionPath = resolveVersionPath(cwd, argVal(args, "--version-path"));
+ const versionRel = resolveVersionRel(cwd, argVal(args, "--version-path"));
+ const versionPath = join(cwd, versionRel);
+
+ // A package.json version-path (#2501) is written in place, keeping the rest
+ // of the file intact — and it is the ONLY file written. Also syncing a root
+ // package.json here would be a guess about which of two JSON files the repo
+ // actually publishes from; in a monorepo whose truth is frontend/package.json
+ // the root one either doesn't exist or isn't the version users see.
+ if (isJsonVersionPath(versionRel)) {
+ if (!existsSync(versionPath)) {
+ fail(`write: ${versionRel} does not exist. Check --version-path / .gstack/version-path.`, 2);
+ }
+ // Decision 11: a JSON manifest can only carry npm-valid semver. A repo
+ // whose package.json still mirrors the legacy 4-digit form and pins it as
+ // the version-path would otherwise get "1.67.0.1" written into a manifest
+ // npm rejects forever — with no drift state to catch it (a JSON source is
+ // self-consistent by construction).
+ const jsonV = npmVersion(version!);
+ let manifestWritten = false;
+ let lockSynced: string[] = [];
+ try {
+ writeFileSync(versionPath, setVersionInJson(readFileSync(versionPath, "utf-8"), jsonV));
+ manifestWritten = true;
+ // The pinned manifest's OWN lockfiles (beside it) stay in step too.
+ lockSynced = syncNpmLockfiles(dirname(versionPath), jsonV, cwd);
+ } catch {
+ fail(
+ manifestWritten
+ ? `write: ${versionRel} was updated but its npm lockfiles were not (corrupt lockfile?). ` +
+ "Fix or delete the lockfile beside it, then re-run write with the same --version."
+ : `write: failed to update ${versionRel} (is it valid JSON?).`,
+ 3,
+ );
+ }
+ if (jsonV !== version) {
+ process.stderr.write(
+ `write: ${versionRel} carries the npm-valid translation ${jsonV} (a JSON manifest cannot hold 4-digit ${version}). ` +
+ "Consecutive MICRO releases translate to the SAME manifest version — pin a plain VERSION file if that matters.\n",
+ );
+ }
+ process.stdout.write(
+ JSON.stringify({
+ wrote: jsonV,
+ // Only surfaced when a 4-digit request was translated (the healthy
+ // 3-digit-pinned path is an identity write).
+ ...(jsonV !== version ? { requestedVersion: version } : {}),
+ versionPath: versionRel,
+ packageJson: true,
+ packageLock: lockSynced.length > 0,
+ }) + "\n",
+ );
+ return;
+ }
+
+ const pkgPath = resolvePkgPath(cwd, argVal(args, "--package-json-path"));
+ const hasPkg = existsSync(pkgPath);
writeFileSync(versionPath, version + "\n");
- if (existsSync(join(cwd, "package.json"))) {
+ let lockSynced: string[] = [];
+ // Decision 11: the manifest (and its lockfiles) carry the npm-valid
+ // 3-digit translation — npm rejects a fourth component, so mirroring the
+ // raw 4-digit form breaks `npm ci` in any repo npm actually manages.
+ // VERSION keeps the full 4-digit form; it stays the source of truth.
+ const manifestV = npmVersion(version!);
+ if (hasPkg) {
+ let pkgWritten = false;
try {
- writePkgVersion(cwd, version!);
+ writePkgVersion(pkgPath, manifestV);
+ pkgWritten = true;
+ lockSynced = syncNpmLockfiles(dirname(pkgPath), manifestV, cwd);
} catch {
+ // Accurate recovery per failure point: classify only reads
+ // package.json (never lockfiles), so "re-run and repair" is only true
+ // when package.json itself is the stale file.
fail(
- "failed to update package.json. VERSION was written but package.json is now stale. " +
- "Re-run — classify will report DRIFT_STALE_PKG and repair will sync it.",
+ pkgWritten
+ ? `VERSION and ${relative(cwd, pkgPath)} were written but the npm lockfiles were not ` +
+ "(corrupt lockfile?). classify cannot see lockfile drift — fix or delete the lockfile, " +
+ "then re-run write with the same --version."
+ : `failed to update ${relative(cwd, pkgPath)}. VERSION was written but package.json is now ` +
+ "stale. Re-run — classify will report DRIFT_STALE_PKG and repair will sync it.",
3,
);
}
}
- process.stdout.write(JSON.stringify({ wrote: version, packageJson: existsSync(join(cwd, "package.json")) }) + "\n");
+ process.stdout.write(
+ JSON.stringify({
+ wrote: version,
+ packageJson: hasPkg,
+ packageJsonPath: hasPkg ? relative(cwd, pkgPath) : null,
+ packageJsonVersion: hasPkg ? manifestV : null,
+ packageLock: lockSynced.length > 0,
+ }) + "\n",
+ );
}
function cmdRepair(args: string[], cwd: string): void {
- const versionPath = resolveVersionPath(cwd, argVal(args, "--version-path"));
- const current = readVersionFile(versionPath);
+ const versionRel = resolveVersionRel(cwd, argVal(args, "--version-path"));
+ const versionPath = join(cwd, versionRel);
+ // Nothing to repair when the version lives in a package.json (#2501): there
+ // is no second file to drift from, and classify never reports DRIFT_* for
+ // that shape.
+ if (isJsonVersionPath(versionRel)) {
+ process.stdout.write(
+ JSON.stringify({ repaired: null, reason: `${versionRel} is the single source of truth; no drift possible` }) + "\n",
+ );
+ return;
+ }
+ const current = readVersionFile(versionPath, versionRel);
if (!VERSION_RE.test(current)) {
fail(
- `VERSION file contents (${current}) do not match MAJOR.MINOR.PATCH.MICRO. ` +
+ `VERSION file contents (${current}) do not match MAJOR.MINOR.PATCH[.MICRO]. ` +
"Refusing to propagate invalid semver into package.json. Fix VERSION, then re-run /ship.",
2,
);
}
- if (!existsSync(join(cwd, "package.json"))) {
- fail("repair: no package.json to sync.", 2);
+ const pkgPath = resolvePkgPath(cwd, argVal(args, "--package-json-path"));
+ if (!existsSync(pkgPath)) {
+ fail(`repair: no package.json to sync (looked at ${relative(cwd, pkgPath)}).`, 2);
}
+ // Decision 11: repair syncs the manifest + lockfiles to the npm-valid
+ // 3-digit translation of the current VERSION.
+ const manifestV = npmVersion(current);
try {
- writePkgVersion(cwd, current);
+ writePkgVersion(pkgPath, manifestV);
+ syncNpmLockfiles(dirname(pkgPath), manifestV, cwd);
} catch {
- fail("drift repair failed — could not update package.json.", 3);
+ fail("drift repair failed — could not update package.json/npm lockfiles.", 3);
}
- process.stdout.write(JSON.stringify({ repaired: current }) + "\n");
+ process.stdout.write(
+ JSON.stringify({
+ repaired: current,
+ packageJsonPath: relative(cwd, pkgPath),
+ packageJsonVersion: manifestV,
+ }) + "\n",
+ );
}
// Exported for unit tests (pure logic, no I/O).
diff --git a/browse/SKILL.md b/browse/SKILL.md
index d977f363f..964c6d3c2 100644
--- a/browse/SKILL.md
+++ b/browse/SKILL.md
@@ -108,9 +108,11 @@ else
fi
~/.claude/skills/gstack/bin/gstack-timeline-log '{"skill":"browse","event":"started","branch":"'"$_BRANCH"'","session":"'"$_SESSION_ID"'"}' 2>/dev/null &
_HAS_ROUTING="no"
-if [ -f CLAUDE.md ] && grep -q "## Skill routing" CLAUDE.md 2>/dev/null; then
- _HAS_ROUTING="yes"
-fi
+for _RF in CLAUDE.md AGENTS.md; do
+ if [ -f "$_RF" ] && grep -q "## Skill routing" "$_RF" 2>/dev/null; then
+ _HAS_ROUTING="yes"
+ fi
+done
_ROUTING_DECLINED=$(~/.claude/skills/gstack/bin/gstack-config get routing_declined 2>/dev/null || echo "false")
echo "HAS_ROUTING: $_HAS_ROUTING"
echo "ROUTING_DECLINED: $_ROUTING_DECLINED"
@@ -379,10 +381,13 @@ _BRAIN_SYNC_MODE=$("$_BRAIN_CONFIG_BIN" get artifacts_sync_mode 2>/dev/null || e
# Detect remote-MCP mode (Path 4 of /setup-gbrain). Local artifacts sync is
# a no-op in remote mode; the brain server pulls from GitHub/GitLab on its
# own cadence. Read claude.json directly to keep this preamble fast (no
-# subprocess to claude CLI on every skill start).
+# subprocess to claude CLI on every skill start). Both registration scopes
+# are read (#2499): user scope, then the nearest-ancestor project scope.
_GBRAIN_MCP_MODE="none"
+_GBRAIN_MCP_ENTRY=""
if command -v jq >/dev/null 2>&1 && [ -f "$HOME/.claude.json" ]; then
- _GBRAIN_MCP_TYPE=$(jq -r '.mcpServers.gbrain.type // .mcpServers.gbrain.transport // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_ENTRY=$(jq -c --arg cwd "$PWD" '.mcpServers.gbrain // ((.projects // {}) | to_entries | map(select((.key as $k | $cwd == $k or ($cwd | startswith($k + "/"))) and ((try .value.mcpServers.gbrain catch null) != null))) | sort_by(.key | length) | last | .value.mcpServers.gbrain) // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_TYPE=$(printf '%s' "$_GBRAIN_MCP_ENTRY" | jq -r '.type // .transport // empty' 2>/dev/null)
case "$_GBRAIN_MCP_TYPE" in
url|http|sse) _GBRAIN_MCP_MODE="remote-http" ;;
stdio) _GBRAIN_MCP_MODE="local-stdio" ;;
@@ -403,6 +408,7 @@ if [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_DO_PULL=1
if [ -f "$_BRAIN_LAST_PULL_FILE" ]; then
_BRAIN_LAST=$(cat "$_BRAIN_LAST_PULL_FILE" 2>/dev/null || echo 0)
+ case "$_BRAIN_LAST" in ''|*[!0-9]*) _BRAIN_LAST=0 ;; esac
_BRAIN_AGE=$(( _BRAIN_NOW - _BRAIN_LAST ))
[ "$_BRAIN_AGE" -lt 86400 ] && _BRAIN_DO_PULL=0
fi
@@ -416,7 +422,7 @@ fi
if [ "$_GBRAIN_MCP_MODE" = "remote-http" ]; then
# Remote-MCP mode: local artifacts sync is a no-op (brain admin's server
# pulls from GitHub/GitLab). Show the user this is by design, not broken.
- _GBRAIN_HOST=$(jq -r '.mcpServers.gbrain.url // empty' "$HOME/.claude.json" 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|')
+ _GBRAIN_HOST=$(printf '%s' "${_GBRAIN_MCP_ENTRY:-}" | jq -r '.url // empty' 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|' | head -1 | tr -cd 'A-Za-z0-9._-')
echo "ARTIFACTS_SYNC: remote-mode (managed by brain server ${_GBRAIN_HOST:-remote})"
elif [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_QUEUE_DEPTH=0
@@ -618,6 +624,18 @@ $B screenshot /tmp/bug.png # plain screenshot
$B console # error log
```
+Two behaviors that silently invalidate screenshots (#2445 — designed, but
+surprising):
+- **`hover` scrolls its target into view.** Hovering anything below the fold
+ scrolls the page first, so a "rest state" shot taken afterwards captures
+ the wrong section with exit 0. Before a rest-state screenshot, hover only
+ something already visible, and assert position when it matters:
+ `$B js "window.scrollY"` should be `0` (or your intended offset).
+- **The tab persists across sessions.** The daemon keeps its tab between your
+ sessions, so `reload` or `screenshot` without a preceding `goto` can act on
+ whatever page earlier work left open. Start verification passes with an
+ explicit `$B goto <url>`, never a bare `reload`.
+
### 5. Find all clickable elements (including non-ARIA)
```bash
$B snapshot -C # finds divs with cursor:pointer, onclick, tabindex
diff --git a/browse/SKILL.md.tmpl b/browse/SKILL.md.tmpl
index 1da7698b2..81a91775e 100644
--- a/browse/SKILL.md.tmpl
+++ b/browse/SKILL.md.tmpl
@@ -65,6 +65,18 @@ $B screenshot /tmp/bug.png # plain screenshot
$B console # error log
```
+Two behaviors that silently invalidate screenshots (#2445 — designed, but
+surprising):
+- **`hover` scrolls its target into view.** Hovering anything below the fold
+ scrolls the page first, so a "rest state" shot taken afterwards captures
+ the wrong section with exit 0. Before a rest-state screenshot, hover only
+ something already visible, and assert position when it matters:
+ `$B js "window.scrollY"` should be `0` (or your intended offset).
+- **The tab persists across sessions.** The daemon keeps its tab between your
+ sessions, so `reload` or `screenshot` without a preceding `goto` can act on
+ whatever page earlier work left open. Start verification passes with an
+ explicit `$B goto <url>`, never a bare `reload`.
+
### 5. Find all clickable elements (including non-ARIA)
```bash
$B snapshot -C # finds divs with cursor:pointer, onclick, tabindex
diff --git a/browse/scripts/build-node-server.sh b/browse/scripts/build-node-server.sh
index 5ee2dd4d0..c7b1b09b7 100755
--- a/browse/scripts/build-node-server.sh
+++ b/browse/scripts/build-node-server.sh
@@ -8,8 +8,14 @@
set -e
GSTACK_DIR="$(cd "$(dirname "$0")/../.." && pwd)"
+# Windows (MSYS/Git Bash): convert to a Windows-style path — Bun cannot open
+# MSYS /c/... absolute paths ("FileNotFound opening root directory").
+case "$(uname -s)" in
+ MINGW*|MSYS*|CYGWIN*) GSTACK_DIR="$(cygpath -m "$GSTACK_DIR")" ;;
+esac
SRC_DIR="$GSTACK_DIR/browse/src"
DIST_DIR="$GSTACK_DIR/browse/dist"
+mkdir -p "$DIST_DIR"
echo "Building Node-compatible server bundle..."
diff --git a/browse/src/browse-client.ts b/browse/src/browse-client.ts
index 435f57546..499b366f7 100644
--- a/browse/src/browse-client.ts
+++ b/browse/src/browse-client.ts
@@ -103,7 +103,7 @@ export function resolveBrowseAuth(opts: BrowseClientOptions = {}): ResolvedAuth
function defaultStateFile(): string | null {
try {
- const proc = cp.spawnSync('git', ['rev-parse', '--show-toplevel'], { encoding: 'utf-8', timeout: 2000 });
+ const proc = cp.spawnSync('git', ['rev-parse', '--show-toplevel'], { encoding: 'utf-8', timeout: 2000, windowsHide: true });
const root = proc.status === 0 ? proc.stdout.trim() : null;
const base = root || process.cwd();
return path.join(base, '.gstack', 'browse.json');
diff --git a/browse/src/browser-manager.ts b/browse/src/browser-manager.ts
index a18bb92bd..6a0050a7d 100644
--- a/browse/src/browser-manager.ts
+++ b/browse/src/browser-manager.ts
@@ -22,6 +22,7 @@ import { emitActivity } from './activity';
import { validateNavigationUrl } from './url-validation';
import { TabSession, type RefEntry } from './tab-session';
import { resolveChromiumProfile, cleanSingletonLocks } from './config';
+import { launchWithXProtectHeal } from './xprotect-heal';
import { withCdpSession } from './cdp-bridge';
import type { MemorySnapshot, MemoryStructureStats, MemoryTabSnapshot, MemoryProcess } from './memory-snapshot';
@@ -458,8 +459,23 @@ export class BrowserManager {
console.log(`[browse] Extensions loaded from: ${extensionsDir}`);
}
- this.browser = await chromium.launch({
+ // XProtect self-heal wrapper (P0 #2554): a macOS definition update can
+ // start SIGKILLing the pinned Chromium at spawn. On the classified
+ // signature, clear quarantine on the Playwright cache + force-reinstall
+ // once, then retry this launch once. This headless path always uses the
+ // Playwright cache (no executablePath), so the heal is never scoped out.
+ this.browser = await launchWithXProtectHeal(() => chromium.launch({
headless: useHeadless,
+ // #2220: the daemon owns signal policy, not Playwright. Playwright's
+ // default handlers close Chromium the moment THIS process receives
+ // SIGINT/SIGTERM/SIGHUP — which fights the deliberate headless
+ // SIGTERM-ignore in server.ts (the daemon survives the signal but
+ // loses its browser out from under it). All three are false; server.ts
+ // routes the signals it actually honors through activeShutdown, which
+ // closes Chromium itself.
+ handleSIGINT: false,
+ handleSIGTERM: false,
+ handleSIGHUP: false,
// On Windows, Chromium's sandbox fails when the server is spawned through
// the Bun→Node process chain (GitHub #276). Disable it — local daemon
// browsing user-specified URLs has marginal sandbox benefit. Also disabled
@@ -468,7 +484,7 @@ export class BrowserManager {
chromiumSandbox: shouldEnableChromiumSandbox(),
...(launchArgs.length > 0 ? { args: launchArgs } : {}),
...(this.proxyConfig ? { proxy: this.proxyConfig } : {}),
- });
+ }));
// Chromium disconnect → distinguish clean user-quit from crash. Both
// events look identical to Playwright (one 'disconnected' fires), but
@@ -651,8 +667,16 @@ export class BrowserManager {
// three more (--disable-popup-blocking, --disable-component-update,
// --disable-default-apps — each a documented automation tell per Patchright).
const { STEALTH_IGNORE_DEFAULT_ARGS } = await import('./stealth');
- this.context = await chromium.launchPersistentContext(userDataDir, {
+ // XProtect self-heal wrapper (P0 #2554). usesCustomExecutable scopes the
+ // heal out when GSTACK_CHROMIUM_PATH supplies the bundle — that bundle
+ // belongs to the wrapper/embedder and is never quarantine-cleared or
+ // reinstalled over (probePoisonedChromiumBundle's scope contract).
+ this.context = await launchWithXProtectHeal(() => chromium.launchPersistentContext(userDataDir, {
headless: false,
+ // #2220: daemon owns signal policy — see launch() for the rationale.
+ handleSIGINT: false,
+ handleSIGTERM: false,
+ handleSIGHUP: false,
// Match the sandbox policy used by launch() above. Without this,
// Playwright auto-adds --no-sandbox on every headed launch and the user
// sees Chromium's "unsupported command-line flag" yellow infobar.
@@ -663,7 +687,7 @@ export class BrowserManager {
...(executablePath ? { executablePath } : {}),
...(this.proxyConfig ? { proxy: this.proxyConfig } : {}),
ignoreDefaultArgs: STEALTH_IGNORE_DEFAULT_ARGS,
- });
+ }), { usesCustomExecutable: Boolean(executablePath) });
this.browser = this.context.browser();
this.connectionMode = 'headed';
this.intentionalDisconnect = false;
@@ -1702,8 +1726,15 @@ export class BrowserManager {
// The handoff path (headless → headed re-launch) takes the same
// anti-detection posture.
const { STEALTH_IGNORE_DEFAULT_ARGS } = await import('./stealth');
- newContext = await chromium.launchPersistentContext(userDataDir, {
+ // XProtect self-heal wrapper (P0 #2554): handoff always launches the
+ // Playwright-cache bundle (no executablePath), so the heal applies
+ // exactly as in launch()/launchHeaded().
+ newContext = await launchWithXProtectHeal(() => chromium.launchPersistentContext(userDataDir, {
headless: false,
+ // #2220: daemon owns signal policy — see launch() for the rationale.
+ handleSIGINT: false,
+ handleSIGTERM: false,
+ handleSIGHUP: false,
// Match the sandbox policy used by launchHeaded() / launch(). The
// handoff path is the headless→headed re-launch and shares the same
// anti-detection posture, including no spurious --no-sandbox infobar.
@@ -1713,7 +1744,7 @@ export class BrowserManager {
...(this.proxyConfig ? { proxy: this.proxyConfig } : {}),
ignoreDefaultArgs: STEALTH_IGNORE_DEFAULT_ARGS,
timeout: 15000,
- });
+ }));
} catch (err: unknown) {
const msg = err instanceof Error ? err.message : String(err);
return `ERROR: Cannot open headed browser — ${msg}. Headless browser still running.`;
diff --git a/browse/src/browser-skill-commands.ts b/browse/src/browser-skill-commands.ts
index 3c0805f5d..5174e76d3 100644
--- a/browse/src/browser-skill-commands.ts
+++ b/browse/src/browser-skill-commands.ts
@@ -19,6 +19,7 @@
*/
import * as fs from 'fs';
+import * as os from 'os';
import * as path from 'path';
import {
listBrowserSkills,
@@ -185,19 +186,122 @@ async function handleTest(args: string[], ctx: SkillCommandContext): Promise<str
throw new Error(`Skill "${name}" has no script.test.ts at ${testFile}`);
}
- const proc = Bun.spawn(['bun', 'test', testFile], {
+ const { stdout, stderr, exitCode } = await runToFiles(['bun', 'test', testFile], {
cwd: skill.dir,
- stdout: 'pipe',
- stderr: 'pipe',
env: process.env,
});
- const exitCode = await proc.exited;
- const stdout = proc.stdout ? await new Response(proc.stdout).text() : '';
- const stderr = proc.stderr ? await new Response(proc.stderr).text() : '';
+
if (exitCode !== 0) {
- throw new Error(`Skill "${name}" tests failed (exit ${exitCode}).\n${stderr}`);
+ throw new Error(`Skill "${name}" tests failed (exit ${exitCode}).\n${stderr || stdout}`);
+ }
+
+ // Return both streams, concatenated in bun's own layout (banner, blank line,
+ // summary). Picking one drops half the report, and the half callers assert on
+ // (the summary) is the half that lives on stderr.
+ const report = (stdout + stderr).trim();
+ if (!report) {
+ // A passing `bun test` always prints a summary, so exit 0 with no output at
+ // all means we failed to capture the run rather than that it went well.
+ // Say so instead of returning a synthetic "passed" that can't be verified.
+ throw new Error(`Skill "${name}" tests exited 0 but produced no output — the run was not captured.`);
+ }
+ return report + '\n';
+}
+
+interface RunToFilesOptions {
+ cwd: string;
+ env: Record<string, string> | NodeJS.ProcessEnv;
+ /** Kill the child after this many ms. Omit for no timeout. */
+ timeoutMs?: number;
+ /** Cap the captured stdout. Bytes past the cap are dropped, `truncated` set. */
+ maxStdoutBytes?: number;
+}
+
+interface RunToFilesResult {
+ stdout: string;
+ stderr: string;
+ exitCode: number;
+ timedOut: boolean;
+ truncated: boolean;
+}
+
+/**
+ * Run a command, capturing stdout/stderr by pointing the child's file
+ * descriptors at temp files rather than at pipes.
+ *
+ * Why not `stdout: 'pipe'`: under a loaded parent, the FIRST piped spawn in a
+ * process intermittently yields an empty stderr even though the child wrote it
+ * and exited 0. The data is lost inside Bun's async pipe plumbing, so neither
+ * draining before awaiting exit nor a manual `getReader()` loop avoids it —
+ * both were measured losing the same bytes in the same position. It surfaced in
+ * `$B skill test`, where `bun test` splits its report across streams (banner ->
+ * stdout, pass/fail summary -> stderr) so a dropped stderr silently degraded
+ * the result to just the banner; for `$B skill run` the same loss would blank
+ * the skill's JSON result and still look like success.
+ *
+ * Writing to files takes user-space streams out of the path: the kernel has
+ * flushed every byte by the time the child exits, so the post-exit read is
+ * always complete. It also removes the pipe-buffer stall risk on chatty
+ * children. `Bun.spawnSync` captures reliably too, but blocking the event loop
+ * is not an option here — a spawned skill calls back into this same daemon on
+ * GSTACK_PORT, so a synchronous wait would deadlock it.
+ */
+async function runToFiles(cmd: string[], opts: RunToFilesOptions): Promise<RunToFilesResult> {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-skill-'));
+ const outPath = path.join(dir, 'stdout');
+ const errPath = path.join(dir, 'stderr');
+ try {
+ // Hand Bun the destinations as BunFiles rather than raw fds we opened: Bun
+ // then owns the descriptors for the child's whole lifetime. Opening them
+ // here and closing them after exit instead put us in Bun's fd bookkeeping,
+ // which surfaced as a stray EBADF from epoll_ctl on a later spawn.
+ const proc = Bun.spawn(cmd, {
+ cwd: opts.cwd,
+ env: opts.env as any,
+ stdout: Bun.file(outPath) as any,
+ stderr: Bun.file(errPath) as any,
+ });
+
+ let timedOut = false;
+ const killer = opts.timeoutMs === undefined ? undefined : setTimeout(() => {
+ timedOut = true;
+ try { proc.kill(); } catch {}
+ }, opts.timeoutMs);
+
+ const exitCode = await proc.exited;
+ if (killer !== undefined) clearTimeout(killer);
+
+ // The child's own writes are flushed by the kernel when it exits, so
+ // everything it wrote is readable here.
+ const cap = opts.maxStdoutBytes ?? Infinity;
+ const stdout = readCappedFile(outPath, cap);
+ const stderr = readCappedFile(errPath, cap);
+ return {
+ stdout: stdout.text,
+ stderr: stderr.text,
+ exitCode: timedOut ? 124 : exitCode,
+ timedOut,
+ truncated: stdout.truncated,
+ };
+ } finally {
+ fs.rmSync(dir, { recursive: true, force: true });
+ }
+}
+
+interface CappedRead { text: string; truncated: boolean; }
+
+/** Read at most `capBytes` from a file, reporting whether anything was dropped. */
+function readCappedFile(p: string, capBytes: number): CappedRead {
+ const size = fs.statSync(p).size;
+ if (size <= capBytes) return { text: fs.readFileSync(p, 'utf-8'), truncated: false };
+ const fd = fs.openSync(p, 'r');
+ try {
+ const buf = Buffer.alloc(capBytes);
+ const read = fs.readSync(fd, buf, 0, capBytes, 0);
+ return { text: buf.subarray(0, read).toString('utf-8'), truncated: true };
+ } finally {
+ try { fs.closeSync(fd); } catch {}
}
- return stderr || stdout || `tests passed for "${name}"`;
}
// ─── rm ─────────────────────────────────────────────────────────
@@ -263,71 +367,19 @@ export async function spawnSkill(opts: SpawnSkillOptions): Promise<SpawnSkillRes
throw new Error(`Skill "${opts.skill.name}" missing script.ts at ${scriptPath}`);
}
- const proc = Bun.spawn(['bun', 'run', scriptPath, '--', ...opts.skillArgs], {
+ // Captured via temp files, not pipes — see runToFiles for why. A dropped
+ // read here would blank the skill's JSON result and still report success.
+ return await runToFiles(['bun', 'run', scriptPath, '--', ...opts.skillArgs], {
cwd: opts.skill.dir,
env,
- stdout: 'pipe',
- stderr: 'pipe',
+ timeoutMs: opts.timeoutSeconds * 1000,
+ maxStdoutBytes: MAX_STDOUT_BYTES,
});
-
- let timedOut = false;
- const killer = setTimeout(() => {
- timedOut = true;
- try { proc.kill(); } catch {}
- }, opts.timeoutSeconds * 1000);
-
- const stdoutPromise = readCapped(proc.stdout, MAX_STDOUT_BYTES);
- const stderrPromise = readCapped(proc.stderr, MAX_STDOUT_BYTES);
-
- const exitCode = await proc.exited;
- clearTimeout(killer);
-
- const stdoutResult = await stdoutPromise;
- const stderrResult = await stderrPromise;
-
- return {
- stdout: stdoutResult.text,
- stderr: stderrResult.text,
- exitCode: timedOut ? 124 : exitCode,
- timedOut,
- truncated: stdoutResult.truncated,
- };
} finally {
revokeSkillToken(opts.skill.name, spawnId);
}
}
-interface CappedRead { text: string; truncated: boolean; }
-
-async function readCapped(stream: ReadableStream<Uint8Array> | undefined, capBytes: number): Promise<CappedRead> {
- if (!stream) return { text: '', truncated: false };
- const reader = stream.getReader();
- const chunks: Uint8Array[] = [];
- let total = 0;
- let truncated = false;
- try {
- while (true) {
- const { done, value } = await reader.read();
- if (done) break;
- if (!value) continue;
- total += value.length;
- if (total > capBytes) {
- truncated = true;
- // Take only what fits; drop the rest of the stream (release reader).
- const fits = value.length - (total - capBytes);
- if (fits > 0) chunks.push(value.subarray(0, fits));
- try { await reader.cancel(); } catch {}
- break;
- }
- chunks.push(value);
- }
- } finally {
- try { reader.releaseLock(); } catch {}
- }
- const buf = Buffer.concat(chunks.map(c => Buffer.from(c)));
- return { text: buf.toString('utf-8'), truncated };
-}
-
// ─── env construction (security-critical) ───────────────────────
/**
diff --git a/browse/src/browser-skills.ts b/browse/src/browser-skills.ts
index 5bf7241be..277f38096 100644
--- a/browse/src/browser-skills.ts
+++ b/browse/src/browser-skills.ts
@@ -98,7 +98,7 @@ export function defaultTierPaths(opts: { projectRoot?: string; home?: string; bu
function detectProjectRoot(): string | null {
try {
- const proc = cp.spawnSync('git', ['rev-parse', '--show-toplevel'], { encoding: 'utf-8', timeout: 2000 });
+ const proc = cp.spawnSync('git', ['rev-parse', '--show-toplevel'], { encoding: 'utf-8', timeout: 2000, windowsHide: true });
if (proc.status === 0) {
const out = proc.stdout.trim();
return out || null;
diff --git a/browse/src/bun-polyfill.cjs b/browse/src/bun-polyfill.cjs
index 89e16c4fd..e383042c7 100644
--- a/browse/src/bun-polyfill.cjs
+++ b/browse/src/bun-polyfill.cjs
@@ -11,7 +11,43 @@
'use strict';
const http = require('http');
-const { spawnSync, spawn } = require('child_process');
+const { spawnSync: nodeSpawnSync, spawn: nodeSpawn } = require('child_process');
+// Node's spawn on Windows without shell:true only matches an EXACT
+// executable name — no PATHEXT resolution the way a real shell (or
+// Bun.spawn, which this file exists to polyfill) does. A bare command
+// name like 'bun' (no .exe/.cmd) then fails ENOENT even though `bun`
+// works fine typed at a prompt (confirmed live in #2461: this is what
+// produced "[browse] FATAL uncaught exception: spawn bun ENOENT" from
+// terminal-agent-control.ts's respawn path, once daemon output was
+// actually being captured to a file instead of silently discarded).
+//
+// Two things this is NOT fixed with, both tried and rejected in #2461:
+//
+// 1. shell:true + array args. This file is also reached (via server.ts →
+// write-commands.ts/meta-commands.ts → cookie-import-browser.ts/
+// browser-skill-commands.ts) by calls that pass genuinely variable
+// content — browser-skill-commands.ts spreads `...opts.skillArgs`,
+// sourced from `$B skill run <name> --arg k=v`'s passthrough CLI args,
+// into the spawned argv. shell:true on Windows routes through cmd.exe,
+// and Node's own array-arg handling for that combination does NOT
+// neutralize cmd.exe metacharacters (& | ^ % < >) — verified in #2461 by
+// directly spawning a resolved .cmd path with an arg containing
+// `& echo INJECTED > proof.txt`: the file was created. Hand-rolled
+// double-quote-only escaping doesn't close that either.
+//
+// 2. Resolve the .exe/.cmd path ourselves and spawn it with NO shell.
+// Works for .exe targets, but Node refuses (EINVAL) to spawn a
+// .cmd/.bat file without shell:true — deliberately, as part of Node's
+// CVE-2024-27980 fix for implicit unsafe .cmd execution. bun's own
+// Windows install (npm global) is exactly a .cmd shim, so this path is
+// not optional to support.
+//
+// cross-spawn (previously a transitive dep, now direct) is the established
+// library for precisely this problem: PATHEXT resolution AND correct
+// Windows/cmd.exe argument escaping together. #2461 verified the injection
+// payload above reaches the child as a single literal argument while
+// normal resolution (`bun --version`) still works.
+const crossSpawn = require('cross-spawn');
globalThis.Bun = {
serve(options) {
@@ -66,7 +102,8 @@ globalThis.Bun = {
spawnSync(cmd, options = {}) {
const [command, ...args] = cmd;
- const result = spawnSync(command, args, {
+ const spawnSyncFn = process.platform === 'win32' ? crossSpawn.sync : nodeSpawnSync;
+ const result = spawnSyncFn(command, args, {
stdio: [
options.stdin || 'pipe',
options.stdout === 'pipe' ? 'pipe' : 'ignore',
@@ -92,7 +129,8 @@ globalThis.Bun = {
spawn(cmd, options = {}) {
const [command, ...args] = cmd;
const stdio = options.stdio || ['pipe', 'pipe', 'pipe'];
- const proc = spawn(command, args, {
+ const spawnFn = process.platform === 'win32' ? crossSpawn : nodeSpawn;
+ const proc = spawnFn(command, args, {
stdio,
env: options.env,
cwd: options.cwd,
diff --git a/browse/src/cdp-allowlist.ts b/browse/src/cdp-allowlist.ts
index b9c3a9538..9e1f9f655 100644
--- a/browse/src/cdp-allowlist.ts
+++ b/browse/src/cdp-allowlist.ts
@@ -155,6 +155,13 @@ export const CDP_ALLOWLIST: ReadonlyArray<CdpAllowEntry> = Object.freeze([
output: 'trusted',
justification: 'UA override on the active tab. NOTE: changes affect future requests; fine for tests.',
},
+ {
+ domain: 'Emulation',
+ method: 'setEmulatedMedia',
+ scope: 'tab',
+ output: 'trusted',
+ justification: 'Media type/feature override (prefers-color-scheme, prefers-reduced-motion, prefers-contrast, forced-colors) so a11y and dark-mode CSS branches are testable. Returns an empty result; no page content. NOTE: like setUserAgentOverride the override persists on the tab until cleared with an empty features array.',
+ },
// ─── Page capture (output, not navigation) ─────────────────
{
domain: 'Page',
diff --git a/browse/src/cli.ts b/browse/src/cli.ts
index 9732053c7..08f7f24c9 100644
--- a/browse/src/cli.ts
+++ b/browse/src/cli.ts
@@ -146,10 +146,10 @@ function readState(): ServerState | null {
* HTTP health check — definitive proof the server is alive and responsive.
* Used in all polling loops instead of isProcessAlive() (which is slow on Windows).
*/
-export async function isServerHealthy(port: number): Promise<boolean> {
+export async function isServerHealthy(port: number, timeoutMs = 2000): Promise<boolean> {
try {
const resp = await fetch(`http://127.0.0.1:${port}/health`, {
- signal: AbortSignal.timeout(2000),
+ signal: AbortSignal.timeout(timeoutMs),
});
if (!resp.ok) return false;
const health = await resp.json() as any;
@@ -270,15 +270,82 @@ async function killOrphanChromium(profileDir: string = chromiumProfileDir()): Pr
}
}
-/** Bounded /health probe. Returns true if the server answers within `attempts`
- * tries spaced `backoffMs` apart — distinguishes a busy-but-alive daemon from a
- * dead one (#1781) so a slow server isn't killed and restarted into a crash-loop. */
-async function probeHealthWithBackoff(port: number, attempts = 3, backoffMs = 250): Promise<boolean> {
- for (let i = 0; i < attempts; i++) {
- if (await isServerHealthy(port)) return true;
- if (i < attempts - 1) await Bun.sleep(backoffMs);
+/** Total wall-clock budget for the busy-vs-dead health probe (#2219,
+ * decision F10). The old ~1s window (3 × 250ms) was shorter than how long a
+ * daemon stays unresponsive while Chromium chews a heavy dev-mode page with a
+ * timed-out navigation still in flight — so live daemons got killed and every
+ * kill lost the session's cookies/tabs/logins. ~8s covers the observed busy
+ * windows; past it we REPORT busy instead of killing (never auto-kill). */
+export const HEALTH_PROBE_TOTAL_BUDGET_MS = 8_000;
+
+/** Bounded /health probe. Returns true if the server answers within the
+ * total budget — distinguishes a busy-but-alive daemon from a dead one
+ * (#1781, #2219) so a slow server isn't killed and restarted into a
+ * crash-loop.
+ *
+ * P4 wall-time honesty: every call site reaches here right after a probe or
+ * command already failed, so iterations START with the sleep (an immediate
+ * re-probe would just re-fail), and each probe's timeout is clamped to the
+ * remaining budget — otherwise the last 2s probe could start 1ms before the
+ * deadline and the reported "~8s" budget would really be ~10s. */
+async function probeHealthWithBackoff(
+ port: number,
+ totalBudgetMs = HEALTH_PROBE_TOTAL_BUDGET_MS,
+ intervalMs = 500,
+): Promise<boolean> {
+ const deadline = Date.now() + totalBudgetMs;
+ for (;;) {
+ if (Date.now() + intervalMs >= deadline) return false;
+ await Bun.sleep(intervalMs);
+ const remainingMs = deadline - Date.now();
+ if (remainingMs <= 0) return false;
+ if (await isServerHealthy(port, Math.min(2000, remainingMs))) return true;
}
- return false;
+}
+
+export type DaemonRestartAction =
+ | 'retry-command' // healthy again after the bounded probe — retry against the SAME daemon
+ | 'report-busy' // alive but unresponsive — report + nonzero exit, daemon untouched
+ | 'force-restart' // alive but the user explicitly passed --force-restart
+ | 'restart-dead'; // process is gone — safe to clean up and restart
+
+/**
+ * Decide what to do about a daemon that failed to answer (#2219, decision 9).
+ *
+ * IRON RULE: an alive pid is NEVER auto-killed. A kill loses the session's
+ * tabs, cookies, and logins — strictly worse than a slow command. The ONLY
+ * path that kills a live daemon is the user explicitly passing
+ * --force-restart. Pure and exported for unit coverage.
+ */
+export function decideDaemonRestart(opts: {
+ pidAlive: boolean;
+ healthyAfterProbe: boolean;
+ forceRestart: boolean;
+}): DaemonRestartAction {
+ if (opts.pidAlive && opts.healthyAfterProbe) return 'retry-command';
+ if (opts.pidAlive && opts.forceRestart) return 'force-restart';
+ if (opts.pidAlive) return 'report-busy';
+ return 'restart-dead';
+}
+
+/** #2219 IRON RULE refusal for `connect`: a live daemon is never replaced
+ * without explicit consent. Single source for the refusal text (M7) — the
+ * two call sites (healthy fast-path, busy-but-alive after the bounded probe)
+ * previously duplicated it, and the tabs/cookies/logins explainer had
+ * already drifted out of one of them. */
+function refuseHeadedOverLiveDaemon(state: { pid: number; mode?: string }): never {
+ console.error(`[browse] A healthy daemon is already running (PID ${state.pid}, ${state.mode} mode).`);
+ console.error('[browse] Connecting headed would kill it and lose its tabs/cookies/logins.');
+ console.error("[browse] Run 'browse disconnect' first, or pass --force-restart to replace it.");
+ process.exit(1);
+}
+
+/** The busy report (F10): what happened, what to do, what a force costs. */
+function reportDaemonBusyAndExit(pid: number): never {
+ console.error(`[browse] Daemon busy — process ${pid} is alive but did not answer /health within ~${HEALTH_PROBE_TOTAL_BUDGET_MS / 1000}s.`);
+ console.error('[browse] Retry shortly (heavy page loads pass), or force a restart — which LOSES tabs, cookies, and logins:');
+ console.error('[browse] browse --force-restart <command>');
+ process.exit(1);
}
/**
@@ -310,6 +377,7 @@ function raiseHeadedWindowMacOS(): void {
nodeSpawn('osascript', ['-e', 'tell application "Google Chrome for Testing" to activate'], {
stdio: 'ignore',
detached: true,
+ windowsHide: true,
}).unref();
} catch {
// osascript missing or app not present — non-fatal
@@ -317,9 +385,64 @@ function raiseHeadedWindowMacOS(): void {
}
// ─── Server Lifecycle ──────────────────────────────────────────
+// The detached daemon's stdout/stderr used to be wired to 'ignore' on every
+// platform, so console.error('[browse] FATAL: ...') from a Chromium crash,
+// an uncaughtException, or an unhandledRejection (see server.ts's handlers
+// and browser-manager.ts's handleChromiumDisconnect) went nowhere — not to
+// a file, not to the terminal, discarded at the OS level (#2461). That made
+// a crash-and-respawn indistinguishable from any other cause of a dropped
+// session: nothing on disk ever recorded WHY. Redirect both streams to
+// <stateDir>/browse-daemon.log — append mode, so it accumulates across the
+// daemon's full lifetime and every respawn stays visible in one place.
+//
+// F6 log hygiene: nothing that reaches the daemon's stdout/stderr may carry
+// an auth token or unsanitized page-derived strings —
+// browse/test/daemon-log-hygiene.test.ts pins this with needle tests.
+//
+// Single source for the log path (M4): the Unix fd-open path and the Windows
+// launcher string both build it, and a drifted spelling would silently split
+// the daemon's history across two files.
+function daemonLogPath(): string {
+ return path.join(config.stateDir, 'browse-daemon.log');
+}
+
+/** Append-mode growth bound: the log accumulates across every respawn (a
+ * crash-respawn loop would otherwise fill the disk), so on daemon start a
+ * log past 10MB (the repo's rotation convention — tunnel-denial-log.ts uses
+ * the same cap) is renamed to browse-daemon.log.1, single generation.
+ * Best-effort: a failed stat/rename must never block the launch.
+ * Path + cap injectable for unit coverage; exported for the same reason. */
+export const DAEMON_LOG_MAX_BYTES = 10 * 1024 * 1024;
+export function rotateDaemonLogIfOversized(
+ p: string = daemonLogPath(),
+ maxBytes: number = DAEMON_LOG_MAX_BYTES,
+): void {
+ try {
+ if (fs.statSync(p).size > maxBytes) {
+ fs.renameSync(p, `${p}.1`);
+ }
+ } catch {
+ // Missing log (first launch) or unwritable state dir — rotation is
+ // best-effort, the launch matters more.
+ }
+}
+
+function openDaemonLogSink(): number | 'ignore' {
+ try {
+ return fs.openSync(daemonLogPath(), 'a');
+ } catch {
+ // stateDir not writable (permissions, disk full) — fall back to the
+ // previous behavior rather than fail the whole launch over logging.
+ return 'ignore';
+ }
+}
+
async function startServer(extraEnv?: Record<string, string>): Promise<ServerState> {
ensureStateDir(config);
+ // Bound the append-mode daemon log before the new daemon starts writing.
+ rotateDaemonLogIfOversized();
+
// Clean up stale state file and error log
safeUnlink(config.stateFile);
safeUnlink(path.join(config.stateDir, 'browse-startup-error.log'));
@@ -345,10 +468,18 @@ async function startServer(extraEnv?: Record<string, string>): Promise<ServerSta
// with { detached: true } instead, which is the gold standard for Windows
// process independence. Credit: PR #191 by @fqueiro.
const extraEnvStr = JSON.stringify({ BROWSE_STATE_FILE: config.stateFile, BROWSE_PARENT_PID: parentPid, ...(extraEnv || {}) });
+ // The daemon's real process is spawned inside the launcher's own
+ // `node -e` invocation, not in cli.ts's process — so the log file has
+ // to be opened from inside the launcher string too; an fd opened here
+ // in cli.ts wouldn't cross the spawn boundary. Falls back to 'ignore'
+ // the same way openDaemonLogSink() does if the state dir isn't writable.
+ const daemonLogPathStr = JSON.stringify(daemonLogPath());
const launcherCode =
`const{spawn}=require('child_process');` +
+ `const fs=require('fs');` +
+ `let logFd;try{logFd=fs.openSync(${daemonLogPathStr},'a');}catch(e){logFd='ignore';}` +
`spawn(process.execPath,[${JSON.stringify(NODE_SERVER_SCRIPT)}],` +
- `{detached:true,windowsHide:true,stdio:['ignore','ignore','ignore'],env:Object.assign({},process.env,` +
+ `{detached:true,windowsHide:true,stdio:['ignore',logFd,logFd],env:Object.assign({},process.env,` +
`${extraEnvStr})}).unref()`;
Bun.spawnSync(['node', '-e', launcherCode], { stdio: ['ignore', 'ignore', 'ignore'], windowsHide: true });
} else {
@@ -363,10 +494,11 @@ async function startServer(extraEnv?: Record<string, string>): Promise<ServerSta
// which calls setsid() so the server becomes its own session leader
// (PPID=1, STAT=Ss) and survives the spawning shell's exit. Mirrors
// the Windows path's rationale — same root cause, different OS API.
+ const daemonLogFd = openDaemonLogSink();
nodeSpawn('bun', ['run', SERVER_SCRIPT], {
detached: true,
windowsHide: true,
- stdio: ['ignore', 'ignore', 'ignore'],
+ stdio: ['ignore', daemonLogFd, daemonLogFd],
env: { ...process.env, BROWSE_STATE_FILE: config.stateFile, BROWSE_PARENT_PID: parentPid, ...extraEnv },
}).unref();
}
@@ -482,7 +614,12 @@ async function ensureServer(flags?: GlobalFlags): Promise<ServerState> {
// Health-check-first: HTTP is definitive proof the server is alive and responsive.
// This replaces the PID-gated approach which breaks on Windows (Bun's process.kill
// always throws ESRCH for Windows PIDs in compiled binaries).
- if (state && await isServerHealthy(state.port)) {
+ //
+ // #2219: when the single 2s probe fails but the PID is alive, extend to the
+ // bounded ~8s probe before concluding anything — a daemon chewing a heavy
+ // page is busy, not dead, and killing it loses the session.
+ const daemonPidAlive = Boolean(state?.pid && isProcessAlive(state.pid));
+ if (state && (await isServerHealthy(state.port) || (daemonPidAlive && await probeHealthWithBackoff(state.port)))) {
// D2 daemon-mismatch check: existing daemon's configHash must match the
// CLI's resolved hash. If --proxy or --headed are passed and the existing
// daemon was started with different config, refuse with a `disconnect`
@@ -530,6 +667,18 @@ async function ensureServer(flags?: GlobalFlags): Promise<ServerState> {
process.exit(1);
}
+ // #2219 IRON RULE: never auto-kill an alive pid. The daemon didn't answer
+ // /health within the bounded ~8s budget but its process is alive — that's
+ // busy, not dead. Report + nonzero exit; only an explicit --force-restart
+ // proceeds to the kill-and-restart below.
+ if (state && daemonPidAlive) {
+ if (flags?.forceRestart) {
+ console.error('[browse] --force-restart: replacing live-but-unresponsive daemon (tabs/cookies/logins will be lost)...');
+ } else {
+ reportDaemonBusyAndExit(state.pid);
+ }
+ }
+
// Ensure state directory exists before lock acquisition (lock file lives there)
ensureStateDir(config);
@@ -656,18 +805,42 @@ async function sendCommand(state: ServerState, command: string, args: string[],
// Connection error — server may have crashed, OR may just be busy.
if (err.code === 'ECONNREFUSED' || err.code === 'ECONNRESET' || err.message?.includes('fetch failed')) {
const oldState = readState();
- // #1781 busy-vs-dead: a single-threaded daemon under beacon/extension load
- // can briefly stop answering HTTP while still alive. Before declaring a
- // crash, if the process is alive give /health a bounded chance to recover
- // and just retry the command — never kill+restart a live-but-busy server.
- if (oldState?.pid && isProcessAlive(oldState.pid) && await probeHealthWithBackoff(oldState.port)) {
+ // #1781/#2219 busy-vs-dead: a single-threaded daemon under beacon/
+ // extension load (or with a timed-out navigation still churning) can
+ // stop answering HTTP for seconds while fully alive. Give /health a
+ // bounded ~8s to recover, then decide via the pure rule: retry against
+ // the same daemon, report busy (NEVER kill an alive pid), or restart a
+ // genuinely dead one. Only --force-restart may kill a live daemon.
+ const pidAlive = Boolean(oldState?.pid && isProcessAlive(oldState.pid));
+ const healthyAfterProbe = pidAlive ? await probeHealthWithBackoff(oldState!.port) : false;
+ const action = decideDaemonRestart({
+ pidAlive,
+ healthyAfterProbe,
+ forceRestart: Boolean(_globalFlags?.forceRestart),
+ });
+ if (action === 'retry-command') {
if (retries >= 1) throw new Error('[browse] Server unresponsive after retry — aborting');
console.error('[browse] Server was briefly unresponsive (busy); retrying command...');
- return sendCommand(oldState, command, args, retries + 1);
+ return sendCommand(oldState!, command, args, retries + 1);
+ }
+ if (action === 'report-busy') {
+ reportDaemonBusyAndExit(oldState!.pid);
}
- // Truly dead (or health never recovered) → restart.
+ // #2254: `stop` against a daemon that died mid-flight is SUCCESS — the
+ // desired end state (no daemon) already holds. Restarting a daemon just
+ // to stop it again was the crash-restart loop the issue reports.
+ if (action === 'restart-dead' && command === 'stop') {
+ safeUnlinkQuiet(config.stateFile);
+ console.log('Daemon already stopped (cleaned stale state).');
+ process.exit(0);
+ }
+ // 'restart-dead' or explicit 'force-restart' → restart.
if (retries >= 1) throw new Error('[browse] Server crashed twice in a row — aborting');
- console.error('[browse] Server connection lost. Restarting...');
+ if (action === 'force-restart') {
+ console.error('[browse] --force-restart: killing live daemon and restarting (tabs/cookies/logins will be lost)...');
+ } else {
+ console.error('[browse] Server connection lost. Restarting...');
+ }
if (oldState && oldState.pid) {
await killServer(oldState.pid);
}
@@ -844,6 +1017,9 @@ export interface GlobalFlags {
configHash: string;
/** Redacted form of proxyUrl, safe for logs. */
redactedProxyUrl: string;
+ /** Whether --force-restart was passed (#2219): the ONLY thing that may
+ * kill a live-but-unresponsive daemon. */
+ forceRestart: boolean;
}
/**
@@ -857,9 +1033,11 @@ export function extractGlobalFlags(rawArgs: string[], env: NodeJS.ProcessEnv): G
const out: string[] = [];
let proxyUrl: string | null = null;
let headed = false;
+ let forceRestart = false;
for (let i = 0; i < rawArgs.length; i++) {
const arg = rawArgs[i];
+ if (arg === '--force-restart') { forceRestart = true; continue; }
if (arg === '--proxy') {
const value = rawArgs[i + 1];
if (!value) {
@@ -902,6 +1080,7 @@ export function extractGlobalFlags(rawArgs: string[], env: NodeJS.ProcessEnv): G
headed,
configHash: computeConfigHash({ proxyUrl: canonicalProxyUrl, headed }),
redactedProxyUrl: redactProxyUrl(canonicalProxyUrl),
+ forceRestart,
};
}
@@ -1107,6 +1286,8 @@ Multi-step: chain (reads JSON from stdin)
Tabs: tabs | tab <id> | newtab [url] | closetab [id]
Server: status | cookie <n>=<v> | header <n>:<v>
useragent <str> | stop | restart
+ --force-restart: replace a live-but-busy daemon (any command;
+ LOSES tabs/cookies/logins — never done automatically)
Dialogs: dialog-accept [text] | dialog-dismiss
Refs: After 'snapshot', use @e1, @e2... as selectors:
@@ -1137,12 +1318,30 @@ Refs: After 'snapshot', use @e1, @e2... as selectors:
process.exit(0);
}
} catch {
- // Headed server alive but not responding — kill and restart
+ // Headed server alive but not responding — handled below (#2219:
+ // busy semantics; only --force-restart may kill it).
}
}
- // Kill ANY existing server (SIGTERM → wait 2s → SIGKILL)
+ // #2219 IRON RULE: a HEALTHY daemon survives connect. The old behavior
+ // ("kill ANY existing server") silently destroyed a working headless
+ // session — tabs, cookies, logins — whenever someone opened the headed
+ // browser. A live daemon is only replaced with explicit consent.
+ if (existingState && isProcessAlive(existingState.pid) && !globalFlags.forceRestart) {
+ if (await isServerHealthy(existingState.port)) {
+ refuseHeadedOverLiveDaemon(existingState);
+ }
+ // Alive but unhealthy after the bounded probe → busy, not dead.
+ if (await probeHealthWithBackoff(existingState.port)) {
+ refuseHeadedOverLiveDaemon(existingState);
+ }
+ reportDaemonBusyAndExit(existingState.pid);
+ }
+
+ // Explicit --force-restart (or a dead pid): kill any remnant
+ // (SIGTERM → wait 2s → SIGKILL).
if (existingState && isProcessAlive(existingState.pid)) {
+ console.error('[browse] --force-restart: replacing live daemon (tabs/cookies/logins will be lost)...');
safeKill(existingState.pid, 'SIGTERM');
await new Promise(resolve => setTimeout(resolve, 2000));
if (isProcessAlive(existingState.pid)) {
@@ -1386,6 +1585,45 @@ Refs: After 'snapshot', use @e1, @e2... as selectors:
process.exit(0);
}
+ // ─── Stop (pre-server short-circuit, #2254) ──────────────────
+ // stop must be handled BEFORE ensureServer(): stopping a daemon that is
+ // not running must not START one just to stop it. The old flow booted a
+ // fresh daemon + Chromium (multi-second, resource churn) and then told it
+ // to shut down — or crashed trying. No state, or dead pid + dead port →
+ // report "nothing to stop" and exit 0.
+ if (command === 'stop') {
+ const stopState = readState();
+ if (!stopState) {
+ console.log('No daemon running — nothing to stop.');
+ process.exit(0);
+ }
+ if (!isProcessAlive(stopState.pid) && !(await isServerHealthy(stopState.port))) {
+ safeUnlinkQuiet(config.stateFile);
+ console.log('No daemon running (cleaned stale state) — nothing to stop.');
+ process.exit(0);
+ }
+ // stop --force-restart on a LIVE daemon (healthy or busy): kill it and
+ // clean up right here. Falling through would hand ensureServer() the
+ // force-restart flag, which kills the daemon and then BOOTS A FRESH ONE
+ // (daemon + Chromium, multi-second churn) just so sendCommand('stop')
+ // can shut it down again — the #2254 churn in force clothing, and
+ // gstack-upgrade's Step 4.8 sends users down exactly this path when a
+ // stale daemon is busy. The desired end state is "no daemon"; get there
+ // directly.
+ if (isProcessAlive(stopState.pid) && globalFlags.forceRestart) {
+ await killServer(stopState.pid);
+ // Reap the orphaned Chromium child + clear its profile locks so the
+ // NEXT launch is clean (same cleanup as the disconnect force path).
+ await killOrphanChromium();
+ cleanChromiumProfileLocks();
+ safeUnlinkQuiet(config.stateFile);
+ console.log('Daemon stopped (forced — tabs/cookies/logins discarded).');
+ process.exit(0);
+ }
+ // Live daemon without --force-restart → fall through to the normal
+ // sendCommand('stop') path (graceful shutdown; busy semantics apply).
+ }
+
// Special case: chain reads from stdin
if (command === 'chain' && commandArgs.length === 0) {
const stdin = await Bun.stdin.text();
@@ -1403,7 +1641,10 @@ Refs: After 'snapshot', use @e1, @e2... as selectors:
// In compiled binaries, process.argv[1] is /$bunfs/... (virtual).
// Use process.execPath which is the real binary on disk.
const browseBin = process.execPath;
- const connectProc = Bun.spawn([browseBin, 'connect'], {
+ // --force-restart: the headed switch is this command's explicit purpose
+ // (the user asked to SEE the shared browser), and connect's #2219 guard
+ // would otherwise refuse to replace the healthy headless daemon.
+ const connectProc = Bun.spawn([browseBin, 'connect', '--force-restart'], {
cwd: process.cwd(),
stdio: ['ignore', 'inherit', 'inherit'],
// Disable parent-PID monitoring: pair-agent needs the server to outlive
diff --git a/browse/src/error-handling.ts b/browse/src/error-handling.ts
index 3be921fa2..6c0247a04 100644
--- a/browse/src/error-handling.ts
+++ b/browse/src/error-handling.ts
@@ -7,8 +7,6 @@
import * as fs from 'fs';
-const IS_WINDOWS = process.platform === 'win32';
-
// ─── Filesystem ────────────────────────────────────────────────
/** Remove a file, ignoring ENOENT (already gone). Rethrows other errors. */
@@ -36,23 +34,39 @@ export function safeKill(pid: number, signal: NodeJS.Signals | number): void {
}
}
-/** Check if a PID is alive. Pure boolean probe — returns false for ALL errors. */
+/**
+ * Check if a PID is alive. Pure boolean probe — never throws.
+ *
+ * Signal 0 on EVERY platform (#1952). Node maps `process.kill(pid, 0)` to an
+ * OpenProcess existence check on Windows — and on Windows the browse daemon
+ * runs under Node (dist/server-node.mjs + bun-polyfill, the documented
+ * fallback for oven-sh/bun#4253) — so the POSIX idiom is portable here.
+ *
+ * Windows used to shell out to `tasklist /FI "PID eq <pid>"` and
+ * string-match the CSV. That was wrong in two ways, both hit in production:
+ *
+ * 1. FALSE NEGATIVES UNDER LOAD (#2414/#2295): tasklist takes ~700-1700ms
+ * on an idle box and far longer under memory pressure. A Bun.spawnSync
+ * that hits its `timeout` still RETURNS, carrying partial stdout — so
+ * the `.includes()` match came back false and a LIVE process was
+ * reported dead. Callers that validate liveness before killing
+ * (killAgentByRecord, the terminal-agent watchdog) then skipped the
+ * kill and respawned around the survivor — one leaked terminal-agent
+ * per tick, self-reinforcing (each orphan slows the next tasklist).
+ * 2. A console window per probe (#1952): the watchdog blinked a conhost
+ * window into the foreground every 60s for the whole session.
+ *
+ * Signal 0 spawns nothing, cannot time out, and is orders of magnitude
+ * faster (~0.004ms vs ~270ms measured in #2414).
+ *
+ * EPERM means the process EXISTS but we lack rights to signal it. That is
+ * alive — returning false there would reintroduce failure mode 1.
+ */
export function isProcessAlive(pid: number): boolean {
- if (IS_WINDOWS) {
- try {
- const result = Bun.spawnSync(
- ['tasklist', '/FI', `PID eq ${pid}`, '/NH', '/FO', 'CSV'],
- { stdout: 'pipe', stderr: 'pipe', timeout: 3000, windowsHide: true }
- );
- return result.stdout.toString().includes(`"${pid}"`);
- } catch {
- return false;
- }
- }
try {
process.kill(pid, 0);
return true;
- } catch {
- return false;
+ } catch (err: any) {
+ return err?.code === 'EPERM';
}
}
diff --git a/browse/src/file-permissions.ts b/browse/src/file-permissions.ts
index 5a5c5462e..078fcac89 100644
--- a/browse/src/file-permissions.ts
+++ b/browse/src/file-permissions.ts
@@ -60,6 +60,7 @@ function currentUserSid(): string | null {
const systemRoot = process.env.SystemRoot || process.env.windir || 'C:\\Windows';
const out = execFileSync(`${systemRoot}\\System32\\whoami.exe`, ['/user', '/fo', 'csv', '/nh'], {
encoding: 'utf8',
+ windowsHide: true,
});
const match = out.match(/S-1-[\d-]+/);
cachedSid = match ? match[0] : null;
diff --git a/browse/src/find-security-sidecar.ts b/browse/src/find-security-sidecar.ts
index 0ba242523..aeee96685 100644
--- a/browse/src/find-security-sidecar.ts
+++ b/browse/src/find-security-sidecar.ts
@@ -30,7 +30,7 @@ export interface SidecarLocation {
function nodeOnPath(): string | null {
try {
- execFileSync("node", ["--version"], { stdio: "ignore", timeout: 2000 });
+ execFileSync("node", ["--version"], { stdio: "ignore", timeout: 2000, windowsHide: true });
return "node";
} catch {
return null;
diff --git a/browse/src/meta-commands.ts b/browse/src/meta-commands.ts
index 521c65a20..a2bc1f4d2 100644
--- a/browse/src/meta-commands.ts
+++ b/browse/src/meta-commands.ts
@@ -777,7 +777,7 @@ export async function handleMetaCommand(
let activated = false;
for (const appName of appNames) {
try {
- execSync(`osascript -e 'tell application "${appName}" to activate'`, { stdio: 'pipe', timeout: 3000 });
+ execSync(`osascript -e 'tell application "${appName}" to activate'`, { stdio: 'pipe', timeout: 3000, windowsHide: true });
activated = true;
break;
} catch (err: any) {
@@ -841,7 +841,7 @@ export async function handleMetaCommand(
const { execSync } = await import('child_process');
let gitRoot: string;
try {
- gitRoot = execSync('git rev-parse --show-toplevel', { encoding: 'utf-8', stdio: ['pipe', 'pipe', 'pipe'] }).trim();
+ gitRoot = execSync('git rev-parse --show-toplevel', { encoding: 'utf-8', stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true }).trim();
} catch (err: any) {
// execSync throws with exit status on non-git directories
if (err?.status === undefined && !err?.message?.includes('Command failed')) throw err;
diff --git a/browse/src/port-allocator.ts b/browse/src/port-allocator.ts
new file mode 100644
index 000000000..133747695
--- /dev/null
+++ b/browse/src/port-allocator.ts
@@ -0,0 +1,140 @@
+/**
+ * Shared loopback port allocation (#2314, decision 8).
+ *
+ * One fixed scan range (10000-49151) for EVERY long-lived gstack listener:
+ * the main browse daemon and the terminal-agent. Binding `port: 0` instead
+ * hands out a port from the OS EPHEMERAL range (49152-65535 on macOS) — the
+ * same pool every short-lived test server draws from — so a daemon that
+ * lives for weeks ends up squatting ports that `app.listen(0)` test servers
+ * expect to receive, silently absorbing their traffic as phantom 404s. The
+ * range therefore ends AT 49151: a max above it would put a fraction of
+ * picks back inside the pool this module exists to avoid (the original
+ * 60000 cap left ~22% of allocations in 49152-59999).
+ *
+ * Extracted from server.ts (which had this logic since #486) so
+ * terminal-agent.ts can reuse it without importing the whole server module.
+ */
+
+import * as net from 'net';
+
+export type PortCheckResult =
+ | { available: true }
+ | { available: false; code?: string; message: string };
+
+export type FailedPortAttempt = {
+ port: number;
+ result: Extract<PortCheckResult, { available: false }>;
+};
+
+export const RANDOM_PORT_MIN = 10000;
+export const RANDOM_PORT_MAX = 49151; // last port BELOW the macOS ephemeral pool (49152-65535)
+export const RANDOM_PORT_RETRIES = 5;
+
+export function normalizePortError(err: unknown): Extract<PortCheckResult, { available: false }> {
+ const maybeNodeError = err as NodeJS.ErrnoException | undefined;
+ return {
+ available: false,
+ code: maybeNodeError?.code,
+ message: maybeNodeError?.message || String(err),
+ };
+}
+
+export function isOccupiedPort(result: Extract<PortCheckResult, { available: false }>): boolean {
+ return result.code === 'EADDRINUSE';
+}
+
+export function formatPortFailureDetail(attempt: FailedPortAttempt): string {
+ const { code, message } = attempt.result;
+ return code ? `${attempt.port} (${code}: ${message})` : `${attempt.port} (${message})`;
+}
+
+export function formatExplicitPortUnavailableError(
+ port: number,
+ result: Extract<PortCheckResult, { available: false }>
+): Error {
+ if (isOccupiedPort(result)) {
+ return new Error(`[browse] Port ${port} (from BROWSE_PORT env) is in use`);
+ }
+
+ const detail = result.code ? `${result.code}: ${result.message}` : result.message;
+ return new Error(
+ `[browse] Cannot bind BROWSE_PORT=${port} on 127.0.0.1 (${detail}). ` +
+ `This usually means localhost port binding is blocked by the current sandbox or OS permissions, ` +
+ `not that the port is occupied. Allow localhost binding, or run browse from an unrestricted terminal.`
+ );
+}
+
+export function formatRandomPortUnavailableError(attempts: FailedPortAttempt[]): Error {
+ const blockingAttempts = attempts.filter((attempt) => !isOccupiedPort(attempt.result));
+
+ if (blockingAttempts.length > 0) {
+ const last = blockingAttempts[blockingAttempts.length - 1];
+ return new Error(
+ `[browse] Cannot bind localhost ports after ${attempts.length} attempts in range ` +
+ `${RANDOM_PORT_MIN}-${RANDOM_PORT_MAX}. Last error: ${formatPortFailureDetail(last)}. ` +
+ `This usually means the current sandbox or OS permissions are blocking localhost port binding, ` +
+ `not that every sampled port is occupied. Allow localhost binding, set BROWSE_PORT to an approved ` +
+ `port, or run browse from an unrestricted terminal.`
+ );
+ }
+
+ return new Error(
+ `[browse] No available port after ${RANDOM_PORT_RETRIES} attempts in range ` +
+ `${RANDOM_PORT_MIN}-${RANDOM_PORT_MAX}; every sampled port was already in use`
+ );
+}
+
+// Test if a port is available by binding and immediately releasing.
+// Uses net.createServer instead of Bun.serve to avoid a race condition
+// in the Node.js polyfill where listen/close are async but the caller
+// expects synchronous bind semantics. See: #486
+export function checkPortAvailable(port: number, hostname: string = '127.0.0.1'): Promise<PortCheckResult> {
+ return new Promise((resolve) => {
+ const srv = net.createServer();
+ let settled = false;
+ const finish = (result: PortCheckResult) => {
+ if (settled) return;
+ settled = true;
+ resolve(result);
+ };
+
+ srv.once('error', (err) => finish(normalizePortError(err)));
+ try {
+ srv.listen(port, hostname, () => {
+ srv.close(() => finish({ available: true }));
+ });
+ } catch (err) {
+ finish(normalizePortError(err));
+ }
+ });
+}
+
+export function isPortAvailable(port: number, hostname: string = '127.0.0.1'): Promise<boolean> {
+ return checkPortAvailable(port, hostname).then((result) => result.available);
+}
+
+/**
+ * Find a port: the explicit override when given, otherwise a random port in
+ * the fixed 10000-49151 scan range with bounded retries. NEVER `port: 0` —
+ * see the module header for why the ephemeral range is off-limits.
+ */
+export async function findAvailablePort(explicitPort?: number | null): Promise<number> {
+ if (explicitPort) {
+ const result = await checkPortAvailable(explicitPort);
+ if (result.available) {
+ return explicitPort;
+ }
+ throw formatExplicitPortUnavailableError(explicitPort, result);
+ }
+
+ const attempts: FailedPortAttempt[] = [];
+ for (let attempt = 0; attempt < RANDOM_PORT_RETRIES; attempt++) {
+ const port = RANDOM_PORT_MIN + Math.floor(Math.random() * (RANDOM_PORT_MAX - RANDOM_PORT_MIN));
+ const result = await checkPortAvailable(port);
+ if (result.available) {
+ return port;
+ }
+ attempts.push({ port, result });
+ }
+ throw formatRandomPortUnavailableError(attempts);
+}
diff --git a/browse/src/project-slug.ts b/browse/src/project-slug.ts
index 0a840ebea..2ad34e754 100644
--- a/browse/src/project-slug.ts
+++ b/browse/src/project-slug.ts
@@ -21,7 +21,7 @@ export function getCurrentProjectSlug(): string {
}
try {
const slugBin = path.join(os.homedir(), '.claude/skills/gstack/bin/gstack-slug');
- const out = execSync(slugBin, { encoding: 'utf8', timeout: 2000 }).trim();
+ const out = execSync(slugBin, { encoding: 'utf8', timeout: 2000, windowsHide: true }).trim();
const m = out.match(/SLUG="?([^"\n]+)"?/);
cachedSlug = m ? m[1]! : (out || 'unknown');
} catch {
diff --git a/browse/src/security-sidecar-client.ts b/browse/src/security-sidecar-client.ts
index da481671a..95e226070 100644
--- a/browse/src/security-sidecar-client.ts
+++ b/browse/src/security-sidecar-client.ts
@@ -138,6 +138,9 @@ function spawnSidecar(): boolean {
const child = spawn(location.node, [location.entry], {
stdio: ["pipe", "pipe", "pipe"],
detached: false,
+ // Long-lived Node sidecar — without this, Windows gives it a console
+ // window that sits on the taskbar for the daemon's whole lifetime.
+ windowsHide: true,
});
child.stdout.on("data", (chunk: Buffer) => {
s.buffer += chunk.toString("utf-8");
diff --git a/browse/src/security.ts b/browse/src/security.ts
index 6475aea73..3da662a00 100644
--- a/browse/src/security.ts
+++ b/browse/src/security.ts
@@ -23,18 +23,19 @@
* host process): the combiner is pure and tested, and server.ts's
* inline L4 path is the consumer of record.
*
- * Cross-process state lives at ~/.gstack/security/session-state.json.
- * classifierStatus in that state has no live writer since the chat-path rip
- * (the sidecar reports status over its own NDJSON protocol instead).
+ * There is no longer any cross-process session state (#2557).
+ * ~/.gstack/security/session-state.json existed to carry classifier status
+ * across the server.ts / sidebar-agent.ts boundary; sidebar-agent.ts went
+ * away with the PTY terminal rewrite, leaving nothing to write the file and
+ * a /health.security status that reported stale or empty data — a permanent
+ * 'inactive', or a false-green 'protected' wherever an old state file
+ * survived on disk. getStatus / SessionState / read+writeSessionState and
+ * the /health field were removed together. Per-tab decision files under
+ * ~/.gstack/security/decisions/ are unaffected, and the L4 sidecar reports
+ * status over its own NDJSON protocol (security-sidecar-client.ts).
*/
-import { randomBytes, createHash } from 'crypto';
-import { spawn } from 'child_process';
-import * as fs from 'fs';
-import * as path from 'path';
-import * as os from 'os';
-import { restrictFilePermissions, appendSecureFile, mkdirSecure } from './file-permissions';
-import { atomicWriteQuiet } from '../../lib/fs-atomic';
+import { randomBytes } from 'crypto';
// ─── Thresholds + verdict types ──────────────────────────────
@@ -83,17 +84,6 @@ export interface SecurityResult {
confidence: number;
}
-export type SecurityStatus = 'protected' | 'degraded' | 'inactive';
-
-export interface StatusDetail {
- status: SecurityStatus;
- layers: {
- testsavant: 'ok' | 'degraded' | 'off';
- canary: 'ok' | 'off';
- };
- lastUpdated: string;
-}
-
// ─── Verdict combiner (ensemble rule, label-first for transcript) ────
/**
@@ -322,79 +312,8 @@ export function checkCanaryInStructure(value: unknown, canary: string): boolean
// attempts.jsonl rotation + telemetry spawn plumbing) lived here until the
// chat-path scanner that called it was ripped with sidebar-agent.ts. The
// LIVE attempts.jsonl writer is tunnel-denial-log.ts, which owns its own
-// rotation.
-
-const SECURITY_DIR = path.join(os.homedir(), '.gstack', 'security');
-
-// ─── Cross-process session state ─────────────────────────────
-
-const STATE_FILE = path.join(SECURITY_DIR, 'session-state.json');
-
-/**
- * SessionState is a DISK FORMAT (~/.gstack/security/session-state.json).
- * Old files may carry a `transcript` field inside classifierStatus from the
- * removed Haiku layer — readSessionState tolerates it (JSON.parse keeps the
- * extra key; getStatus ignores it), but we never write it.
- */
-export interface SessionState {
- sessionId: string;
- canary: string;
- warnedDomains: string[]; // per-session rate limit for special telemetry
- classifierStatus: {
- testsavant: 'ok' | 'degraded' | 'off';
- };
- lastUpdated: string;
-}
-
-/**
- * Atomic write of session state (via lib/fs-atomic). Writes are safe
- * across process boundaries. Swallow-with-log polarity: a failed write
- * must never take down the caller (security state is best-effort cache).
- */
-export function writeSessionState(state: SessionState): void {
- try { mkdirSecure(SECURITY_DIR); } catch { /* write below fails and logs */ }
- if (atomicWriteQuiet(STATE_FILE, JSON.stringify(state, null, 2), { mode: 0o600 })) {
- // Windows ACL hardening (POSIX chmod is redundant with mode above).
- restrictFilePermissions(STATE_FILE);
- } else {
- console.error('[security] writeSessionState failed');
- }
-}
-
-export function readSessionState(): SessionState | null {
- try {
- if (!fs.existsSync(STATE_FILE)) return null;
- return JSON.parse(fs.readFileSync(STATE_FILE, 'utf8'));
- } catch {
- return null;
- }
-}
-
-// ─── Status reporting (for shield icon via /health) ──────────
-
-export function getStatus(): StatusDetail {
- const state = readSessionState();
- // Read the field explicitly (never spread classifierStatus): old on-disk
- // state may carry a stale `transcript` key from the removed Haiku layer,
- // and spreading would leak it into the /health payload.
- const testsavant = state?.classifierStatus?.testsavant ?? 'off';
- const canary = state?.canary ? 'ok' : 'off';
-
- let status: SecurityStatus;
- if (testsavant === 'ok' && canary === 'ok') {
- status = 'protected';
- } else if (testsavant === 'off' && canary === 'off') {
- status = 'inactive';
- } else {
- status = 'degraded';
- }
-
- return {
- status,
- layers: { testsavant, canary: canary as 'ok' | 'off' },
- lastUpdated: state?.lastUpdated ?? new Date().toISOString(),
- };
-}
+// rotation. The cross-process session state + getStatus shield feed went
+// the same way (#2557) — see the module header.
/**
* Extract url domain for logging. Never logs path or query string.
diff --git a/browse/src/server.ts b/browse/src/server.ts
index be6f5438b..9d42ff71d 100644
--- a/browse/src/server.ts
+++ b/browse/src/server.ts
@@ -24,7 +24,6 @@ import {
runContentFilters, type ContentFilterResult,
markHiddenElements, getCleanTextWithStripping, cleanupHiddenMarkers,
} from './content-security';
-import { getStatus as getSecurityStatus } from './security';
import { isSidecarAvailable, scanWithSidecar } from './security-sidecar-client';
import { writeSecureFile, mkdirSecure, appendSecureFile } from './file-permissions';
import { handleSnapshot, SNAPSHOT_FLAGS } from './snapshot';
@@ -47,6 +46,9 @@ import { inspectElement, modifyStyle, resetModifications, getModificationHistory
// Bun.spawn used instead of child_process.spawn (compiled bun binaries
// fail posix_spawn on all executables including /bin/bash)
import { safeUnlink, safeUnlinkQuiet, safeKill } from './error-handling';
+import {
+ findAvailablePort, formatExplicitPortUnavailableError, formatRandomPortUnavailableError,
+} from './port-allocator';
import { readAgentRecord, killAgentByRecord, agentRecordPath, spawnTerminalAgent } from './terminal-agent-control';
import { isProcessAlive } from './error-handling';
import { sanitizeBody, stripLoneSurrogateEscapes, stripLoneSurrogates, sanitizeReplacer } from './sanitize';
@@ -915,124 +917,14 @@ let isShuttingDown = false;
// the good final snapshot with a degraded one (zero tabs).
let sessionPersistInterval: ReturnType<typeof setInterval> | null = null;
-type PortCheckResult =
- | { available: true }
- | { available: false; code?: string; message: string };
-
-type FailedPortAttempt = {
- port: number;
- result: Extract<PortCheckResult, { available: false }>;
-};
-
-const RANDOM_PORT_MIN = 10000;
-const RANDOM_PORT_MAX = 60000;
-const RANDOM_PORT_RETRIES = 5;
-
-function normalizePortError(err: unknown): Extract<PortCheckResult, { available: false }> {
- const maybeNodeError = err as NodeJS.ErrnoException | undefined;
- return {
- available: false,
- code: maybeNodeError?.code,
- message: maybeNodeError?.message || String(err),
- };
-}
-
-function isOccupiedPort(result: Extract<PortCheckResult, { available: false }>): boolean {
- return result.code === 'EADDRINUSE';
-}
-
-function formatPortFailureDetail(attempt: FailedPortAttempt): string {
- const { code, message } = attempt.result;
- return code ? `${attempt.port} (${code}: ${message})` : `${attempt.port} (${message})`;
-}
-
-function formatExplicitPortUnavailableError(
- port: number,
- result: Extract<PortCheckResult, { available: false }>
-): Error {
- if (isOccupiedPort(result)) {
- return new Error(`[browse] Port ${port} (from BROWSE_PORT env) is in use`);
- }
-
- const detail = result.code ? `${result.code}: ${result.message}` : result.message;
- return new Error(
- `[browse] Cannot bind BROWSE_PORT=${port} on 127.0.0.1 (${detail}). ` +
- `This usually means localhost port binding is blocked by the current sandbox or OS permissions, ` +
- `not that the port is occupied. Allow localhost binding, or run browse from an unrestricted terminal.`
- );
-}
-
-function formatRandomPortUnavailableError(attempts: FailedPortAttempt[]): Error {
- const blockingAttempts = attempts.filter((attempt) => !isOccupiedPort(attempt.result));
-
- if (blockingAttempts.length > 0) {
- const last = blockingAttempts[blockingAttempts.length - 1];
- return new Error(
- `[browse] Cannot bind localhost ports after ${attempts.length} attempts in range ` +
- `${RANDOM_PORT_MIN}-${RANDOM_PORT_MAX}. Last error: ${formatPortFailureDetail(last)}. ` +
- `This usually means the current sandbox or OS permissions are blocking localhost port binding, ` +
- `not that every sampled port is occupied. Allow localhost binding, set BROWSE_PORT to an approved ` +
- `port, or run browse from an unrestricted terminal.`
- );
- }
-
- return new Error(
- `[browse] No available port after ${RANDOM_PORT_RETRIES} attempts in range ` +
- `${RANDOM_PORT_MIN}-${RANDOM_PORT_MAX}; every sampled port was already in use`
- );
-}
-
-// Test if a port is available by binding and immediately releasing.
-// Uses net.createServer instead of Bun.serve to avoid a race condition
-// in the Node.js polyfill where listen/close are async but the caller
-// expects synchronous bind semantics. See: #486
-function checkPortAvailable(port: number, hostname: string = '127.0.0.1'): Promise<PortCheckResult> {
- return new Promise((resolve) => {
- const srv = net.createServer();
- let settled = false;
- const finish = (result: PortCheckResult) => {
- if (settled) return;
- settled = true;
- resolve(result);
- };
-
- srv.once('error', (err) => finish(normalizePortError(err)));
- try {
- srv.listen(port, hostname, () => {
- srv.close(() => finish({ available: true }));
- });
- } catch (err) {
- finish(normalizePortError(err));
- }
- });
-}
-
-function isPortAvailable(port: number, hostname: string = '127.0.0.1'): Promise<boolean> {
- return checkPortAvailable(port, hostname).then((result) => result.available);
-}
+// Port allocation lives in port-allocator.ts (#2314, decision 8) so the
+// terminal-agent shares the SAME fixed 10000-60000 scan range instead of
+// binding port:0 into the OS ephemeral range. The imports at the top of
+// this file re-expose the pieces __testInternals__ pins.
// Find port: explicit BROWSE_PORT, or random in 10000-60000
-async function findPort(): Promise<number> {
- // Explicit port override (for debugging)
- if (BROWSE_PORT) {
- const result = await checkPortAvailable(BROWSE_PORT);
- if (result.available) {
- return BROWSE_PORT;
- }
- throw formatExplicitPortUnavailableError(BROWSE_PORT, result);
- }
-
- // Random port with retry
- const attempts: FailedPortAttempt[] = [];
- for (let attempt = 0; attempt < RANDOM_PORT_RETRIES; attempt++) {
- const port = RANDOM_PORT_MIN + Math.floor(Math.random() * (RANDOM_PORT_MAX - RANDOM_PORT_MIN));
- const result = await checkPortAvailable(port);
- if (result.available) {
- return port;
- }
- attempts.push({ port, result });
- }
- throw formatRandomPortUnavailableError(attempts);
+function findPort(): Promise<number> {
+ return findAvailablePort(BROWSE_PORT);
}
/**
@@ -1493,6 +1385,13 @@ async function handleCommand(body: any, tokenInfo?: TokenInfo | null): Promise<R
if (import.meta.main) {
// SIGINT (Ctrl+C): user intentionally stopping → shutdown.
process.on('SIGINT', () => activeShutdown?.());
+ // SIGHUP (terminal hangup): with handleSIGHUP:false at the three launch
+ // sites (#2220), Playwright no longer closes Chromium when this process
+ // gets hung up on — this handler is now the ONLY Chromium cleanup on
+ // SIGHUP (ENG-OV4). Route to the same shutdown path as SIGINT:
+ // activeShutdown closes the browser, releases ports, and removes the
+ // state file. Without it, a hangup would leak a live Chromium.
+ process.on('SIGHUP', () => activeShutdown?.());
// SIGTERM behavior depends on mode:
// - Normal (headless) mode: Claude Code's Bash sandbox fires SIGTERM when the
// parent shell exits between tool invocations. Ignoring it keeps the server
@@ -1999,10 +1898,13 @@ export function buildFetchHandler(cfg: ServerConfig): ServerHandle {
mode: browserManager.getConnectionMode(),
uptime: Math.floor((Date.now() - startTime) / 1000),
tabs: browserManager.getTabCount(),
- // Security module status — drives the shield icon in the sidepanel.
- // Returns {status: 'protected'|'degraded'|'inactive', layers: {...}}.
- // Fed by the page-content side (testsavant sidecar, canary state).
- security: getSecurityStatus(),
+ // No `security` field (#2557): the only writer of the status it
+ // reported (sidebar-agent.ts's session-state file) went away with
+ // the chat path, so it read from a file nothing wrote — reporting
+ // a permanent 'inactive', or a stale false-green 'protected'
+ // wherever an old state file survived on disk. The live defenses
+ // (content-security L1-L3, the L4 sidecar on /pty-inject-scan)
+ // report through their own call sites, not through /health.
// Terminal-agent discovery. ONLY a port number — never a token.
// Tokens flow via the /pty-session HttpOnly cookie path. See
// `pty-session-cookie.ts` for the rationale (codex outside-voice
diff --git a/browse/src/terminal-agent.ts b/browse/src/terminal-agent.ts
index 0c9de3d47..21ce5581a 100644
--- a/browse/src/terminal-agent.ts
+++ b/browse/src/terminal-agent.ts
@@ -27,6 +27,7 @@ import { writeSecureFile, restrictFilePermissions, mkdirSecure } from './file-pe
import { atomicWriteSync, atomicWriteQuiet } from '../../lib/fs-atomic';
import { safeUnlink } from './error-handling';
import { writeAgentRecord, clearAgentRecord } from './terminal-agent-control';
+import { findAvailablePort } from './port-allocator';
import { extractPtyCookie } from './pty-session-cookie';
const STATE_FILE = process.env.BROWSE_STATE_FILE || path.join(process.env.HOME || '/tmp', '.gstack', 'browse.json');
@@ -490,10 +491,15 @@ function maybeSpawnPty(ws: any, session: PtySession): boolean {
return true;
}
-function buildServer() {
+function buildServer(port: number) {
return Bun.serve({
hostname: '127.0.0.1',
- port: 0,
+ // #2314: allocated from the SAME fixed 10000-60000 scan range the main
+ // server uses (port-allocator.ts, decision 8) — never `port: 0`. Binding
+ // 0 drew from the OS EPHEMERAL range (49152-65535 on macOS), where this
+ // weeks-lived agent squatted ports that short-lived `app.listen(0)` test
+ // servers expected to receive, absorbing their traffic as phantom 404s.
+ port,
idleTimeout: 0, // PTY connections are long-lived; default idleTimeout would kill them
fetch(req, server) {
@@ -944,9 +950,27 @@ function readBrowseToken(): string {
}
// Boot.
-function main() {
+async function main() {
writeClaudeAvailable();
- const server = buildServer();
+ // #2314: allocate from the shared fixed scan range, then bind. Probe-then-
+ // bind has a TOCTOU window — a concurrent process can take the port between
+ // the probe and Bun.serve, which throws and would kill the boot with no
+ // retry (main().catch → exit 1). Re-allocate and retry a few times; each
+ // iteration probes fresh, so only a genuine race lands here.
+ let server: ReturnType<typeof buildServer> | undefined;
+ let lastBindErr: unknown;
+ for (let attempt = 0; attempt < 5 && !server; attempt++) {
+ const allocatedPort = await findAvailablePort();
+ try {
+ server = buildServer(allocatedPort);
+ } catch (err) {
+ lastBindErr = err;
+ }
+ }
+ if (!server) {
+ console.error(`[terminal-agent] failed to bind after 5 attempts: ${lastBindErr}`);
+ process.exit(1);
+ }
const port = (server as any).port || (server as any).address?.port;
if (!port) {
console.error('[terminal-agent] failed to bind: no port');
@@ -1015,4 +1039,7 @@ try {
writeSecureFile(INTERNAL_TOKEN_FILE, INTERNAL_TOKEN);
} catch {}
-main();
+main().catch((err) => {
+ console.error(`[terminal-agent] boot failed: ${err instanceof Error ? err.message : String(err)}`);
+ process.exit(1);
+});
diff --git a/browse/src/xprotect-heal.ts b/browse/src/xprotect-heal.ts
new file mode 100644
index 000000000..6c366975a
--- /dev/null
+++ b/browse/src/xprotect-heal.ts
@@ -0,0 +1,438 @@
+/**
+ * XProtect launch-kill self-heal (P0 #2554).
+ *
+ * macOS XProtect definition updates can start killing the exact Chromium
+ * revision the committed bun.lock pins (observed: revision 1208 under
+ * playwright 1.58.2 — xprotectd SIGKILLs chrome-headless-shell at spawn, so
+ * the failure surfaces as a Playwright launch timeout or a "Browser closed"
+ * error carrying `signal=SIGKILL`, never anything naming XProtect).
+ *
+ * The heal, in order, at most ONCE per process (F4):
+ * 1. Classify the launch failure against the XProtect kill signature
+ * (positive AND negative fixtures under test, F9).
+ * 2. Clear com.apple.quarantine on the Playwright cache bundles ONLY —
+ * a GSTACK_CHROMIUM_PATH bundle belongs to the wrapper/embedder and is
+ * never touched (same scope contract as probePoisonedChromiumBundle).
+ * 3. Force-reinstall Chromium FROM THE GSTACK INSTALL ROOT (ENG-OV3: the
+ * root whose node_modules pins the same playwright-core our compiled
+ * binary embeds — a cwd-resolved `bunx playwright install` would fetch
+ * the LATEST playwright's revision, which the embedded playwright-core
+ * won't find, and the one-shot guard would then block the retry).
+ * The install is BOUNDED (~120s, process-GROUP kill on timeout; E1).
+ * 4. Verify the revision dir the embedded playwright-core EXPECTS exists
+ * post-heal (registry-derived expectation, not merely install exit 0).
+ *
+ * Every action emits one structured stderr line (F11). When the heal cannot
+ * complete (offline, timeout, no install root, one-shot spent), the caller
+ * surfaces the ORIGINAL launch error plus manual
+ * `bunx playwright install chromium` guidance — the CLI never hangs on it.
+ */
+
+import * as fs from 'fs';
+import * as os from 'os';
+import * as path from 'path';
+import { spawn } from 'child_process';
+import { chromium } from 'playwright';
+
+/** F11: one structured stderr line per self-heal action. */
+function logHeal(action: string, fields: Record<string, unknown> = {}): void {
+ console.error(`[browse:xprotect-heal] ${JSON.stringify({ action, ...fields })}`);
+}
+
+// ─── Classifier (F9: positives AND negatives) ────────────────────────────
+
+/**
+ * Failure shapes that are definitively NOT an XProtect kill. Checked before
+ * the positives so an ambiguous message never triggers a pointless reinstall:
+ * - missing executable (browser was never installed / cache wiped)
+ * - spawn-level permission errors (EACCES / EPERM / ENOENT)
+ * - Linux sandbox denials (wrong OS anyway, but the text is distinctive)
+ */
+const NEGATIVE_SIGNATURES: RegExp[] = [
+ /executable doesn't exist/i,
+ /spawn\s+\S+\s+(EACCES|EPERM|ENOENT)/i,
+ /\b(EACCES|EPERM)\b/,
+ /no usable sandbox/i,
+ /failed to move to new namespace/i,
+ /suid sandbox helper/i,
+];
+
+/**
+ * Failure shapes an OS-level kill produces (sourced from the #2554 report
+ * plus Playwright's launch-error format): the browser process SPAWNED, then
+ * died to SIGKILL, or never became ready (launch timeout with a `<launched>`
+ * marker — the report's visible symptom, since xprotectd kills the child
+ * without Playwright ever learning why).
+ */
+const POSITIVE_SIGNATURES: RegExp[] = [
+ /<process did exit:[^>]*signal=SIGKILL/i,
+ /signal[:=]\s*['"]?SIGKILL/i,
+];
+
+/**
+ * True when a launch failure message matches the macOS XProtect kill
+ * signature. Platform-gated: XProtect exists only on darwin.
+ */
+export function isXProtectKillSignature(
+ message: string,
+ platform: NodeJS.Platform = process.platform,
+): boolean {
+ if (platform !== 'darwin') return false;
+ if (!message) return false;
+ for (const neg of NEGATIVE_SIGNATURES) {
+ if (neg.test(message)) return false;
+ }
+ for (const pos of POSITIVE_SIGNATURES) {
+ if (pos.test(message)) return true;
+ }
+ // XProtect kill at spawn also surfaces as a launch timeout where the
+ // process DID launch (<launched> marker present) but never became ready —
+ // this is the exact symptom the #2554 report describes.
+ return /timeout \d+\s*ms exceeded/i.test(message) && /<launched>/i.test(message);
+}
+
+// ─── Playwright cache path helpers (pure) ────────────────────────────────
+
+const REVISION_DIR_RE = /^chromium(?:_headless_shell)?-\d+$/;
+
+/**
+ * Walk up from a Chromium executable to its Playwright cache revision dir
+ * (e.g. …/ms-playwright/chromium-1234 or …/chromium_headless_shell-1234).
+ * Returns null when the executable is not in the standard cache layout.
+ */
+export function findPlaywrightRevisionDir(executablePath: string): string | null {
+ let dir = path.dirname(executablePath);
+ for (let i = 0; i < 8; i++) {
+ if (REVISION_DIR_RE.test(path.basename(dir))) return dir;
+ const parent = path.dirname(dir);
+ if (parent === dir) return null;
+ dir = parent;
+ }
+ return null;
+}
+
+/**
+ * The Chromium revision the EMBEDDED playwright-core expects, derived from
+ * the registry-computed executable path (chromium.executablePath() embeds
+ * the revision from playwright-core's browsers.json — it is not read from
+ * disk, so it stays correct even when nothing is installed yet).
+ */
+export function expectedChromiumRevision(executablePath: string): string | null {
+ const revDir = findPlaywrightRevisionDir(executablePath);
+ if (!revDir) return null;
+ const m = path.basename(revDir).match(/-(\d+)$/);
+ return m ? m[1] : null;
+}
+
+/**
+ * Find the gstack install root whose node_modules pins the SAME
+ * playwright-core revision our binary embeds (ENG-OV3). Candidates:
+ * the dev checkout (source runs) and the global ./setup install. A candidate
+ * qualifies only when its playwright-core/browsers.json chromium revision
+ * matches — running the reinstall anywhere else heals to the WRONG revision.
+ */
+export function findGstackInstallRoot(
+ expectedRevision: string,
+ candidates?: string[],
+): string | null {
+ const roots = candidates ?? [
+ // Dev checkout: browse/src/ → repo root. In the compiled binary
+ // __dirname points into the bunfs bundle and won't exist on disk,
+ // so this candidate simply fails the existsSync below.
+ path.resolve(__dirname, '..', '..'),
+ // Global install root (the ./setup target). os.homedir() rather than
+ // process.env.HOME: with HOME unset the env form produced the RELATIVE
+ // path '.claude/skills/gstack' under the daemon's cwd — often an
+ // untrusted repo being QA'd, whose planted node_modules would then be
+ // where the heal runs the playwright install (repo-controlled code
+ // execution). The absolute-or-skip guard below backstops the class.
+ path.join(os.homedir(), '.claude', 'skills', 'gstack'),
+ ];
+ for (const root of roots) {
+ if (!path.isAbsolute(root)) continue;
+ try {
+ const browsersJson = path.join(root, 'node_modules', 'playwright-core', 'browsers.json');
+ if (!fs.existsSync(browsersJson)) continue;
+ const parsed = JSON.parse(fs.readFileSync(browsersJson, 'utf-8'));
+ const rev = parsed?.browsers?.find((b: { name?: string }) => b?.name === 'chromium')?.revision;
+ if (String(rev) === String(expectedRevision)) return root;
+ } catch {
+ continue; // unreadable/malformed candidate — try the next one
+ }
+ }
+ return null;
+}
+
+// ─── Quarantine clear ────────────────────────────────────────────────────
+
+function defaultRunXattr(target: string): number | null {
+ const res = Bun.spawnSync(['xattr', '-dr', 'com.apple.quarantine', target], {
+ stdout: 'pipe',
+ stderr: 'pipe',
+ timeout: 10_000,
+ });
+ return res.exitCode;
+}
+
+/**
+ * Clear com.apple.quarantine on every chromium* revision dir in the
+ * Playwright cache (the headless shell is what XProtect actually killed in
+ * #2554; the headed bundle rides along so a later headed launch doesn't
+ * re-trip). Scope contract mirrors probePoisonedChromiumBundle: NEVER act
+ * on a GSTACK_CHROMIUM_PATH bundle — that belongs to the wrapper/embedder.
+ * Best-effort: xattr failures are logged, never thrown (the forced
+ * reinstall below is the real heal).
+ */
+export function clearQuarantineOnPlaywrightCache(
+ executablePath: string,
+ runXattr: (target: string) => number | null = defaultRunXattr,
+): boolean {
+ const customPath = process.env.GSTACK_CHROMIUM_PATH;
+ if (customPath && path.resolve(executablePath) === path.resolve(customPath)) {
+ logHeal('quarantine-clear-skipped', { reason: 'custom-chromium-path' });
+ return false;
+ }
+ const revDir = findPlaywrightRevisionDir(executablePath);
+ if (!revDir) {
+ logHeal('quarantine-clear-skipped', { reason: 'not-in-playwright-cache', executablePath });
+ return false;
+ }
+ const cacheRoot = path.dirname(revDir);
+ let cleared = 0;
+ let entries: string[];
+ try {
+ entries = fs.readdirSync(cacheRoot);
+ } catch (err) {
+ logHeal('quarantine-clear-skipped', {
+ reason: 'cache-unreadable',
+ error: err instanceof Error ? err.message : String(err),
+ });
+ return false;
+ }
+ for (const entry of entries) {
+ if (!REVISION_DIR_RE.test(entry)) continue;
+ const target = path.join(cacheRoot, entry);
+ try {
+ const exitCode = runXattr(target);
+ // Non-zero usually means "no such xattr" — nothing to clear, fine.
+ logHeal('quarantine-clear', { target, exitCode });
+ cleared++;
+ } catch (err) {
+ logHeal('quarantine-clear', {
+ target,
+ error: err instanceof Error ? err.message : String(err),
+ });
+ }
+ }
+ return cleared > 0;
+}
+
+// ─── Bounded forced reinstall (E1) ───────────────────────────────────────
+
+export const XPROTECT_REINSTALL_TIMEOUT_MS = 120_000;
+
+export interface ReinstallResult {
+ ok: boolean;
+ reason?: string;
+ exitCode?: number | null;
+}
+
+/**
+ * Run `bunx playwright install --force chromium` from the gstack install
+ * root, bounded at ~120s. The child gets its own process group (detached)
+ * so a timeout kills the WHOLE tree (bunx → playwright CLI → download
+ * workers), never leaving a zombie download saturating the network.
+ */
+export function runBoundedChromiumReinstall(
+ installRoot: string,
+ timeoutMs: number = XPROTECT_REINSTALL_TIMEOUT_MS,
+): Promise<ReinstallResult> {
+ return new Promise((resolve) => {
+ let settled = false;
+ let child: ReturnType<typeof spawn>;
+ try {
+ child = spawn('bunx', ['playwright', 'install', '--force', 'chromium'], {
+ cwd: installRoot,
+ detached: true, // own process group → group-kill on timeout
+ stdio: ['ignore', 'ignore', 'pipe'],
+ windowsHide: true,
+ });
+ } catch (err) {
+ resolve({ ok: false, reason: `spawn-error: ${err instanceof Error ? err.message : String(err)}` });
+ return;
+ }
+ let stderrTail = '';
+ child.stderr?.on('data', (d: Buffer) => {
+ stderrTail = (stderrTail + String(d)).slice(-2000);
+ });
+ const timer = setTimeout(() => {
+ if (settled) return;
+ settled = true;
+ try {
+ if (child.pid) process.kill(-child.pid, 'SIGKILL'); // whole group
+ } catch (err: unknown) {
+ if ((err as NodeJS.ErrnoException)?.code !== 'ESRCH') {
+ try { child.kill('SIGKILL'); } catch { /* already gone */ }
+ }
+ }
+ resolve({ ok: false, reason: 'timeout' });
+ }, timeoutMs);
+ child.on('error', (err) => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ resolve({ ok: false, reason: `spawn-error: ${err.message}` });
+ });
+ child.on('exit', (code) => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ if (code === 0) {
+ resolve({ ok: true, exitCode: code });
+ } else {
+ resolve({
+ ok: false,
+ reason: `install-exit-${code}${stderrTail ? `: ${stderrTail.slice(-300)}` : ''}`,
+ exitCode: code,
+ });
+ }
+ });
+ });
+}
+
+// ─── One-shot orchestration (F4) ─────────────────────────────────────────
+
+let healAttempted = false;
+
+/** Test seam only — production never resets the one-shot guard. */
+export function resetXProtectHealForTests(): void {
+ healAttempted = false;
+}
+
+export interface XProtectHealDeps {
+ platform?: NodeJS.Platform;
+ executablePath?: () => string;
+ clearQuarantine?: (execPath: string) => boolean;
+ installRoot?: (expectedRevision: string) => string | null;
+ runReinstall?: (installRoot: string) => Promise<ReinstallResult>;
+ verifyInstalled?: (execPath: string) => boolean;
+}
+
+/**
+ * Attempt the XProtect self-heal for a classified launch failure.
+ *
+ * Returns true when the heal completed AND the revision dir the embedded
+ * playwright-core expects exists on disk — the caller should retry the
+ * launch exactly once. Returns false when the error doesn't match the
+ * signature, the launch used a custom executable, the one-shot guard
+ * already fired, or any heal step failed (the caller then surfaces the
+ * original error + manual guidance).
+ */
+export async function maybeHealXProtectKill(
+ err: unknown,
+ opts: { usesCustomExecutable?: boolean } = {},
+ deps: XProtectHealDeps = {},
+): Promise<boolean> {
+ const message = err instanceof Error ? err.message : String(err);
+ if (!isXProtectKillSignature(message, deps.platform ?? process.platform)) return false;
+ if (opts.usesCustomExecutable) {
+ // A GSTACK_CHROMIUM_PATH bundle belongs to the wrapper/embedder — never
+ // quarantine-clear or reinstall over it (probePoisonedChromiumBundle's
+ // scope contract).
+ logHeal('skip', { reason: 'custom-executable' });
+ return false;
+ }
+ if (healAttempted) {
+ logHeal('skip', { reason: 'already-attempted-this-process' });
+ return false;
+ }
+ healAttempted = true; // F4: at most one heal per process, even on failure
+ logHeal('classified', { signature: 'xprotect-kill' });
+
+ const execPath = (deps.executablePath ?? (() => chromium.executablePath()))();
+ (deps.clearQuarantine ?? clearQuarantineOnPlaywrightCache)(execPath);
+
+ const revision = expectedChromiumRevision(execPath);
+ if (!revision) {
+ logHeal('reinstall-skipped', { reason: 'no-revision-in-path', execPath });
+ return false;
+ }
+ const root = (deps.installRoot ?? findGstackInstallRoot)(revision);
+ if (!root) {
+ // No install root pins our revision — a cwd-resolved install would heal
+ // to the WRONG revision (ENG-OV3), so surface guidance instead.
+ logHeal('reinstall-skipped', { reason: 'no-install-root', revision });
+ return false;
+ }
+
+ logHeal('reinstall-start', { installRoot: root, revision, timeoutMs: XPROTECT_REINSTALL_TIMEOUT_MS });
+ const result = await (deps.runReinstall ?? runBoundedChromiumReinstall)(root);
+ if (!result.ok) {
+ logHeal('reinstall-failed', { reason: result.reason });
+ return false;
+ }
+
+ // F9/ENG-OV3: assert the revision dir the embedded playwright-core
+ // EXPECTS exists post-heal — install exit 0 alone can mean "installed the
+ // wrong revision" when resolution went sideways.
+ const verify = deps.verifyInstalled ?? ((p: string) => fs.existsSync(p));
+ if (!verify(execPath)) {
+ logHeal('verify-failed', { expected: execPath });
+ return false;
+ }
+ logHeal('reinstall-ok', { installRoot: root, revision });
+ return true;
+}
+
+/**
+ * Original launch error + manual remediation, for classified failures the
+ * heal could not fix (offline, timeout, one-shot spent, no install root).
+ */
+export function buildXProtectGuidance(originalMessage: string): string {
+ return (
+ `${originalMessage}\n` +
+ '[browse] This launch failure matches the macOS XProtect kill signature (#2554): ' +
+ "the OS killed Playwright's Chromium at spawn. Automatic self-heal did not complete. " +
+ 'Fix manually: run `bunx playwright install chromium` from your gstack install ' +
+ '(the directory whose node_modules pins playwright — ~/.claude/skills/gstack for ' +
+ 'global installs), then retry.'
+ );
+}
+
+/**
+ * Wrap a Playwright launch call with the XProtect self-heal: on a classified
+ * failure, heal once and retry the launch once. On a classified failure the
+ * heal could not fix, throw the ORIGINAL error text augmented with manual
+ * guidance. Unclassified failures pass through untouched.
+ */
+export async function launchWithXProtectHeal<T>(
+ doLaunch: () => Promise<T>,
+ opts: { usesCustomExecutable?: boolean } = {},
+ deps: XProtectHealDeps = {},
+): Promise<T> {
+ try {
+ return await doLaunch();
+ } catch (err) {
+ const healed = await maybeHealXProtectKill(err, opts, deps);
+ if (healed) {
+ logHeal('retry-launch', {});
+ try {
+ return await doLaunch();
+ } catch (retryErr) {
+ // The heal ran but the retry died too. Without this wrap the second
+ // error propagated raw and the manual-remediation guidance was lost
+ // exactly when the automatic path had just proven insufficient.
+ const retryMessage = retryErr instanceof Error ? retryErr.message : String(retryErr);
+ if (isXProtectKillSignature(retryMessage, deps.platform ?? process.platform)) {
+ throw new Error(buildXProtectGuidance(retryMessage), { cause: retryErr });
+ }
+ throw retryErr;
+ }
+ }
+ const message = err instanceof Error ? err.message : String(err);
+ if (isXProtectKillSignature(message, deps.platform ?? process.platform)) {
+ throw new Error(buildXProtectGuidance(message), { cause: err });
+ }
+ throw err;
+ }
+}
diff --git a/browse/test/browser-skill-commands.test.ts b/browse/test/browser-skill-commands.test.ts
index 889c2d46e..c93a908e2 100644
--- a/browse/test/browser-skill-commands.test.ts
+++ b/browse/test/browser-skill-commands.test.ts
@@ -382,3 +382,42 @@ describe.skipIf(SKIP_SPAWN)('spawnSkill: lifecycle', () => {
expect(result.stdout.length).toBeLessThanOrEqual(1024 * 1024);
}, 10_000);
});
+
+describe('subprocess capture goes through temp files, not pipes', () => {
+ // Tripwire. Capturing a child's output through `stdout: 'pipe'` is lossy
+ // here: under a loaded parent, the first piped spawn in the process
+ // intermittently yields an empty stderr even though the child wrote it and
+ // exited 0. Neither draining before awaiting exit nor a manual getReader()
+ // loop avoids it — both were measured losing the same bytes. It flaked
+ // `$B skill test` (a dropped stderr left only bun's banner) and would blank
+ // a skill's JSON result on `$B skill run` while still reporting success.
+ //
+ // runToFiles() points the child's fds at temp files instead, so the kernel
+ // has flushed everything by the time the child exits. This test fails if a
+ // refactor reintroduces pipe capture in this module.
+ //
+ // Comments are stripped first, so the module's own prose — which names the
+ // banned pattern in order to explain it — doesn't trip checks meant for code.
+ const src = fs.readFileSync(
+ path.join(import.meta.dir, '..', 'src', 'browser-skill-commands.ts'), 'utf-8')
+ .replace(/\/\*[\s\S]*?\*\//g, '')
+ .replace(/^\s*\/\/.*$/gm, '');
+
+ it("does not spawn with stdout/stderr: 'pipe'", () => {
+ expect(src).not.toMatch(/std(out|err):\s*'pipe'/);
+ });
+
+ it('does not read child output via Response(proc.stdout/stderr) or getReader', () => {
+ expect(src).not.toMatch(/new Response\(\s*proc\.(stdout|stderr)/);
+ expect(src).not.toMatch(/proc\.(stdout|stderr)[\s\S]{0,40}getReader\(/);
+ });
+
+ it('every spawn site routes through runToFiles', () => {
+ // The structural invariant: runToFiles owns the module's only Bun.spawn,
+ // so any present or future spawn site inherits the file-based capture.
+ // Counted rather than name-checked so adding a spawn site that bypasses
+ // the helper fails here instead of silently reintroducing the bug.
+ expect(src.match(/Bun\.spawn\(/g) ?? []).toHaveLength(1);
+ expect((src.match(/await runToFiles\(/g) ?? []).length).toBeGreaterThanOrEqual(2);
+ });
+});
diff --git a/browse/test/browser-skills-e2e.test.ts b/browse/test/browser-skills-e2e.test.ts
index 039a451a8..8fa76fd08 100644
--- a/browse/test/browser-skills-e2e.test.ts
+++ b/browse/test/browser-skills-e2e.test.ts
@@ -85,7 +85,17 @@ describe('browser-skills E2E — bundled hackernews-frontpage', () => {
// It takes ~1s. Run it last so other assertions are quick.
test('$B skill test hackernews-frontpage runs script.test.ts and reports pass', async () => {
const result = await handleSkillCommand(['test', 'hackernews-frontpage'], { port: 0 });
- // bun test prints summary to stderr; handleSkillCommand returns stderr || stdout
- expect(result).toMatch(/13 pass|0 fail|tests passed/);
+ // `bun test` splits its report across streams: the version banner goes to
+ // stdout, the pass/fail summary to stderr. handleSkillCommand must return
+ // both, so assert on each stream's half.
+ //
+ // This used to flake under full-suite load: capturing the child through
+ // pipes dropped stderr on the first piped spawn in the process, so the
+ // result was just the banner. The old `13 pass|0 fail|tests passed` regex
+ // also had a `tests passed` alternative that matched a synthetic fallback
+ // string, which would have passed vacuously on an empty capture.
+ expect(result).toMatch(/bun test v/); // stdout half
+ expect(result).toMatch(/\b0 fail\b/); // stderr half
+ expect(result).toMatch(/Ran \d+ tests/);
}, 30_000);
});
diff --git a/browse/test/busy-daemon-iron-rule.test.ts b/browse/test/busy-daemon-iron-rule.test.ts
new file mode 100644
index 000000000..53149cb31
--- /dev/null
+++ b/browse/test/busy-daemon-iron-rule.test.ts
@@ -0,0 +1,232 @@
+/**
+ * #2219 IRON RULE regression tests (E5): an alive daemon pid is NEVER
+ * auto-killed. Killing a live daemon loses the session's tabs, cookies, and
+ * logins — strictly worse than a slow command. Only an explicit
+ * --force-restart may replace a live daemon.
+ *
+ * Integration legs follow the busy-daemon-recovery.test.ts pattern: a fake
+ * HTTP daemon + a live `sleep` child standing in for the daemon PID, wired
+ * through BROWSE_STATE_FILE. Unit legs pin the pure decision function.
+ */
+
+import { describe, test, expect, afterEach } from 'bun:test';
+import { spawn, type ChildProcess } from 'child_process';
+import * as fs from 'fs';
+import * as os from 'os';
+import * as path from 'path';
+import * as http from 'http';
+import { isProcessAlive } from '../src/error-handling';
+import { decideDaemonRestart, HEALTH_PROBE_TOTAL_BUDGET_MS } from '../src/cli';
+
+// ─── Unit: the pure restart decision (decision 9 / F10) ──────────────────
+
+describe('decideDaemonRestart (pure)', () => {
+ test('healthy after probe → retry against the SAME daemon', () => {
+ expect(decideDaemonRestart({ pidAlive: true, healthyAfterProbe: true, forceRestart: false }))
+ .toBe('retry-command');
+ // Even with --force-restart in hand, a healthy daemon is retried, not killed.
+ expect(decideDaemonRestart({ pidAlive: true, healthyAfterProbe: true, forceRestart: true }))
+ .toBe('retry-command');
+ });
+
+ test('IRON RULE: alive + unhealthy + no flag → report busy, never kill', () => {
+ expect(decideDaemonRestart({ pidAlive: true, healthyAfterProbe: false, forceRestart: false }))
+ .toBe('report-busy');
+ });
+
+ test('alive + unhealthy + explicit --force-restart → force-restart', () => {
+ expect(decideDaemonRestart({ pidAlive: true, healthyAfterProbe: false, forceRestart: true }))
+ .toBe('force-restart');
+ });
+
+ test('dead pid → restart, with or without the flag', () => {
+ expect(decideDaemonRestart({ pidAlive: false, healthyAfterProbe: false, forceRestart: false }))
+ .toBe('restart-dead');
+ expect(decideDaemonRestart({ pidAlive: false, healthyAfterProbe: false, forceRestart: true }))
+ .toBe('restart-dead');
+ });
+
+ test('probe budget is ~8s (F10) — long enough for heavy-page busy windows', () => {
+ expect(HEALTH_PROBE_TOTAL_BUDGET_MS).toBeGreaterThanOrEqual(7_000);
+ expect(HEALTH_PROBE_TOTAL_BUDGET_MS).toBeLessThanOrEqual(10_000);
+ });
+});
+
+// ─── Integration: real spawned CLI vs fake daemons ───────────────────────
+
+/** A daemon whose /health always answers healthy but never serves /command. */
+async function startHealthyDaemon(): Promise<{ port: number; close: () => Promise<void> }> {
+ const server = http.createServer((req, res) => {
+ if (req.url === '/health') {
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ status: 'healthy' }));
+ return;
+ }
+ res.writeHead(200, { 'Content-Type': 'text/plain' });
+ res.end('ok');
+ });
+ await new Promise<void>((resolve, reject) => {
+ server.once('error', reject);
+ server.listen(0, '127.0.0.1', () => resolve());
+ });
+ const addr = server.address();
+ if (!addr || typeof addr === 'string') throw new Error('fake daemon: bad address');
+ return { port: addr.port, close: () => new Promise((r) => server.close(() => r())) };
+}
+
+/** A WEDGED daemon: alive socket, but /health always answers unhealthy. */
+async function startWedgedDaemon(): Promise<{ port: number; close: () => Promise<void> }> {
+ const server = http.createServer((req, res) => {
+ res.writeHead(503, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ status: 'wedged' }));
+ });
+ await new Promise<void>((resolve, reject) => {
+ server.once('error', reject);
+ server.listen(0, '127.0.0.1', () => resolve());
+ });
+ const addr = server.address();
+ if (!addr || typeof addr === 'string') throw new Error('fake daemon: bad address');
+ return { port: addr.port, close: () => new Promise((r) => server.close(() => r())) };
+}
+
+function runCli(args: string[], env: Record<string, string>, timeoutMs = 30_000):
+ Promise<{ code: number; stdout: string; stderr: string }> {
+ const cliPath = path.resolve(import.meta.dir, '../src/cli.ts');
+ return new Promise((resolve) => {
+ const proc = spawn('bun', ['run', cliPath, ...args], { timeout: timeoutMs, env });
+ let stdout = ''; let stderr = '';
+ proc.stdout.on('data', (d) => stdout += d.toString());
+ proc.stderr.on('data', (d) => stderr += d.toString());
+ proc.on('close', (code) => resolve({ code: code ?? 1, stdout, stderr }));
+ });
+}
+
+function baseEnv(stateFile: string): Record<string, string> {
+ const env: Record<string, string> = {};
+ for (const [k, v] of Object.entries(process.env)) {
+ if (v !== undefined) env[k] = v;
+ }
+ env.BROWSE_STATE_FILE = stateFile;
+ return env;
+}
+
+let pidChild: ChildProcess | null = null;
+afterEach(() => { pidChild?.kill('SIGKILL'); pidChild = null; });
+
+describe('#2219 iron rule (CLI integration)', () => {
+ test('healthy daemon SURVIVES `browse connect` — refused with guidance, no kill', async () => {
+ const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'browse-iron-'));
+ const stateFile = path.join(tmpDir, 'browse.json');
+ const daemon = await startHealthyDaemon();
+ try {
+ pidChild = spawn('sleep', ['60'], { stdio: 'ignore' });
+ const daemonPid = pidChild.pid!;
+ const stateContent = {
+ pid: daemonPid,
+ port: daemon.port,
+ token: 'iron-rule-token',
+ startedAt: new Date().toISOString(),
+ serverPath: '',
+ mode: 'launched' as const,
+ };
+ fs.writeFileSync(stateFile, JSON.stringify(stateContent, null, 2));
+
+ const result = await runCli(['connect'], baseEnv(stateFile));
+
+ expect(result.code).not.toBe(0);
+ expect(result.stderr).toContain('healthy daemon is already running');
+ expect(result.stderr).toContain('--force-restart');
+ // THE IRON RULE: the daemon process was not killed.
+ expect(isProcessAlive(daemonPid)).toBe(true);
+ // And the state file was not clobbered.
+ expect(JSON.parse(fs.readFileSync(stateFile, 'utf-8'))).toEqual(stateContent);
+ } finally {
+ await daemon.close();
+ fs.rmSync(tmpDir, { recursive: true, force: true });
+ }
+ }, 30_000);
+
+ test('wedged-alive daemon + plain command → busy report + nonzero exit, NO kill', async () => {
+ const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'browse-iron-'));
+ const stateFile = path.join(tmpDir, 'browse.json');
+ const daemon = await startWedgedDaemon();
+ try {
+ pidChild = spawn('sleep', ['120'], { stdio: 'ignore' });
+ const daemonPid = pidChild.pid!;
+ fs.writeFileSync(stateFile, JSON.stringify({
+ pid: daemonPid,
+ port: daemon.port,
+ token: 'iron-rule-token',
+ startedAt: new Date().toISOString(),
+ serverPath: '',
+ mode: 'launched' as const,
+ }, null, 2));
+
+ const result = await runCli(['status'], baseEnv(stateFile));
+
+ expect(result.code).not.toBe(0);
+ expect(result.stderr).toContain('Daemon busy');
+ expect(result.stderr).toContain('--force-restart');
+ // Never killed, never restarted.
+ expect(isProcessAlive(daemonPid)).toBe(true);
+ expect(result.stderr).not.toContain('Restarting');
+ } finally {
+ await daemon.close();
+ fs.rmSync(tmpDir, { recursive: true, force: true });
+ }
+ }, 45_000);
+
+ test('wedged-alive daemon + --force-restart IS killed (explicit consent path)', async () => {
+ // Unix lanes only: the consent path must boot a REAL replacement daemon
+ // to answer the command, which the secretless/browserless Windows lane
+ // cannot do (no Chromium install), and the teardown relies on setsid
+ // process-group semantics Windows lacks. The Windows-relevant half of
+ // the iron rule — busy → refusal, never an implicit kill — runs above.
+ if (process.platform === 'win32') return;
+ const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'browse-iron-'));
+ const stateFile = path.join(tmpDir, 'browse.json');
+ const daemon = await startWedgedDaemon();
+ try {
+ pidChild = spawn('sleep', ['120'], { stdio: 'ignore' });
+ const daemonPid = pidChild.pid!;
+ fs.writeFileSync(stateFile, JSON.stringify({
+ pid: daemonPid,
+ port: daemon.port,
+ token: 'iron-rule-token',
+ startedAt: new Date().toISOString(),
+ serverPath: '',
+ mode: 'launched' as const,
+ }, null, 2));
+
+ // `status` with --force-restart: the wedged "daemon" must be killed and
+ // a REAL daemon started in its place.
+ const result = await runCli(['--force-restart', 'status'], baseEnv(stateFile), 60_000);
+
+ // The wedged pid was killed — the explicit consent path.
+ expect(isProcessAlive(daemonPid)).toBe(false);
+ expect(result.stderr).toContain('--force-restart');
+ // The replacement daemon answered the command.
+ expect(result.code).toBe(0);
+ } finally {
+ // Kill the REAL daemon's whole PROCESS GROUP, not just its pid.
+ // startServer spawns the daemon detached (setsid — its own group
+ // leader), so a bare SIGKILL on the pid orphans its Chromium child,
+ // which then squats memory for the REST of the suite (~100 files) —
+ // enough pressure on a loaded box for the OS to kill a LATER test's
+ // in-process Chromium, whose disconnect handler process.exit(1)s the
+ // whole bun run mid-suite with no summary.
+ try {
+ const newState = JSON.parse(fs.readFileSync(stateFile, 'utf-8'));
+ if (newState?.pid && isProcessAlive(newState.pid)) {
+ try {
+ process.kill(-newState.pid, 'SIGKILL'); // group: daemon + Chromium
+ } catch {
+ process.kill(newState.pid, 'SIGKILL'); // fallback: pid only
+ }
+ }
+ } catch { /* state file gone — nothing started */ }
+ await daemon.close();
+ fs.rmSync(tmpDir, { recursive: true, force: true });
+ }
+ }, 90_000);
+});
diff --git a/browse/test/cdp-allowlist.test.ts b/browse/test/cdp-allowlist.test.ts
index 8c80b2cdd..73d339f23 100644
--- a/browse/test/cdp-allowlist.test.ts
+++ b/browse/test/cdp-allowlist.test.ts
@@ -70,6 +70,18 @@ describe('CDP allowlist (T2: deny-default)', () => {
expect(isCdpMethodAllowed('Page.captureScreenshot')).toBe(true);
});
+ it('Emulation.setEmulatedMedia is allowed, tab-scoped, trusted (#2419)', () => {
+ // Media type/feature override (prefers-color-scheme, prefers-reduced-motion,
+ // prefers-contrast, forced-colors) so a11y and dark-mode CSS branches are
+ // testable via $B cdp. Returns an empty result — no page content, so
+ // trusted output is correct.
+ expect(isCdpMethodAllowed('Emulation.setEmulatedMedia')).toBe(true);
+ const e = lookupCdpMethod('Emulation.setEmulatedMedia');
+ expect(e).not.toBeNull();
+ expect(e!.scope).toBe('tab');
+ expect(e!.output).toBe('trusted');
+ });
+
it('untrusted-output methods cover the read-everything-attacker-controlled cases', () => {
// Anything that reads attacker-controlled strings (DOM/AX/CSS selectors)
// should be tagged untrusted so the envelope wraps the result.
diff --git a/browse/test/cdp-e2e.test.ts b/browse/test/cdp-e2e.test.ts
index c6b2c8a8a..c2d731350 100644
--- a/browse/test/cdp-e2e.test.ts
+++ b/browse/test/cdp-e2e.test.ts
@@ -18,6 +18,12 @@ import { startTestServer } from './test-server';
import { BrowserManager } from '../src/browser-manager';
const TMP_HOME = path.join(os.tmpdir(), `gstack-cdp-e2e-${process.pid}-${Date.now()}`);
+// Shard runs execute many test files in ONE bun process: a module-scope env
+// mutation without restore leaks into every LATER file in the shard. This
+// exact leak once pointed a sibling test's GSTACK_HOME at our temp dir,
+// which then got baked into artifacts that outlived it (dangling symlinks
+// into a deleted render dir). Save + restore in afterAll.
+const ORIGINAL_GSTACK_HOME = process.env.GSTACK_HOME;
process.env.GSTACK_HOME = TMP_HOME;
process.env.GSTACK_TELEMETRY_OFF = '1'; // don't pollute analytics during tests
@@ -36,6 +42,8 @@ beforeAll(async () => {
});
afterAll(async () => {
+ if (ORIGINAL_GSTACK_HOME === undefined) delete process.env.GSTACK_HOME;
+ else process.env.GSTACK_HOME = ORIGINAL_GSTACK_HOME;
try { await bm.cleanup?.(); } catch {}
try { testServer.server.stop(); } catch {}
await fs.rm(TMP_HOME, { recursive: true, force: true });
diff --git a/browse/test/daemon-log-hygiene.test.ts b/browse/test/daemon-log-hygiene.test.ts
new file mode 100644
index 000000000..77e021bca
--- /dev/null
+++ b/browse/test/daemon-log-hygiene.test.ts
@@ -0,0 +1,135 @@
+/**
+ * #2461 daemon crash log + F6 log hygiene needles.
+ *
+ * The detached daemon's stdout/stderr now land in <stateDir>/browse-daemon.log
+ * (both spawn paths) instead of 'ignore'. That makes crashes diagnosable —
+ * and makes it load-bearing that NOTHING secret or page-derived reaches the
+ * daemon's console streams:
+ *
+ * - No console.* call anywhere in src/ may pass a token VALUE (AUTH_TOKEN,
+ * state.token, attachToken, INTERNAL_TOKEN, setup keys). Names like
+ * tokenInfo.clientId are fine — the needle targets expressions whose
+ * value IS a token.
+ * - The page-content carrier modules (tab-session, buffers,
+ * content-security, activity) stay console-free, so raw page-derived
+ * strings can't be echoed into the log unsanitized.
+ *
+ * Source-level, same style as windows-spawn-hide.test.ts.
+ */
+
+import { describe, expect, test } from 'bun:test';
+import * as fs from 'fs';
+import * as path from 'path';
+
+const SRC_DIR = path.join(import.meta.dir, '../src');
+const SRC = (f: string) => fs.readFileSync(path.join(SRC_DIR, f), 'utf-8');
+
+describe('#2461 daemon log wiring', () => {
+ test('both daemon spawn paths capture stdout/stderr to browse-daemon.log', () => {
+ const cli = SRC('cli.ts');
+ // Unix path: fd from openDaemonLogSink wired into stdio.
+ expect(cli).toContain("stdio: ['ignore', daemonLogFd, daemonLogFd]");
+ expect(cli).toMatch(/openDaemonLogSink/);
+ // Windows path: the fd must be opened INSIDE the node -e launcher (an fd
+ // opened in cli.ts wouldn't cross the spawn boundary).
+ expect(cli).toContain("stdio:['ignore',logFd,logFd]");
+ expect(cli).toContain('browse-daemon.log');
+ // The old fully-discarded wiring must not come back on either daemon path.
+ expect(cli).not.toContain("stdio:['ignore','ignore','ignore']");
+ });
+
+ test('log sink is append-mode (accumulates across respawns)', () => {
+ const cli = SRC('cli.ts');
+ // Both spawn paths open through the single daemonLogPath() source (M4),
+ // which itself must build from the state dir.
+ expect(cli).toMatch(/openSync\(daemonLogPath\(\), 'a'\)/);
+ expect(cli).toMatch(/path\.join\(config\.stateDir, 'browse-daemon\.log'\)/);
+ expect(cli).toMatch(/openSync\(\$\{daemonLogPathStr\},'a'\)/);
+ });
+
+ test('append-mode log is growth-bounded: rotated at 10MB before daemon start', () => {
+ const cli = SRC('cli.ts');
+ expect(cli).toMatch(/DAEMON_LOG_MAX_BYTES = 10 \* 1024 \* 1024/);
+ expect(cli).toMatch(/rotateDaemonLogIfOversized\(\);/);
+ // Single generation: rename to .1, matching the repo's 10MB conventions.
+ expect(cli).toMatch(/renameSync\(p, `\$\{p\}\.1`\)/);
+ });
+
+ test('rotation behavior: oversized rotates to a single .1 generation, small/missing are no-ops', () => {
+ const os = require('os');
+ const { rotateDaemonLogIfOversized } = require('../src/cli');
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-daemon-log-'));
+ try {
+ const p = path.join(tmp, 'browse-daemon.log');
+ // Missing log: no throw (first launch).
+ rotateDaemonLogIfOversized(p, 1024);
+ // Under the cap: untouched, no generation created.
+ fs.writeFileSync(p, 'x'.repeat(10));
+ rotateDaemonLogIfOversized(p, 1024);
+ expect(fs.existsSync(p)).toBe(true);
+ expect(fs.existsSync(`${p}.1`)).toBe(false);
+ // Over the cap: rotated out of the way so the daemon starts fresh.
+ fs.writeFileSync(p, 'y'.repeat(2048));
+ rotateDaemonLogIfOversized(p, 1024);
+ expect(fs.existsSync(p)).toBe(false);
+ expect(fs.readFileSync(`${p}.1`, 'utf-8')).toContain('y');
+ // Single generation: the next rotation REPLACES .1 (bounded at ~2x cap
+ // total, never a .2).
+ fs.writeFileSync(p, 'z'.repeat(2048));
+ rotateDaemonLogIfOversized(p, 1024);
+ expect(fs.readFileSync(`${p}.1`, 'utf-8')).toContain('z');
+ expect(fs.existsSync(`${p}.2`)).toBe(false);
+ } finally {
+ fs.rmSync(tmp, { recursive: true, force: true });
+ }
+ });
+
+ test('bun-polyfill routes Windows spawns through cross-spawn (ENOENT + cmd.exe injection fix)', () => {
+ const polyfill = SRC('bun-polyfill.cjs');
+ expect(polyfill).toContain("require('cross-spawn')");
+ expect(polyfill).toMatch(/process\.platform === 'win32' \? crossSpawn\.sync : nodeSpawnSync/);
+ expect(polyfill).toMatch(/process\.platform === 'win32' \? crossSpawn : nodeSpawn/);
+ // The rejected-for-cause alternative must not creep back in: shell:true
+ // on Windows routes through cmd.exe and does NOT neutralize & | ^ % < >.
+ // (Strip comments — the header documents WHY shell:true was rejected.)
+ const code = polyfill.replace(/\/\*[\s\S]*?\*\//g, '').replace(/^\s*\/\/.*$/gm, '');
+ expect(code).not.toMatch(/shell:\s*true/);
+ });
+});
+
+describe('F6 log hygiene: nothing secret or page-derived reaches daemon console', () => {
+ const files = fs.readdirSync(SRC_DIR).filter((f) => f.endsWith('.ts') || f.endsWith('.cjs'));
+
+ test('no console.* call passes a token value', () => {
+ const offenders: string[] = [];
+ for (const file of files) {
+ const content = SRC(file);
+ for (const [idx, line] of content.split('\n').entries()) {
+ if (!/console\.(log|error|warn|info)\(/.test(line)) continue;
+ // Interpolated token values: ${...token} / ${...Token} — the
+ // expression ENDS in token, i.e. the value IS the token. Names like
+ // ${tokenInfo.clientId} don't match.
+ if (/\$\{[^}]*[tT]oken\s*\}/.test(line)) {
+ offenders.push(`${file}:${idx + 1}: ${line.trim().slice(0, 120)}`);
+ continue;
+ }
+ // Bare token args: console.log('x', token) / (..., authToken)
+ if (/console\.(log|error|warn|info)\([^)]*[^a-zA-Z_.][tT]oken\s*[,)]/.test(line)) {
+ offenders.push(`${file}:${idx + 1}: ${line.trim().slice(0, 120)}`);
+ }
+ }
+ }
+ expect(offenders).toEqual([]);
+ });
+
+ test('page-content carrier modules are console-free', () => {
+ // Page-derived strings flow through these modules. Keeping them
+ // console-free guarantees raw page content can't be echoed into
+ // browse-daemon.log without passing an egress sanitizer first.
+ for (const file of ['tab-session.ts', 'buffers.ts', 'content-security.ts', 'activity.ts']) {
+ const content = SRC(file);
+ const calls = content.match(/console\.(log|error|warn|info)\(/g) || [];
+ expect({ file, count: calls.length }).toEqual({ file, count: 0 });
+ }
+ });
+});
diff --git a/browse/test/launch-signal-flags.test.ts b/browse/test/launch-signal-flags.test.ts
new file mode 100644
index 000000000..2a26fa4bc
--- /dev/null
+++ b/browse/test/launch-signal-flags.test.ts
@@ -0,0 +1,74 @@
+/**
+ * Static tripwire for #2220: every Playwright launch site must disable
+ * Playwright's process-level signal handlers (handleSIGINT / handleSIGTERM /
+ * handleSIGHUP), and server.ts must own the SIGHUP cleanup those flags
+ * remove.
+ *
+ * WHY handleSIGTERM:false is correct here: server.ts DELIBERATELY ignores
+ * SIGTERM in normal headless mode (the process.on('SIGTERM') handler —
+ * Claude Code's Bash sandbox fires SIGTERM when the parent shell exits
+ * between tool invocations, and the daemon must survive it). Playwright's
+ * default handleSIGTERM:true registers its OWN handler that closes Chromium
+ * on the same signal — so the daemon survived but its browser died out from
+ * under it. With the flag false, the daemon's signal policy is the only
+ * signal policy: the signals server.ts honors route through activeShutdown,
+ * which closes Chromium itself.
+ *
+ * WHY server.ts needs a SIGHUP handler (ENG-OV4): before #2220 the daemon
+ * had NO process-level SIGHUP handler — Playwright's default handleSIGHUP
+ * was the only thing closing Chromium on hangup. Flipping the flag without
+ * adding a handler would leak a live Chromium on every hangup.
+ *
+ * Source-level, same style as windows-spawn-hide.test.ts: cheap,
+ * deterministic, runs on every platform.
+ */
+
+import { describe, expect, test } from 'bun:test';
+import * as fs from 'fs';
+import * as path from 'path';
+
+const SRC = (f: string) => fs.readFileSync(path.join(import.meta.dir, '../src', f), 'utf-8');
+
+/** Every occurrence of `needle` must carry all three handleSIG* flags within
+ * the next `window` chars (the launch options object). */
+function expectSignalFlagsNearEvery(src: string, needle: string, window = 1200): number {
+ let idx = src.indexOf(needle);
+ expect(idx).toBeGreaterThanOrEqual(0);
+ let count = 0;
+ while (idx !== -1) {
+ const slice = src.slice(idx, idx + window);
+ expect(slice).toMatch(/handleSIGINT:\s*false/);
+ expect(slice).toMatch(/handleSIGTERM:\s*false/);
+ expect(slice).toMatch(/handleSIGHUP:\s*false/);
+ count++;
+ idx = src.indexOf(needle, idx + needle.length);
+ }
+ return count;
+}
+
+describe('Playwright launch sites disable signal handlers (#2220)', () => {
+ test('all chromium.launch / launchPersistentContext sites carry the three flags', () => {
+ const src = SRC('browser-manager.ts');
+ const launchCount = expectSignalFlagsNearEvery(src, 'chromium.launch({');
+ const persistentCount = expectSignalFlagsNearEvery(src, 'chromium.launchPersistentContext(');
+ // Three launch sites today: headless launch(), headed launchHeaded(),
+ // and the handoff relaunch. A NEW launch site must carry the flags too —
+ // bump this only after adding them.
+ expect(launchCount + persistentCount).toBe(3);
+ });
+
+ test('server.ts owns SIGHUP cleanup now that Playwright does not (ENG-OV4)', () => {
+ const src = SRC('server.ts');
+ // The SIGHUP handler must route to the same shutdown path Chromium
+ // cleanup uses (activeShutdown), like SIGINT does.
+ expect(src).toMatch(/process\.on\('SIGHUP',\s*\(\)\s*=>\s*activeShutdown\?\.\(\)\)/);
+ });
+
+ test('the deliberate headless SIGTERM-ignore still exists (the reason handleSIGTERM:false is safe)', () => {
+ const src = SRC('server.ts');
+ // If this handler ever disappears, revisit handleSIGTERM:false — the
+ // flag is correct BECAUSE server.ts owns SIGTERM policy.
+ expect(src).toContain("process.on('SIGTERM'");
+ expect(src).toContain('Received SIGTERM (ignoring');
+ });
+});
diff --git a/browse/test/playwright-core-patch.test.ts b/browse/test/playwright-core-patch.test.ts
new file mode 100644
index 000000000..d09e136c9
--- /dev/null
+++ b/browse/test/playwright-core-patch.test.ts
@@ -0,0 +1,62 @@
+/**
+ * #2160/#1989: playwright-core is bun-patched to pass windowsHide at its two
+ * Windows-visible child_process sites — the browser launch spawn (Node
+ * defaults windowsHide to FALSE for spawn, so browser children could flash a
+ * console window) and the force-kill taskkill spawnSync. This is the repo's
+ * first patchedDependencies entry; these static checks pin the three-legged
+ * coherence (patch file ↔ package.json ↔ installed tree) so a playwright
+ * bump that forgets to re-target the patch fails CI instead of silently
+ * dropping it. NOTE: bumping playwright (c25-style) REQUIRES regenerating
+ * this patch against the new version — see the revert pairing in the wave
+ * plan (reverting the bump means dropping the patch too).
+ */
+
+import { describe, expect, test } from 'bun:test';
+import * as fs from 'fs';
+import * as path from 'path';
+
+const ROOT = path.resolve(import.meta.dir, '..', '..');
+
+function installedPlaywrightCoreVersion(): string {
+ const pkg = JSON.parse(fs.readFileSync(
+ path.join(ROOT, 'node_modules', 'playwright-core', 'package.json'), 'utf-8',
+ ));
+ return pkg.version as string;
+}
+
+describe('playwright-core windowsHide patch (#2160, #1989)', () => {
+ test('package.json declares the patch for the installed version', () => {
+ const pkg = JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf-8'));
+ const version = installedPlaywrightCoreVersion();
+ const key = `playwright-core@${version}`;
+ expect(pkg.patchedDependencies).toBeDefined();
+ // Version-keyed on purpose: if playwright is bumped without re-targeting
+ // the patch, this fails with the exact key that needs regenerating.
+ expect(pkg.patchedDependencies[key]).toBe(`patches/playwright-core@${version}.patch`);
+ });
+
+ test('the patch file exists and carries both windowsHide sites', () => {
+ const version = installedPlaywrightCoreVersion();
+ const patchPath = path.join(ROOT, 'patches', `playwright-core@${version}.patch`);
+ expect(fs.existsSync(patchPath)).toBe(true);
+ const patch = fs.readFileSync(patchPath, 'utf-8');
+ // Launch spawnOptions site.
+ expect(patch).toContain('+ windowsHide: true,');
+ // taskkill force-kill site.
+ expect(patch).toContain('shell: true, windowsHide: true');
+ });
+
+ test('bun.lock is coherent: the lockfile records the patched dependency', () => {
+ const lock = fs.readFileSync(path.join(ROOT, 'bun.lock'), 'utf-8');
+ const version = installedPlaywrightCoreVersion();
+ expect(lock).toContain(`patches/playwright-core@${version}.patch`);
+ });
+
+ test('the INSTALLED tree actually has the patch applied (bun install ran it)', () => {
+ const bundle = fs.readFileSync(
+ path.join(ROOT, 'node_modules', 'playwright-core', 'lib', 'coreBundle.js'), 'utf-8',
+ );
+ expect(bundle).toContain('gstack patch (#2160/#1989)');
+ expect(bundle).toContain('shell: true, windowsHide: true');
+ });
+});
diff --git a/browse/test/process-liveness-windows.test.ts b/browse/test/process-liveness-windows.test.ts
index d474473dc..de907af40 100644
--- a/browse/test/process-liveness-windows.test.ts
+++ b/browse/test/process-liveness-windows.test.ts
@@ -54,16 +54,24 @@ describe('process liveness probe (Windows terminal-agent leak)', () => {
expect(isProcessAlive(2147483646)).toBe(false);
});
- test('3. isProcessAlive spawns NO subprocess on POSIX (signal-0 path)', () => {
+ test('2b. EPERM means ALIVE: an unsignalable-but-existing PID is not dead (T2)', () => {
+ // signal-0 to a process we lack permission over throws EPERM — the
+ // process EXISTS, we just can't signal it. Treating EPERM as "dead" is
+ // the false negative that leaked agents. PID 1 (launchd/init) on POSIX
+ // and PID 4 (System) on Windows always exist and are either signalable
+ // or EPERM — both must read as alive.
+ expect(isProcessAlive(process.platform === 'win32' ? 4 : 1)).toBe(true);
+ });
+
+ test('3. isProcessAlive spawns NO subprocess on ANY platform (signal-0, #1952)', () => {
// The heart of the bug: a liveness probe that forks is slow enough to
// time out, and a timed-out probe silently answers "dead". Signal 0
- // cannot time out because it never leaves the process.
- //
- // Merged design note: on win32 the helper DOES keep a single hardened
- // tasklist probe (windowsHide, bounded timeout, quoted-CSV PID match)
- // because Bun's process.kill(pid, 0) throws ESRCH for live Windows PIDs
- // in compiled binaries. The POSIX path stays subprocess-free.
- if (process.platform === 'win32') return;
+ // cannot time out because it never leaves the process. Node maps
+ // process.kill(pid, 0) to an OpenProcess existence check on Windows —
+ // and the Windows daemon runs under Node (server-node.mjs +
+ // bun-polyfill), so the POSIX idiom is portable and the win32 tasklist
+ // branch is GONE (it caused both the false negatives above and the
+ // per-tick console flash of #1952).
const origSpawn = (Bun as any).spawn;
const origSpawnSync = (Bun as any).spawnSync;
const spawns: string[] = [];
@@ -79,16 +87,14 @@ describe('process liveness probe (Windows terminal-agent leak)', () => {
}
});
- test('4. no source file probes liveness via tasklist outside the central helper', () => {
- // Static tripwire: ad-hoc tasklist existence checks scattered across src/
- // resurrect the false-negative class (each call site re-invents the
- // timeout/parse handling and gets it subtly wrong). The ONE sanctioned
- // site is error-handling.ts's isProcessAlive win32 branch — centralized,
- // windowsHide, bounded timeout, quoted-CSV `"${pid}"` match. Every other
- // file must route through the helper.
+ test('4. no source file probes liveness via tasklist — signal-0 is the only probe (#1952)', () => {
+ // Static tripwire: a tasklist existence check ANYWHERE in src/
+ // resurrects both the false-negative class (#2414: a timed-out spawnSync
+ // still returns, with partial stdout, so a live process reads as dead)
+ // and the per-tick console flash (#1952). isProcessAlive uses
+ // process.kill(pid, 0) on every platform; nothing gets an exemption.
const offenders: string[] = [];
for (const { file, content } of readAllSourceFiles()) {
- if (file === 'error-handling.ts') continue; // the canonical helper
const code = stripComments(content);
// `PID eq` is the existence-probe form specifically. Other tasklist
// uses (e.g. IMAGENAME filters for browser detection) are unaffected.
diff --git a/browse/test/security.test.ts b/browse/test/security.test.ts
index ac1642e4f..d49d5ed0b 100644
--- a/browse/test/security.test.ts
+++ b/browse/test/security.test.ts
@@ -10,18 +10,12 @@
*/
import { describe, test, expect } from 'bun:test';
-import * as fs from 'fs';
-import * as os from 'os';
-import * as path from 'path';
import {
THRESHOLDS,
combineVerdict,
generateCanary,
injectCanary,
checkCanaryInStructure,
- writeSessionState,
- readSessionState,
- getStatus,
extractDomain,
type LayerSignal,
} from '../src/security';
@@ -244,57 +238,13 @@ describe('canary', () => {
// ─── Attack log + rotation ───────────────────────────────────
-// ─── Session state (cross-process, atomic) ───────────────────
-
-describe('session state', () => {
- test('write + read round-trip', () => {
- const state = {
- sessionId: 'test-session-123',
- canary: 'CANARY-TEST',
- warnedDomains: ['example.com'],
- classifierStatus: { testsavant: 'ok' as const },
- lastUpdated: '2026-04-19T12:34:56Z',
- };
- writeSessionState(state);
- const got = readSessionState();
- expect(got).not.toBeNull();
- expect(got!.sessionId).toBe('test-session-123');
- expect(got!.canary).toBe('CANARY-TEST');
- expect(got!.warnedDomains).toEqual(['example.com']);
- });
-
- test('tolerates stale transcript field from pre-rip on-disk state', () => {
- // SessionState is a disk format. Files written before the Haiku
- // transcript layer was removed carry classifierStatus.transcript —
- // getStatus must read them fine, not require transcript for
- // 'protected', and never leak the stale key into /health.
- const stateFile = path.join(os.homedir(), '.gstack', 'security', 'session-state.json');
- fs.mkdirSync(path.dirname(stateFile), { recursive: true });
- fs.writeFileSync(stateFile, JSON.stringify({
- sessionId: 'legacy-session',
- canary: 'CANARY-LEGACY',
- warnedDomains: [],
- classifierStatus: { testsavant: 'ok', transcript: 'degraded' },
- lastUpdated: '2026-04-19T12:34:56Z',
- }));
- const s = getStatus();
- expect(s.status).toBe('protected');
- expect('transcript' in s.layers).toBe(false);
- });
-});
-
-// ─── Status reporting for shield icon ────────────────────────
-
-describe('getStatus', () => {
- test('returns a valid SecurityStatus shape', () => {
- const s = getStatus();
- expect(['protected', 'degraded', 'inactive']).toContain(s.status);
- expect(s.layers).toBeDefined();
- expect(['ok', 'degraded', 'off']).toContain(s.layers.testsavant);
- expect(['ok', 'off']).toContain(s.layers.canary);
- expect(s.lastUpdated).toBeTruthy();
- });
-});
+// NOTE (#2557): the session-state + getStatus tests that lived here wrote
+// REAL fixture data into ~/.gstack/security/session-state.json — after which
+// /health reported a false-green 'protected' indefinitely. The surfaces they
+// covered (SessionState, read/writeSessionState, getStatus, the /health
+// security field, the sidepanel SEC shield) were dead since the PTY terminal
+// rewrite and are now removed. server-security-surface.test.ts pins the
+// removal + the live L4 wiring.
// ─── URL domain extraction ───────────────────────────────────
diff --git a/browse/test/server-security-surface.test.ts b/browse/test/server-security-surface.test.ts
new file mode 100644
index 000000000..cdfb76c96
--- /dev/null
+++ b/browse/test/server-security-surface.test.ts
@@ -0,0 +1,86 @@
+/**
+ * #2557 / ENG-OV9: pins the dead-shield removal AND the live L4 wiring.
+ *
+ * The removed surface: /health's `security` field read getStatus(), whose
+ * only data source (~/.gstack/security/session-state.json) lost its only
+ * writer when sidebar-agent.ts was ripped — so /health reported a permanent
+ * 'inactive' or, wherever an old state file survived, a stale FALSE-GREEN
+ * 'protected' ("no threats detected" when the real state was "not
+ * measured"). Same fail-open class as #2026.
+ *
+ * The kept surface (ENG-OV9): security.ts is NOT dead — server.ts's
+ * /pty-inject-scan path is the live L4 consumer (sidecar scan + URL
+ * blocklist + datamark envelope), and security.ts's pure combiner/canary
+ * exports stay. This test pins both directions so a future "cleanup" can't
+ * silently take the live half, and a future re-feed of /health.security
+ * from LIVE signals (isSidecarAvailable, content filters) must update this
+ * test deliberately rather than resurrect the state-file path.
+ *
+ * Source-level, same style as windows-spawn-hide.test.ts.
+ */
+
+import { describe, expect, test } from 'bun:test';
+import * as fs from 'fs';
+import * as path from 'path';
+
+const SRC = (f: string) => fs.readFileSync(path.join(import.meta.dir, '../src', f), 'utf-8');
+
+describe('#2557: dead shield surface stays dead', () => {
+ test('/health carries no security field and server.ts does not import getStatus', () => {
+ const server = SRC('server.ts');
+ expect(server).not.toMatch(/security:\s*getSecurityStatus\(\)/);
+ expect(server).not.toMatch(/getStatus as getSecurityStatus/);
+ // The SECURITY session-state file must not be read anywhere in src/ —
+ // that file has no writer, so any reader is a false-signal feed.
+ // (session-persist.ts's per-project <stateDir>/session-state.json is a
+ // different, live file — only the ~/.gstack/security/ one is dead.)
+ for (const f of fs.readdirSync(path.join(import.meta.dir, '../src')).filter((x) => x.endsWith('.ts'))) {
+ const code = SRC(f).replace(/\/\*[\s\S]*?\*\//g, '').replace(/^\s*\/\/.*$/gm, '').replace(/^\s*\*.*$/gm, '');
+ const refs = /security[/'",\s][^\n]{0,80}session-state\.json/.test(code);
+ expect({ file: f, refs }).toEqual({ file: f, refs: false });
+ }
+ });
+
+ test('security.ts no longer exports the unfed status surface', () => {
+ const security = SRC('security.ts');
+ expect(security).not.toMatch(/export function getStatus/);
+ expect(security).not.toMatch(/export function (read|write)SessionState/);
+ expect(security).not.toMatch(/export interface SessionState/);
+ expect(security).not.toMatch(/export interface StatusDetail/);
+ });
+
+ test('the sidepanel shield markup is gone', () => {
+ const html = fs.readFileSync(path.join(import.meta.dir, '../../extension/sidepanel.html'), 'utf-8');
+ const css = fs.readFileSync(path.join(import.meta.dir, '../../extension/sidepanel.css'), 'utf-8');
+ expect(html).not.toContain('security-shield');
+ expect(css).not.toMatch(/\.security-shield\s*\{/);
+ });
+});
+
+describe('ENG-OV9: the LIVE L4 path is untouched', () => {
+ test('server.ts still consumes the sidecar on the inject-scan path', () => {
+ const server = SRC('server.ts');
+ expect(server).toContain("from './security-sidecar-client'");
+ expect(server).toMatch(/isSidecarAvailable/);
+ expect(server).toMatch(/scanWithSidecar\(/);
+ });
+
+ test('security.ts keeps the pure combiner + canary exports', () => {
+ const security = SRC('security.ts');
+ expect(security).toMatch(/export const THRESHOLDS/);
+ expect(security).toMatch(/export function combineVerdict/);
+ expect(security).toMatch(/export function generateCanary/);
+ expect(security).toMatch(/export function injectCanary/);
+ expect(security).toMatch(/export function checkCanaryInStructure/);
+ expect(security).toMatch(/export function extractDomain/);
+ });
+
+ test('/health stays liveness-only: no token in any mode (regression wall from v1.63)', () => {
+ const server = SRC('server.ts');
+ // The /health handler block must not interpolate a token.
+ const healthIdx = server.indexOf("url.pathname === '/health'");
+ expect(healthIdx).toBeGreaterThan(0);
+ const healthBlock = server.slice(healthIdx, healthIdx + 1500);
+ expect(healthBlock).not.toMatch(/token:\s*[^n]/i);
+ });
+});
diff --git a/browse/test/stealth-webdriver.test.ts b/browse/test/stealth-webdriver.test.ts
index 541dc0237..b5365ea80 100644
--- a/browse/test/stealth-webdriver.test.ts
+++ b/browse/test/stealth-webdriver.test.ts
@@ -315,5 +315,11 @@ describe('applyStealth — persistent context (headed + handoff parity)', () =>
await ctx.close();
fs.rmSync(userDataDir, { recursive: true, force: true });
}
- });
+ }, 45000);
+ // ^ 45s: this is the one HEADED persistent-context launch in the free
+ // suite. A cold headed launch on macOS runs 8-25s — worse on the first
+ // launch of a freshly downloaded Chromium (XProtect scans the new bundle,
+ // the #2554 class) and under shard concurrency. bun's 5s default made this
+ // the suite's most reliable false-negative: it timed out on the pre-wave
+ // baseline run of main too, and passes at 15/15 with an honest budget.
});
diff --git a/browse/test/stop-dead-daemon.test.ts b/browse/test/stop-dead-daemon.test.ts
new file mode 100644
index 000000000..b92a669d3
--- /dev/null
+++ b/browse/test/stop-dead-daemon.test.ts
@@ -0,0 +1,144 @@
+/**
+ * #2254: `browse stop` against a daemon that isn't running must report
+ * success and exit 0 — WITHOUT starting a daemon just to stop it. The old
+ * flow routed stop through ensureServer(), which booted a fresh daemon +
+ * Chromium (multi-second, resource churn) and then shut it down — or
+ * crash-restarted on a stale state file.
+ *
+ * Integration pattern follows busy-daemon-recovery.test.ts: a scratch
+ * BROWSE_STATE_FILE + a real spawned CLI.
+ */
+
+import { describe, test, expect } from 'bun:test';
+import { spawn } from 'child_process';
+import * as fs from 'fs';
+import * as net from 'net';
+import * as os from 'os';
+import * as path from 'path';
+import { isProcessAlive } from '../src/error-handling';
+
+function runCli(args: string[], env: Record<string, string>, timeoutMs = 30_000):
+ Promise<{ code: number; stdout: string; stderr: string }> {
+ const cliPath = path.resolve(import.meta.dir, '../src/cli.ts');
+ return new Promise((resolve) => {
+ const proc = spawn('bun', ['run', cliPath, ...args], { timeout: timeoutMs, env });
+ let stdout = ''; let stderr = '';
+ proc.stdout.on('data', (d) => stdout += d.toString());
+ proc.stderr.on('data', (d) => stderr += d.toString());
+ proc.on('close', (code) => resolve({ code: code ?? 1, stdout, stderr }));
+ });
+}
+
+function baseEnv(stateFile: string): Record<string, string> {
+ const env: Record<string, string> = {};
+ for (const [k, v] of Object.entries(process.env)) {
+ if (v !== undefined) env[k] = v;
+ }
+ env.BROWSE_STATE_FILE = stateFile;
+ return env;
+}
+
+/** Grab a port that is definitely closed (bind, read, release). */
+async function closedPort(): Promise<number> {
+ return new Promise((resolve, reject) => {
+ const srv = net.createServer();
+ srv.once('error', reject);
+ srv.listen(0, '127.0.0.1', () => {
+ const addr = srv.address();
+ if (!addr || typeof addr === 'string') { reject(new Error('bad address')); return; }
+ const port = addr.port;
+ srv.close(() => resolve(port));
+ });
+ });
+}
+
+describe('#2254 stop on a dead daemon', () => {
+ test('no daemon state at all → exit 0, nothing spawned', async () => {
+ const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'browse-stop-'));
+ const stateFile = path.join(tmpDir, 'browse.json');
+ try {
+ const result = await runCli(['stop'], baseEnv(stateFile));
+
+ expect(result.code).toBe(0);
+ expect(result.stdout).toContain('nothing to stop');
+ // The load-bearing half: NO daemon was started to serve the stop —
+ // a spawned daemon would have written the state file.
+ expect(fs.existsSync(stateFile)).toBe(false);
+ expect(result.stderr).not.toContain('Starting server');
+ } finally {
+ fs.rmSync(tmpDir, { recursive: true, force: true });
+ }
+ }, 30_000);
+
+ test('stale state (dead pid + closed port) → exit 0, state cleaned, nothing spawned', async () => {
+ const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'browse-stop-'));
+ const stateFile = path.join(tmpDir, 'browse.json');
+ try {
+ // A pid that is certainly not alive and a port nothing listens on.
+ const port = await closedPort();
+ fs.writeFileSync(stateFile, JSON.stringify({
+ pid: 2147483646,
+ port,
+ token: 'stale-token',
+ startedAt: new Date().toISOString(),
+ serverPath: '',
+ mode: 'launched' as const,
+ }, null, 2));
+
+ const result = await runCli(['stop'], baseEnv(stateFile));
+
+ expect(result.code).toBe(0);
+ expect(result.stdout).toContain('nothing to stop');
+ // Stale state cleaned, and no daemon spawned to replace it.
+ expect(fs.existsSync(stateFile)).toBe(false);
+ expect(result.stderr).not.toContain('Starting server');
+ expect(result.stderr).not.toContain('Restarting');
+ } finally {
+ fs.rmSync(tmpDir, { recursive: true, force: true });
+ }
+ }, 30_000);
+});
+
+describe('stop --force-restart on a LIVE daemon', () => {
+ test('kills it directly — never boots a fresh daemon just to stop it', async () => {
+ // A live-but-BUSY daemon: the pid is alive but nothing answers /health.
+ // Pre-fix, stop --force-restart fell through to ensureServer(), whose
+ // force-restart path killed the daemon and then STARTED a fresh one
+ // (daemon + Chromium) so sendCommand('stop') could stop it again —
+ // exactly what gstack-upgrade Step 4.8 triggers on a stale-busy daemon.
+ const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'browse-stop-force-'));
+ const stateFile = path.join(tmpDir, 'browse.json');
+ // Portable long-lived child standing in for the wedged daemon process.
+ const wedged = spawn('bun', ['-e', 'await Bun.sleep(300000)'], { stdio: 'ignore' });
+ try {
+ const port = await closedPort();
+ fs.writeFileSync(stateFile, JSON.stringify({
+ pid: wedged.pid,
+ port,
+ token: 'busy-token',
+ startedAt: new Date().toISOString(),
+ serverPath: '',
+ mode: 'launched' as const,
+ }, null, 2));
+
+ const result = await runCli(['stop', '--force-restart'], baseEnv(stateFile));
+
+ expect(result.code).toBe(0);
+ expect(result.stdout).toContain('Daemon stopped (forced');
+ // The load-bearing half: NO fresh daemon was booted to serve the stop.
+ // A spawned daemon would have re-written the state file.
+ expect(fs.existsSync(stateFile)).toBe(false);
+ expect(result.stderr).not.toContain('Starting server');
+ expect(result.stdout + result.stderr).not.toContain('Restarting');
+ // And the live pid is actually gone.
+ const deadline = Date.now() + 3000;
+ while (Date.now() < deadline && isProcessAlive(wedged.pid!)) {
+ await new Promise((r) => setTimeout(r, 100));
+ }
+ expect(isProcessAlive(wedged.pid!)).toBe(false);
+ } finally {
+ try { wedged.kill('SIGKILL'); } catch { /* already gone */ }
+ fs.rmSync(tmpDir, { recursive: true, force: true });
+ }
+ }, 30_000);
+});
diff --git a/browse/test/terminal-agent-port-range.test.ts b/browse/test/terminal-agent-port-range.test.ts
new file mode 100644
index 000000000..9fcf0e1fe
--- /dev/null
+++ b/browse/test/terminal-agent-port-range.test.ts
@@ -0,0 +1,80 @@
+/**
+ * #2314: the terminal-agent must allocate its port from the SAME fixed
+ * 10000-49151 scan range the main server uses (port-allocator.ts,
+ * decision 8) — never `port: 0`. Binding 0 drew from the OS ephemeral range
+ * (49152-65535 on macOS), where the weeks-lived agent squatted ports that
+ * short-lived `app.listen(0)` test servers expected to receive, absorbing
+ * their traffic as phantom 404s across every Node test suite on the machine.
+ */
+
+import { describe, test, expect } from 'bun:test';
+import * as fs from 'fs';
+import * as net from 'net';
+import * as path from 'path';
+import {
+ findAvailablePort,
+ RANDOM_PORT_MIN,
+ RANDOM_PORT_MAX,
+} from '../src/port-allocator';
+
+const AGENT_TS = path.resolve(import.meta.dir, '..', 'src', 'terminal-agent.ts');
+const SERVER_TS = path.resolve(import.meta.dir, '..', 'src', 'server.ts');
+
+describe('shared port allocator (#2314)', () => {
+ test('allocates inside the fixed scan range, never the ephemeral range', async () => {
+ for (let i = 0; i < 5; i++) {
+ const port = await findAvailablePort();
+ expect(port).toBeGreaterThanOrEqual(RANDOM_PORT_MIN);
+ expect(port).toBeLessThan(RANDOM_PORT_MAX);
+ // The load-bearing property: the WHOLE range sits below the ephemeral
+ // floor (49152). The original 60000 cap left ~22% of picks inside the
+ // pool this allocator exists to avoid.
+ expect(RANDOM_PORT_MAX).toBeLessThan(49152);
+ expect(RANDOM_PORT_MIN).toBeGreaterThanOrEqual(1024);
+ }
+ });
+
+ test('explicit free port is honored', async () => {
+ // Find a free port by binding 0, then ask the allocator for exactly it.
+ const free = await new Promise<number>((resolve, reject) => {
+ const srv = net.createServer();
+ srv.once('error', reject);
+ srv.listen(0, '127.0.0.1', () => {
+ const p = (srv.address() as net.AddressInfo).port;
+ srv.close(() => resolve(p));
+ });
+ });
+ expect(await findAvailablePort(free)).toBe(free);
+ });
+
+ test('explicit occupied port throws an actionable error', async () => {
+ const srv = net.createServer();
+ await new Promise<void>((resolve, reject) => {
+ srv.once('error', reject);
+ srv.listen(0, '127.0.0.1', () => resolve());
+ });
+ const occupied = (srv.address() as net.AddressInfo).port;
+ try {
+ await expect(findAvailablePort(occupied)).rejects.toThrow(/in use/);
+ } finally {
+ await new Promise<void>((r) => srv.close(() => r()));
+ }
+ });
+});
+
+describe('terminal-agent uses the shared allocator (static tripwire)', () => {
+ test('terminal-agent.ts never binds port: 0', () => {
+ const src = fs.readFileSync(AGENT_TS, 'utf-8');
+ // Strip comments so the explanatory history above the bind doesn't trip.
+ const code = src.replace(/\/\*[\s\S]*?\*\//g, '').replace(/^\s*\/\/.*$/gm, '');
+ expect(code).not.toMatch(/port:\s*0\b/);
+ expect(src).toContain("from './port-allocator'");
+ expect(src).toContain('findAvailablePort');
+ });
+
+ test('server.ts routes findPort through the same allocator', () => {
+ const src = fs.readFileSync(SERVER_TS, 'utf-8');
+ expect(src).toContain("from './port-allocator'");
+ expect(src).toMatch(/findAvailablePort\(BROWSE_PORT\)/);
+ });
+});
diff --git a/browse/test/windows-spawn-hide.test.ts b/browse/test/windows-spawn-hide.test.ts
index 086a28657..a9949a566 100644
--- a/browse/test/windows-spawn-hide.test.ts
+++ b/browse/test/windows-spawn-hide.test.ts
@@ -39,8 +39,9 @@ describe('windowsHide on Windows-reachable spawns (#1835)', () => {
});
test('Windows-only process probes pass windowsHide', () => {
- // tasklist in isProcessAlive — runs in polling loops.
- expectHideNearEvery(SRC('error-handling.ts'), "'tasklist'");
+ // isProcessAlive no longer spawns anything (signal-0 on every platform,
+ // #1952) — process-liveness-windows.test.ts pins that it stays
+ // subprocess-free, which is stronger than hiding a window.
// powershell DPAPI + tasklist in cookie import.
const cookie = SRC('cookie-import-browser.ts');
expectHideNearEvery(cookie, "'powershell'");
@@ -61,4 +62,69 @@ describe('windowsHide on Windows-reachable spawns (#1835)', () => {
// spawn's options object carries the full env wiring before the flag.
expectHideNearEvery(SRC('terminal-agent-control.ts'), '(Bun as any).spawn(', 700);
});
+
+ test('SWEEP: every direct child_process call in src/ passes windowsHide (#2160, #2415)', () => {
+ // Full-census tripwire: a NEW child_process call site without windowsHide
+ // fails CI. Each exemption carries a reason — an interactive console
+ // child must NOT get CREATE_NO_WINDOW.
+ const EXEMPT: Array<{ file: string; needle: string; reason: string }> = [
+ {
+ file: 'domain-skill-commands.ts',
+ needle: 'spawnSync(editor',
+ reason: "interactive $EDITOR with stdio:'inherit' — windowsHide would detach a console editor into an invisible console",
+ },
+ ];
+
+ const srcDir = path.join(import.meta.dir, '../src');
+ const offenders: string[] = [];
+ for (const file of fs.readdirSync(srcDir).filter((f) => f.endsWith('.ts'))) {
+ const raw = fs.readFileSync(path.join(srcDir, file), 'utf-8');
+ if (!raw.includes('child_process')) continue;
+ // Strip comments so documented history doesn't trip the census.
+ const code = raw.replace(/\/\*[\s\S]*?\*\//g, '').replace(/^\s*\/\/.*$/gm, '');
+
+ // Collect the callable names this file binds to child_process:
+ // import { spawn as nodeSpawn } from 'child_process'
+ // const { execSync } = await import('child_process') / require(...)
+ // import * as cp from 'child_process' → cp.<fn>( pattern
+ const names = new Set<string>();
+ const namespaces = new Set<string>();
+ const importRe = /import\s*\{([^}]*)\}\s*from\s*['"](?:node:)?child_process['"]/g;
+ const dynRe = /(?:const|let|var)\s*\{([^}]*)\}\s*=\s*(?:await\s+import\(|require\()['"](?:node:)?child_process['"]\)/g;
+ const nsRe = /import\s*\*\s*as\s*(\w+)\s*from\s*['"](?:node:)?child_process['"]/g;
+ for (const m of code.matchAll(importRe)) {
+ for (const part of m[1].split(',')) {
+ const alias = part.split(/\s+as\s+/).map((s) => s.trim()).filter(Boolean);
+ const name = alias[alias.length - 1];
+ if (name && /^(spawn|spawnSync|exec|execSync|execFile|execFileSync|nodeSpawn|cpSpawn)/.test(alias[0].trim())) names.add(name);
+ }
+ }
+ for (const m of code.matchAll(dynRe)) {
+ for (const part of m[1].split(',')) {
+ const alias = part.split(':').map((s) => s.trim()).filter(Boolean);
+ const name = alias[alias.length - 1];
+ if (name && /^(spawn|spawnSync|exec|execSync|execFile|execFileSync)/.test(alias[0].trim())) names.add(name);
+ }
+ }
+ for (const m of code.matchAll(nsRe)) namespaces.add(m[1]);
+
+ const patterns: RegExp[] = [];
+ for (const n of names) patterns.push(new RegExp(`(?<![.\\w'"\`])${n}\\(`, 'g'));
+ for (const ns of namespaces) {
+ patterns.push(new RegExp(`(?<![\\w'"\`])${ns}\\.(?:spawn|spawnSync|exec|execSync|execFile|execFileSync)\\(`, 'g'));
+ }
+
+ for (const re of patterns) {
+ for (const m of code.matchAll(re)) {
+ const slice = code.slice(m.index!, m.index! + 700);
+ const exempt = EXEMPT.some((e) => e.file === file && slice.startsWith(e.needle));
+ if (exempt) continue;
+ if (!/windowsHide:\s*true/.test(slice)) {
+ offenders.push(`${file}: ${slice.split('\n')[0].slice(0, 100)}`);
+ }
+ }
+ }
+ }
+ expect(offenders).toEqual([]);
+ });
});
diff --git a/browse/test/xprotect-heal.test.ts b/browse/test/xprotect-heal.test.ts
new file mode 100644
index 000000000..5a41898fe
--- /dev/null
+++ b/browse/test/xprotect-heal.test.ts
@@ -0,0 +1,457 @@
+/**
+ * XProtect launch-kill self-heal (P0 #2554) — unit tests.
+ *
+ * F9: the classifier is tested with POSITIVE signatures (sourced from the
+ * #2554 report + Playwright's launch-error format) AND NEGATIVES (missing
+ * executable, EPERM/EACCES, sandbox denial, plain crash) so a generic launch
+ * failure can never trigger a pointless reinstall.
+ *
+ * F4: the one-shot guard is pinned — at most one heal attempt per process,
+ * even when the heal fails.
+ *
+ * ENG-OV3/F9: the post-heal verification target is REGISTRY-derived (the
+ * revision playwright-core's browsers.json expects), not disk-derived, and
+ * the install-root finder rejects roots pinning a different revision.
+ */
+import { describe, it, expect, beforeEach, afterEach } from 'bun:test';
+import * as fs from 'fs';
+import * as path from 'path';
+import * as os from 'os';
+import { chromium } from 'playwright';
+import {
+ isXProtectKillSignature,
+ findPlaywrightRevisionDir,
+ expectedChromiumRevision,
+ findGstackInstallRoot,
+ clearQuarantineOnPlaywrightCache,
+ maybeHealXProtectKill,
+ launchWithXProtectHeal,
+ resetXProtectHealForTests,
+ buildXProtectGuidance,
+ runBoundedChromiumReinstall,
+} from '../src/xprotect-heal';
+
+const REPO_ROOT = path.resolve(import.meta.dir, '..', '..');
+
+// ─── Fixtures: POSITIVE signatures (real Playwright error shapes for an
+// OS-level SIGKILL at spawn — what xprotectd does per the #2554 report) ────
+
+const SIGKILL_BROWSER_CLOSED = `browserType.launch: Browser closed.
+==================== Browser output: ====================
+<launched> pid=48213
+[pid=48213] <process did exit: exitCode=null, signal=SIGKILL>
+[pid=48213] starting temporary directories cleanup
+=========================== logs ===========================`;
+
+const SIGKILL_PERSISTENT_CONTEXT = `browserType.launchPersistentContext: Target page, context or browser has been closed
+Browser logs:
+<launched> pid=9021
+[pid=9021] <process did exit: exitCode=null, signal=SIGKILL>`;
+
+// The #2554 report's visible symptom: the kill surfaces as a launch timeout
+// where the process DID spawn (<launched>) but never became ready.
+const LAUNCH_TIMEOUT_AFTER_SPAWN = `browserType.launch: Timeout 180000ms exceeded.
+=========================== logs ===========================
+<launched> pid=51677
+============================================================`;
+
+// ─── Fixtures: NEGATIVE signatures (F9) ──────────────────────────────────
+
+const MISSING_EXECUTABLE = `browserType.launch: Executable doesn't exist at /Users/dev/Library/Caches/ms-playwright/chromium_headless_shell-1234/chrome-mac-arm64/headless_shell
+╔═══════════════════════════════════════════════════════╗
+║ Looks like Playwright was just installed or updated. ║
+║ Please run the following command to download browsers:║
+║ bunx playwright install ║
+╚═══════════════════════════════════════════════════════╝`;
+
+const SPAWN_EACCES = `browserType.launch: spawn /Users/dev/Library/Caches/ms-playwright/chromium-1234/chrome-mac-arm64/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing EACCES`;
+
+const EPERM_FAILURE = `browserType.launch: Browser closed.
+==================== Browser output: ====================
+Error: EPERM: operation not permitted, open '/Users/dev/Library/Caches/ms-playwright/.links/lock'`;
+
+const SANDBOX_DENIAL = `browserType.launch: Browser closed.
+==================== Browser output: ====================
+<launched> pid=7211
+[pid=7211][err] Failed to move to new namespace: PID namespaces supported, Network namespace supported, but failed: errno = Operation not permitted
+[pid=7211] <process did exit: exitCode=1, signal=null>`;
+
+const PLAIN_CRASH_EXIT_1 = `browserType.launch: Browser closed.
+==================== Browser output: ====================
+<launched> pid=3300
+[pid=3300] <process did exit: exitCode=1, signal=null>`;
+
+// ─── Classifier ──────────────────────────────────────────────────────────
+
+describe('isXProtectKillSignature — positives (darwin)', () => {
+ it('classifies SIGKILL in a Browser closed error', () => {
+ expect(isXProtectKillSignature(SIGKILL_BROWSER_CLOSED, 'darwin')).toBe(true);
+ });
+
+ it('classifies SIGKILL in a launchPersistentContext error', () => {
+ expect(isXProtectKillSignature(SIGKILL_PERSISTENT_CONTEXT, 'darwin')).toBe(true);
+ });
+
+ it('classifies a launch timeout where the process spawned (<launched>)', () => {
+ expect(isXProtectKillSignature(LAUNCH_TIMEOUT_AFTER_SPAWN, 'darwin')).toBe(true);
+ });
+});
+
+describe('isXProtectKillSignature — negatives (F9)', () => {
+ it('rejects a missing executable', () => {
+ expect(isXProtectKillSignature(MISSING_EXECUTABLE, 'darwin')).toBe(false);
+ });
+
+ it('rejects spawn EACCES', () => {
+ expect(isXProtectKillSignature(SPAWN_EACCES, 'darwin')).toBe(false);
+ });
+
+ it('rejects EPERM failures', () => {
+ expect(isXProtectKillSignature(EPERM_FAILURE, 'darwin')).toBe(false);
+ });
+
+ it('rejects Linux sandbox denials even with a <launched> marker', () => {
+ expect(isXProtectKillSignature(SANDBOX_DENIAL, 'darwin')).toBe(false);
+ });
+
+ it('rejects a plain crash (exitCode=1, no signal)', () => {
+ expect(isXProtectKillSignature(PLAIN_CRASH_EXIT_1, 'darwin')).toBe(false);
+ });
+
+ it('rejects a bare timeout with no <launched> marker (process never spawned)', () => {
+ expect(isXProtectKillSignature('browserType.launch: Timeout 180000ms exceeded.', 'darwin')).toBe(false);
+ });
+
+ it('rejects empty messages', () => {
+ expect(isXProtectKillSignature('', 'darwin')).toBe(false);
+ });
+
+ it('is platform-gated: the SIGKILL signature on linux/win32 is NOT XProtect', () => {
+ expect(isXProtectKillSignature(SIGKILL_BROWSER_CLOSED, 'linux')).toBe(false);
+ expect(isXProtectKillSignature(SIGKILL_BROWSER_CLOSED, 'win32')).toBe(false);
+ });
+});
+
+// ─── Cache path helpers ──────────────────────────────────────────────────
+
+describe('findPlaywrightRevisionDir', () => {
+ it('finds the revision dir for the headed bundle layout', () => {
+ const p = '/Users/dev/Library/Caches/ms-playwright/chromium-1234/chrome-mac-arm64/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing';
+ expect(findPlaywrightRevisionDir(p)).toBe('/Users/dev/Library/Caches/ms-playwright/chromium-1234');
+ });
+
+ it('finds the revision dir for the headless shell layout', () => {
+ const p = '/Users/dev/Library/Caches/ms-playwright/chromium_headless_shell-1234/chrome-mac-arm64/headless_shell';
+ expect(findPlaywrightRevisionDir(p)).toBe('/Users/dev/Library/Caches/ms-playwright/chromium_headless_shell-1234');
+ });
+
+ it('returns null outside the Playwright cache layout', () => {
+ expect(findPlaywrightRevisionDir('/Applications/GStack Browser.app/Contents/MacOS/Chromium')).toBe(null);
+ });
+});
+
+describe('expectedChromiumRevision — registry-derived expectation (F9/ENG-OV3)', () => {
+ it('matches the revision playwright-core browsers.json declares for chromium', () => {
+ const browsersJson = JSON.parse(fs.readFileSync(
+ path.join(REPO_ROOT, 'node_modules', 'playwright-core', 'browsers.json'), 'utf-8',
+ ));
+ const registryRevision = browsersJson.browsers.find((b: { name: string }) => b.name === 'chromium').revision;
+ // chromium.executablePath() is computed from the embedded registry (not
+ // read from disk) — the heal's post-install verification target is
+ // therefore the revision dir playwright-core EXPECTS, which is exactly
+ // what a wrong-revision heal would fail.
+ expect(expectedChromiumRevision(chromium.executablePath())).toBe(registryRevision);
+ });
+});
+
+describe('findGstackInstallRoot (ENG-OV3: revision-matched roots only)', () => {
+ let tmpRoot: string;
+
+ beforeEach(() => {
+ tmpRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'xprotect-root-'));
+ const pwCore = path.join(tmpRoot, 'node_modules', 'playwright-core');
+ fs.mkdirSync(pwCore, { recursive: true });
+ fs.writeFileSync(path.join(pwCore, 'browsers.json'), JSON.stringify({
+ browsers: [{ name: 'chromium', revision: '1234' }],
+ }));
+ });
+
+ afterEach(() => {
+ fs.rmSync(tmpRoot, { recursive: true, force: true });
+ });
+
+ it('accepts a root whose pinned playwright-core expects the same revision', () => {
+ expect(findGstackInstallRoot('1234', [tmpRoot])).toBe(tmpRoot);
+ });
+
+ it('rejects a root pinning a DIFFERENT revision (wrong-revision heal guard)', () => {
+ expect(findGstackInstallRoot('9999', [tmpRoot])).toBe(null);
+ });
+
+ it('rejects roots without node_modules/playwright-core', () => {
+ const bare = fs.mkdtempSync(path.join(os.tmpdir(), 'xprotect-bare-'));
+ try {
+ expect(findGstackInstallRoot('1234', [bare])).toBe(null);
+ } finally {
+ fs.rmSync(bare, { recursive: true, force: true });
+ }
+ });
+
+ it('resolves the dev checkout by default (its node_modules pins our revision)', () => {
+ const browsersJson = JSON.parse(fs.readFileSync(
+ path.join(REPO_ROOT, 'node_modules', 'playwright-core', 'browsers.json'), 'utf-8',
+ ));
+ const registryRevision = browsersJson.browsers.find((b: { name: string }) => b.name === 'chromium').revision;
+ const root = findGstackInstallRoot(registryRevision);
+ expect(root).not.toBe(null);
+ expect(fs.existsSync(path.join(root!, 'node_modules', 'playwright-core', 'browsers.json'))).toBe(true);
+ });
+});
+
+// ─── Quarantine-clear scope contract ─────────────────────────────────────
+
+describe('clearQuarantineOnPlaywrightCache', () => {
+ let tmpCache: string;
+ let execPath: string;
+ const savedCustomPath = process.env.GSTACK_CHROMIUM_PATH;
+
+ beforeEach(() => {
+ tmpCache = fs.mkdtempSync(path.join(os.tmpdir(), 'xprotect-cache-'));
+ for (const dir of ['chromium-1234', 'chromium_headless_shell-1234', 'firefox-5678', 'webkit-2222']) {
+ fs.mkdirSync(path.join(tmpCache, dir), { recursive: true });
+ }
+ execPath = path.join(tmpCache, 'chromium-1234', 'chrome-mac-arm64', 'App.app', 'Contents', 'MacOS', 'chromium');
+ delete process.env.GSTACK_CHROMIUM_PATH;
+ });
+
+ afterEach(() => {
+ fs.rmSync(tmpCache, { recursive: true, force: true });
+ if (savedCustomPath === undefined) delete process.env.GSTACK_CHROMIUM_PATH;
+ else process.env.GSTACK_CHROMIUM_PATH = savedCustomPath;
+ });
+
+ it('clears every chromium* revision dir, never firefox/webkit', () => {
+ const cleared: string[] = [];
+ const ok = clearQuarantineOnPlaywrightCache(execPath, (target) => {
+ cleared.push(path.basename(target));
+ return 0;
+ });
+ expect(ok).toBe(true);
+ expect(cleared.sort()).toEqual(['chromium-1234', 'chromium_headless_shell-1234']);
+ });
+
+ it('NEVER touches a GSTACK_CHROMIUM_PATH bundle (embedder scope contract)', () => {
+ process.env.GSTACK_CHROMIUM_PATH = execPath;
+ const cleared: string[] = [];
+ const ok = clearQuarantineOnPlaywrightCache(execPath, (target) => {
+ cleared.push(target);
+ return 0;
+ });
+ expect(ok).toBe(false);
+ expect(cleared).toEqual([]);
+ });
+
+ it('skips executables outside the Playwright cache layout', () => {
+ const cleared: string[] = [];
+ const ok = clearQuarantineOnPlaywrightCache('/Applications/Foo.app/Contents/MacOS/foo', (target) => {
+ cleared.push(target);
+ return 0;
+ });
+ expect(ok).toBe(false);
+ expect(cleared).toEqual([]);
+ });
+});
+
+// ─── One-shot heal orchestration (F4) ────────────────────────────────────
+
+function makeDeps(counters: { installs: number; quarantines: number }, overrides: Record<string, unknown> = {}) {
+ return {
+ platform: 'darwin' as NodeJS.Platform,
+ executablePath: () => '/tmp/ms-playwright/chromium-1234/chrome-mac-arm64/App.app/Contents/MacOS/chromium',
+ clearQuarantine: () => { counters.quarantines++; return true; },
+ installRoot: () => '/tmp/fake-gstack-root',
+ runReinstall: async () => { counters.installs++; return { ok: true }; },
+ verifyInstalled: () => true,
+ ...overrides,
+ };
+}
+
+describe('maybeHealXProtectKill', () => {
+ beforeEach(() => resetXProtectHealForTests());
+
+ it('heals a classified failure: quarantine-clear + reinstall + verify', async () => {
+ const counters = { installs: 0, quarantines: 0 };
+ const healed = await maybeHealXProtectKill(new Error(SIGKILL_BROWSER_CLOSED), {}, makeDeps(counters));
+ expect(healed).toBe(true);
+ expect(counters.quarantines).toBe(1);
+ expect(counters.installs).toBe(1);
+ });
+
+ it('F4: runs AT MOST ONCE per process, even across distinct errors', async () => {
+ const counters = { installs: 0, quarantines: 0 };
+ expect(await maybeHealXProtectKill(new Error(SIGKILL_BROWSER_CLOSED), {}, makeDeps(counters))).toBe(true);
+ expect(await maybeHealXProtectKill(new Error(LAUNCH_TIMEOUT_AFTER_SPAWN), {}, makeDeps(counters))).toBe(false);
+ expect(counters.installs).toBe(1);
+ });
+
+ it('F4: a FAILED heal also consumes the one-shot (no reinstall loops)', async () => {
+ const counters = { installs: 0, quarantines: 0 };
+ const failing = makeDeps(counters, { runReinstall: async () => { counters.installs++; return { ok: false, reason: 'timeout' }; } });
+ expect(await maybeHealXProtectKill(new Error(SIGKILL_BROWSER_CLOSED), {}, failing)).toBe(false);
+ expect(await maybeHealXProtectKill(new Error(SIGKILL_BROWSER_CLOSED), {}, makeDeps(counters))).toBe(false);
+ expect(counters.installs).toBe(1);
+ });
+
+ it('an unclassified error does NOT consume the one-shot', async () => {
+ const counters = { installs: 0, quarantines: 0 };
+ expect(await maybeHealXProtectKill(new Error(MISSING_EXECUTABLE), {}, makeDeps(counters))).toBe(false);
+ expect(counters.installs).toBe(0);
+ // Guard not consumed — a real signature afterwards still heals.
+ expect(await maybeHealXProtectKill(new Error(SIGKILL_BROWSER_CLOSED), {}, makeDeps(counters))).toBe(true);
+ });
+
+ it('never heals over a custom executable (GSTACK_CHROMIUM_PATH scope)', async () => {
+ const counters = { installs: 0, quarantines: 0 };
+ const healed = await maybeHealXProtectKill(
+ new Error(SIGKILL_BROWSER_CLOSED),
+ { usesCustomExecutable: true },
+ makeDeps(counters),
+ );
+ expect(healed).toBe(false);
+ expect(counters.quarantines).toBe(0);
+ expect(counters.installs).toBe(0);
+ });
+
+ it('fails the heal when no install root pins our revision (ENG-OV3)', async () => {
+ const counters = { installs: 0, quarantines: 0 };
+ const deps = makeDeps(counters, { installRoot: () => null });
+ expect(await maybeHealXProtectKill(new Error(SIGKILL_BROWSER_CLOSED), {}, deps)).toBe(false);
+ expect(counters.installs).toBe(0);
+ });
+
+ it('fails the heal when post-install verification misses the expected revision dir (F9)', async () => {
+ const counters = { installs: 0, quarantines: 0 };
+ const deps = makeDeps(counters, { verifyInstalled: () => false });
+ expect(await maybeHealXProtectKill(new Error(SIGKILL_BROWSER_CLOSED), {}, deps)).toBe(false);
+ expect(counters.installs).toBe(1);
+ });
+});
+
+// ─── Launch wrapper ──────────────────────────────────────────────────────
+
+describe('launchWithXProtectHeal', () => {
+ beforeEach(() => resetXProtectHealForTests());
+
+ it('retries the launch exactly once after a successful heal', async () => {
+ const counters = { installs: 0, quarantines: 0 };
+ let attempts = 0;
+ const result = await launchWithXProtectHeal(async () => {
+ attempts++;
+ if (attempts === 1) throw new Error(SIGKILL_BROWSER_CLOSED);
+ return 'browser';
+ }, {}, makeDeps(counters));
+ expect(result).toBe('browser');
+ expect(attempts).toBe(2);
+ expect(counters.installs).toBe(1);
+ });
+
+ it('surfaces the ORIGINAL error + manual guidance when the heal fails (E1)', async () => {
+ const counters = { installs: 0, quarantines: 0 };
+ const deps = makeDeps(counters, { runReinstall: async () => ({ ok: false, reason: 'timeout' }) });
+ let thrown: Error | null = null;
+ try {
+ await launchWithXProtectHeal(async () => { throw new Error(SIGKILL_BROWSER_CLOSED); }, {}, deps);
+ } catch (err) {
+ thrown = err as Error;
+ }
+ expect(thrown).not.toBe(null);
+ // Original launch error text preserved…
+ expect(thrown!.message).toContain('signal=SIGKILL');
+ // …plus the manual remediation.
+ expect(thrown!.message).toContain('bunx playwright install chromium');
+ });
+
+ it('passes unclassified failures through untouched', async () => {
+ const counters = { installs: 0, quarantines: 0 };
+ let thrown: Error | null = null;
+ try {
+ await launchWithXProtectHeal(async () => { throw new Error(MISSING_EXECUTABLE); }, {}, makeDeps(counters));
+ } catch (err) {
+ thrown = err as Error;
+ }
+ expect(thrown!.message).toBe(MISSING_EXECUTABLE);
+ expect(counters.installs).toBe(0);
+ });
+});
+
+describe('buildXProtectGuidance', () => {
+ it('carries both the original message and the manual command', () => {
+ const out = buildXProtectGuidance('original launch error');
+ expect(out).toContain('original launch error');
+ expect(out).toContain('bunx playwright install chromium');
+ expect(out).toContain('#2554');
+ });
+});
+
+// ─── runBoundedChromiumReinstall (T3) — previously zero coverage ──────────
+//
+// Exercised end-to-end against a STUB `bunx` on a prepended PATH: real spawn,
+// real process group, real timer — only the binary is fake. Shell stubs
+// don't exist on Windows, and the group-kill path is POSIX (`kill(-pid)`),
+// so the suite is Unix-only like the shape it tests.
+describe.skipIf(process.platform === 'win32')('runBoundedChromiumReinstall', () => {
+ let stubDir: string;
+ let savedPath: string | undefined;
+
+ function installStubBunx(script: string): void {
+ const stub = path.join(stubDir, 'bunx');
+ fs.writeFileSync(stub, `#!/bin/sh\n${script}\n`, { mode: 0o755 });
+ }
+
+ beforeEach(() => {
+ stubDir = fs.mkdtempSync(path.join(os.tmpdir(), 'xprotect-stub-'));
+ savedPath = process.env.PATH;
+ process.env.PATH = `${stubDir}${path.delimiter}${process.env.PATH ?? ''}`;
+ });
+
+ afterEach(() => {
+ process.env.PATH = savedPath;
+ fs.rmSync(stubDir, { recursive: true, force: true });
+ });
+
+ it('resolves ok on exit 0', async () => {
+ installStubBunx('exit 0');
+ const result = await runBoundedChromiumReinstall(stubDir, 10_000);
+ expect(result).toEqual({ ok: true, exitCode: 0 });
+ });
+
+ it('reports install-exit-N with the stderr tail on a nonzero exit', async () => {
+ installStubBunx('echo "download failed: mirror unreachable" >&2\nexit 7');
+ const result = await runBoundedChromiumReinstall(stubDir, 10_000);
+ expect(result.ok).toBe(false);
+ expect(result.exitCode).toBe(7);
+ expect(result.reason).toStartWith('install-exit-7');
+ expect(result.reason).toContain('download failed: mirror unreachable');
+ });
+
+ it('group-kills a hung install at timeoutMs and reports timeout', async () => {
+ // The stub spawns its own child (like bunx → playwright CLI → download
+ // workers) and sleeps well past the bound; the detached process group
+ // must take BOTH down, and the result must arrive at ~timeoutMs, not
+ // after the sleep.
+ installStubBunx('sleep 30 &\nsleep 30');
+ const started = Date.now();
+ const result = await runBoundedChromiumReinstall(stubDir, 500);
+ const elapsed = Date.now() - started;
+ expect(result).toEqual({ ok: false, reason: 'timeout' });
+ expect(elapsed).toBeLessThan(5_000); // resolved at the bound, not the sleep
+ });
+
+ it('reports spawn-error when the binary cannot be executed', async () => {
+ // No stub installed and PATH reduced to the empty stub dir only.
+ process.env.PATH = stubDir;
+ const result = await runBoundedChromiumReinstall(stubDir, 10_000);
+ expect(result.ok).toBe(false);
+ expect(result.reason).toStartWith('spawn-error:');
+ });
+});
diff --git a/browser-skills/hackernews-frontpage/_lib/browse-client.ts b/browser-skills/hackernews-frontpage/_lib/browse-client.ts
index 435f57546..499b366f7 100644
--- a/browser-skills/hackernews-frontpage/_lib/browse-client.ts
+++ b/browser-skills/hackernews-frontpage/_lib/browse-client.ts
@@ -103,7 +103,7 @@ export function resolveBrowseAuth(opts: BrowseClientOptions = {}): ResolvedAuth
function defaultStateFile(): string | null {
try {
- const proc = cp.spawnSync('git', ['rev-parse', '--show-toplevel'], { encoding: 'utf-8', timeout: 2000 });
+ const proc = cp.spawnSync('git', ['rev-parse', '--show-toplevel'], { encoding: 'utf-8', timeout: 2000, windowsHide: true });
const root = proc.status === 0 ? proc.stdout.trim() : null;
const base = root || process.cwd();
return path.join(base, '.gstack', 'browse.json');
diff --git a/bun.lock b/bun.lock
index 445752c06..8ae092985 100644
--- a/bun.lock
+++ b/bun.lock
@@ -5,14 +5,14 @@
"": {
"name": "gstack",
"dependencies": {
- "@huggingface/transformers": "^4.1.0",
+ "@huggingface/transformers": "^4.2.0",
"@ngrok/ngrok": "^1.7.0",
+ "cross-spawn": "^7.0.6",
"diff": "^9.0.0",
"html-to-docx": "1.8.0",
- "marked": "^18.0.2",
- "playwright": "^1.58.2",
- "puppeteer-core": "^24.40.0",
- "socks": "^2.8.8",
+ "marked": "^18.0.9",
+ "playwright": "^1.62.1",
+ "socks": "^2.8.9",
},
"devDependencies": {
"@anthropic-ai/claude-agent-sdk": "0.2.117",
@@ -22,8 +22,11 @@
},
},
},
+ "patchedDependencies": {
+ },
"overrides": {
- "basic-ftp": "5.3.1",
+ "adm-zip": "^0.6.0",
},
"packages": {
"@anthropic-ai/claude-agent-sdk": ["@anthropic-ai/[email protected]", "", { "dependencies": { "@anthropic-ai/sdk": "^0.81.0", "@modelcontextprotocol/sdk": "^1.29.0" }, "optionalDependencies": { "@anthropic-ai/claude-agent-sdk-darwin-arm64": "0.2.117", "@anthropic-ai/claude-agent-sdk-darwin-x64": "0.2.117", "@anthropic-ai/claude-agent-sdk-linux-arm64": "0.2.117", "@anthropic-ai/claude-agent-sdk-linux-arm64-musl": "0.2.117", "@anthropic-ai/claude-agent-sdk-linux-x64": "0.2.117", "@anthropic-ai/claude-agent-sdk-linux-x64-musl": "0.2.117", "@anthropic-ai/claude-agent-sdk-win32-arm64": "0.2.117", "@anthropic-ai/claude-agent-sdk-win32-x64": "0.2.117" }, "peerDependencies": { "zod": "^4.0.0" } }, "sha512-pVBss1Vu0w87nKCBhWtjMggSgCh6GVUtdRmuE58ZvXv0E2q0JcnUCQHehmn92BAW0+VCwPY8q/k7uKWkgwz/gA=="],
@@ -56,7 +59,7 @@
"@huggingface/tokenizers": ["@huggingface/[email protected]", "", {}, "sha512-8rF/RRT10u+kn7YuUbUg0OF30K8rjTc78aHpxT+qJ1uWSqxT1MHi8+9ltwYfkFYJzT/oS+qw3JVfHtNMGAdqyA=="],
- "@huggingface/transformers": ["@huggingface/[email protected]", "", { "dependencies": { "@huggingface/jinja": "^0.5.6", "@huggingface/tokenizers": "^0.1.3", "onnxruntime-node": "1.24.3", "onnxruntime-web": "1.26.0-dev.20260410-5e55544225", "sharp": "^0.34.5" } }, "sha512-WiMf9eyvF6V2pj4gs12A7GQV3svyFIBtB/W+Hn5lT5E5DyqWUno1ZrWoAfJv69X1RNv/0GoOo6DFmL6NOYd+rg=="],
+ "@huggingface/transformers": ["@huggingface/[email protected]", "", { "dependencies": { "@huggingface/jinja": "^0.5.6", "@huggingface/tokenizers": "^0.1.3", "onnxruntime-node": "1.24.3", "onnxruntime-web": "1.26.0-dev.20260416-b7804b056c", "sharp": "^0.34.5" } }, "sha512-8BRCoBMH0XsWaEIamuR0LrJGAfftgHAfb2Vrffy0VKlSAE/MnUJ5/h/zTfEP3fDIft+nk7TqB8xXEyABGitBjQ=="],
"@img/colour": ["@img/[email protected]", "", {}, "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ=="],
@@ -166,54 +169,22 @@
"@protobufjs/utf8": ["@protobufjs/[email protected]", "", {}, "sha512-Vvn3zZrhQZkkBE8LSuW3em98c0FwgO4nxzv6OdSxPKJIEKY2bGbHn+mhGIPerzI4twdxaP8/0+06HBpwf345Lw=="],
- "@puppeteer/browsers": ["@puppeteer/[email protected]", "", { "dependencies": { "debug": "^4.4.3", "extract-zip": "^2.0.1", "progress": "^2.0.3", "proxy-agent": "^6.5.0", "semver": "^7.7.4", "tar-fs": "^3.1.1", "yargs": "^17.7.2" }, "bin": { "browsers": "lib/cjs/main-cli.js" } }, "sha512-46BZJYJjc/WwmKjsvDFykHtXrtomsCIrwYQPOP7VfMJoZY2bsDF9oROBABR3paDjDcmkUye1Pb1BqdcdiipaWA=="],
-
- "@tootallnate/quickjs-emscripten": ["@tootallnate/[email protected]", "", {}, "sha512-C5Mc6rdnsaJDjO3UpGW/CQTHtCKaYlScZTly4JIu97Jxo/odCiH0ITnDXSJPTOrEKk/ycSZ0AOgTmkDtkOsvIA=="],
-
"@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~7.18.0" } }, "sha512-jp2P3tQMSxWugkCUKLRPVUpGaL5MVFwF8RDuSRztfwgN1wmqJeMSbKlnEtQqU8UrhTmzEmZdu2I6v2dpp7XIxw=="],
- "@types/yauzl": ["@types/[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-oJoftv0LSuaDZE3Le4DbKX+KS9G36NzOeSap90UIK0yMA/NhKJhqlSGtNDORNRaIbQfzjXDrQa0ytJ6mNRGz/Q=="],
-
"accepts": ["[email protected]", "", { "dependencies": { "mime-types": "^3.0.0", "negotiator": "^1.0.0" } }, "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng=="],
- "adm-zip": ["[email protected]", "", {}, "sha512-+Ut8d9LLqwEvHHJl1+PIHqoyDxFgVN847JTVM3Izi3xHDWPE4UtzzXysMZQs64DMcrJfBeS/uoEP4AD3HQHnQQ=="],
-
- "agent-base": ["[email protected]", "", {}, "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ=="],
+ "adm-zip": ["[email protected]", "", {}, "sha512-XleryMhbuksdKtofnWZ9Sk+4CUTbms4Mb/EU32SZwToAyZ5RgVos/ki8n+yr0LWHOGKuakbXTuuYNHLQjhddgg=="],
"ajv": ["[email protected]", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-PlXPeEWMXMZ7sPYOHqmDyCJzcfNrUr3fGNKtezX14ykXOEIvyK81d+qydx89KY5O71FKMPaQ2vBfBFI5NHR63A=="],
"ajv-formats": ["[email protected]", "", { "dependencies": { "ajv": "^8.0.0" } }, "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ=="],
- "ansi-regex": ["[email protected]", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="],
-
- "ansi-styles": ["[email protected]", "", { "dependencies": { "color-convert": "^2.0.1" } }, "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg=="],
-
- "ast-types": ["[email protected]", "", { "dependencies": { "tslib": "^2.0.1" } }, "sha512-x1FCFnFifvYDDzTaLII71vG5uvDwgtmDTEVWAxrgeiR8VjMONcCXJx7E+USjDtHlwFmt9MysbqgF9b9Vjr6w+w=="],
-
- "b4a": ["[email protected]", "", { "peerDependencies": { "react-native-b4a": "*" }, "optionalPeers": ["react-native-b4a"] }, "sha512-qRuSmNSkGQaHwNbM7J78Wwy+ghLEYF1zNrSeMxj4Kgw6y33O3mXcQ6Ie9fRvfU/YnxWkOchPXbaLb73TkIsfdg=="],
-
- "bare-events": ["[email protected]", "", { "peerDependencies": { "bare-abort-controller": "*" }, "optionalPeers": ["bare-abort-controller"] }, "sha512-riJjyv1/mHLIPX4RwiK+oW9/4c3TEUeORHKefKAKnZ5kyslbN+HXowtbaVEqt4IMUB7OXlfixcs6gsFeo/jhiQ=="],
-
- "bare-fs": ["[email protected]", "", { "dependencies": { "bare-events": "^2.5.4", "bare-path": "^3.0.0", "bare-stream": "^2.6.4", "bare-url": "^2.2.2", "fast-fifo": "^1.3.2" }, "peerDependencies": { "bare-buffer": "*" }, "optionalPeers": ["bare-buffer"] }, "sha512-1QovqDrR80Pmt5HPAsMsXTCFcDYr+NSUKW6nd6WO5v0JBmnItc/irNRzm2KOQ5oZ69P37y+AMujNyNtG+1Rggw=="],
-
- "bare-os": ["[email protected]", "", {}, "sha512-6g8rIdyQqYL6XbghpOgS8AOSvWQUf0zT0XaYUrJIX5VugpCGUyJaz1zfcKCecOnUkI76oVJXuHg1LMGYVXTvKw=="],
-
- "bare-path": ["[email protected]", "", { "dependencies": { "bare-os": "^3.0.1" } }, "sha512-tyfW2cQcB5NN8Saijrhqn0Zh7AnFNsnczRcuWODH0eYAXBsJ5gVxAUuNr7tsHSC6IZ77cA0SitzT+s47kot8Mw=="],
-
- "bare-stream": ["[email protected]", "", { "dependencies": { "streamx": "^2.25.0", "teex": "^1.0.1" }, "peerDependencies": { "bare-abort-controller": "*", "bare-buffer": "*", "bare-events": "*" }, "optionalPeers": ["bare-abort-controller", "bare-buffer", "bare-events"] }, "sha512-Y/+iQ49fL3rIn6w/AVxI/2+BRrpmzJvdWt5Jv8Za6Ngqc6V227c+pYjYYgLdpR3MwQ9ObVXD0ZrqoBztakM0rw=="],
-
- "bare-url": ["[email protected]", "", { "dependencies": { "bare-path": "^3.0.0" } }, "sha512-NSTU5WN+fy/L0DDenfE8SXQna4voXuW0FHM7wH8i3/q9khUSchfPbPezO4zSFMnDGIf9YE+mt/RWhZgNRKRIXA=="],
-
- "basic-ftp": ["[email protected]", "", {}, "sha512-bopVNp6ugyA150DDuZfPFdt1KZ5a94ZDiwX4hMgZDzF+GttD80lEy8kj98kbyhLXnPvhtIo93mdnLIjpCAeeOw=="],
-
"body-parser": ["[email protected]", "", { "dependencies": { "bytes": "^3.1.2", "content-type": "^1.0.5", "debug": "^4.4.3", "http-errors": "^2.0.0", "iconv-lite": "^0.7.0", "on-finished": "^2.4.1", "qs": "^6.14.1", "raw-body": "^3.0.1", "type-is": "^2.0.1" } }, "sha512-oP5VkATKlNwcgvxi0vM0p/D3n2C3EReYVX+DNYs5TjZFn/oQt2j+4sVJtSMr18pdRr8wjTcBl6LoV+FUwzPmNA=="],
"boolean": ["[email protected]", "", {}, "sha512-d0II/GO9uf9lfUHH2BQsjxzRJZBdsjgsBiW4BvhWk/3qoKwQFjIDVN19PfX8F2D/r9PCMTtLWjYVCFrpeYUzsw=="],
"browser-split": ["[email protected]", "", {}, "sha512-JhvgRb2ihQhsljNda3BI8/UcRHVzrVwo3Q+P8vDtSiyobXuFpuZ9mq+MbRGMnC22CjW3RrfXdg6j6ITX8M+7Ow=="],
- "buffer-crc32": ["[email protected]", "", {}, "sha512-VO9Ht/+p3SN7SKWqcrgEzjGbRSJYTx+Q1pTQC0wrWqHx0vpJraQ6GtHx8tvcg1rlK1byhU5gccxgOgj7B0TDkQ=="],
-
"bytes": ["[email protected]", "", {}, "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg=="],
"call-bind-apply-helpers": ["[email protected]", "", { "dependencies": { "es-errors": "^1.3.0", "function-bind": "^1.1.2" } }, "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ=="],
@@ -222,12 +193,6 @@
"camelize": ["[email protected]", "", {}, "sha512-dU+Tx2fsypxTgtLoE36npi3UqcjSSMNYfkqgmoEhtZrraP5VWq0K7FkWVTYa8eMPtnU/G2txVsfdCJTn9uzpuQ=="],
- "chromium-bidi": ["[email protected]", "", { "dependencies": { "mitt": "^3.0.1", "zod": "^3.24.1" }, "peerDependencies": { "devtools-protocol": "*" } }, "sha512-9gYlLtS6tStdRWzrtXaTMnqcM4dudNegMXJxkR0I/CXObHalYeYcAMPrL19eroNZHtJ8DQmu1E+ZNOYu/IXMXw=="],
-
- "cliui": ["[email protected]", "", { "dependencies": { "string-width": "^4.2.0", "strip-ansi": "^6.0.1", "wrap-ansi": "^7.0.0" } }, "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ=="],
-
- "color-convert": ["[email protected]", "", { "dependencies": { "color-name": "~1.1.4" } }, "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ=="],
-
"color-name": ["[email protected]", "", {}, "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA=="],
"content-disposition": ["[email protected]", "", {}, "sha512-5jRCH9Z/+DRP7rkvY83B+yGIGX96OYdJmzngqnw2SBSxqCFPd0w2km3s5iawpGX8krnwSGmF0FW5Nhr0Hfai3g=="],
@@ -244,24 +209,18 @@
"cross-spawn": ["[email protected]", "", { "dependencies": { "path-key": "^3.1.0", "shebang-command": "^2.0.0", "which": "^2.0.1" } }, "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA=="],
- "data-uri-to-buffer": ["[email protected]", "", {}, "sha512-7hvf7/GW8e86rW0ptuwS3OcBGDjIi6SZva7hCyWC0yYry2cOPmLIjXAUHI6DK2HsnwJd9ifmt57i8eV2n4YNpw=="],
-
"debug": ["[email protected]", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="],
"define-data-property": ["[email protected]", "", { "dependencies": { "es-define-property": "^1.0.0", "es-errors": "^1.3.0", "gopd": "^1.0.1" } }, "sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A=="],
"define-properties": ["[email protected]", "", { "dependencies": { "define-data-property": "^1.0.1", "has-property-descriptors": "^1.0.0", "object-keys": "^1.1.1" } }, "sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg=="],
- "degenerator": ["[email protected]", "", { "dependencies": { "ast-types": "^0.13.4", "escodegen": "^2.1.0", "esprima": "^4.0.1" } }, "sha512-TllpMR/t0M5sqCXfj85i4XaAzxmS5tVA16dqvdkMwGmzI+dXLXnw3J+3Vdv7VKw+ThlTMboK6i9rnZ6Nntj5CQ=="],
-
"depd": ["[email protected]", "", {}, "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw=="],
"detect-libc": ["[email protected]", "", {}, "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ=="],
"detect-node": ["[email protected]", "", {}, "sha512-T0NIuQpnTvFDATNuHN5roPwSBG83rFsuO+MXXH9/3N1eFbn4wcPjttvjMLEPWJ0RGUYgQE7cGgS3tNxbqCGM7g=="],
- "devtools-protocol": ["[email protected]", "", {}, "sha512-nv7iKtNZQshSW2hKzYNr46nM/Cfh5SEvE2oV0/SEGgc9XupIY5ggf84Cz8eJIkBce7S3bmTAauFD6aysMpnqsQ=="],
-
"diff": ["[email protected]", "", {}, "sha512-svtcdpS8CgJyqAjEQIXdb3OjhFVVYjzGAPO8WGCmRbrml64SPw/jJD4GoE98aR7r25A0XcgrK3F02yw9R/vhQw=="],
"dom-serializer": ["[email protected]", "", { "dependencies": { "domelementtype": "^2.0.1", "entities": "^2.0.0" } }, "sha512-2/xPb3ORsQ42nHYiSunXkDjPLBaEj/xTwUO4B7XCZQTRk7EBtTOPaygh10YAAh2OI1Qrp6NWfpAhzswj0ydt9g=="],
@@ -278,12 +237,8 @@
"ee-first": ["[email protected]", "", {}, "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow=="],
- "emoji-regex": ["[email protected]", "", {}, "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A=="],
-
"encodeurl": ["[email protected]", "", {}, "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg=="],
- "end-of-stream": ["[email protected]", "", { "dependencies": { "once": "^1.4.0" } }, "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg=="],
-
"ent": ["[email protected]", "", { "dependencies": { "call-bound": "^1.0.3", "es-errors": "^1.3.0", "punycode": "^1.4.1", "safe-regex-test": "^1.1.0" } }, "sha512-kKvD1tO6BM+oK9HzCPpUdRb4vKFQY/FPTFmurMvh6LlN68VMrdj77w8yp51/kDbpkFOS9J8w5W6zIzgM2H8/hw=="],
"entities": ["[email protected]", "", {}, "sha512-f2LZMYl1Fzu7YSBKg+RoROelpOaNrcGmE9AZubeDfrCEia483oW4MI4VyFd5VNHIgQ/7qm1I0wUHK1eJnn2y2w=="],
@@ -298,26 +253,14 @@
"es6-error": ["[email protected]", "", {}, "sha512-Um/+FxMr9CISWh0bi5Zv0iOD+4cFh5qLeks1qhAopKVAJw3drgKbKySikp7wGhDL0HPeaja0P5ULZrxLkniUVg=="],
- "escalade": ["[email protected]", "", {}, "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA=="],
-
"escape-html": ["[email protected]", "", {}, "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow=="],
"escape-string-regexp": ["[email protected]", "", {}, "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA=="],
- "escodegen": ["[email protected]", "", { "dependencies": { "esprima": "^4.0.1", "estraverse": "^5.2.0", "esutils": "^2.0.2" }, "optionalDependencies": { "source-map": "~0.6.1" }, "bin": { "esgenerate": "bin/esgenerate.js", "escodegen": "bin/escodegen.js" } }, "sha512-2NlIDTwUWJN0mRPQOdtQBzbUHvdGY2P1VXSyU83Q3xKxM7WHX2Ql8dKq782Q9TgQUNOLEzEYu9bzLNj1q88I5w=="],
-
- "esprima": ["[email protected]", "", { "bin": { "esparse": "./bin/esparse.js", "esvalidate": "./bin/esvalidate.js" } }, "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A=="],
-
- "estraverse": ["[email protected]", "", {}, "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA=="],
-
- "esutils": ["[email protected]", "", {}, "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g=="],
-
"etag": ["[email protected]", "", {}, "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg=="],
"ev-store": ["[email protected]", "", { "dependencies": { "individual": "^3.0.0" } }, "sha512-otazchNRnGzp2YarBJ+GXKVGvhxVATB1zmaStxJBYet0Dyq7A9VhH8IUEB/gRcL6Ch52lfpgPTRJ2m49epyMsQ=="],
- "events-universal": ["[email protected]", "", { "dependencies": { "bare-events": "^2.7.0" } }, "sha512-LUd5euvbMLpwOF8m6ivPCbhQeSiYVNb8Vs0fQ8QjXo0JTkEHpz8pxdQf0gStltaPpw0Cca8b39KxvK9cfKRiAw=="],
-
"eventsource": ["[email protected]", "", { "dependencies": { "eventsource-parser": "^3.0.1" } }, "sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA=="],
"eventsource-parser": ["[email protected]", "", {}, "sha512-70QWGkr4snxr0OXLRWsFLeRBIRPuQOvt4s8QYjmUlmlkyTZkRqS7EDVRZtzU3TiyDbXSzaOeF0XUKy8PchzukQ=="],
@@ -326,16 +269,10 @@
"express-rate-limit": ["[email protected]", "", { "dependencies": { "ip-address": "10.1.0" }, "peerDependencies": { "express": ">= 4.11" } }, "sha512-77VmFeJkO0/rvimEDuUC5H30oqUC4EyOhyGccfqoLebB0oiEYfM7nwPrsDsBL1gsTpwfzX8SFy2MT3TDyRq+bg=="],
- "extract-zip": ["[email protected]", "", { "dependencies": { "debug": "^4.1.1", "get-stream": "^5.1.0", "yauzl": "^2.10.0" }, "optionalDependencies": { "@types/yauzl": "^2.9.1" }, "bin": { "extract-zip": "cli.js" } }, "sha512-GDhU9ntwuKyGXdZBUgTIe+vXnWj0fppUEtMDL0+idd5Sta8TGpHssn/eusA9mrPr9qNDym6SxAYZjNvCn/9RBg=="],
-
"fast-deep-equal": ["[email protected]", "", {}, "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q=="],
- "fast-fifo": ["[email protected]", "", {}, "sha512-/d9sfos4yxzpwkDkuN7k2SqFKtYNmCTzgfEpz82x34IM9/zc8KGxQoXg1liNC/izpRM/MBdt44Nmx41ZWqk+FQ=="],
-
"fast-uri": ["[email protected]", "", {}, "sha512-iPeeDKJSWf4IEOasVVrknXpaBV0IApz/gp7S2bb7Z4Lljbl2MGJRqInZiUrQwV16cpzw/D3S5j5Julj/gT52AA=="],
- "fd-slicer": ["[email protected]", "", { "dependencies": { "pend": "~1.2.0" } }, "sha512-cE1qsB/VwyQozZ+q1dGxR8LBYNZeofhEdUNGSMbQD3Gw2lAzX9Zb3uIU6Ebc/Fmyjo9AWWfnn0AUCHqtevs/8g=="],
-
"finalhandler": ["[email protected]", "", { "dependencies": { "debug": "^4.4.0", "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "on-finished": "^2.4.1", "parseurl": "^1.3.3", "statuses": "^2.0.1" } }, "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA=="],
"flatbuffers": ["[email protected]", "", {}, "sha512-MI1qs7Lo4Syw0EOzUl0xjs2lsoeqFku44KpngfIduHBYvzm8h2+7K8YMQh1JtVVVrUvhLpNwqVi4DERegUJhPQ=="],
@@ -348,16 +285,10 @@
"function-bind": ["[email protected]", "", {}, "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA=="],
- "get-caller-file": ["[email protected]", "", {}, "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg=="],
-
"get-intrinsic": ["[email protected]", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.2", "es-define-property": "^1.0.1", "es-errors": "^1.3.0", "es-object-atoms": "^1.1.1", "function-bind": "^1.1.2", "get-proto": "^1.0.1", "gopd": "^1.2.0", "has-symbols": "^1.1.0", "hasown": "^2.0.2", "math-intrinsics": "^1.1.0" } }, "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ=="],
"get-proto": ["[email protected]", "", { "dependencies": { "dunder-proto": "^1.0.1", "es-object-atoms": "^1.0.0" } }, "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g=="],
- "get-stream": ["[email protected]", "", { "dependencies": { "pump": "^3.0.0" } }, "sha512-nBF+F1rAZVCu/p7rjzgA+Yb4lfYXrpl7a6VmJrU8wF9I1CKvP/QwPNZHnOlwbTkY6dvtFIzFMSyQXbLoTQPRpA=="],
-
- "get-uri": ["[email protected]", "", { "dependencies": { "basic-ftp": "^5.0.2", "data-uri-to-buffer": "^6.0.2", "debug": "^4.3.4" } }, "sha512-b1O07XYq8eRuVzBNgJLstU6FYc1tS6wnMtF1I1D9lE8LxZSOGZ7LhxN54yPP6mGw5f2CkXY2BQUL9Fx41qvcIg=="],
-
"global": ["[email protected]", "", { "dependencies": { "min-document": "^2.19.0", "process": "^0.11.10" } }, "sha512-wv/LAoHdRE3BeTGz53FAamhGlPLhlssK45usmGFThIi4XqnBmjKQ16u+RNbP7WvigRZDxUsM0J3gcQ5yicaL0w=="],
"global-agent": ["[email protected]", "", { "dependencies": { "boolean": "^3.0.1", "es6-error": "^4.1.1", "matcher": "^3.0.0", "roarr": "^2.15.3", "semver": "^7.3.2", "serialize-error": "^7.0.1" } }, "sha512-PT6XReJ+D07JvGoxQMkT6qji/jVNfX/h364XHZOWeRzy64sSFr+xJ5OX7LI3b4MPQzdL4H8Y8M0xzPpsVMwA8Q=="],
@@ -388,10 +319,6 @@
"http-errors": ["[email protected]", "", { "dependencies": { "depd": "~2.0.0", "inherits": "~2.0.4", "setprototypeof": "~1.2.0", "statuses": "~2.0.2", "toidentifier": "~1.0.1" } }, "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ=="],
- "http-proxy-agent": ["[email protected]", "", { "dependencies": { "agent-base": "^7.1.0", "debug": "^4.3.4" } }, "sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig=="],
-
- "https-proxy-agent": ["[email protected]", "", { "dependencies": { "agent-base": "^7.1.2", "debug": "4" } }, "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw=="],
-
"iconv-lite": ["[email protected]", "", { "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" } }, "sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw=="],
"image-size": ["[email protected]", "", { "dependencies": { "queue": "6.0.2" }, "bin": { "image-size": "bin/image-size.js" } }, "sha512-rH+46sQJ2dlwfjfhCyNx5thzrv+dtmBIhPHk0zgRUukHzZ/kRueTJXoYYsclBaKcSMBWuGbOFXtioLpzTb5euw=="],
@@ -408,8 +335,6 @@
"ipaddr.js": ["[email protected]", "", {}, "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g=="],
- "is-fullwidth-code-point": ["[email protected]", "", {}, "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg=="],
-
"is-object": ["[email protected]", "", {}, "sha512-2rRIahhZr2UWb45fIOuvZGpFtz0TyOZLf32KxBbSoUCeZR495zCKlWUKKUByk3geS2eAs7ZAABt0Y/Rx0GiQGA=="],
"is-promise": ["[email protected]", "", {}, "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ=="],
@@ -438,9 +363,7 @@
"long": ["[email protected]", "", {}, "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA=="],
- "lru-cache": ["[email protected]", "", {}, "sha512-jumlc0BIUrS3qJGgIkWZsyfAM7NCWiBcCDhnd+3NNM5KbBmLTgHVfWBcg6W+rLUsIpzpERPsvwUP7CckAQSOoA=="],
-
- "marked": ["[email protected]", "", { "bin": { "marked": "bin/marked.js" } }, "sha512-NsmlUYBS/Zg57rgDWMYdnre6OTj4e+qq/JS2ot3KrYLSoHLw+sDu0Nm1ZGpRgYAq6c+b1ekaY5NzVchMCQnzcg=="],
+ "marked": ["[email protected]", "", { "bin": { "marked": "bin/marked.js" } }, "sha512-/Sa4qiiHZxf0/FQdBBowr9q4r10krCwMvpK48FUBdXdUXScDxiQGR9zCPrFgRVR5LU3iySOiIjy09ZQvADir1w=="],
"matcher": ["[email protected]", "", { "dependencies": { "escape-string-regexp": "^4.0.0" } }, "sha512-OkeDaAZ/bQCxeFAozM55PKcKU0yJMPGifLwV4Qgjitu+5MoAfSQN4lsLJeXZ1b8w0x+/Emda6MZgXS1jvsapng=="],
@@ -456,16 +379,12 @@
"min-document": ["[email protected]", "", { "dependencies": { "dom-walk": "^0.1.0" } }, "sha512-8S5I8db/uZN8r9HSLFVWPdJCvYOejMcEC82VIzNUc6Zkklf/d1gg2psfE79/vyhWOj4+J8MtwmoOz3TmvaGu5A=="],
- "mitt": ["[email protected]", "", {}, "sha512-vKivATfr97l2/QBCYAkXYDbrIWPM2IIKEl7YPhjCvKlG3kE2gm+uBo6nEXK3M5/Ffh/FLpKExzOQ3JJoJGFKBw=="],
-
"ms": ["[email protected]", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="],
"nanoid": ["[email protected]", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-ZB9RH/39qpq5Vu6Y+NmUaFhQR6pp+M2Xt76XBnEwDaGcVAqhlvxrl3B2bKS5D3NH3QR76v3aSrKaF/Kiy7lEtQ=="],
"negotiator": ["[email protected]", "", {}, "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg=="],
- "netmask": ["[email protected]", "", {}, "sha512-dBpDMdxv9Irdq66304OLfEmQ9tbNRFnFTuZiLo+bD+r332bBmMJ8GBLXklIXXgxd3+v9+KUnZaUR5PJMa75Gsg=="],
-
"next-tick": ["[email protected]", "", {}, "sha512-f7h4svPtl+QidoBv4taKXUjJ70G2asaZ8G28nS0OkqaalX8dwwrtWtyxEDPK62AC00ur/+/E0pUwBwY5EPn15Q=="],
"node-fetch": ["[email protected]", "", { "dependencies": { "whatwg-url": "^5.0.0" }, "peerDependencies": { "encoding": "^0.1.0" }, "optionalPeers": ["encoding"] }, "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A=="],
@@ -484,11 +403,7 @@
"onnxruntime-node": ["[email protected]", "", { "dependencies": { "adm-zip": "^0.5.16", "global-agent": "^3.0.0", "onnxruntime-common": "1.24.3" }, "os": [ "linux", "win32", "darwin", ] }, "sha512-JH7+czbc8ALA819vlTgcV+Q214/+VjGeBHDjX81+ZCD0PCVCIFGFNtT0V4sXG/1JXypKPgScQcB3ij/hk3YnTg=="],
- "onnxruntime-web": ["[email protected]", "", { "dependencies": { "flatbuffers": "^25.1.24", "guid-typescript": "^1.0.9", "long": "^5.2.3", "onnxruntime-common": "1.24.0-dev.20251116-b39e144322", "platform": "^1.3.6", "protobufjs": "^7.2.4" } }, "sha512-hHd9n8DzIfGSAjM4Dvslesc8i6h9HEEcl8qt7X3LfhUxMgls6FBJ32j2xrDtJjKJFEehFeJmyB/pvad1I8KS8w=="],
-
- "pac-proxy-agent": ["[email protected]", "", { "dependencies": { "@tootallnate/quickjs-emscripten": "^0.23.0", "agent-base": "^7.1.2", "debug": "^4.3.4", "get-uri": "^6.0.1", "http-proxy-agent": "^7.0.0", "https-proxy-agent": "^7.0.6", "pac-resolver": "^7.0.1", "socks-proxy-agent": "^8.0.5" } }, "sha512-TEB8ESquiLMc0lV8vcd5Ql/JAKAoyzHFXaStwjkzpOpC5Yv+pIzLfHvjTSdf3vpa2bMiUQrg9i6276yn8666aA=="],
-
- "pac-resolver": ["[email protected]", "", { "dependencies": { "degenerator": "^5.0.0", "netmask": "^2.0.2" } }, "sha512-5NPgf87AT2STgwa2ntRMr45jTKrYBGkVU36yT0ig/n/GMAa3oPqhZfIQ2kMEimReg0+t9kZViDVZ83qfVUlckg=="],
+ "onnxruntime-web": ["[email protected]", "", { "dependencies": { "flatbuffers": "^25.1.24", "guid-typescript": "^1.0.9", "long": "^5.2.3", "onnxruntime-common": "1.24.0-dev.20251116-b39e144322", "platform": "^1.3.6", "protobufjs": "^7.2.4" } }, "sha512-MD6Ss4GSpQBo6zqoJzyT9LRbKYs7x/JVN23FT24EcEvlqF4VuzPOeH6X38orZPKHQDbprn7K+SBpu0/mj2CQiw=="],
"pako": ["[email protected]", "", {}, "sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw=="],
@@ -498,36 +413,24 @@
"path-to-regexp": ["[email protected]", "", {}, "sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA=="],
- "pend": ["[email protected]", "", {}, "sha512-F3asv42UuXchdzt+xXqfW1OGlVBe+mxa2mqI0pg5yAHZPvFmY3Y6drSf/GQ1A86WgWEN9Kzh/WrgKa6iGcHXLg=="],
-
"pkce-challenge": ["[email protected]", "", {}, "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ=="],
"platform": ["[email protected]", "", {}, "sha512-fnWVljUchTro6RiCFvCXBbNhJc2NijN7oIQxbwsyL0buWJPG85v81ehlHI9fXrJsMNgTofEoWIQeClKpgxFLrg=="],
- "playwright": ["[email protected]", "", { "dependencies": { "playwright-core": "1.58.2" }, "optionalDependencies": { "fsevents": "2.3.2" }, "bin": { "playwright": "cli.js" } }, "sha512-vA30H8Nvkq/cPBnNw4Q8TWz1EJyqgpuinBcHET0YVJVFldr8JDNiU9LaWAE1KqSkRYazuaBhTpB5ZzShOezQ6A=="],
+ "playwright": ["[email protected]", "", { "dependencies": { "playwright-core": "1.62.1" }, "optionalDependencies": { "fsevents": "2.3.2" }, "bin": { "playwright": "cli.js" } }, "sha512-0M+L3LAD8/nm554LOla9Ayx0j0tmFZ0FBcoQ7F1VuVHpM/XpiC8RcDzBQB8W5+hA8L22THxELzeF+2WcUzvcLg=="],
- "playwright-core": ["[email protected]", "", { "bin": { "playwright-core": "cli.js" } }, "sha512-yZkEtftgwS8CsfYo7nm0KE8jsvm6i/PTgVtB8DL726wNf6H2IMsDuxCpJj59KDaxCtSnrWan2AeDqM7JBaultg=="],
+ "playwright-core": ["[email protected]", "", { "bin": { "playwright-core": "cli.js" } }, "sha512-wPYSwEBJY9GHraISXqyqtx0na0LpO3XEX7jNDhntbex7tzUS7kLnZsOlFruFJB4Hi/rhDMjXGqHewDZ68nYZVw=="],
"process": ["[email protected]", "", {}, "sha512-cdGef/drWFoydD1JsMzuFf8100nZl+GT+yacc2bEced5f9Rjk4z+WtFUTBu9PhOi9j/jfmBPu0mMEY4wIdAF8A=="],
"process-nextick-args": ["[email protected]", "", {}, "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag=="],
- "progress": ["[email protected]", "", {}, "sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA=="],
-
"protobufjs": ["[email protected]", "", { "dependencies": { "@protobufjs/aspromise": "^1.1.2", "@protobufjs/base64": "^1.1.2", "@protobufjs/codegen": "^2.0.4", "@protobufjs/eventemitter": "^1.1.0", "@protobufjs/fetch": "^1.1.0", "@protobufjs/float": "^1.0.2", "@protobufjs/inquire": "^1.1.0", "@protobufjs/path": "^1.1.2", "@protobufjs/pool": "^1.1.0", "@protobufjs/utf8": "^1.1.0", "@types/node": ">=13.7.0", "long": "^5.0.0" } }, "sha512-3wY1AxV+VBNW8Yypfd1yQY9pXnqTAN+KwQxL8iYm3/BjKYMNg4i0owhEe26PWDOMaIrzeeF98Lqd5NGz4omiIg=="],
"proxy-addr": ["[email protected]", "", { "dependencies": { "forwarded": "0.2.0", "ipaddr.js": "1.9.1" } }, "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg=="],
- "proxy-agent": ["[email protected]", "", { "dependencies": { "agent-base": "^7.1.2", "debug": "^4.3.4", "http-proxy-agent": "^7.0.1", "https-proxy-agent": "^7.0.6", "lru-cache": "^7.14.1", "pac-proxy-agent": "^7.1.0", "proxy-from-env": "^1.1.0", "socks-proxy-agent": "^8.0.5" } }, "sha512-TmatMXdr2KlRiA2CyDu8GqR8EjahTG3aY3nXjdzFyoZbmB8hrBsTyMezhULIXKnC0jpfjlmiZ3+EaCzoInSu/A=="],
-
- "proxy-from-env": ["[email protected]", "", {}, "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg=="],
-
- "pump": ["[email protected]", "", { "dependencies": { "end-of-stream": "^1.1.0", "once": "^1.3.1" } }, "sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA=="],
-
"punycode": ["[email protected]", "", {}, "sha512-jmYNElW7yvO7TV33CjSmvSiE2yco3bV2czu/OzDKdMNVZQWfxCblURLhf+47syQRBntjfLdd/H0egrzIG+oaFQ=="],
- "puppeteer-core": ["[email protected]", "", { "dependencies": { "@puppeteer/browsers": "2.13.0", "chromium-bidi": "14.0.0", "debug": "^4.4.3", "devtools-protocol": "0.0.1581282", "typed-query-selector": "^2.12.1", "webdriver-bidi-protocol": "0.4.1", "ws": "^8.19.0" } }, "sha512-MWL3XbUCfVgGR0gRsidzT6oKJT2QydPLhMITU6HoVWiiv4gkb6gJi3pcdAa8q4HwjBTbqISOWVP4aJiiyUJvag=="],
-
"qs": ["[email protected]", "", { "dependencies": { "side-channel": "^1.1.0" } }, "sha512-6YHEFRL9mfgcAvql/XhwTvf5jKcOiiupt2FiJxHkiX1z4j7WL8J/jRHYLluORvc1XxB5rV20KoeK00gVJamspg=="],
"queue": ["[email protected]", "", { "dependencies": { "inherits": "~2.0.3" } }, "sha512-iHZWu+q3IdFZFX36ro/lKBkSvfkztY5Y7HMiPlOUjhupPcG2JMfst2KKEpu5XndviX/3UhFbRngUPNKtgvtZiA=="],
@@ -538,8 +441,6 @@
"readable-stream": ["[email protected]", "", { "dependencies": { "core-util-is": "~1.0.0", "inherits": "~2.0.3", "isarray": "~1.0.0", "process-nextick-args": "~2.0.0", "safe-buffer": "~5.1.1", "string_decoder": "~1.1.1", "util-deprecate": "~1.0.1" } }, "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA=="],
- "require-directory": ["[email protected]", "", {}, "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q=="],
-
"require-from-string": ["[email protected]", "", {}, "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw=="],
"roarr": ["[email protected]", "", { "dependencies": { "boolean": "^3.0.1", "detect-node": "^2.0.4", "globalthis": "^1.0.1", "json-stringify-safe": "^5.0.1", "semver-compare": "^1.0.0", "sprintf-js": "^1.1.2" } }, "sha512-CHhPh+UNHD2GTXNYhPWLnU8ONHdI+5DI+4EYIAOaiD63rHeYlZvyh8P+in5999TTSFgUYuKUAjzRI4mdh/p+2A=="],
@@ -582,34 +483,16 @@
"smart-buffer": ["[email protected]", "", {}, "sha512-94hK0Hh8rPqQl2xXc3HsaBoOXKV20MToPkcXvwbISWLEs+64sBq5kFgn2kJDHb1Pry9yrP0dxrCI9RRci7RXKg=="],
- "socks": ["[email protected]", "", { "dependencies": { "ip-address": "^10.1.1", "smart-buffer": "^4.2.0" } }, "sha512-NlGELfPrgX2f1TAAcz0WawlLn+0r3FyhhCRpFFK2CemXenPYvzMWWZINv3eDNo9ucdwme7oCHRY0Jnbs4aIkog=="],
-
- "socks-proxy-agent": ["[email protected]", "", { "dependencies": { "agent-base": "^7.1.2", "debug": "^4.3.4", "socks": "^2.8.3" } }, "sha512-HehCEsotFqbPW9sJ8WVYB6UbmIMv7kUUORIF2Nncq4VQvBfNBLibW9YZR5dlYCSUhwcD628pRllm7n+E+YTzJw=="],
-
- "source-map": ["[email protected]", "", {}, "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g=="],
+ "socks": ["[email protected]", "", { "dependencies": { "ip-address": "^10.1.1", "smart-buffer": "^4.2.0" } }, "sha512-LJhUYUvItdQ0LkJTmPeaEObWXAqFyfmP85x0tch/ez9cahmhlBBLbIqDFnvBnUJGagb0JbIQrkBs1wJ+yRYpEw=="],
"sprintf-js": ["[email protected]", "", {}, "sha512-Oo+0REFV59/rz3gfJNKQiBlwfHaSESl1pcGyABQsnnIfWOFt6JNj5gCog2U6MLZ//IGYD+nA8nI+mTShREReaA=="],
"statuses": ["[email protected]", "", {}, "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw=="],
- "streamx": ["[email protected]", "", { "dependencies": { "events-universal": "^1.0.0", "fast-fifo": "^1.3.2", "text-decoder": "^1.1.0" } }, "sha512-0nQuG6jf1w+wddNEEXCF4nTg3LtufWINB5eFEN+5TNZW7KWJp6x87+JFL43vaAUPyCfH1wID+mNVyW6OHtFamg=="],
-
"string-template": ["[email protected]", "", {}, "sha512-Yptehjogou2xm4UJbxJ4CxgZx12HBfeystp0y3x7s4Dj32ltVVG1Gg8YhKjHZkHicuKpZX/ffilA8505VbUbpw=="],
- "string-width": ["[email protected]", "", { "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" } }, "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g=="],
-
"string_decoder": ["[email protected]", "", { "dependencies": { "safe-buffer": "~5.1.0" } }, "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg=="],
- "strip-ansi": ["[email protected]", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="],
-
- "tar-fs": ["[email protected]", "", { "dependencies": { "pump": "^3.0.0", "tar-stream": "^3.1.5" }, "optionalDependencies": { "bare-fs": "^4.0.1", "bare-path": "^3.0.0" } }, "sha512-QGxxTxxyleAdyM3kpFs14ymbYmNFrfY+pHj7Z8FgtbZ7w2//VAgLMac7sT6nRpIHjppXO2AwwEOg0bPFVRcmXw=="],
-
- "tar-stream": ["[email protected]", "", { "dependencies": { "b4a": "^1.6.4", "bare-fs": "^4.5.5", "fast-fifo": "^1.2.0", "streamx": "^2.15.0" } }, "sha512-U6QpVRyCGHva435KoNWy9PRoi2IFYCgtEhq9nmrPPpbRacPs9IH4aJ3gbrFC8dPcXvdSZ4XXfXT5Fshbp2MtlQ=="],
-
- "teex": ["[email protected]", "", { "dependencies": { "streamx": "^2.12.5" } }, "sha512-eYE6iEI62Ni1H8oIa7KlDU6uQBtqr4Eajni3wX7rpfXD8ysFx8z0+dri+KWEPWpBsxXfxu58x/0jvTVT1ekOSg=="],
-
- "text-decoder": ["[email protected]", "", { "dependencies": { "b4a": "^1.6.4" } }, "sha512-vlLytXkeP4xvEq2otHeJfSQIRyWxo/oZGEbXrtEEF9Hnmrdly59sUbzZ/QgyWuLYHctCHxFF4tRQZNQ9k60ExQ=="],
-
"toidentifier": ["[email protected]", "", {}, "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA=="],
"tr46": ["[email protected]", "", {}, "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw=="],
@@ -622,8 +505,6 @@
"type-is": ["[email protected]", "", { "dependencies": { "content-type": "^1.0.5", "media-typer": "^1.1.0", "mime-types": "^3.0.0" } }, "sha512-OZs6gsjF4vMp32qrCbiVSkrFmXtG/AZhY3t0iAMrMBiAZyV9oALtXO8hsrHbMXF9x6L3grlFuwW2oAz7cav+Gw=="],
- "typed-query-selector": ["[email protected]", "", {}, "sha512-uzR+FzI8qrUEIu96oaeBJmd9E7CFEiQ3goA5qCVgc4s5llSubcfGHq9yUstZx/k4s9dXHVKsE35YWoFyvEqEHA=="],
-
"undici-types": ["[email protected]", "", {}, "sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w=="],
"unpipe": ["[email protected]", "", {}, "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ=="],
@@ -634,20 +515,14 @@
"virtual-dom": ["[email protected]", "", { "dependencies": { "browser-split": "0.0.1", "error": "^4.3.0", "ev-store": "^7.0.0", "global": "^4.3.0", "is-object": "^1.0.1", "next-tick": "^0.2.2", "x-is-array": "0.1.0", "x-is-string": "0.1.0" } }, "sha512-wb6Qc9Lbqug0kRqo/iuApfBpJJAq14Sk1faAnSmtqXiwahg7PVTvWMs9L02Z8nNIMqbwsxzBAA90bbtRLbw0zg=="],
- "webdriver-bidi-protocol": ["[email protected]", "", {}, "sha512-ARrjNjtWRRs2w4Tk7nqrf2gBI0QXWuOmMCx2hU+1jUt6d00MjMxURrhxhGbrsoiZKJrhTSTzbIrc554iKI10qw=="],
-
"webidl-conversions": ["[email protected]", "", {}, "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ=="],
"whatwg-url": ["[email protected]", "", { "dependencies": { "tr46": "~0.0.3", "webidl-conversions": "^3.0.0" } }, "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw=="],
"which": ["[email protected]", "", { "dependencies": { "isexe": "^2.0.0" }, "bin": { "node-which": "./bin/node-which" } }, "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA=="],
- "wrap-ansi": ["[email protected]", "", { "dependencies": { "ansi-styles": "^4.0.0", "string-width": "^4.1.0", "strip-ansi": "^6.0.0" } }, "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q=="],
-
"wrappy": ["[email protected]", "", {}, "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ=="],
- "ws": ["[email protected]", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-sAt8BhgNbzCtgGbt2OxmpuryO63ZoDk/sqaB/znQm94T4fCEsy/yV+7CdC1kJhOU9lboAEU7R3kquuycDoibVA=="],
-
"x-is-array": ["[email protected]", "", {}, "sha512-goHPif61oNrr0jJgsXRfc8oqtYzvfiMJpTqwE7Z4y9uH+T3UozkGqQ4d2nX9mB9khvA8U2o/UbPOFjgC7hLWIA=="],
"x-is-string": ["[email protected]", "", {}, "sha512-GojqklwG8gpzOVEVki5KudKNoq7MbbjYZCbyWzEz7tyPA7eleiE0+ePwOWQQRb5fm86rD3S8Tc0tSFf3AOv50w=="],
@@ -660,14 +535,6 @@
"xterm-addon-fit": ["[email protected]", "", { "peerDependencies": { "xterm": "^5.0.0" } }, "sha512-yj3Np7XlvxxhYF/EJ7p3KHaMt6OdwQ+HDu573Vx1lRXsVxOcnVJs51RgjZOouIZOczTsskaS+CpXspK81/DLqw=="],
- "y18n": ["[email protected]", "", {}, "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA=="],
-
- "yargs": ["[email protected]", "", { "dependencies": { "cliui": "^8.0.1", "escalade": "^3.1.1", "get-caller-file": "^2.0.5", "require-directory": "^2.1.1", "string-width": "^4.2.3", "y18n": "^5.0.5", "yargs-parser": "^21.1.1" } }, "sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w=="],
-
- "yargs-parser": ["[email protected]", "", {}, "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw=="],
-
- "yauzl": ["[email protected]", "", { "dependencies": { "buffer-crc32": "~0.2.3", "fd-slicer": "~1.1.0" } }, "sha512-p4a9I6X6nu6IhoGmBqAcbJy1mlC4j27vEPZX9F4L4/vZT3Lyq1VkFHw/V/PUcB9Buo+DG3iHkT0x3Qya58zc3g=="],
-
"zod": ["[email protected]", "", {}, "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ=="],
"zod-to-json-schema": ["[email protected]", "", { "peerDependencies": { "zod": "^3.25.28 || ^4" } }, "sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA=="],
@@ -696,8 +563,6 @@
"send/mime-types": ["[email protected]", "", { "dependencies": { "mime-db": "^1.54.0" } }, "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A=="],
- "socks-proxy-agent/socks": ["[email protected]", "", { "dependencies": { "ip-address": "^10.0.1", "smart-buffer": "^4.2.0" } }, "sha512-HLpt+uLy/pxB+bum/9DzAgiKS8CX1EvbWxI4zlmgGCExImLdiad2iCwXT5Z4c9c3Eq8rP2318mPW2c+QbtjK8A=="],
-
"type-is/mime-types": ["[email protected]", "", { "dependencies": { "mime-db": "^1.54.0" } }, "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A=="],
"xmlbuilder2/@oozcitak/dom": ["@oozcitak/[email protected]", "", { "dependencies": { "@oozcitak/infra": "1.0.5", "@oozcitak/url": "1.0.0", "@oozcitak/util": "8.0.0" } }, "sha512-L6v3Mwb0TaYBYgeYlIeBaHnc+2ZEaDSbFiRm5KmqZQSoBlbPlf+l6aIH/sD5GUf2MYwULw00LT7+dOnEuAEC0A=="],
@@ -712,8 +577,6 @@
"send/mime-types/mime-db": ["[email protected]", "", {}, "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ=="],
- "socks-proxy-agent/socks/ip-address": ["[email protected]", "", {}, "sha512-XXADHxXmvT9+CRxhXg56LJovE+bmWnEWB78LB83VZTprKTmaC5QfruXocxzTZ2Kl0DNwKuBdlIhjL8LeY8Sf8Q=="],
-
"type-is/mime-types/mime-db": ["[email protected]", "", {}, "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ=="],
"xmlbuilder2/@oozcitak/dom/@oozcitak/util": ["@oozcitak/[email protected]", "", {}, "sha512-+9Hq6yuoq/3TRV/n/xcpydGBq2qN2/DEDMqNTG7rm95K6ZE2/YY/sPyx62+1n8QsE9O26e5M1URlXsk+AnN9Jw=="],
diff --git a/canary/SKILL.md b/canary/SKILL.md
index 8b28c47e6..096efc2be 100644
--- a/canary/SKILL.md
+++ b/canary/SKILL.md
@@ -108,9 +108,11 @@ else
fi
~/.claude/skills/gstack/bin/gstack-timeline-log '{"skill":"canary","event":"started","branch":"'"$_BRANCH"'","session":"'"$_SESSION_ID"'"}' 2>/dev/null &
_HAS_ROUTING="no"
-if [ -f CLAUDE.md ] && grep -q "## Skill routing" CLAUDE.md 2>/dev/null; then
- _HAS_ROUTING="yes"
-fi
+for _RF in CLAUDE.md AGENTS.md; do
+ if [ -f "$_RF" ] && grep -q "## Skill routing" "$_RF" 2>/dev/null; then
+ _HAS_ROUTING="yes"
+ fi
+done
_ROUTING_DECLINED=$(~/.claude/skills/gstack/bin/gstack-config get routing_declined 2>/dev/null || echo "false")
echo "HAS_ROUTING: $_HAS_ROUTING"
echo "ROUTING_DECLINED: $_ROUTING_DECLINED"
@@ -504,10 +506,13 @@ _BRAIN_SYNC_MODE=$("$_BRAIN_CONFIG_BIN" get artifacts_sync_mode 2>/dev/null || e
# Detect remote-MCP mode (Path 4 of /setup-gbrain). Local artifacts sync is
# a no-op in remote mode; the brain server pulls from GitHub/GitLab on its
# own cadence. Read claude.json directly to keep this preamble fast (no
-# subprocess to claude CLI on every skill start).
+# subprocess to claude CLI on every skill start). Both registration scopes
+# are read (#2499): user scope, then the nearest-ancestor project scope.
_GBRAIN_MCP_MODE="none"
+_GBRAIN_MCP_ENTRY=""
if command -v jq >/dev/null 2>&1 && [ -f "$HOME/.claude.json" ]; then
- _GBRAIN_MCP_TYPE=$(jq -r '.mcpServers.gbrain.type // .mcpServers.gbrain.transport // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_ENTRY=$(jq -c --arg cwd "$PWD" '.mcpServers.gbrain // ((.projects // {}) | to_entries | map(select((.key as $k | $cwd == $k or ($cwd | startswith($k + "/"))) and ((try .value.mcpServers.gbrain catch null) != null))) | sort_by(.key | length) | last | .value.mcpServers.gbrain) // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_TYPE=$(printf '%s' "$_GBRAIN_MCP_ENTRY" | jq -r '.type // .transport // empty' 2>/dev/null)
case "$_GBRAIN_MCP_TYPE" in
url|http|sse) _GBRAIN_MCP_MODE="remote-http" ;;
stdio) _GBRAIN_MCP_MODE="local-stdio" ;;
@@ -528,6 +533,7 @@ if [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_DO_PULL=1
if [ -f "$_BRAIN_LAST_PULL_FILE" ]; then
_BRAIN_LAST=$(cat "$_BRAIN_LAST_PULL_FILE" 2>/dev/null || echo 0)
+ case "$_BRAIN_LAST" in ''|*[!0-9]*) _BRAIN_LAST=0 ;; esac
_BRAIN_AGE=$(( _BRAIN_NOW - _BRAIN_LAST ))
[ "$_BRAIN_AGE" -lt 86400 ] && _BRAIN_DO_PULL=0
fi
@@ -541,7 +547,7 @@ fi
if [ "$_GBRAIN_MCP_MODE" = "remote-http" ]; then
# Remote-MCP mode: local artifacts sync is a no-op (brain admin's server
# pulls from GitHub/GitLab). Show the user this is by design, not broken.
- _GBRAIN_HOST=$(jq -r '.mcpServers.gbrain.url // empty' "$HOME/.claude.json" 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|')
+ _GBRAIN_HOST=$(printf '%s' "${_GBRAIN_MCP_ENTRY:-}" | jq -r '.url // empty' 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|' | head -1 | tr -cd 'A-Za-z0-9._-')
echo "ARTIFACTS_SYNC: remote-mode (managed by brain server ${_GBRAIN_HOST:-remote})"
elif [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_QUEUE_DEPTH=0
@@ -626,8 +632,8 @@ eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)"
_PROJ="${GSTACK_HOME:-$HOME/.gstack}/projects/${SLUG:-unknown}"
if [ -d "$_PROJ" ]; then
echo "--- RECENT ARTIFACTS ---"
- find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs ls -t 2>/dev/null | head -3
- [ -f "$_PROJ/${_BRANCH}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/${_BRANCH}-reviews.jsonl" | tr -d ' ') entries"
+ find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3
+ [ -f "$_PROJ/${BRANCH:-unknown}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/${BRANCH:-unknown}-reviews.jsonl" | tr -d ' ') entries"
[ -f "$_PROJ/timeline.jsonl" ] && tail -5 "$_PROJ/timeline.jsonl"
if [ -f "$_PROJ/timeline.jsonl" ]; then
_LAST=$(grep "\"branch\":\"${_BRANCH}\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -1)
@@ -635,7 +641,7 @@ if [ -d "$_PROJ" ]; then
_RECENT_SKILLS=$(grep "\"branch\":\"${_BRANCH}\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -3 | grep -o '"skill":"[^"]*"' | sed 's/"skill":"//;s/"//' | tr '\n' ',')
[ -n "$_RECENT_SKILLS" ] && echo "RECENT_PATTERN: $_RECENT_SKILLS"
fi
- _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs ls -t 2>/dev/null | head -1)
+ _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs -r ls -t 2>/dev/null | head -1)
[ -n "$_LATEST_CP" ] && echo "LATEST_CHECKPOINT: $_LATEST_CP"
if [ -f "$_PROJ/decisions.active.json" ]; then
echo "--- ACTIVE DECISIONS (recent, scope-relevant) ---"
@@ -711,7 +717,7 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST
## Question Tuning (skip entirely if `QUESTION_TUNING: false`)
-Before each AskUserQuestion, choose `question_id` from `scripts/question-registry.ts` or `{skill}-{slug}`, then run `printf '%s' "<question summary>" | ~/.claude/skills/gstack/bin/gstack-question-preference --check "<id>" --summary-stdin` (piped summary feeds the one-way keyword net, #2024). `AUTO_DECIDE` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." `ASK_NORMALLY` means ask.
+Before each AskUserQuestion, choose `question_id` from `~/.claude/skills/gstack/scripts/question-registry.ts` or `{skill}-{slug}`, then run `printf '%s' "<question summary>" | ~/.claude/skills/gstack/bin/gstack-question-preference --check "<id>" --summary-stdin` (piped summary feeds the one-way keyword net, #2024). `AUTO_DECIDE` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." `ASK_NORMALLY` means ask.
**Embed the question_id as a marker in the question text** so hooks can identify it deterministically (plan-tune cathedral T14 / D18 progressive markers). Append `<gstack-qid:{question_id}>` somewhere in the rendered question (the leading line or trailing line is fine; the marker doesn't render visibly to the user when wrapped in HTML-style angle brackets, but the hook strips it). Without the marker the PreToolUse enforcement hook treats the AUQ as observed-only and never auto-decides — so always include it when the question matches a registered `question_id`.
diff --git a/codex/SKILL.md b/codex/SKILL.md
index ff14f92c8..f171320b1 100644
--- a/codex/SKILL.md
+++ b/codex/SKILL.md
@@ -111,9 +111,11 @@ else
fi
~/.claude/skills/gstack/bin/gstack-timeline-log '{"skill":"codex","event":"started","branch":"'"$_BRANCH"'","session":"'"$_SESSION_ID"'"}' 2>/dev/null &
_HAS_ROUTING="no"
-if [ -f CLAUDE.md ] && grep -q "## Skill routing" CLAUDE.md 2>/dev/null; then
- _HAS_ROUTING="yes"
-fi
+for _RF in CLAUDE.md AGENTS.md; do
+ if [ -f "$_RF" ] && grep -q "## Skill routing" "$_RF" 2>/dev/null; then
+ _HAS_ROUTING="yes"
+ fi
+done
_ROUTING_DECLINED=$(~/.claude/skills/gstack/bin/gstack-config get routing_declined 2>/dev/null || echo "false")
echo "HAS_ROUTING: $_HAS_ROUTING"
echo "ROUTING_DECLINED: $_ROUTING_DECLINED"
@@ -507,10 +509,13 @@ _BRAIN_SYNC_MODE=$("$_BRAIN_CONFIG_BIN" get artifacts_sync_mode 2>/dev/null || e
# Detect remote-MCP mode (Path 4 of /setup-gbrain). Local artifacts sync is
# a no-op in remote mode; the brain server pulls from GitHub/GitLab on its
# own cadence. Read claude.json directly to keep this preamble fast (no
-# subprocess to claude CLI on every skill start).
+# subprocess to claude CLI on every skill start). Both registration scopes
+# are read (#2499): user scope, then the nearest-ancestor project scope.
_GBRAIN_MCP_MODE="none"
+_GBRAIN_MCP_ENTRY=""
if command -v jq >/dev/null 2>&1 && [ -f "$HOME/.claude.json" ]; then
- _GBRAIN_MCP_TYPE=$(jq -r '.mcpServers.gbrain.type // .mcpServers.gbrain.transport // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_ENTRY=$(jq -c --arg cwd "$PWD" '.mcpServers.gbrain // ((.projects // {}) | to_entries | map(select((.key as $k | $cwd == $k or ($cwd | startswith($k + "/"))) and ((try .value.mcpServers.gbrain catch null) != null))) | sort_by(.key | length) | last | .value.mcpServers.gbrain) // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_TYPE=$(printf '%s' "$_GBRAIN_MCP_ENTRY" | jq -r '.type // .transport // empty' 2>/dev/null)
case "$_GBRAIN_MCP_TYPE" in
url|http|sse) _GBRAIN_MCP_MODE="remote-http" ;;
stdio) _GBRAIN_MCP_MODE="local-stdio" ;;
@@ -531,6 +536,7 @@ if [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_DO_PULL=1
if [ -f "$_BRAIN_LAST_PULL_FILE" ]; then
_BRAIN_LAST=$(cat "$_BRAIN_LAST_PULL_FILE" 2>/dev/null || echo 0)
+ case "$_BRAIN_LAST" in ''|*[!0-9]*) _BRAIN_LAST=0 ;; esac
_BRAIN_AGE=$(( _BRAIN_NOW - _BRAIN_LAST ))
[ "$_BRAIN_AGE" -lt 86400 ] && _BRAIN_DO_PULL=0
fi
@@ -544,7 +550,7 @@ fi
if [ "$_GBRAIN_MCP_MODE" = "remote-http" ]; then
# Remote-MCP mode: local artifacts sync is a no-op (brain admin's server
# pulls from GitHub/GitLab). Show the user this is by design, not broken.
- _GBRAIN_HOST=$(jq -r '.mcpServers.gbrain.url // empty' "$HOME/.claude.json" 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|')
+ _GBRAIN_HOST=$(printf '%s' "${_GBRAIN_MCP_ENTRY:-}" | jq -r '.url // empty' 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|' | head -1 | tr -cd 'A-Za-z0-9._-')
echo "ARTIFACTS_SYNC: remote-mode (managed by brain server ${_GBRAIN_HOST:-remote})"
elif [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_QUEUE_DEPTH=0
@@ -629,8 +635,8 @@ eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)"
_PROJ="${GSTACK_HOME:-$HOME/.gstack}/projects/${SLUG:-unknown}"
if [ -d "$_PROJ" ]; then
echo "--- RECENT ARTIFACTS ---"
- find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs ls -t 2>/dev/null | head -3
- [ -f "$_PROJ/${_BRANCH}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/${_BRANCH}-reviews.jsonl" | tr -d ' ') entries"
+ find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3
+ [ -f "$_PROJ/${BRANCH:-unknown}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/${BRANCH:-unknown}-reviews.jsonl" | tr -d ' ') entries"
[ -f "$_PROJ/timeline.jsonl" ] && tail -5 "$_PROJ/timeline.jsonl"
if [ -f "$_PROJ/timeline.jsonl" ]; then
_LAST=$(grep "\"branch\":\"${_BRANCH}\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -1)
@@ -638,7 +644,7 @@ if [ -d "$_PROJ" ]; then
_RECENT_SKILLS=$(grep "\"branch\":\"${_BRANCH}\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -3 | grep -o '"skill":"[^"]*"' | sed 's/"skill":"//;s/"//' | tr '\n' ',')
[ -n "$_RECENT_SKILLS" ] && echo "RECENT_PATTERN: $_RECENT_SKILLS"
fi
- _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs ls -t 2>/dev/null | head -1)
+ _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs -r ls -t 2>/dev/null | head -1)
[ -n "$_LATEST_CP" ] && echo "LATEST_CHECKPOINT: $_LATEST_CP"
if [ -f "$_PROJ/decisions.active.json" ]; then
echo "--- ACTIVE DECISIONS (recent, scope-relevant) ---"
@@ -714,7 +720,7 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST
## Question Tuning (skip entirely if `QUESTION_TUNING: false`)
-Before each AskUserQuestion, choose `question_id` from `scripts/question-registry.ts` or `{skill}-{slug}`, then run `printf '%s' "<question summary>" | ~/.claude/skills/gstack/bin/gstack-question-preference --check "<id>" --summary-stdin` (piped summary feeds the one-way keyword net, #2024). `AUTO_DECIDE` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." `ASK_NORMALLY` means ask.
+Before each AskUserQuestion, choose `question_id` from `~/.claude/skills/gstack/scripts/question-registry.ts` or `{skill}-{slug}`, then run `printf '%s' "<question summary>" | ~/.claude/skills/gstack/bin/gstack-question-preference --check "<id>" --summary-stdin` (piped summary feeds the one-way keyword net, #2024). `AUTO_DECIDE` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." `ASK_NORMALLY` means ask.
**Embed the question_id as a marker in the question text** so hooks can identify it deterministically (plan-tune cathedral T14 / D18 progressive markers). Append `<gstack-qid:{question_id}>` somewhere in the rendered question (the leading line or trailing line is fine; the marker doesn't render visibly to the user when wrapped in HTML-style angle brackets, but the hook strips it). Without the marker the PreToolUse enforcement hook treats the AUQ as observed-only and never auto-decides — so always include it when the question matches a registered `question_id`.
@@ -878,26 +884,50 @@ source ~/.claude/skills/gstack/bin/gstack-codex-probe 2>/dev/null && _gstack_cod
---
-## Step 0.5: Auth probe + version check
+## Step 0.5: Auth probe + model probe + version check
-Before building expensive prompts, verify Codex has valid auth AND the installed
-CLI version isn't in the known-bad list. Sourcing `gstack-codex-probe` loads the
-shared helpers that both `/codex` and `/autoplan` use.
+Before building expensive prompts, verify Codex has valid auth, that the account
+can actually USE its configured model, AND the installed CLI version isn't in the
+known-bad list. Sourcing `gstack-codex-probe` loads the shared helpers that both
+`/codex` and `/autoplan` use.
```bash
_TEL=$(~/.claude/skills/gstack/bin/gstack-config get telemetry 2>/dev/null || echo off)
source ~/.claude/skills/gstack/bin/gstack-codex-probe
-if ! _gstack_codex_auth_probe >/dev/null; then
+# Running-under-Codex presence probe (#2519): a live Codex session exports
+# CODEX_THREAD_ID / CODEX_SANDBOX into every shell it spawns.
+if [ "${GSTACK_FORCE_CODEX_REVIEW:-0}" != "1" ] && { [ -n "${CODEX_THREAD_ID:-}" ] || [ -n "${CODEX_SANDBOX:-}" ]; }; then
+ echo "UNDER_CODEX"
+elif ! _gstack_codex_auth_probe >/dev/null; then
_gstack_codex_log_event "codex_auth_failed"
echo "AUTH_FAILED"
+else
+ _gstack_codex_model_probe # ~10s round trip on first run, cached 1h (#2477)
fi
_gstack_codex_version_check # warns if known-bad, non-blocking
```
+If the output contains `UNDER_CODEX`, stop with exactly one line:
+"[running under Codex — /codex would nest the same model at multiplied token
+cost; skipped. Set `GSTACK_FORCE_CODEX_REVIEW=1` to force.]" The whole value
+of this skill is a SECOND model's opinion; inside a Codex host it is the same
+model reviewing itself, and nested spawns have burned 15M tokens in one
+/review (#2519).
+
If the output contains `AUTH_FAILED`, stop and tell the user:
"No Codex authentication found. Run `codex login` or set `$CODEX_API_KEY` / `$OPENAI_API_KEY`, then re-run this skill."
+If the output contains `MODEL_UNUSABLE`, stop — auth exists but the account
+cannot use the configured model (a stale `model =` pin in
+`~/.codex/config.toml` is the usual cause). Relay the probe's HINT lines and
+follow the "Model not supported (HTTP 400)" recovery steps in
+`## Error Handling` below. Running the modes anyway just burns four
+invocations on the same 400 (#2477).
+
+`MODEL_PROBE_INCONCLUSIVE` is non-blocking (timeout/transient network): pass
+the warning through and continue.
+
If the version check printed a `WARN:` line, pass it through to the user verbatim
(non-blocking — Codex may still work, but the user should upgrade).
@@ -1024,7 +1054,7 @@ cd "$_REPO_ROOT"
# The 330s wrapper sits BELOW the 360s Bash gate so the wrapper fires FIRST
# and a stall surfaces as a diagnosable exit 124 with an explicit message,
# never as a silent harness kill that downstream reads as "no findings".
-_gstack_codex_timeout_wrapper 330 codex review --base <base> -c 'sandbox_mode="read-only"' -c 'model_reasoning_effort="high"' --enable web_search_cached < /dev/null 2>"$TMPERR"
+_gstack_codex_timeout_wrapper 330 codex review --base <base> -c 'sandbox_mode="read-only"' -c 'model_reasoning_effort="high"' -c 'web_search="cached"' < /dev/null 2>"$TMPERR"
_CODEX_EXIT=$?
if [ "$_CODEX_EXIT" = "124" ]; then
_gstack_codex_log_event "codex_timeout" "330"
@@ -1065,7 +1095,7 @@ _PROMPT_FILE=$(mktemp "$TMP_ROOT/codex-prompt-XXXXXX")
git diff "<base>...HEAD" 2>/dev/null
printf '\nDIFF_END\n'
} > "$_PROMPT_FILE"
-_gstack_codex_timeout_wrapper 330 codex exec -s read-only "$(cat "$_PROMPT_FILE")" -c 'model_reasoning_effort="high"' --enable web_search_cached < /dev/null 2>"$TMPERR"
+_gstack_codex_timeout_wrapper 330 codex exec -s read-only "$(cat "$_PROMPT_FILE")" -c 'model_reasoning_effort="high"' -c 'web_search="cached"' < /dev/null 2>"$TMPERR"
_CODEX_EXIT=$?
rm -f "$_PROMPT_FILE"
if [ "$_CODEX_EXIT" = "124" ]; then
@@ -1346,7 +1376,7 @@ fi
# Fix 1+2: wrap with timeout (gtimeout/timeout fallback chain via probe helper),
# capture stderr to $TMPERR for auth error detection (was: 2>/dev/null).
TMPERR=${TMPERR:-$(mktemp "$TMP_ROOT/codex-err-XXXXXX")}
-_gstack_codex_timeout_wrapper 600 codex exec "<prompt>" -C "$_REPO_ROOT" -s read-only -c 'model_reasoning_effort="high"' --enable web_search_cached --json < /dev/null 2>"$TMPERR" | PYTHONUNBUFFERED=1 "$PYTHON_CMD" -u -c "
+_gstack_codex_timeout_wrapper 600 codex exec "<prompt>" -C "$_REPO_ROOT" -s read-only -c 'model_reasoning_effort="high"' -c 'web_search="cached"' --json < /dev/null 2>"$TMPERR" | PYTHONUNBUFFERED=1 "$PYTHON_CMD" -u -c "
import sys, json
turn_completed_count = 0
for line in sys.stdin:
@@ -1504,7 +1534,7 @@ if [ -z "$PYTHON_CMD" ]; then
exit 1
fi
# Fix 1: wrap with timeout (gtimeout/timeout fallback chain via probe helper)
-_gstack_codex_timeout_wrapper 600 codex exec "<prompt>" -C "$_REPO_ROOT" -s read-only -c 'model_reasoning_effort="medium"' --enable web_search_cached --json < /dev/null 2>"$TMPERR" | PYTHONUNBUFFERED=1 "$PYTHON_CMD" -u -c "
+_gstack_codex_timeout_wrapper 600 codex exec "<prompt>" -C "$_REPO_ROOT" -s read-only -c 'model_reasoning_effort="medium"' -c 'web_search="cached"' --json < /dev/null 2>"$TMPERR" | PYTHONUNBUFFERED=1 "$PYTHON_CMD" -u -c "
import sys, json
for line in sys.stdin:
line = line.strip()
@@ -1558,7 +1588,7 @@ if [ -z "$PYTHON_CMD" ]; then
fi
cd "$_REPO_ROOT" || exit 1
# Fix 1: wrap with timeout (gtimeout/timeout fallback chain via probe helper)
-_gstack_codex_timeout_wrapper 600 codex exec resume <session-id> "<prompt>" -c 'sandbox_mode="read-only"' -c 'model_reasoning_effort="medium"' --enable web_search_cached --json < /dev/null 2>"$TMPERR" | PYTHONUNBUFFERED=1 "$PYTHON_CMD" -u -c "
+_gstack_codex_timeout_wrapper 600 codex exec resume <session-id> "<prompt>" -c 'sandbox_mode="read-only"' -c 'model_reasoning_effort="medium"' -c 'web_search="cached"' --json < /dev/null 2>"$TMPERR" | PYTHONUNBUFFERED=1 "$PYTHON_CMD" -u -c "
<same python streaming parser as above, with flush=True on all print() calls>
"
# Fix 1: same hang detection pattern as new-session block
@@ -1631,8 +1661,13 @@ by mode (see below).
tasks (OpenAI issues #8545, #8402, #6931). Users can override with `--xhigh` flag
(e.g., `/codex review --xhigh`) when they want maximum reasoning and are willing to wait.
-**Web search:** All codex commands use `--enable web_search_cached` so Codex can look up
-docs and APIs during review. This is OpenAI's cached index — fast, no extra cost.
+**Web search:** All codex commands pass `-c 'web_search="cached"'` so `codex exec`
+invocations can look up docs and APIs during review. This is OpenAI's cached index —
+fast, no extra cost. Unlike the legacy `--enable`-based spelling (deprecated by
+codex >=0.144), the `-c` form explicitly overrides any top-level
+`web_search` setting in `~/.codex/config.toml`. Note: native `codex review` disables
+web search regardless of configuration, so on the default Review path the flag is a
+harmless no-op — only exec-based modes actually search.
If the user specifies a model (e.g., `/codex review -m gpt-5.1-codex-max` or
`/codex challenge -m gpt-5.2`), the flag to pass depends on the underlying command:
diff --git a/codex/SKILL.md.tmpl b/codex/SKILL.md.tmpl
index ce3b84295..e641fe283 100644
--- a/codex/SKILL.md.tmpl
+++ b/codex/SKILL.md.tmpl
@@ -57,26 +57,50 @@ source ~/.claude/skills/gstack/bin/gstack-codex-probe 2>/dev/null && _gstack_cod
---
-## Step 0.5: Auth probe + version check
+## Step 0.5: Auth probe + model probe + version check
-Before building expensive prompts, verify Codex has valid auth AND the installed
-CLI version isn't in the known-bad list. Sourcing `gstack-codex-probe` loads the
-shared helpers that both `/codex` and `/autoplan` use.
+Before building expensive prompts, verify Codex has valid auth, that the account
+can actually USE its configured model, AND the installed CLI version isn't in the
+known-bad list. Sourcing `gstack-codex-probe` loads the shared helpers that both
+`/codex` and `/autoplan` use.
```bash
_TEL=$(~/.claude/skills/gstack/bin/gstack-config get telemetry 2>/dev/null || echo off)
source ~/.claude/skills/gstack/bin/gstack-codex-probe
-if ! _gstack_codex_auth_probe >/dev/null; then
+# Running-under-Codex presence probe (#2519): a live Codex session exports
+# CODEX_THREAD_ID / CODEX_SANDBOX into every shell it spawns.
+if [ "${GSTACK_FORCE_CODEX_REVIEW:-0}" != "1" ] && { [ -n "${CODEX_THREAD_ID:-}" ] || [ -n "${CODEX_SANDBOX:-}" ]; }; then
+ echo "UNDER_CODEX"
+elif ! _gstack_codex_auth_probe >/dev/null; then
_gstack_codex_log_event "codex_auth_failed"
echo "AUTH_FAILED"
+else
+ _gstack_codex_model_probe # ~10s round trip on first run, cached 1h (#2477)
fi
_gstack_codex_version_check # warns if known-bad, non-blocking
```
+If the output contains `UNDER_CODEX`, stop with exactly one line:
+"[running under Codex — /codex would nest the same model at multiplied token
+cost; skipped. Set `GSTACK_FORCE_CODEX_REVIEW=1` to force.]" The whole value
+of this skill is a SECOND model's opinion; inside a Codex host it is the same
+model reviewing itself, and nested spawns have burned 15M tokens in one
+/review (#2519).
+
If the output contains `AUTH_FAILED`, stop and tell the user:
"No Codex authentication found. Run `codex login` or set `$CODEX_API_KEY` / `$OPENAI_API_KEY`, then re-run this skill."
+If the output contains `MODEL_UNUSABLE`, stop — auth exists but the account
+cannot use the configured model (a stale `model =` pin in
+`~/.codex/config.toml` is the usual cause). Relay the probe's HINT lines and
+follow the "Model not supported (HTTP 400)" recovery steps in
+`## Error Handling` below. Running the modes anyway just burns four
+invocations on the same 400 (#2477).
+
+`MODEL_PROBE_INCONCLUSIVE` is non-blocking (timeout/transient network): pass
+the warning through and continue.
+
If the version check printed a `WARN:` line, pass it through to the user verbatim
(non-blocking — Codex may still work, but the user should upgrade).
@@ -203,7 +227,7 @@ cd "$_REPO_ROOT"
# The 330s wrapper sits BELOW the 360s Bash gate so the wrapper fires FIRST
# and a stall surfaces as a diagnosable exit 124 with an explicit message,
# never as a silent harness kill that downstream reads as "no findings".
-_gstack_codex_timeout_wrapper 330 codex review --base <base> -c 'sandbox_mode="read-only"' -c 'model_reasoning_effort="high"' --enable web_search_cached < /dev/null 2>"$TMPERR"
+_gstack_codex_timeout_wrapper 330 codex review --base <base> -c 'sandbox_mode="read-only"' -c 'model_reasoning_effort="high"' {{CODEX_WEB_SEARCH_FLAG}} < /dev/null 2>"$TMPERR"
_CODEX_EXIT=$?
if [ "$_CODEX_EXIT" = "124" ]; then
_gstack_codex_log_event "codex_timeout" "330"
@@ -244,7 +268,7 @@ _PROMPT_FILE=$(mktemp "$TMP_ROOT/codex-prompt-XXXXXX")
git diff "<base>...HEAD" 2>/dev/null
printf '\nDIFF_END\n'
} > "$_PROMPT_FILE"
-_gstack_codex_timeout_wrapper 330 codex exec -s read-only "$(cat "$_PROMPT_FILE")" -c 'model_reasoning_effort="high"' --enable web_search_cached < /dev/null 2>"$TMPERR"
+_gstack_codex_timeout_wrapper 330 codex exec -s read-only "$(cat "$_PROMPT_FILE")" -c 'model_reasoning_effort="high"' {{CODEX_WEB_SEARCH_FLAG}} < /dev/null 2>"$TMPERR"
_CODEX_EXIT=$?
rm -f "$_PROMPT_FILE"
if [ "$_CODEX_EXIT" = "124" ]; then
@@ -403,7 +427,7 @@ fi
# Fix 1+2: wrap with timeout (gtimeout/timeout fallback chain via probe helper),
# capture stderr to $TMPERR for auth error detection (was: 2>/dev/null).
TMPERR=${TMPERR:-$(mktemp "$TMP_ROOT/codex-err-XXXXXX")}
-_gstack_codex_timeout_wrapper 600 codex exec "<prompt>" -C "$_REPO_ROOT" -s read-only -c 'model_reasoning_effort="high"' --enable web_search_cached --json < /dev/null 2>"$TMPERR" | PYTHONUNBUFFERED=1 "$PYTHON_CMD" -u -c "
+_gstack_codex_timeout_wrapper 600 codex exec "<prompt>" -C "$_REPO_ROOT" -s read-only -c 'model_reasoning_effort="high"' {{CODEX_WEB_SEARCH_FLAG}} --json < /dev/null 2>"$TMPERR" | PYTHONUNBUFFERED=1 "$PYTHON_CMD" -u -c "
import sys, json
turn_completed_count = 0
for line in sys.stdin:
@@ -561,7 +585,7 @@ if [ -z "$PYTHON_CMD" ]; then
exit 1
fi
# Fix 1: wrap with timeout (gtimeout/timeout fallback chain via probe helper)
-_gstack_codex_timeout_wrapper 600 codex exec "<prompt>" -C "$_REPO_ROOT" -s read-only -c 'model_reasoning_effort="medium"' --enable web_search_cached --json < /dev/null 2>"$TMPERR" | PYTHONUNBUFFERED=1 "$PYTHON_CMD" -u -c "
+_gstack_codex_timeout_wrapper 600 codex exec "<prompt>" -C "$_REPO_ROOT" -s read-only -c 'model_reasoning_effort="medium"' {{CODEX_WEB_SEARCH_FLAG}} --json < /dev/null 2>"$TMPERR" | PYTHONUNBUFFERED=1 "$PYTHON_CMD" -u -c "
import sys, json
for line in sys.stdin:
line = line.strip()
@@ -615,7 +639,7 @@ if [ -z "$PYTHON_CMD" ]; then
fi
cd "$_REPO_ROOT" || exit 1
# Fix 1: wrap with timeout (gtimeout/timeout fallback chain via probe helper)
-_gstack_codex_timeout_wrapper 600 codex exec resume <session-id> "<prompt>" -c 'sandbox_mode="read-only"' -c 'model_reasoning_effort="medium"' --enable web_search_cached --json < /dev/null 2>"$TMPERR" | PYTHONUNBUFFERED=1 "$PYTHON_CMD" -u -c "
+_gstack_codex_timeout_wrapper 600 codex exec resume <session-id> "<prompt>" -c 'sandbox_mode="read-only"' -c 'model_reasoning_effort="medium"' {{CODEX_WEB_SEARCH_FLAG}} --json < /dev/null 2>"$TMPERR" | PYTHONUNBUFFERED=1 "$PYTHON_CMD" -u -c "
<same python streaming parser as above, with flush=True on all print() calls>
"
# Fix 1: same hang detection pattern as new-session block
@@ -688,8 +712,13 @@ by mode (see below).
tasks (OpenAI issues #8545, #8402, #6931). Users can override with `--xhigh` flag
(e.g., `/codex review --xhigh`) when they want maximum reasoning and are willing to wait.
-**Web search:** All codex commands use `--enable web_search_cached` so Codex can look up
-docs and APIs during review. This is OpenAI's cached index — fast, no extra cost.
+**Web search:** All codex commands pass `{{CODEX_WEB_SEARCH_FLAG}}` so `codex exec`
+invocations can look up docs and APIs during review. This is OpenAI's cached index —
+fast, no extra cost. Unlike the legacy `--enable`-based spelling (deprecated by
+codex >=0.144), the `-c` form explicitly overrides any top-level
+`web_search` setting in `~/.codex/config.toml`. Note: native `codex review` disables
+web search regardless of configuration, so on the default Review path the flag is a
+harmless no-op — only exec-based modes actually search.
If the user specifies a model (e.g., `/codex review -m gpt-5.1-codex-max` or
`/codex challenge -m gpt-5.2`), the flag to pass depends on the underlying command:
diff --git a/context-restore/SKILL.md b/context-restore/SKILL.md
index e3dc24782..268a4d161 100644
--- a/context-restore/SKILL.md
+++ b/context-restore/SKILL.md
@@ -112,9 +112,11 @@ else
fi
~/.claude/skills/gstack/bin/gstack-timeline-log '{"skill":"context-restore","event":"started","branch":"'"$_BRANCH"'","session":"'"$_SESSION_ID"'"}' 2>/dev/null &
_HAS_ROUTING="no"
-if [ -f CLAUDE.md ] && grep -q "## Skill routing" CLAUDE.md 2>/dev/null; then
- _HAS_ROUTING="yes"
-fi
+for _RF in CLAUDE.md AGENTS.md; do
+ if [ -f "$_RF" ] && grep -q "## Skill routing" "$_RF" 2>/dev/null; then
+ _HAS_ROUTING="yes"
+ fi
+done
_ROUTING_DECLINED=$(~/.claude/skills/gstack/bin/gstack-config get routing_declined 2>/dev/null || echo "false")
echo "HAS_ROUTING: $_HAS_ROUTING"
echo "ROUTING_DECLINED: $_ROUTING_DECLINED"
@@ -508,10 +510,13 @@ _BRAIN_SYNC_MODE=$("$_BRAIN_CONFIG_BIN" get artifacts_sync_mode 2>/dev/null || e
# Detect remote-MCP mode (Path 4 of /setup-gbrain). Local artifacts sync is
# a no-op in remote mode; the brain server pulls from GitHub/GitLab on its
# own cadence. Read claude.json directly to keep this preamble fast (no
-# subprocess to claude CLI on every skill start).
+# subprocess to claude CLI on every skill start). Both registration scopes
+# are read (#2499): user scope, then the nearest-ancestor project scope.
_GBRAIN_MCP_MODE="none"
+_GBRAIN_MCP_ENTRY=""
if command -v jq >/dev/null 2>&1 && [ -f "$HOME/.claude.json" ]; then
- _GBRAIN_MCP_TYPE=$(jq -r '.mcpServers.gbrain.type // .mcpServers.gbrain.transport // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_ENTRY=$(jq -c --arg cwd "$PWD" '.mcpServers.gbrain // ((.projects // {}) | to_entries | map(select((.key as $k | $cwd == $k or ($cwd | startswith($k + "/"))) and ((try .value.mcpServers.gbrain catch null) != null))) | sort_by(.key | length) | last | .value.mcpServers.gbrain) // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_TYPE=$(printf '%s' "$_GBRAIN_MCP_ENTRY" | jq -r '.type // .transport // empty' 2>/dev/null)
case "$_GBRAIN_MCP_TYPE" in
url|http|sse) _GBRAIN_MCP_MODE="remote-http" ;;
stdio) _GBRAIN_MCP_MODE="local-stdio" ;;
@@ -532,6 +537,7 @@ if [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_DO_PULL=1
if [ -f "$_BRAIN_LAST_PULL_FILE" ]; then
_BRAIN_LAST=$(cat "$_BRAIN_LAST_PULL_FILE" 2>/dev/null || echo 0)
+ case "$_BRAIN_LAST" in ''|*[!0-9]*) _BRAIN_LAST=0 ;; esac
_BRAIN_AGE=$(( _BRAIN_NOW - _BRAIN_LAST ))
[ "$_BRAIN_AGE" -lt 86400 ] && _BRAIN_DO_PULL=0
fi
@@ -545,7 +551,7 @@ fi
if [ "$_GBRAIN_MCP_MODE" = "remote-http" ]; then
# Remote-MCP mode: local artifacts sync is a no-op (brain admin's server
# pulls from GitHub/GitLab). Show the user this is by design, not broken.
- _GBRAIN_HOST=$(jq -r '.mcpServers.gbrain.url // empty' "$HOME/.claude.json" 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|')
+ _GBRAIN_HOST=$(printf '%s' "${_GBRAIN_MCP_ENTRY:-}" | jq -r '.url // empty' 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|' | head -1 | tr -cd 'A-Za-z0-9._-')
echo "ARTIFACTS_SYNC: remote-mode (managed by brain server ${_GBRAIN_HOST:-remote})"
elif [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_QUEUE_DEPTH=0
@@ -630,8 +636,8 @@ eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)"
_PROJ="${GSTACK_HOME:-$HOME/.gstack}/projects/${SLUG:-unknown}"
if [ -d "$_PROJ" ]; then
echo "--- RECENT ARTIFACTS ---"
- find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs ls -t 2>/dev/null | head -3
- [ -f "$_PROJ/${_BRANCH}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/${_BRANCH}-reviews.jsonl" | tr -d ' ') entries"
+ find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3
+ [ -f "$_PROJ/${BRANCH:-unknown}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/${BRANCH:-unknown}-reviews.jsonl" | tr -d ' ') entries"
[ -f "$_PROJ/timeline.jsonl" ] && tail -5 "$_PROJ/timeline.jsonl"
if [ -f "$_PROJ/timeline.jsonl" ]; then
_LAST=$(grep "\"branch\":\"${_BRANCH}\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -1)
@@ -639,7 +645,7 @@ if [ -d "$_PROJ" ]; then
_RECENT_SKILLS=$(grep "\"branch\":\"${_BRANCH}\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -3 | grep -o '"skill":"[^"]*"' | sed 's/"skill":"//;s/"//' | tr '\n' ',')
[ -n "$_RECENT_SKILLS" ] && echo "RECENT_PATTERN: $_RECENT_SKILLS"
fi
- _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs ls -t 2>/dev/null | head -1)
+ _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs -r ls -t 2>/dev/null | head -1)
[ -n "$_LATEST_CP" ] && echo "LATEST_CHECKPOINT: $_LATEST_CP"
if [ -f "$_PROJ/decisions.active.json" ]; then
echo "--- ACTIVE DECISIONS (recent, scope-relevant) ---"
@@ -715,7 +721,7 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST
## Question Tuning (skip entirely if `QUESTION_TUNING: false`)
-Before each AskUserQuestion, choose `question_id` from `scripts/question-registry.ts` or `{skill}-{slug}`, then run `printf '%s' "<question summary>" | ~/.claude/skills/gstack/bin/gstack-question-preference --check "<id>" --summary-stdin` (piped summary feeds the one-way keyword net, #2024). `AUTO_DECIDE` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." `ASK_NORMALLY` means ask.
+Before each AskUserQuestion, choose `question_id` from `~/.claude/skills/gstack/scripts/question-registry.ts` or `{skill}-{slug}`, then run `printf '%s' "<question summary>" | ~/.claude/skills/gstack/bin/gstack-question-preference --check "<id>" --summary-stdin` (piped summary feeds the one-way keyword net, #2024). `AUTO_DECIDE` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." `ASK_NORMALLY` means ask.
**Embed the question_id as a marker in the question text** so hooks can identify it deterministically (plan-tune cathedral T14 / D18 progressive markers). Append `<gstack-qid:{question_id}>` somewhere in the rendered question (the leading line or trailing line is fine; the marker doesn't render visibly to the user when wrapped in HTML-style angle brackets, but the hook strips it). Without the marker the PreToolUse enforcement hook treats the AUQ as observed-only and never auto-decides — so always include it when the question matches a registered `question_id`.
diff --git a/context-save/SKILL.md b/context-save/SKILL.md
index 775b0de48..e26731de5 100644
--- a/context-save/SKILL.md
+++ b/context-save/SKILL.md
@@ -111,9 +111,11 @@ else
fi
~/.claude/skills/gstack/bin/gstack-timeline-log '{"skill":"context-save","event":"started","branch":"'"$_BRANCH"'","session":"'"$_SESSION_ID"'"}' 2>/dev/null &
_HAS_ROUTING="no"
-if [ -f CLAUDE.md ] && grep -q "## Skill routing" CLAUDE.md 2>/dev/null; then
- _HAS_ROUTING="yes"
-fi
+for _RF in CLAUDE.md AGENTS.md; do
+ if [ -f "$_RF" ] && grep -q "## Skill routing" "$_RF" 2>/dev/null; then
+ _HAS_ROUTING="yes"
+ fi
+done
_ROUTING_DECLINED=$(~/.claude/skills/gstack/bin/gstack-config get routing_declined 2>/dev/null || echo "false")
echo "HAS_ROUTING: $_HAS_ROUTING"
echo "ROUTING_DECLINED: $_ROUTING_DECLINED"
@@ -507,10 +509,13 @@ _BRAIN_SYNC_MODE=$("$_BRAIN_CONFIG_BIN" get artifacts_sync_mode 2>/dev/null || e
# Detect remote-MCP mode (Path 4 of /setup-gbrain). Local artifacts sync is
# a no-op in remote mode; the brain server pulls from GitHub/GitLab on its
# own cadence. Read claude.json directly to keep this preamble fast (no
-# subprocess to claude CLI on every skill start).
+# subprocess to claude CLI on every skill start). Both registration scopes
+# are read (#2499): user scope, then the nearest-ancestor project scope.
_GBRAIN_MCP_MODE="none"
+_GBRAIN_MCP_ENTRY=""
if command -v jq >/dev/null 2>&1 && [ -f "$HOME/.claude.json" ]; then
- _GBRAIN_MCP_TYPE=$(jq -r '.mcpServers.gbrain.type // .mcpServers.gbrain.transport // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_ENTRY=$(jq -c --arg cwd "$PWD" '.mcpServers.gbrain // ((.projects // {}) | to_entries | map(select((.key as $k | $cwd == $k or ($cwd | startswith($k + "/"))) and ((try .value.mcpServers.gbrain catch null) != null))) | sort_by(.key | length) | last | .value.mcpServers.gbrain) // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_TYPE=$(printf '%s' "$_GBRAIN_MCP_ENTRY" | jq -r '.type // .transport // empty' 2>/dev/null)
case "$_GBRAIN_MCP_TYPE" in
url|http|sse) _GBRAIN_MCP_MODE="remote-http" ;;
stdio) _GBRAIN_MCP_MODE="local-stdio" ;;
@@ -531,6 +536,7 @@ if [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_DO_PULL=1
if [ -f "$_BRAIN_LAST_PULL_FILE" ]; then
_BRAIN_LAST=$(cat "$_BRAIN_LAST_PULL_FILE" 2>/dev/null || echo 0)
+ case "$_BRAIN_LAST" in ''|*[!0-9]*) _BRAIN_LAST=0 ;; esac
_BRAIN_AGE=$(( _BRAIN_NOW - _BRAIN_LAST ))
[ "$_BRAIN_AGE" -lt 86400 ] && _BRAIN_DO_PULL=0
fi
@@ -544,7 +550,7 @@ fi
if [ "$_GBRAIN_MCP_MODE" = "remote-http" ]; then
# Remote-MCP mode: local artifacts sync is a no-op (brain admin's server
# pulls from GitHub/GitLab). Show the user this is by design, not broken.
- _GBRAIN_HOST=$(jq -r '.mcpServers.gbrain.url // empty' "$HOME/.claude.json" 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|')
+ _GBRAIN_HOST=$(printf '%s' "${_GBRAIN_MCP_ENTRY:-}" | jq -r '.url // empty' 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|' | head -1 | tr -cd 'A-Za-z0-9._-')
echo "ARTIFACTS_SYNC: remote-mode (managed by brain server ${_GBRAIN_HOST:-remote})"
elif [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_QUEUE_DEPTH=0
@@ -629,8 +635,8 @@ eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)"
_PROJ="${GSTACK_HOME:-$HOME/.gstack}/projects/${SLUG:-unknown}"
if [ -d "$_PROJ" ]; then
echo "--- RECENT ARTIFACTS ---"
- find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs ls -t 2>/dev/null | head -3
- [ -f "$_PROJ/${_BRANCH}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/${_BRANCH}-reviews.jsonl" | tr -d ' ') entries"
+ find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3
+ [ -f "$_PROJ/${BRANCH:-unknown}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/${BRANCH:-unknown}-reviews.jsonl" | tr -d ' ') entries"
[ -f "$_PROJ/timeline.jsonl" ] && tail -5 "$_PROJ/timeline.jsonl"
if [ -f "$_PROJ/timeline.jsonl" ]; then
_LAST=$(grep "\"branch\":\"${_BRANCH}\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -1)
@@ -638,7 +644,7 @@ if [ -d "$_PROJ" ]; then
_RECENT_SKILLS=$(grep "\"branch\":\"${_BRANCH}\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -3 | grep -o '"skill":"[^"]*"' | sed 's/"skill":"//;s/"//' | tr '\n' ',')
[ -n "$_RECENT_SKILLS" ] && echo "RECENT_PATTERN: $_RECENT_SKILLS"
fi
- _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs ls -t 2>/dev/null | head -1)
+ _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs -r ls -t 2>/dev/null | head -1)
[ -n "$_LATEST_CP" ] && echo "LATEST_CHECKPOINT: $_LATEST_CP"
if [ -f "$_PROJ/decisions.active.json" ]; then
echo "--- ACTIVE DECISIONS (recent, scope-relevant) ---"
@@ -714,7 +720,7 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST
## Question Tuning (skip entirely if `QUESTION_TUNING: false`)
-Before each AskUserQuestion, choose `question_id` from `scripts/question-registry.ts` or `{skill}-{slug}`, then run `printf '%s' "<question summary>" | ~/.claude/skills/gstack/bin/gstack-question-preference --check "<id>" --summary-stdin` (piped summary feeds the one-way keyword net, #2024). `AUTO_DECIDE` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." `ASK_NORMALLY` means ask.
+Before each AskUserQuestion, choose `question_id` from `~/.claude/skills/gstack/scripts/question-registry.ts` or `{skill}-{slug}`, then run `printf '%s' "<question summary>" | ~/.claude/skills/gstack/bin/gstack-question-preference --check "<id>" --summary-stdin` (piped summary feeds the one-way keyword net, #2024). `AUTO_DECIDE` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." `ASK_NORMALLY` means ask.
**Embed the question_id as a marker in the question text** so hooks can identify it deterministically (plan-tune cathedral T14 / D18 progressive markers). Append `<gstack-qid:{question_id}>` somewhere in the rendered question (the leading line or trailing line is fine; the marker doesn't render visibly to the user when wrapped in HTML-style angle brackets, but the hook strips it). Without the marker the PreToolUse enforcement hook treats the AUQ as observed-only and never auto-decides — so always include it when the question matches a registered `question_id`.
diff --git a/cso/SKILL.md b/cso/SKILL.md
index 18f7321b0..1deca1ef1 100644
--- a/cso/SKILL.md
+++ b/cso/SKILL.md
@@ -114,9 +114,11 @@ else
fi
~/.claude/skills/gstack/bin/gstack-timeline-log '{"skill":"cso","event":"started","branch":"'"$_BRANCH"'","session":"'"$_SESSION_ID"'"}' 2>/dev/null &
_HAS_ROUTING="no"
-if [ -f CLAUDE.md ] && grep -q "## Skill routing" CLAUDE.md 2>/dev/null; then
- _HAS_ROUTING="yes"
-fi
+for _RF in CLAUDE.md AGENTS.md; do
+ if [ -f "$_RF" ] && grep -q "## Skill routing" "$_RF" 2>/dev/null; then
+ _HAS_ROUTING="yes"
+ fi
+done
_ROUTING_DECLINED=$(~/.claude/skills/gstack/bin/gstack-config get routing_declined 2>/dev/null || echo "false")
echo "HAS_ROUTING: $_HAS_ROUTING"
echo "ROUTING_DECLINED: $_ROUTING_DECLINED"
@@ -510,10 +512,13 @@ _BRAIN_SYNC_MODE=$("$_BRAIN_CONFIG_BIN" get artifacts_sync_mode 2>/dev/null || e
# Detect remote-MCP mode (Path 4 of /setup-gbrain). Local artifacts sync is
# a no-op in remote mode; the brain server pulls from GitHub/GitLab on its
# own cadence. Read claude.json directly to keep this preamble fast (no
-# subprocess to claude CLI on every skill start).
+# subprocess to claude CLI on every skill start). Both registration scopes
+# are read (#2499): user scope, then the nearest-ancestor project scope.
_GBRAIN_MCP_MODE="none"
+_GBRAIN_MCP_ENTRY=""
if command -v jq >/dev/null 2>&1 && [ -f "$HOME/.claude.json" ]; then
- _GBRAIN_MCP_TYPE=$(jq -r '.mcpServers.gbrain.type // .mcpServers.gbrain.transport // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_ENTRY=$(jq -c --arg cwd "$PWD" '.mcpServers.gbrain // ((.projects // {}) | to_entries | map(select((.key as $k | $cwd == $k or ($cwd | startswith($k + "/"))) and ((try .value.mcpServers.gbrain catch null) != null))) | sort_by(.key | length) | last | .value.mcpServers.gbrain) // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_TYPE=$(printf '%s' "$_GBRAIN_MCP_ENTRY" | jq -r '.type // .transport // empty' 2>/dev/null)
case "$_GBRAIN_MCP_TYPE" in
url|http|sse) _GBRAIN_MCP_MODE="remote-http" ;;
stdio) _GBRAIN_MCP_MODE="local-stdio" ;;
@@ -534,6 +539,7 @@ if [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_DO_PULL=1
if [ -f "$_BRAIN_LAST_PULL_FILE" ]; then
_BRAIN_LAST=$(cat "$_BRAIN_LAST_PULL_FILE" 2>/dev/null || echo 0)
+ case "$_BRAIN_LAST" in ''|*[!0-9]*) _BRAIN_LAST=0 ;; esac
_BRAIN_AGE=$(( _BRAIN_NOW - _BRAIN_LAST ))
[ "$_BRAIN_AGE" -lt 86400 ] && _BRAIN_DO_PULL=0
fi
@@ -547,7 +553,7 @@ fi
if [ "$_GBRAIN_MCP_MODE" = "remote-http" ]; then
# Remote-MCP mode: local artifacts sync is a no-op (brain admin's server
# pulls from GitHub/GitLab). Show the user this is by design, not broken.
- _GBRAIN_HOST=$(jq -r '.mcpServers.gbrain.url // empty' "$HOME/.claude.json" 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|')
+ _GBRAIN_HOST=$(printf '%s' "${_GBRAIN_MCP_ENTRY:-}" | jq -r '.url // empty' 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|' | head -1 | tr -cd 'A-Za-z0-9._-')
echo "ARTIFACTS_SYNC: remote-mode (managed by brain server ${_GBRAIN_HOST:-remote})"
elif [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_QUEUE_DEPTH=0
@@ -632,8 +638,8 @@ eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)"
_PROJ="${GSTACK_HOME:-$HOME/.gstack}/projects/${SLUG:-unknown}"
if [ -d "$_PROJ" ]; then
echo "--- RECENT ARTIFACTS ---"
- find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs ls -t 2>/dev/null | head -3
- [ -f "$_PROJ/${_BRANCH}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/${_BRANCH}-reviews.jsonl" | tr -d ' ') entries"
+ find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3
+ [ -f "$_PROJ/${BRANCH:-unknown}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/${BRANCH:-unknown}-reviews.jsonl" | tr -d ' ') entries"
[ -f "$_PROJ/timeline.jsonl" ] && tail -5 "$_PROJ/timeline.jsonl"
if [ -f "$_PROJ/timeline.jsonl" ]; then
_LAST=$(grep "\"branch\":\"${_BRANCH}\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -1)
@@ -641,7 +647,7 @@ if [ -d "$_PROJ" ]; then
_RECENT_SKILLS=$(grep "\"branch\":\"${_BRANCH}\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -3 | grep -o '"skill":"[^"]*"' | sed 's/"skill":"//;s/"//' | tr '\n' ',')
[ -n "$_RECENT_SKILLS" ] && echo "RECENT_PATTERN: $_RECENT_SKILLS"
fi
- _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs ls -t 2>/dev/null | head -1)
+ _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs -r ls -t 2>/dev/null | head -1)
[ -n "$_LATEST_CP" ] && echo "LATEST_CHECKPOINT: $_LATEST_CP"
if [ -f "$_PROJ/decisions.active.json" ]; then
echo "--- ACTIVE DECISIONS (recent, scope-relevant) ---"
@@ -717,7 +723,7 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST
## Question Tuning (skip entirely if `QUESTION_TUNING: false`)
-Before each AskUserQuestion, choose `question_id` from `scripts/question-registry.ts` or `{skill}-{slug}`, then run `printf '%s' "<question summary>" | ~/.claude/skills/gstack/bin/gstack-question-preference --check "<id>" --summary-stdin` (piped summary feeds the one-way keyword net, #2024). `AUTO_DECIDE` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." `ASK_NORMALLY` means ask.
+Before each AskUserQuestion, choose `question_id` from `~/.claude/skills/gstack/scripts/question-registry.ts` or `{skill}-{slug}`, then run `printf '%s' "<question summary>" | ~/.claude/skills/gstack/bin/gstack-question-preference --check "<id>" --summary-stdin` (piped summary feeds the one-way keyword net, #2024). `AUTO_DECIDE` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." `ASK_NORMALLY` means ask.
**Embed the question_id as a marker in the question text** so hooks can identify it deterministically (plan-tune cathedral T14 / D18 progressive markers). Append `<gstack-qid:{question_id}>` somewhere in the rendered question (the leading line or trailing line is fine; the marker doesn't render visibly to the user when wrapped in HTML-style angle brackets, but the hook strips it). Without the marker the PreToolUse enforcement hook treats the AUQ as observed-only and never auto-decides — so always include it when the question matches a registered `question_id`.
diff --git a/design-consultation/SKILL.md b/design-consultation/SKILL.md
index 241b5c3d8..659a46a29 100644
--- a/design-consultation/SKILL.md
+++ b/design-consultation/SKILL.md
@@ -134,9 +134,11 @@ else
fi
~/.claude/skills/gstack/bin/gstack-timeline-log '{"skill":"design-consultation","event":"started","branch":"'"$_BRANCH"'","session":"'"$_SESSION_ID"'"}' 2>/dev/null &
_HAS_ROUTING="no"
-if [ -f CLAUDE.md ] && grep -q "## Skill routing" CLAUDE.md 2>/dev/null; then
- _HAS_ROUTING="yes"
-fi
+for _RF in CLAUDE.md AGENTS.md; do
+ if [ -f "$_RF" ] && grep -q "## Skill routing" "$_RF" 2>/dev/null; then
+ _HAS_ROUTING="yes"
+ fi
+done
_ROUTING_DECLINED=$(~/.claude/skills/gstack/bin/gstack-config get routing_declined 2>/dev/null || echo "false")
echo "HAS_ROUTING: $_HAS_ROUTING"
echo "ROUTING_DECLINED: $_ROUTING_DECLINED"
@@ -530,10 +532,13 @@ _BRAIN_SYNC_MODE=$("$_BRAIN_CONFIG_BIN" get artifacts_sync_mode 2>/dev/null || e
# Detect remote-MCP mode (Path 4 of /setup-gbrain). Local artifacts sync is
# a no-op in remote mode; the brain server pulls from GitHub/GitLab on its
# own cadence. Read claude.json directly to keep this preamble fast (no
-# subprocess to claude CLI on every skill start).
+# subprocess to claude CLI on every skill start). Both registration scopes
+# are read (#2499): user scope, then the nearest-ancestor project scope.
_GBRAIN_MCP_MODE="none"
+_GBRAIN_MCP_ENTRY=""
if command -v jq >/dev/null 2>&1 && [ -f "$HOME/.claude.json" ]; then
- _GBRAIN_MCP_TYPE=$(jq -r '.mcpServers.gbrain.type // .mcpServers.gbrain.transport // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_ENTRY=$(jq -c --arg cwd "$PWD" '.mcpServers.gbrain // ((.projects // {}) | to_entries | map(select((.key as $k | $cwd == $k or ($cwd | startswith($k + "/"))) and ((try .value.mcpServers.gbrain catch null) != null))) | sort_by(.key | length) | last | .value.mcpServers.gbrain) // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_TYPE=$(printf '%s' "$_GBRAIN_MCP_ENTRY" | jq -r '.type // .transport // empty' 2>/dev/null)
case "$_GBRAIN_MCP_TYPE" in
url|http|sse) _GBRAIN_MCP_MODE="remote-http" ;;
stdio) _GBRAIN_MCP_MODE="local-stdio" ;;
@@ -554,6 +559,7 @@ if [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_DO_PULL=1
if [ -f "$_BRAIN_LAST_PULL_FILE" ]; then
_BRAIN_LAST=$(cat "$_BRAIN_LAST_PULL_FILE" 2>/dev/null || echo 0)
+ case "$_BRAIN_LAST" in ''|*[!0-9]*) _BRAIN_LAST=0 ;; esac
_BRAIN_AGE=$(( _BRAIN_NOW - _BRAIN_LAST ))
[ "$_BRAIN_AGE" -lt 86400 ] && _BRAIN_DO_PULL=0
fi
@@ -567,7 +573,7 @@ fi
if [ "$_GBRAIN_MCP_MODE" = "remote-http" ]; then
# Remote-MCP mode: local artifacts sync is a no-op (brain admin's server
# pulls from GitHub/GitLab). Show the user this is by design, not broken.
- _GBRAIN_HOST=$(jq -r '.mcpServers.gbrain.url // empty' "$HOME/.claude.json" 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|')
+ _GBRAIN_HOST=$(printf '%s' "${_GBRAIN_MCP_ENTRY:-}" | jq -r '.url // empty' 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|' | head -1 | tr -cd 'A-Za-z0-9._-')
echo "ARTIFACTS_SYNC: remote-mode (managed by brain server ${_GBRAIN_HOST:-remote})"
elif [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_QUEUE_DEPTH=0
@@ -652,8 +658,8 @@ eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)"
_PROJ="${GSTACK_HOME:-$HOME/.gstack}/projects/${SLUG:-unknown}"
if [ -d "$_PROJ" ]; then
echo "--- RECENT ARTIFACTS ---"
- find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs ls -t 2>/dev/null | head -3
- [ -f "$_PROJ/${_BRANCH}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/${_BRANCH}-reviews.jsonl" | tr -d ' ') entries"
+ find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3
+ [ -f "$_PROJ/${BRANCH:-unknown}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/${BRANCH:-unknown}-reviews.jsonl" | tr -d ' ') entries"
[ -f "$_PROJ/timeline.jsonl" ] && tail -5 "$_PROJ/timeline.jsonl"
if [ -f "$_PROJ/timeline.jsonl" ]; then
_LAST=$(grep "\"branch\":\"${_BRANCH}\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -1)
@@ -661,7 +667,7 @@ if [ -d "$_PROJ" ]; then
_RECENT_SKILLS=$(grep "\"branch\":\"${_BRANCH}\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -3 | grep -o '"skill":"[^"]*"' | sed 's/"skill":"//;s/"//' | tr '\n' ',')
[ -n "$_RECENT_SKILLS" ] && echo "RECENT_PATTERN: $_RECENT_SKILLS"
fi
- _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs ls -t 2>/dev/null | head -1)
+ _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs -r ls -t 2>/dev/null | head -1)
[ -n "$_LATEST_CP" ] && echo "LATEST_CHECKPOINT: $_LATEST_CP"
if [ -f "$_PROJ/decisions.active.json" ]; then
echo "--- ACTIVE DECISIONS (recent, scope-relevant) ---"
@@ -737,7 +743,7 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST
## Question Tuning (skip entirely if `QUESTION_TUNING: false`)
-Before each AskUserQuestion, choose `question_id` from `scripts/question-registry.ts` or `{skill}-{slug}`, then run `printf '%s' "<question summary>" | ~/.claude/skills/gstack/bin/gstack-question-preference --check "<id>" --summary-stdin` (piped summary feeds the one-way keyword net, #2024). `AUTO_DECIDE` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." `ASK_NORMALLY` means ask.
+Before each AskUserQuestion, choose `question_id` from `~/.claude/skills/gstack/scripts/question-registry.ts` or `{skill}-{slug}`, then run `printf '%s' "<question summary>" | ~/.claude/skills/gstack/bin/gstack-question-preference --check "<id>" --summary-stdin` (piped summary feeds the one-way keyword net, #2024). `AUTO_DECIDE` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." `ASK_NORMALLY` means ask.
**Embed the question_id as a marker in the question text** so hooks can identify it deterministically (plan-tune cathedral T14 / D18 progressive markers). Append `<gstack-qid:{question_id}>` somewhere in the rendered question (the leading line or trailing line is fine; the marker doesn't render visibly to the user when wrapped in HTML-style angle brackets, but the hook strips it). Without the marker the PreToolUse enforcement hook treats the AUQ as observed-only and never auto-decides — so always include it when the question matches a registered `question_id`.
@@ -1164,7 +1170,7 @@ codex exec "Given this product context, propose a complete design direction:
- Differentiation: 2 deliberate departures from category norms
- Anti-slop: no purple gradients, no 3-column icon grids, no centered everything, no decorative blobs
-Be opinionated. Be specific. Do not hedge. This is YOUR design direction — own it." -C "$_REPO_ROOT" -s read-only -c 'model_reasoning_effort="medium"' --enable web_search_cached < /dev/null 2>"$TMPERR_DESIGN"
+Be opinionated. Be specific. Do not hedge. This is YOUR design direction — own it." -C "$_REPO_ROOT" -s read-only -c 'model_reasoning_effort="medium"' -c 'web_search="cached"' < /dev/null 2>"$TMPERR_DESIGN"
```
Use a 5-minute timeout (`timeout: 300000`). After the command completes, read stderr:
```bash
diff --git a/design-html/SKILL.md b/design-html/SKILL.md
index 59178c131..231610bfd 100644
--- a/design-html/SKILL.md
+++ b/design-html/SKILL.md
@@ -115,9 +115,11 @@ else
fi
~/.claude/skills/gstack/bin/gstack-timeline-log '{"skill":"design-html","event":"started","branch":"'"$_BRANCH"'","session":"'"$_SESSION_ID"'"}' 2>/dev/null &
_HAS_ROUTING="no"
-if [ -f CLAUDE.md ] && grep -q "## Skill routing" CLAUDE.md 2>/dev/null; then
- _HAS_ROUTING="yes"
-fi
+for _RF in CLAUDE.md AGENTS.md; do
+ if [ -f "$_RF" ] && grep -q "## Skill routing" "$_RF" 2>/dev/null; then
+ _HAS_ROUTING="yes"
+ fi
+done
_ROUTING_DECLINED=$(~/.claude/skills/gstack/bin/gstack-config get routing_declined 2>/dev/null || echo "false")
echo "HAS_ROUTING: $_HAS_ROUTING"
echo "ROUTING_DECLINED: $_ROUTING_DECLINED"
@@ -511,10 +513,13 @@ _BRAIN_SYNC_MODE=$("$_BRAIN_CONFIG_BIN" get artifacts_sync_mode 2>/dev/null || e
# Detect remote-MCP mode (Path 4 of /setup-gbrain). Local artifacts sync is
# a no-op in remote mode; the brain server pulls from GitHub/GitLab on its
# own cadence. Read claude.json directly to keep this preamble fast (no
-# subprocess to claude CLI on every skill start).
+# subprocess to claude CLI on every skill start). Both registration scopes
+# are read (#2499): user scope, then the nearest-ancestor project scope.
_GBRAIN_MCP_MODE="none"
+_GBRAIN_MCP_ENTRY=""
if command -v jq >/dev/null 2>&1 && [ -f "$HOME/.claude.json" ]; then
- _GBRAIN_MCP_TYPE=$(jq -r '.mcpServers.gbrain.type // .mcpServers.gbrain.transport // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_ENTRY=$(jq -c --arg cwd "$PWD" '.mcpServers.gbrain // ((.projects // {}) | to_entries | map(select((.key as $k | $cwd == $k or ($cwd | startswith($k + "/"))) and ((try .value.mcpServers.gbrain catch null) != null))) | sort_by(.key | length) | last | .value.mcpServers.gbrain) // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_TYPE=$(printf '%s' "$_GBRAIN_MCP_ENTRY" | jq -r '.type // .transport // empty' 2>/dev/null)
case "$_GBRAIN_MCP_TYPE" in
url|http|sse) _GBRAIN_MCP_MODE="remote-http" ;;
stdio) _GBRAIN_MCP_MODE="local-stdio" ;;
@@ -535,6 +540,7 @@ if [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_DO_PULL=1
if [ -f "$_BRAIN_LAST_PULL_FILE" ]; then
_BRAIN_LAST=$(cat "$_BRAIN_LAST_PULL_FILE" 2>/dev/null || echo 0)
+ case "$_BRAIN_LAST" in ''|*[!0-9]*) _BRAIN_LAST=0 ;; esac
_BRAIN_AGE=$(( _BRAIN_NOW - _BRAIN_LAST ))
[ "$_BRAIN_AGE" -lt 86400 ] && _BRAIN_DO_PULL=0
fi
@@ -548,7 +554,7 @@ fi
if [ "$_GBRAIN_MCP_MODE" = "remote-http" ]; then
# Remote-MCP mode: local artifacts sync is a no-op (brain admin's server
# pulls from GitHub/GitLab). Show the user this is by design, not broken.
- _GBRAIN_HOST=$(jq -r '.mcpServers.gbrain.url // empty' "$HOME/.claude.json" 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|')
+ _GBRAIN_HOST=$(printf '%s' "${_GBRAIN_MCP_ENTRY:-}" | jq -r '.url // empty' 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|' | head -1 | tr -cd 'A-Za-z0-9._-')
echo "ARTIFACTS_SYNC: remote-mode (managed by brain server ${_GBRAIN_HOST:-remote})"
elif [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_QUEUE_DEPTH=0
@@ -633,8 +639,8 @@ eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)"
_PROJ="${GSTACK_HOME:-$HOME/.gstack}/projects/${SLUG:-unknown}"
if [ -d "$_PROJ" ]; then
echo "--- RECENT ARTIFACTS ---"
- find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs ls -t 2>/dev/null | head -3
- [ -f "$_PROJ/${_BRANCH}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/${_BRANCH}-reviews.jsonl" | tr -d ' ') entries"
+ find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3
+ [ -f "$_PROJ/${BRANCH:-unknown}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/${BRANCH:-unknown}-reviews.jsonl" | tr -d ' ') entries"
[ -f "$_PROJ/timeline.jsonl" ] && tail -5 "$_PROJ/timeline.jsonl"
if [ -f "$_PROJ/timeline.jsonl" ]; then
_LAST=$(grep "\"branch\":\"${_BRANCH}\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -1)
@@ -642,7 +648,7 @@ if [ -d "$_PROJ" ]; then
_RECENT_SKILLS=$(grep "\"branch\":\"${_BRANCH}\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -3 | grep -o '"skill":"[^"]*"' | sed 's/"skill":"//;s/"//' | tr '\n' ',')
[ -n "$_RECENT_SKILLS" ] && echo "RECENT_PATTERN: $_RECENT_SKILLS"
fi
- _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs ls -t 2>/dev/null | head -1)
+ _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs -r ls -t 2>/dev/null | head -1)
[ -n "$_LATEST_CP" ] && echo "LATEST_CHECKPOINT: $_LATEST_CP"
if [ -f "$_PROJ/decisions.active.json" ]; then
echo "--- ACTIVE DECISIONS (recent, scope-relevant) ---"
@@ -718,7 +724,7 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST
## Question Tuning (skip entirely if `QUESTION_TUNING: false`)
-Before each AskUserQuestion, choose `question_id` from `scripts/question-registry.ts` or `{skill}-{slug}`, then run `printf '%s' "<question summary>" | ~/.claude/skills/gstack/bin/gstack-question-preference --check "<id>" --summary-stdin` (piped summary feeds the one-way keyword net, #2024). `AUTO_DECIDE` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." `ASK_NORMALLY` means ask.
+Before each AskUserQuestion, choose `question_id` from `~/.claude/skills/gstack/scripts/question-registry.ts` or `{skill}-{slug}`, then run `printf '%s' "<question summary>" | ~/.claude/skills/gstack/bin/gstack-question-preference --check "<id>" --summary-stdin` (piped summary feeds the one-way keyword net, #2024). `AUTO_DECIDE` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." `ASK_NORMALLY` means ask.
**Embed the question_id as a marker in the question text** so hooks can identify it deterministically (plan-tune cathedral T14 / D18 progressive markers). Append `<gstack-qid:{question_id}>` somewhere in the rendered question (the leading line or trailing line is fine; the marker doesn't render visibly to the user when wrapped in HTML-style angle brackets, but the hook strips it). Without the marker the PreToolUse enforcement hook treats the AUQ as observed-only and never auto-decides — so always include it when the question matches a registered `question_id`.
diff --git a/design-review/SKILL.md b/design-review/SKILL.md
index 8e177dfe7..e5f052f53 100644
--- a/design-review/SKILL.md
+++ b/design-review/SKILL.md
@@ -112,9 +112,11 @@ else
fi
~/.claude/skills/gstack/bin/gstack-timeline-log '{"skill":"design-review","event":"started","branch":"'"$_BRANCH"'","session":"'"$_SESSION_ID"'"}' 2>/dev/null &
_HAS_ROUTING="no"
-if [ -f CLAUDE.md ] && grep -q "## Skill routing" CLAUDE.md 2>/dev/null; then
- _HAS_ROUTING="yes"
-fi
+for _RF in CLAUDE.md AGENTS.md; do
+ if [ -f "$_RF" ] && grep -q "## Skill routing" "$_RF" 2>/dev/null; then
+ _HAS_ROUTING="yes"
+ fi
+done
_ROUTING_DECLINED=$(~/.claude/skills/gstack/bin/gstack-config get routing_declined 2>/dev/null || echo "false")
echo "HAS_ROUTING: $_HAS_ROUTING"
echo "ROUTING_DECLINED: $_ROUTING_DECLINED"
@@ -508,10 +510,13 @@ _BRAIN_SYNC_MODE=$("$_BRAIN_CONFIG_BIN" get artifacts_sync_mode 2>/dev/null || e
# Detect remote-MCP mode (Path 4 of /setup-gbrain). Local artifacts sync is
# a no-op in remote mode; the brain server pulls from GitHub/GitLab on its
# own cadence. Read claude.json directly to keep this preamble fast (no
-# subprocess to claude CLI on every skill start).
+# subprocess to claude CLI on every skill start). Both registration scopes
+# are read (#2499): user scope, then the nearest-ancestor project scope.
_GBRAIN_MCP_MODE="none"
+_GBRAIN_MCP_ENTRY=""
if command -v jq >/dev/null 2>&1 && [ -f "$HOME/.claude.json" ]; then
- _GBRAIN_MCP_TYPE=$(jq -r '.mcpServers.gbrain.type // .mcpServers.gbrain.transport // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_ENTRY=$(jq -c --arg cwd "$PWD" '.mcpServers.gbrain // ((.projects // {}) | to_entries | map(select((.key as $k | $cwd == $k or ($cwd | startswith($k + "/"))) and ((try .value.mcpServers.gbrain catch null) != null))) | sort_by(.key | length) | last | .value.mcpServers.gbrain) // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_TYPE=$(printf '%s' "$_GBRAIN_MCP_ENTRY" | jq -r '.type // .transport // empty' 2>/dev/null)
case "$_GBRAIN_MCP_TYPE" in
url|http|sse) _GBRAIN_MCP_MODE="remote-http" ;;
stdio) _GBRAIN_MCP_MODE="local-stdio" ;;
@@ -532,6 +537,7 @@ if [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_DO_PULL=1
if [ -f "$_BRAIN_LAST_PULL_FILE" ]; then
_BRAIN_LAST=$(cat "$_BRAIN_LAST_PULL_FILE" 2>/dev/null || echo 0)
+ case "$_BRAIN_LAST" in ''|*[!0-9]*) _BRAIN_LAST=0 ;; esac
_BRAIN_AGE=$(( _BRAIN_NOW - _BRAIN_LAST ))
[ "$_BRAIN_AGE" -lt 86400 ] && _BRAIN_DO_PULL=0
fi
@@ -545,7 +551,7 @@ fi
if [ "$_GBRAIN_MCP_MODE" = "remote-http" ]; then
# Remote-MCP mode: local artifacts sync is a no-op (brain admin's server
# pulls from GitHub/GitLab). Show the user this is by design, not broken.
- _GBRAIN_HOST=$(jq -r '.mcpServers.gbrain.url // empty' "$HOME/.claude.json" 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|')
+ _GBRAIN_HOST=$(printf '%s' "${_GBRAIN_MCP_ENTRY:-}" | jq -r '.url // empty' 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|' | head -1 | tr -cd 'A-Za-z0-9._-')
echo "ARTIFACTS_SYNC: remote-mode (managed by brain server ${_GBRAIN_HOST:-remote})"
elif [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_QUEUE_DEPTH=0
@@ -630,8 +636,8 @@ eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)"
_PROJ="${GSTACK_HOME:-$HOME/.gstack}/projects/${SLUG:-unknown}"
if [ -d "$_PROJ" ]; then
echo "--- RECENT ARTIFACTS ---"
- find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs ls -t 2>/dev/null | head -3
- [ -f "$_PROJ/${_BRANCH}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/${_BRANCH}-reviews.jsonl" | tr -d ' ') entries"
+ find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3
+ [ -f "$_PROJ/${BRANCH:-unknown}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/${BRANCH:-unknown}-reviews.jsonl" | tr -d ' ') entries"
[ -f "$_PROJ/timeline.jsonl" ] && tail -5 "$_PROJ/timeline.jsonl"
if [ -f "$_PROJ/timeline.jsonl" ]; then
_LAST=$(grep "\"branch\":\"${_BRANCH}\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -1)
@@ -639,7 +645,7 @@ if [ -d "$_PROJ" ]; then
_RECENT_SKILLS=$(grep "\"branch\":\"${_BRANCH}\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -3 | grep -o '"skill":"[^"]*"' | sed 's/"skill":"//;s/"//' | tr '\n' ',')
[ -n "$_RECENT_SKILLS" ] && echo "RECENT_PATTERN: $_RECENT_SKILLS"
fi
- _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs ls -t 2>/dev/null | head -1)
+ _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs -r ls -t 2>/dev/null | head -1)
[ -n "$_LATEST_CP" ] && echo "LATEST_CHECKPOINT: $_LATEST_CP"
if [ -f "$_PROJ/decisions.active.json" ]; then
echo "--- ACTIVE DECISIONS (recent, scope-relevant) ---"
@@ -715,7 +721,7 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST
## Question Tuning (skip entirely if `QUESTION_TUNING: false`)
-Before each AskUserQuestion, choose `question_id` from `scripts/question-registry.ts` or `{skill}-{slug}`, then run `printf '%s' "<question summary>" | ~/.claude/skills/gstack/bin/gstack-question-preference --check "<id>" --summary-stdin` (piped summary feeds the one-way keyword net, #2024). `AUTO_DECIDE` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." `ASK_NORMALLY` means ask.
+Before each AskUserQuestion, choose `question_id` from `~/.claude/skills/gstack/scripts/question-registry.ts` or `{skill}-{slug}`, then run `printf '%s' "<question summary>" | ~/.claude/skills/gstack/bin/gstack-question-preference --check "<id>" --summary-stdin` (piped summary feeds the one-way keyword net, #2024). `AUTO_DECIDE` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." `ASK_NORMALLY` means ask.
**Embed the question_id as a marker in the question text** so hooks can identify it deterministically (plan-tune cathedral T14 / D18 progressive markers). Append `<gstack-qid:{question_id}>` somewhere in the rendered question (the leading line or trailing line is fine; the marker doesn't render visibly to the user when wrapped in HTML-style angle brackets, but the hook strips it). Without the marker the PreToolUse enforcement hook treats the AUQ as observed-only and never auto-decides — so always include it when the question matches a registered `question_id`.
@@ -1803,7 +1809,7 @@ HARD REJECTION — flag if ANY apply:
6. Carousel with no narrative purpose
7. App UI made of stacked cards instead of layout
-Be specific. Reference file:line for every finding." -C "$_REPO_ROOT" -s read-only -c 'model_reasoning_effort="high"' --enable web_search_cached < /dev/null 2>"$TMPERR_DESIGN"
+Be specific. Reference file:line for every finding." -C "$_REPO_ROOT" -s read-only -c 'model_reasoning_effort="high"' -c 'web_search="cached"' < /dev/null 2>"$TMPERR_DESIGN"
```
Use a 5-minute timeout (`timeout: 300000`). After the command completes, read stderr:
```bash
diff --git a/design-shotgun/SKILL.md b/design-shotgun/SKILL.md
index 2ba5556ea..8355271ce 100644
--- a/design-shotgun/SKILL.md
+++ b/design-shotgun/SKILL.md
@@ -129,9 +129,11 @@ else
fi
~/.claude/skills/gstack/bin/gstack-timeline-log '{"skill":"design-shotgun","event":"started","branch":"'"$_BRANCH"'","session":"'"$_SESSION_ID"'"}' 2>/dev/null &
_HAS_ROUTING="no"
-if [ -f CLAUDE.md ] && grep -q "## Skill routing" CLAUDE.md 2>/dev/null; then
- _HAS_ROUTING="yes"
-fi
+for _RF in CLAUDE.md AGENTS.md; do
+ if [ -f "$_RF" ] && grep -q "## Skill routing" "$_RF" 2>/dev/null; then
+ _HAS_ROUTING="yes"
+ fi
+done
_ROUTING_DECLINED=$(~/.claude/skills/gstack/bin/gstack-config get routing_declined 2>/dev/null || echo "false")
echo "HAS_ROUTING: $_HAS_ROUTING"
echo "ROUTING_DECLINED: $_ROUTING_DECLINED"
@@ -525,10 +527,13 @@ _BRAIN_SYNC_MODE=$("$_BRAIN_CONFIG_BIN" get artifacts_sync_mode 2>/dev/null || e
# Detect remote-MCP mode (Path 4 of /setup-gbrain). Local artifacts sync is
# a no-op in remote mode; the brain server pulls from GitHub/GitLab on its
# own cadence. Read claude.json directly to keep this preamble fast (no
-# subprocess to claude CLI on every skill start).
+# subprocess to claude CLI on every skill start). Both registration scopes
+# are read (#2499): user scope, then the nearest-ancestor project scope.
_GBRAIN_MCP_MODE="none"
+_GBRAIN_MCP_ENTRY=""
if command -v jq >/dev/null 2>&1 && [ -f "$HOME/.claude.json" ]; then
- _GBRAIN_MCP_TYPE=$(jq -r '.mcpServers.gbrain.type // .mcpServers.gbrain.transport // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_ENTRY=$(jq -c --arg cwd "$PWD" '.mcpServers.gbrain // ((.projects // {}) | to_entries | map(select((.key as $k | $cwd == $k or ($cwd | startswith($k + "/"))) and ((try .value.mcpServers.gbrain catch null) != null))) | sort_by(.key | length) | last | .value.mcpServers.gbrain) // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_TYPE=$(printf '%s' "$_GBRAIN_MCP_ENTRY" | jq -r '.type // .transport // empty' 2>/dev/null)
case "$_GBRAIN_MCP_TYPE" in
url|http|sse) _GBRAIN_MCP_MODE="remote-http" ;;
stdio) _GBRAIN_MCP_MODE="local-stdio" ;;
@@ -549,6 +554,7 @@ if [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_DO_PULL=1
if [ -f "$_BRAIN_LAST_PULL_FILE" ]; then
_BRAIN_LAST=$(cat "$_BRAIN_LAST_PULL_FILE" 2>/dev/null || echo 0)
+ case "$_BRAIN_LAST" in ''|*[!0-9]*) _BRAIN_LAST=0 ;; esac
_BRAIN_AGE=$(( _BRAIN_NOW - _BRAIN_LAST ))
[ "$_BRAIN_AGE" -lt 86400 ] && _BRAIN_DO_PULL=0
fi
@@ -562,7 +568,7 @@ fi
if [ "$_GBRAIN_MCP_MODE" = "remote-http" ]; then
# Remote-MCP mode: local artifacts sync is a no-op (brain admin's server
# pulls from GitHub/GitLab). Show the user this is by design, not broken.
- _GBRAIN_HOST=$(jq -r '.mcpServers.gbrain.url // empty' "$HOME/.claude.json" 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|')
+ _GBRAIN_HOST=$(printf '%s' "${_GBRAIN_MCP_ENTRY:-}" | jq -r '.url // empty' 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|' | head -1 | tr -cd 'A-Za-z0-9._-')
echo "ARTIFACTS_SYNC: remote-mode (managed by brain server ${_GBRAIN_HOST:-remote})"
elif [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_QUEUE_DEPTH=0
@@ -647,8 +653,8 @@ eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)"
_PROJ="${GSTACK_HOME:-$HOME/.gstack}/projects/${SLUG:-unknown}"
if [ -d "$_PROJ" ]; then
echo "--- RECENT ARTIFACTS ---"
- find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs ls -t 2>/dev/null | head -3
- [ -f "$_PROJ/${_BRANCH}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/${_BRANCH}-reviews.jsonl" | tr -d ' ') entries"
+ find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3
+ [ -f "$_PROJ/${BRANCH:-unknown}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/${BRANCH:-unknown}-reviews.jsonl" | tr -d ' ') entries"
[ -f "$_PROJ/timeline.jsonl" ] && tail -5 "$_PROJ/timeline.jsonl"
if [ -f "$_PROJ/timeline.jsonl" ]; then
_LAST=$(grep "\"branch\":\"${_BRANCH}\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -1)
@@ -656,7 +662,7 @@ if [ -d "$_PROJ" ]; then
_RECENT_SKILLS=$(grep "\"branch\":\"${_BRANCH}\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -3 | grep -o '"skill":"[^"]*"' | sed 's/"skill":"//;s/"//' | tr '\n' ',')
[ -n "$_RECENT_SKILLS" ] && echo "RECENT_PATTERN: $_RECENT_SKILLS"
fi
- _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs ls -t 2>/dev/null | head -1)
+ _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs -r ls -t 2>/dev/null | head -1)
[ -n "$_LATEST_CP" ] && echo "LATEST_CHECKPOINT: $_LATEST_CP"
if [ -f "$_PROJ/decisions.active.json" ]; then
echo "--- ACTIVE DECISIONS (recent, scope-relevant) ---"
@@ -732,7 +738,7 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST
## Question Tuning (skip entirely if `QUESTION_TUNING: false`)
-Before each AskUserQuestion, choose `question_id` from `scripts/question-registry.ts` or `{skill}-{slug}`, then run `printf '%s' "<question summary>" | ~/.claude/skills/gstack/bin/gstack-question-preference --check "<id>" --summary-stdin` (piped summary feeds the one-way keyword net, #2024). `AUTO_DECIDE` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." `ASK_NORMALLY` means ask.
+Before each AskUserQuestion, choose `question_id` from `~/.claude/skills/gstack/scripts/question-registry.ts` or `{skill}-{slug}`, then run `printf '%s' "<question summary>" | ~/.claude/skills/gstack/bin/gstack-question-preference --check "<id>" --summary-stdin` (piped summary feeds the one-way keyword net, #2024). `AUTO_DECIDE` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." `ASK_NORMALLY` means ask.
**Embed the question_id as a marker in the question text** so hooks can identify it deterministically (plan-tune cathedral T14 / D18 progressive markers). Append `<gstack-qid:{question_id}>` somewhere in the rendered question (the leading line or trailing line is fine; the marker doesn't render visibly to the user when wrapped in HTML-style angle brackets, but the hook strips it). Without the marker the PreToolUse enforcement hook treats the AUQ as observed-only and never auto-decides — so always include it when the question matches a registered `question_id`.
diff --git a/devex-review/SKILL.md b/devex-review/SKILL.md
index 80a5a256a..13f7e8cf6 100644
--- a/devex-review/SKILL.md
+++ b/devex-review/SKILL.md
@@ -114,9 +114,11 @@ else
fi
~/.claude/skills/gstack/bin/gstack-timeline-log '{"skill":"devex-review","event":"started","branch":"'"$_BRANCH"'","session":"'"$_SESSION_ID"'"}' 2>/dev/null &
_HAS_ROUTING="no"
-if [ -f CLAUDE.md ] && grep -q "## Skill routing" CLAUDE.md 2>/dev/null; then
- _HAS_ROUTING="yes"
-fi
+for _RF in CLAUDE.md AGENTS.md; do
+ if [ -f "$_RF" ] && grep -q "## Skill routing" "$_RF" 2>/dev/null; then
+ _HAS_ROUTING="yes"
+ fi
+done
_ROUTING_DECLINED=$(~/.claude/skills/gstack/bin/gstack-config get routing_declined 2>/dev/null || echo "false")
echo "HAS_ROUTING: $_HAS_ROUTING"
echo "ROUTING_DECLINED: $_ROUTING_DECLINED"
@@ -510,10 +512,13 @@ _BRAIN_SYNC_MODE=$("$_BRAIN_CONFIG_BIN" get artifacts_sync_mode 2>/dev/null || e
# Detect remote-MCP mode (Path 4 of /setup-gbrain). Local artifacts sync is
# a no-op in remote mode; the brain server pulls from GitHub/GitLab on its
# own cadence. Read claude.json directly to keep this preamble fast (no
-# subprocess to claude CLI on every skill start).
+# subprocess to claude CLI on every skill start). Both registration scopes
+# are read (#2499): user scope, then the nearest-ancestor project scope.
_GBRAIN_MCP_MODE="none"
+_GBRAIN_MCP_ENTRY=""
if command -v jq >/dev/null 2>&1 && [ -f "$HOME/.claude.json" ]; then
- _GBRAIN_MCP_TYPE=$(jq -r '.mcpServers.gbrain.type // .mcpServers.gbrain.transport // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_ENTRY=$(jq -c --arg cwd "$PWD" '.mcpServers.gbrain // ((.projects // {}) | to_entries | map(select((.key as $k | $cwd == $k or ($cwd | startswith($k + "/"))) and ((try .value.mcpServers.gbrain catch null) != null))) | sort_by(.key | length) | last | .value.mcpServers.gbrain) // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_TYPE=$(printf '%s' "$_GBRAIN_MCP_ENTRY" | jq -r '.type // .transport // empty' 2>/dev/null)
case "$_GBRAIN_MCP_TYPE" in
url|http|sse) _GBRAIN_MCP_MODE="remote-http" ;;
stdio) _GBRAIN_MCP_MODE="local-stdio" ;;
@@ -534,6 +539,7 @@ if [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_DO_PULL=1
if [ -f "$_BRAIN_LAST_PULL_FILE" ]; then
_BRAIN_LAST=$(cat "$_BRAIN_LAST_PULL_FILE" 2>/dev/null || echo 0)
+ case "$_BRAIN_LAST" in ''|*[!0-9]*) _BRAIN_LAST=0 ;; esac
_BRAIN_AGE=$(( _BRAIN_NOW - _BRAIN_LAST ))
[ "$_BRAIN_AGE" -lt 86400 ] && _BRAIN_DO_PULL=0
fi
@@ -547,7 +553,7 @@ fi
if [ "$_GBRAIN_MCP_MODE" = "remote-http" ]; then
# Remote-MCP mode: local artifacts sync is a no-op (brain admin's server
# pulls from GitHub/GitLab). Show the user this is by design, not broken.
- _GBRAIN_HOST=$(jq -r '.mcpServers.gbrain.url // empty' "$HOME/.claude.json" 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|')
+ _GBRAIN_HOST=$(printf '%s' "${_GBRAIN_MCP_ENTRY:-}" | jq -r '.url // empty' 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|' | head -1 | tr -cd 'A-Za-z0-9._-')
echo "ARTIFACTS_SYNC: remote-mode (managed by brain server ${_GBRAIN_HOST:-remote})"
elif [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_QUEUE_DEPTH=0
@@ -632,8 +638,8 @@ eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)"
_PROJ="${GSTACK_HOME:-$HOME/.gstack}/projects/${SLUG:-unknown}"
if [ -d "$_PROJ" ]; then
echo "--- RECENT ARTIFACTS ---"
- find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs ls -t 2>/dev/null | head -3
- [ -f "$_PROJ/${_BRANCH}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/${_BRANCH}-reviews.jsonl" | tr -d ' ') entries"
+ find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3
+ [ -f "$_PROJ/${BRANCH:-unknown}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/${BRANCH:-unknown}-reviews.jsonl" | tr -d ' ') entries"
[ -f "$_PROJ/timeline.jsonl" ] && tail -5 "$_PROJ/timeline.jsonl"
if [ -f "$_PROJ/timeline.jsonl" ]; then
_LAST=$(grep "\"branch\":\"${_BRANCH}\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -1)
@@ -641,7 +647,7 @@ if [ -d "$_PROJ" ]; then
_RECENT_SKILLS=$(grep "\"branch\":\"${_BRANCH}\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -3 | grep -o '"skill":"[^"]*"' | sed 's/"skill":"//;s/"//' | tr '\n' ',')
[ -n "$_RECENT_SKILLS" ] && echo "RECENT_PATTERN: $_RECENT_SKILLS"
fi
- _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs ls -t 2>/dev/null | head -1)
+ _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs -r ls -t 2>/dev/null | head -1)
[ -n "$_LATEST_CP" ] && echo "LATEST_CHECKPOINT: $_LATEST_CP"
if [ -f "$_PROJ/decisions.active.json" ]; then
echo "--- ACTIVE DECISIONS (recent, scope-relevant) ---"
@@ -717,7 +723,7 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST
## Question Tuning (skip entirely if `QUESTION_TUNING: false`)
-Before each AskUserQuestion, choose `question_id` from `scripts/question-registry.ts` or `{skill}-{slug}`, then run `printf '%s' "<question summary>" | ~/.claude/skills/gstack/bin/gstack-question-preference --check "<id>" --summary-stdin` (piped summary feeds the one-way keyword net, #2024). `AUTO_DECIDE` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." `ASK_NORMALLY` means ask.
+Before each AskUserQuestion, choose `question_id` from `~/.claude/skills/gstack/scripts/question-registry.ts` or `{skill}-{slug}`, then run `printf '%s' "<question summary>" | ~/.claude/skills/gstack/bin/gstack-question-preference --check "<id>" --summary-stdin` (piped summary feeds the one-way keyword net, #2024). `AUTO_DECIDE` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." `ASK_NORMALLY` means ask.
**Embed the question_id as a marker in the question text** so hooks can identify it deterministically (plan-tune cathedral T14 / D18 progressive markers). Append `<gstack-qid:{question_id}>` somewhere in the rendered question (the leading line or trailing line is fine; the marker doesn't render visibly to the user when wrapped in HTML-style angle brackets, but the hook strips it). Without the marker the PreToolUse enforcement hook treats the AUQ as observed-only and never auto-decides — so always include it when the question matches a registered `question_id`.
diff --git a/diagram/SKILL.md b/diagram/SKILL.md
index 04e681ea1..ae98dd629 100644
--- a/diagram/SKILL.md
+++ b/diagram/SKILL.md
@@ -109,9 +109,11 @@ else
fi
~/.claude/skills/gstack/bin/gstack-timeline-log '{"skill":"diagram","event":"started","branch":"'"$_BRANCH"'","session":"'"$_SESSION_ID"'"}' 2>/dev/null &
_HAS_ROUTING="no"
-if [ -f CLAUDE.md ] && grep -q "## Skill routing" CLAUDE.md 2>/dev/null; then
- _HAS_ROUTING="yes"
-fi
+for _RF in CLAUDE.md AGENTS.md; do
+ if [ -f "$_RF" ] && grep -q "## Skill routing" "$_RF" 2>/dev/null; then
+ _HAS_ROUTING="yes"
+ fi
+done
_ROUTING_DECLINED=$(~/.claude/skills/gstack/bin/gstack-config get routing_declined 2>/dev/null || echo "false")
echo "HAS_ROUTING: $_HAS_ROUTING"
echo "ROUTING_DECLINED: $_ROUTING_DECLINED"
@@ -380,10 +382,13 @@ _BRAIN_SYNC_MODE=$("$_BRAIN_CONFIG_BIN" get artifacts_sync_mode 2>/dev/null || e
# Detect remote-MCP mode (Path 4 of /setup-gbrain). Local artifacts sync is
# a no-op in remote mode; the brain server pulls from GitHub/GitLab on its
# own cadence. Read claude.json directly to keep this preamble fast (no
-# subprocess to claude CLI on every skill start).
+# subprocess to claude CLI on every skill start). Both registration scopes
+# are read (#2499): user scope, then the nearest-ancestor project scope.
_GBRAIN_MCP_MODE="none"
+_GBRAIN_MCP_ENTRY=""
if command -v jq >/dev/null 2>&1 && [ -f "$HOME/.claude.json" ]; then
- _GBRAIN_MCP_TYPE=$(jq -r '.mcpServers.gbrain.type // .mcpServers.gbrain.transport // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_ENTRY=$(jq -c --arg cwd "$PWD" '.mcpServers.gbrain // ((.projects // {}) | to_entries | map(select((.key as $k | $cwd == $k or ($cwd | startswith($k + "/"))) and ((try .value.mcpServers.gbrain catch null) != null))) | sort_by(.key | length) | last | .value.mcpServers.gbrain) // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_TYPE=$(printf '%s' "$_GBRAIN_MCP_ENTRY" | jq -r '.type // .transport // empty' 2>/dev/null)
case "$_GBRAIN_MCP_TYPE" in
url|http|sse) _GBRAIN_MCP_MODE="remote-http" ;;
stdio) _GBRAIN_MCP_MODE="local-stdio" ;;
@@ -404,6 +409,7 @@ if [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_DO_PULL=1
if [ -f "$_BRAIN_LAST_PULL_FILE" ]; then
_BRAIN_LAST=$(cat "$_BRAIN_LAST_PULL_FILE" 2>/dev/null || echo 0)
+ case "$_BRAIN_LAST" in ''|*[!0-9]*) _BRAIN_LAST=0 ;; esac
_BRAIN_AGE=$(( _BRAIN_NOW - _BRAIN_LAST ))
[ "$_BRAIN_AGE" -lt 86400 ] && _BRAIN_DO_PULL=0
fi
@@ -417,7 +423,7 @@ fi
if [ "$_GBRAIN_MCP_MODE" = "remote-http" ]; then
# Remote-MCP mode: local artifacts sync is a no-op (brain admin's server
# pulls from GitHub/GitLab). Show the user this is by design, not broken.
- _GBRAIN_HOST=$(jq -r '.mcpServers.gbrain.url // empty' "$HOME/.claude.json" 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|')
+ _GBRAIN_HOST=$(printf '%s' "${_GBRAIN_MCP_ENTRY:-}" | jq -r '.url // empty' 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|' | head -1 | tr -cd 'A-Za-z0-9._-')
echo "ARTIFACTS_SYNC: remote-mode (managed by brain server ${_GBRAIN_HOST:-remote})"
elif [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_QUEUE_DEPTH=0
diff --git a/document-generate/SKILL.md b/document-generate/SKILL.md
index 9eb9e9278..3f74a926b 100644
--- a/document-generate/SKILL.md
+++ b/document-generate/SKILL.md
@@ -114,9 +114,11 @@ else
fi
~/.claude/skills/gstack/bin/gstack-timeline-log '{"skill":"document-generate","event":"started","branch":"'"$_BRANCH"'","session":"'"$_SESSION_ID"'"}' 2>/dev/null &
_HAS_ROUTING="no"
-if [ -f CLAUDE.md ] && grep -q "## Skill routing" CLAUDE.md 2>/dev/null; then
- _HAS_ROUTING="yes"
-fi
+for _RF in CLAUDE.md AGENTS.md; do
+ if [ -f "$_RF" ] && grep -q "## Skill routing" "$_RF" 2>/dev/null; then
+ _HAS_ROUTING="yes"
+ fi
+done
_ROUTING_DECLINED=$(~/.claude/skills/gstack/bin/gstack-config get routing_declined 2>/dev/null || echo "false")
echo "HAS_ROUTING: $_HAS_ROUTING"
echo "ROUTING_DECLINED: $_ROUTING_DECLINED"
@@ -510,10 +512,13 @@ _BRAIN_SYNC_MODE=$("$_BRAIN_CONFIG_BIN" get artifacts_sync_mode 2>/dev/null || e
# Detect remote-MCP mode (Path 4 of /setup-gbrain). Local artifacts sync is
# a no-op in remote mode; the brain server pulls from GitHub/GitLab on its
# own cadence. Read claude.json directly to keep this preamble fast (no
-# subprocess to claude CLI on every skill start).
+# subprocess to claude CLI on every skill start). Both registration scopes
+# are read (#2499): user scope, then the nearest-ancestor project scope.
_GBRAIN_MCP_MODE="none"
+_GBRAIN_MCP_ENTRY=""
if command -v jq >/dev/null 2>&1 && [ -f "$HOME/.claude.json" ]; then
- _GBRAIN_MCP_TYPE=$(jq -r '.mcpServers.gbrain.type // .mcpServers.gbrain.transport // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_ENTRY=$(jq -c --arg cwd "$PWD" '.mcpServers.gbrain // ((.projects // {}) | to_entries | map(select((.key as $k | $cwd == $k or ($cwd | startswith($k + "/"))) and ((try .value.mcpServers.gbrain catch null) != null))) | sort_by(.key | length) | last | .value.mcpServers.gbrain) // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_TYPE=$(printf '%s' "$_GBRAIN_MCP_ENTRY" | jq -r '.type // .transport // empty' 2>/dev/null)
case "$_GBRAIN_MCP_TYPE" in
url|http|sse) _GBRAIN_MCP_MODE="remote-http" ;;
stdio) _GBRAIN_MCP_MODE="local-stdio" ;;
@@ -534,6 +539,7 @@ if [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_DO_PULL=1
if [ -f "$_BRAIN_LAST_PULL_FILE" ]; then
_BRAIN_LAST=$(cat "$_BRAIN_LAST_PULL_FILE" 2>/dev/null || echo 0)
+ case "$_BRAIN_LAST" in ''|*[!0-9]*) _BRAIN_LAST=0 ;; esac
_BRAIN_AGE=$(( _BRAIN_NOW - _BRAIN_LAST ))
[ "$_BRAIN_AGE" -lt 86400 ] && _BRAIN_DO_PULL=0
fi
@@ -547,7 +553,7 @@ fi
if [ "$_GBRAIN_MCP_MODE" = "remote-http" ]; then
# Remote-MCP mode: local artifacts sync is a no-op (brain admin's server
# pulls from GitHub/GitLab). Show the user this is by design, not broken.
- _GBRAIN_HOST=$(jq -r '.mcpServers.gbrain.url // empty' "$HOME/.claude.json" 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|')
+ _GBRAIN_HOST=$(printf '%s' "${_GBRAIN_MCP_ENTRY:-}" | jq -r '.url // empty' 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|' | head -1 | tr -cd 'A-Za-z0-9._-')
echo "ARTIFACTS_SYNC: remote-mode (managed by brain server ${_GBRAIN_HOST:-remote})"
elif [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_QUEUE_DEPTH=0
@@ -632,8 +638,8 @@ eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)"
_PROJ="${GSTACK_HOME:-$HOME/.gstack}/projects/${SLUG:-unknown}"
if [ -d "$_PROJ" ]; then
echo "--- RECENT ARTIFACTS ---"
- find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs ls -t 2>/dev/null | head -3
- [ -f "$_PROJ/${_BRANCH}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/${_BRANCH}-reviews.jsonl" | tr -d ' ') entries"
+ find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3
+ [ -f "$_PROJ/${BRANCH:-unknown}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/${BRANCH:-unknown}-reviews.jsonl" | tr -d ' ') entries"
[ -f "$_PROJ/timeline.jsonl" ] && tail -5 "$_PROJ/timeline.jsonl"
if [ -f "$_PROJ/timeline.jsonl" ]; then
_LAST=$(grep "\"branch\":\"${_BRANCH}\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -1)
@@ -641,7 +647,7 @@ if [ -d "$_PROJ" ]; then
_RECENT_SKILLS=$(grep "\"branch\":\"${_BRANCH}\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -3 | grep -o '"skill":"[^"]*"' | sed 's/"skill":"//;s/"//' | tr '\n' ',')
[ -n "$_RECENT_SKILLS" ] && echo "RECENT_PATTERN: $_RECENT_SKILLS"
fi
- _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs ls -t 2>/dev/null | head -1)
+ _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs -r ls -t 2>/dev/null | head -1)
[ -n "$_LATEST_CP" ] && echo "LATEST_CHECKPOINT: $_LATEST_CP"
if [ -f "$_PROJ/decisions.active.json" ]; then
echo "--- ACTIVE DECISIONS (recent, scope-relevant) ---"
@@ -717,7 +723,7 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST
## Question Tuning (skip entirely if `QUESTION_TUNING: false`)
-Before each AskUserQuestion, choose `question_id` from `scripts/question-registry.ts` or `{skill}-{slug}`, then run `printf '%s' "<question summary>" | ~/.claude/skills/gstack/bin/gstack-question-preference --check "<id>" --summary-stdin` (piped summary feeds the one-way keyword net, #2024). `AUTO_DECIDE` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." `ASK_NORMALLY` means ask.
+Before each AskUserQuestion, choose `question_id` from `~/.claude/skills/gstack/scripts/question-registry.ts` or `{skill}-{slug}`, then run `printf '%s' "<question summary>" | ~/.claude/skills/gstack/bin/gstack-question-preference --check "<id>" --summary-stdin` (piped summary feeds the one-way keyword net, #2024). `AUTO_DECIDE` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." `ASK_NORMALLY` means ask.
**Embed the question_id as a marker in the question text** so hooks can identify it deterministically (plan-tune cathedral T14 / D18 progressive markers). Append `<gstack-qid:{question_id}>` somewhere in the rendered question (the leading line or trailing line is fine; the marker doesn't render visibly to the user when wrapped in HTML-style angle brackets, but the hook strips it). Without the marker the PreToolUse enforcement hook treats the AUQ as observed-only and never auto-decides — so always include it when the question matches a registered `question_id`.
diff --git a/document-release/SKILL.md b/document-release/SKILL.md
index de8b965c1..bdc4161fa 100644
--- a/document-release/SKILL.md
+++ b/document-release/SKILL.md
@@ -112,9 +112,11 @@ else
fi
~/.claude/skills/gstack/bin/gstack-timeline-log '{"skill":"document-release","event":"started","branch":"'"$_BRANCH"'","session":"'"$_SESSION_ID"'"}' 2>/dev/null &
_HAS_ROUTING="no"
-if [ -f CLAUDE.md ] && grep -q "## Skill routing" CLAUDE.md 2>/dev/null; then
- _HAS_ROUTING="yes"
-fi
+for _RF in CLAUDE.md AGENTS.md; do
+ if [ -f "$_RF" ] && grep -q "## Skill routing" "$_RF" 2>/dev/null; then
+ _HAS_ROUTING="yes"
+ fi
+done
_ROUTING_DECLINED=$(~/.claude/skills/gstack/bin/gstack-config get routing_declined 2>/dev/null || echo "false")
echo "HAS_ROUTING: $_HAS_ROUTING"
echo "ROUTING_DECLINED: $_ROUTING_DECLINED"
@@ -508,10 +510,13 @@ _BRAIN_SYNC_MODE=$("$_BRAIN_CONFIG_BIN" get artifacts_sync_mode 2>/dev/null || e
# Detect remote-MCP mode (Path 4 of /setup-gbrain). Local artifacts sync is
# a no-op in remote mode; the brain server pulls from GitHub/GitLab on its
# own cadence. Read claude.json directly to keep this preamble fast (no
-# subprocess to claude CLI on every skill start).
+# subprocess to claude CLI on every skill start). Both registration scopes
+# are read (#2499): user scope, then the nearest-ancestor project scope.
_GBRAIN_MCP_MODE="none"
+_GBRAIN_MCP_ENTRY=""
if command -v jq >/dev/null 2>&1 && [ -f "$HOME/.claude.json" ]; then
- _GBRAIN_MCP_TYPE=$(jq -r '.mcpServers.gbrain.type // .mcpServers.gbrain.transport // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_ENTRY=$(jq -c --arg cwd "$PWD" '.mcpServers.gbrain // ((.projects // {}) | to_entries | map(select((.key as $k | $cwd == $k or ($cwd | startswith($k + "/"))) and ((try .value.mcpServers.gbrain catch null) != null))) | sort_by(.key | length) | last | .value.mcpServers.gbrain) // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_TYPE=$(printf '%s' "$_GBRAIN_MCP_ENTRY" | jq -r '.type // .transport // empty' 2>/dev/null)
case "$_GBRAIN_MCP_TYPE" in
url|http|sse) _GBRAIN_MCP_MODE="remote-http" ;;
stdio) _GBRAIN_MCP_MODE="local-stdio" ;;
@@ -532,6 +537,7 @@ if [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_DO_PULL=1
if [ -f "$_BRAIN_LAST_PULL_FILE" ]; then
_BRAIN_LAST=$(cat "$_BRAIN_LAST_PULL_FILE" 2>/dev/null || echo 0)
+ case "$_BRAIN_LAST" in ''|*[!0-9]*) _BRAIN_LAST=0 ;; esac
_BRAIN_AGE=$(( _BRAIN_NOW - _BRAIN_LAST ))
[ "$_BRAIN_AGE" -lt 86400 ] && _BRAIN_DO_PULL=0
fi
@@ -545,7 +551,7 @@ fi
if [ "$_GBRAIN_MCP_MODE" = "remote-http" ]; then
# Remote-MCP mode: local artifacts sync is a no-op (brain admin's server
# pulls from GitHub/GitLab). Show the user this is by design, not broken.
- _GBRAIN_HOST=$(jq -r '.mcpServers.gbrain.url // empty' "$HOME/.claude.json" 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|')
+ _GBRAIN_HOST=$(printf '%s' "${_GBRAIN_MCP_ENTRY:-}" | jq -r '.url // empty' 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|' | head -1 | tr -cd 'A-Za-z0-9._-')
echo "ARTIFACTS_SYNC: remote-mode (managed by brain server ${_GBRAIN_HOST:-remote})"
elif [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_QUEUE_DEPTH=0
@@ -630,8 +636,8 @@ eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)"
_PROJ="${GSTACK_HOME:-$HOME/.gstack}/projects/${SLUG:-unknown}"
if [ -d "$_PROJ" ]; then
echo "--- RECENT ARTIFACTS ---"
- find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs ls -t 2>/dev/null | head -3
- [ -f "$_PROJ/${_BRANCH}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/${_BRANCH}-reviews.jsonl" | tr -d ' ') entries"
+ find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3
+ [ -f "$_PROJ/${BRANCH:-unknown}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/${BRANCH:-unknown}-reviews.jsonl" | tr -d ' ') entries"
[ -f "$_PROJ/timeline.jsonl" ] && tail -5 "$_PROJ/timeline.jsonl"
if [ -f "$_PROJ/timeline.jsonl" ]; then
_LAST=$(grep "\"branch\":\"${_BRANCH}\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -1)
@@ -639,7 +645,7 @@ if [ -d "$_PROJ" ]; then
_RECENT_SKILLS=$(grep "\"branch\":\"${_BRANCH}\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -3 | grep -o '"skill":"[^"]*"' | sed 's/"skill":"//;s/"//' | tr '\n' ',')
[ -n "$_RECENT_SKILLS" ] && echo "RECENT_PATTERN: $_RECENT_SKILLS"
fi
- _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs ls -t 2>/dev/null | head -1)
+ _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs -r ls -t 2>/dev/null | head -1)
[ -n "$_LATEST_CP" ] && echo "LATEST_CHECKPOINT: $_LATEST_CP"
if [ -f "$_PROJ/decisions.active.json" ]; then
echo "--- ACTIVE DECISIONS (recent, scope-relevant) ---"
@@ -715,7 +721,7 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST
## Question Tuning (skip entirely if `QUESTION_TUNING: false`)
-Before each AskUserQuestion, choose `question_id` from `scripts/question-registry.ts` or `{skill}-{slug}`, then run `printf '%s' "<question summary>" | ~/.claude/skills/gstack/bin/gstack-question-preference --check "<id>" --summary-stdin` (piped summary feeds the one-way keyword net, #2024). `AUTO_DECIDE` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." `ASK_NORMALLY` means ask.
+Before each AskUserQuestion, choose `question_id` from `~/.claude/skills/gstack/scripts/question-registry.ts` or `{skill}-{slug}`, then run `printf '%s' "<question summary>" | ~/.claude/skills/gstack/bin/gstack-question-preference --check "<id>" --summary-stdin` (piped summary feeds the one-way keyword net, #2024). `AUTO_DECIDE` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." `ASK_NORMALLY` means ask.
**Embed the question_id as a marker in the question text** so hooks can identify it deterministically (plan-tune cathedral T14 / D18 progressive markers). Append `<gstack-qid:{question_id}>` somewhere in the rendered question (the leading line or trailing line is fine; the marker doesn't render visibly to the user when wrapped in HTML-style angle brackets, but the hook strips it). Without the marker the PreToolUse enforcement hook treats the AUQ as observed-only and never auto-decides — so always include it when the question matches a registered `question_id`.
diff --git a/document-release/sections/release-body.md b/document-release/sections/release-body.md
index 6b7124327..1c645c9bc 100644
--- a/document-release/sections/release-body.md
+++ b/document-release/sections/release-body.md
@@ -435,10 +435,20 @@ _CODEX_CFG=$(~/.claude/skills/gstack/bin/gstack-config get codex_reviews 2>/dev/
source ~/.claude/skills/gstack/bin/gstack-codex-probe 2>/dev/null || true
if [ "$_CODEX_CFG" = "disabled" ]; then
_CODEX_MODE="disabled"
+# Running-under-Codex presence probe (#2519): a live Codex session exports
+# CODEX_THREAD_ID / CODEX_SANDBOX into every shell it spawns (verified
+# against a live `codex exec 'env | grep -i codex'` capture, codex 0.147.0).
+# Nested codex spawns from inside a Codex host multiply token burn
+# (observed: one /review = 15M tokens). GSTACK_FORCE_CODEX_REVIEW=1 forces
+# the nested passes anyway.
+elif [ "${GSTACK_FORCE_CODEX_REVIEW:-0}" != "1" ] && { [ -n "${CODEX_THREAD_ID:-}" ] || [ -n "${CODEX_SANDBOX:-}" ]; }; then
+ _CODEX_MODE="under_codex"
elif ! command -v codex >/dev/null 2>&1; then
_CODEX_MODE="not_installed"; _gstack_codex_log_event "codex_cli_missing" 2>/dev/null || true
elif ! _gstack_codex_auth_probe >/dev/null 2>&1; then
_CODEX_MODE="not_authed"; _gstack_codex_log_event "codex_auth_failed" 2>/dev/null || true
+elif ! _gstack_codex_model_probe; then
+ _CODEX_MODE="model_unusable"
else
_CODEX_MODE="ready"; _gstack_codex_version_check 2>/dev/null || true
fi
@@ -448,7 +458,9 @@ echo "CODEX_MODE: $_CODEX_MODE"
Branch on the echoed `CODEX_MODE`:
- **`disabled`** — the user turned Codex reviews off (`codex_reviews=disabled`). Skip this section entirely; do NOT fall back to a Claude subagent — disabled means no extra review step. Print: "Codex review skipped (codex_reviews disabled). Re-enable: `gstack-config set codex_reviews enabled`."
- **`not_installed`** — Codex CLI absent. Print: "Codex not installed — using Claude subagent. Install for cross-model coverage: `npm install -g @openai/codex`." Fall back to the Claude subagent path.
+- **`under_codex`** — this session is already running INSIDE a Codex host, so spawning codex again is the same model reviewing itself at multiplied token cost (#2519). Print exactly one line: "[running under Codex — nested codex passes skipped; set GSTACK_FORCE_CODEX_REVIEW=1 to force]" and skip the codex invocations below; run the section's free in-host pass instead if it defines one.
- **`not_authed`** — installed but no credentials. Print: "Codex installed but not authenticated — using Claude subagent. Run `codex login` or set `$CODEX_API_KEY`." Fall back to the Claude subagent path.
+- **`model_unusable`** — authed but the account cannot use its configured model (#2477: HTTP 400 on every call, usually a stale `model =` pin in `~/.codex/config.toml`). Relay the probe's HINT lines, tell the user the one-line fix (update the pin; `[notice.model_migrations]` names the replacement), and fall back to the Claude subagent path. The ~10s round trip is cached for 1h; timeouts fail open to `ready`.
- **`ready`** — run the Codex pass below.
When the mode is `ready`, `not_installed`, or `not_authed`, print one line so the off-switch
@@ -486,7 +498,7 @@ THE DOCS AND DIFF: <list the touched doc paths>"
```bash
TMPERR_DOC=$(mktemp /tmp/codex-docreview-XXXXXXXX)
_REPO_ROOT=$(git rev-parse --show-toplevel) || { echo "ERROR: not in a git repo" >&2; exit 1; }
-codex exec "<prompt>" -C "$_REPO_ROOT" -s read-only -c 'model_reasoning_effort="high"' --enable web_search_cached < /dev/null 2>"$TMPERR_DOC"
+codex exec "<prompt>" -C "$_REPO_ROOT" -s read-only -c 'model_reasoning_effort="high"' -c 'web_search="cached"' < /dev/null 2>"$TMPERR_DOC"
```
Use a 5-minute timeout (`timeout: 300000`). After the command completes, read stderr:
diff --git a/extension/sidepanel.css b/extension/sidepanel.css
index 0bc306b25..cf9f5beb1 100644
--- a/extension/sidepanel.css
+++ b/extension/sidepanel.css
@@ -47,39 +47,6 @@
--radius-full: 9999px;
}
-/* ─── Security Shield ───────────────────────────────────────────── */
-/* 3 states — green=protected, amber=degraded, red=inactive.
- Custom SVG outline + "SEC" label in JetBrains Mono to match the
- industrial/CLI aesthetic (design review Pass 7 decision). */
-
-.security-shield {
- position: absolute;
- top: 6px;
- right: 8px;
- z-index: 10;
- display: inline-flex;
- align-items: center;
- gap: 4px;
- padding: 2px 6px;
- border-radius: var(--radius-sm, 4px);
- font-family: var(--font-mono, 'JetBrains Mono', monospace);
- font-size: 10px;
- font-weight: 500;
- letter-spacing: 0.04em;
- background: rgba(255, 255, 255, 0.02);
- transition: color 200ms ease-out, background 200ms ease-out;
- cursor: default;
-}
-.security-shield[data-status="protected"] {
- color: var(--success, #22C55E);
-}
-.security-shield[data-status="degraded"] {
- color: var(--amber-400, #FBBF24);
-}
-.security-shield[data-status="inactive"] {
- color: var(--error, #EF4444);
-}
-
/* ─── Connection Banner ─────────────────────────────────────────── */
.conn-banner {
@@ -120,202 +87,11 @@
flex: 1;
}
-/* ─── Security Banner ─────────────────────────────────────────────
- Variant A approved in /plan-design-review 2026-04-19. Centered
- alert-heavy. Fires on security_event — canary leaks + ML BLOCK
- verdicts. Trust UX: layer names + confidence scores in mono so
- the user can see exactly WHY the session was terminated.
-*/
-
-.security-banner {
- position: relative;
- /* Sit above the absolutely-positioned security-shield (z-index: 10) so
- the banner's close button and controls receive clicks. Without this
- the shield at top-right overlaps the banner's close X region and
- intercepts pointer events. */
- z-index: 20;
- padding: 20px 16px;
- text-align: center;
- background: rgba(20, 20, 20, 0.98);
- border-bottom: 1px solid rgba(239, 68, 68, 0.3);
- animation: securityBannerEnter 250ms cubic-bezier(0.16, 1, 0.3, 1);
-}
-
-@keyframes securityBannerEnter {
- from { opacity: 0; transform: translateY(-8px); }
- to { opacity: 1; transform: translateY(0); }
-}
-
-.security-banner-close {
- position: absolute;
- top: 6px;
- right: 6px;
- width: 28px;
- height: 28px;
- background: transparent;
- border: none;
- color: var(--zinc-500, #71717A);
- font-size: 20px;
- line-height: 1;
- cursor: pointer;
- border-radius: var(--radius-md, 8px);
- padding: 0;
-}
-.security-banner-close:hover {
- background: rgba(255, 255, 255, 0.05);
- color: var(--zinc-300, #D4D4D8);
-}
-.security-banner-close:focus-visible {
- outline: 2px solid var(--amber-500);
- outline-offset: 2px;
-}
-
-.security-banner-icon {
- color: var(--error);
- display: flex;
- justify-content: center;
- margin-bottom: 8px;
-}
-
-.security-banner-title {
- font-family: var(--font-display, 'Satoshi', sans-serif);
- font-weight: 700;
- font-size: 18px;
- color: var(--error);
- margin-bottom: 2px;
-}
-
-.security-banner-subtitle {
- font-family: var(--font-body, 'DM Sans', sans-serif);
- font-size: 13px;
- color: var(--zinc-400, #A1A1AA);
- margin-bottom: 12px;
-}
-
-.security-banner-expand {
- display: inline-flex;
- align-items: center;
- gap: 6px;
- background: transparent;
- border: 1px solid rgba(255, 255, 255, 0.08);
- border-radius: var(--radius-md, 8px);
- padding: 6px 12px;
- color: var(--zinc-300, #D4D4D8);
- font-family: var(--font-body, 'DM Sans', sans-serif);
- font-size: 12px;
- cursor: pointer;
-}
-.security-banner-expand:hover {
- background: rgba(255, 255, 255, 0.04);
-}
-.security-banner-expand:focus-visible {
- outline: 2px solid var(--amber-500);
- outline-offset: 2px;
-}
-.security-banner-chevron {
- transition: transform 200ms ease-out;
-}
-
-.security-banner-details {
- margin-top: 12px;
- padding-top: 12px;
- border-top: 1px solid rgba(255, 255, 255, 0.06);
- text-align: left;
-}
-
-.security-banner-section-label {
- font-family: var(--font-mono, 'JetBrains Mono', monospace);
- font-size: 10px;
- letter-spacing: 0.08em;
- color: var(--zinc-500, #71717A);
- margin-bottom: 6px;
-}
-
-.security-banner-layers {
- display: flex;
- flex-direction: column;
- gap: 4px;
-}
-
-.security-banner-layer {
- display: flex;
- justify-content: space-between;
- align-items: center;
- padding: 4px 8px;
- background: rgba(255, 255, 255, 0.02);
- border-radius: var(--radius-sm, 4px);
- font-family: var(--font-mono, 'JetBrains Mono', monospace);
- font-size: 12px;
-}
-
-.security-banner-layer-name {
- color: var(--zinc-300, #D4D4D8);
-}
-
-.security-banner-layer-score {
- color: var(--amber-400);
- font-variant-numeric: tabular-nums;
-}
-
-.security-banner-suspect {
- margin: 4px 0 0;
- padding: 8px 10px;
- background: var(--zinc-900, #18181B);
- border: 1px solid var(--zinc-700, #3F3F46);
- border-radius: var(--radius-sm, 4px);
- font-family: var(--font-mono);
- font-size: 11px;
- line-height: 1.4;
- color: var(--zinc-300, #D4D4D8);
- white-space: pre-wrap;
- word-break: break-word;
- max-height: 160px;
- overflow-y: auto;
-}
-
-.security-banner-actions {
- display: flex;
- gap: 8px;
- justify-content: center;
- margin-top: 14px;
-}
-
-.security-banner-btn {
- flex: 1;
- padding: 8px 14px;
- border-radius: var(--radius-md, 6px);
- font-size: 12px;
- font-weight: 600;
- cursor: pointer;
- border: 1px solid transparent;
- transition: background 0.15s, border-color 0.15s;
-}
-
-.security-banner-btn-block {
- background: var(--red-600, #DC2626);
- color: white;
- border-color: var(--red-700, #B91C1C);
-}
-
-.security-banner-btn-block:hover {
- background: var(--red-700, #B91C1C);
-}
-
-.security-banner-btn-allow {
- background: transparent;
- color: var(--zinc-200, #E4E4E7);
- border-color: var(--zinc-600, #52525B);
-}
+/* The .security-banner component (Variant A, 2026-04-19) was removed with
+ its producer: no JS has created a .security-banner element since the
+ chat-path rip, and the hidden shield it guarded against went in #2557.
+ Restore from git history if the banner UX returns. */
-.security-banner-btn-allow:hover {
- background: var(--zinc-800, #27272A);
- border-color: var(--zinc-500, #71717A);
-}
-
-.security-banner-btn:focus-visible {
- outline: 2px solid var(--amber-400);
- outline-offset: 2px;
-}
.conn-btn {
font-size: 9px;
@@ -1165,7 +941,7 @@ footer {
border-radius: var(--radius-md, 6px);
padding: 12px;
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.4);
- font-family: var(--font-sans);
+ font-family: var(--font-system); /* --font-sans was never defined; the invalid var fell back to inheritance by luck */
font-size: 12px;
}
.mem-toast-header {
@@ -1227,7 +1003,7 @@ footer {
font-size: 12px;
padding: 4px 12px;
}
-.mem-toast-btn:hover { background: var(--zinc-700); }
+.mem-toast-btn:hover { background: var(--zinc-700, #3F3F46); } /* --zinc-700 is undefined in :root; without the fallback this hover computed to transparent */
.mem-toast-btn.primary {
background: #ef4444;
border-color: #ef4444;
diff --git a/extension/sidepanel.html b/extension/sidepanel.html
index b2ce8a1b5..105586c52 100644
--- a/extension/sidepanel.html
+++ b/extension/sidepanel.html
@@ -6,16 +6,6 @@
<link rel="stylesheet" href="lib/xterm.css">
</head>
<body>
- <!-- Security shield — reflects ~/.gstack/security/session-state.json status.
- Hidden until the sidebar knows its state (avoids flicker on first load).
- Consumes /health.security — see browse/src/security.ts getStatus(). -->
- <div class="security-shield" id="security-shield" role="status" aria-label="Security status: unknown" style="display:none" title="Security">
- <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
- <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>
- </svg>
- <span class="security-shield-label" id="security-shield-label">SEC</span>
- </div>
-
<!-- Connection status banner -->
<div class="conn-banner" id="conn-banner" style="display:none">
<span class="conn-banner-text" id="conn-banner-text">Reconnecting...</span>
diff --git a/extension/sidepanel.js b/extension/sidepanel.js
index 98c851334..6209592b3 100644
--- a/extension/sidepanel.js
+++ b/extension/sidepanel.js
@@ -1314,9 +1314,6 @@ async function tryConnect() {
`token: yes (from /extension-token)\nStarting SSE + activity feed...`
);
updateConnection(`http://127.0.0.1:${port}`, tokenData.token);
- // The SEC shield used to drive off /health.security via the chat
- // path's classifier; with the chat path ripped, the indicator is
- // not driven yet. Leaving the shield element hidden by default.
return;
}
setLoadingStatus(
diff --git a/gstack-upgrade/SKILL.md b/gstack-upgrade/SKILL.md
index 9f0f2f7ea..f6c8afee5 100644
--- a/gstack-upgrade/SKILL.md
+++ b/gstack-upgrade/SKILL.md
@@ -128,12 +128,22 @@ Use the install type and directory detected in Step 2:
**For git installs** (global-git, local-git):
```bash
cd "$INSTALL_DIR"
+# Discard render-footprint dirt BEFORE stashing (#2569): pre-v1.67
+# gbrain-enabled installs ran gen:skill-docs:user IN PLACE, leaving
+# generated SKILL.md / sections/*.md files permanently modified. Stashing
+# that dirt poisons the stash: the post-upgrade `git stash pop` would
+# restore STALE generated markdown over the fresh checkout permanently.
+# These files are regenerable (setup re-renders brain-aware variants to
+# ~/.gstack/render), so discarding is lossless; anything else the user
+# changed still reaches the stash untouched. Same file classification as
+# migrations/v1.67.0.0.sh, which remains for manual git-pull flows.
+git checkout -- 'SKILL.md' '*/SKILL.md' '*/sections/*.md' 2>/dev/null || true
STASH_OUTPUT=$(git stash 2>&1)
git fetch origin
git reset --hard origin/main
./setup
```
-If `$STASH_OUTPUT` contains "Saved working directory", warn the user: "Note: local changes were stashed. Run `git stash pop` in the skill directory to restore them."
+If `$STASH_OUTPUT` contains "Saved working directory", warn the user: "Note: local changes were stashed (any modified generated SKILL.md/sections files were discarded first — they regenerate on setup). Run `git stash pop` in the skill directory to restore your own changes."
**For vendored installs** (vendored, vendored-global):
```bash
@@ -210,7 +220,10 @@ if [ -d "$MIGRATIONS_DIR" ]; then
# (simple string compare works for dotted versions with same segment count)
if [ "$OLD_VERSION" != "unknown" ] && [ "$(printf '%s\n%s' "$OLD_VERSION" "$m_ver" | sort -V | head -1)" = "$OLD_VERSION" ] && [ "$OLD_VERSION" != "$m_ver" ]; then
echo "Running migration $m_ver..."
- bash "$migration" || echo " Warning: migration $m_ver had errors (non-fatal)"
+ # GSTACK_INSTALL_DIR: migrations that clean the INSTALL (not just
+ # ~/.gstack state) default to ~/.claude/skills/gstack when unset —
+ # a repo-local install would silently no-op without this.
+ GSTACK_INSTALL_DIR="$INSTALL_DIR" bash "$migration" || echo " Warning: migration $m_ver had errors (non-fatal)"
fi
done
fi
@@ -220,6 +233,50 @@ Migrations are idempotent bash scripts in `gstack-upgrade/migrations/`. Each is
`v{VERSION}.sh` and runs only when upgrading from an older version. See CONTRIBUTING.md
for how to add new migrations.
+### Step 4.8: Stop any stale daemon (unconditional)
+
+A browse daemon started before the upgrade keeps serving the OLD binary's code
+until it is stopped — it survives `git reset --hard` and `./setup` because the
+running process holds the old executable (#2551). Always run this step, using
+the install directory detected in Step 2.
+
+```bash
+INSTALL_DIR_PLACEHOLDER="<install dir from Step 2>"
+NEW_HASH=$(cat "$INSTALL_DIR_PLACEHOLDER/browse/dist/.version" 2>/dev/null || echo "")
+_STATE_FILE="${BROWSE_STATE_FILE:-$(git rev-parse --show-toplevel 2>/dev/null || pwd)/.gstack/browse.json}"
+if [ -z "$NEW_HASH" ] || [ ! -f "$_STATE_FILE" ]; then
+ echo "DAEMON_CHECK=none (no state file or no fresh build hash)"
+else
+ DAEMON_PID=$(sed -n 's/.*"pid"[[:space:]]*:[[:space:]]*\([0-9][0-9]*\).*/\1/p' "$_STATE_FILE" | head -1)
+ DAEMON_PORT=$(sed -n 's/.*"port"[[:space:]]*:[[:space:]]*\([0-9][0-9]*\).*/\1/p' "$_STATE_FILE" | head -1)
+ OLD_HASH=$(sed -n 's/.*"binaryVersion"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$_STATE_FILE" | head -1)
+ if [ -z "$DAEMON_PID" ] || ! kill -0 "$DAEMON_PID" 2>/dev/null; then
+ echo "DAEMON_CHECK=dead (no live daemon to stop)"
+ elif [ "$OLD_HASH" = "$NEW_HASH" ]; then
+ echo "DAEMON_CHECK=current (daemon already runs the new binary)"
+ elif curl -fsS --max-time 2 "http://127.0.0.1:$DAEMON_PORT/health" 2>/dev/null | grep -q '"status":"healthy"'; then
+ echo "DAEMON_CHECK=stale-responsive pid=$DAEMON_PID hash=${OLD_HASH:-unknown} -> $NEW_HASH"
+ "$INSTALL_DIR_PLACEHOLDER/browse/dist/browse" stop && echo "DAEMON_STOPPED=yes"
+ else
+ echo "DAEMON_CHECK=stale-busy pid=$DAEMON_PID hash=${OLD_HASH:-unknown} -> $NEW_HASH"
+ fi
+fi
+```
+
+Replace `<install dir from Step 2>` with the actual install directory before
+running. Interpret the `DAEMON_CHECK` result:
+
+1. **`stale-responsive` + `DAEMON_STOPPED=yes`:** Tell the user "Stopped the
+ old browse daemon (binary {OLD_HASH} → {NEW_HASH}). The next browse command
+ starts a fresh daemon on the new binary."
+2. **`stale-busy`:** The daemon runs the old binary but is mid-work — DEFER to
+ it, never kill a busy daemon during upgrade. Tell the user: "A browse daemon
+ is still running the pre-upgrade binary ({OLD_HASH} → {NEW_HASH}) but is
+ busy right now. When it finishes, stop it with `browse stop` — or force it
+ immediately with `browse --force-restart stop` (loses that session's
+ tabs/cookies/logins)."
+3. **`none` / `dead` / `current`:** Nothing to do — say nothing.
+
### Step 5: Write marker + clear cache
```bash
diff --git a/gstack-upgrade/SKILL.md.tmpl b/gstack-upgrade/SKILL.md.tmpl
index 5402a1da3..adbf29adc 100644
--- a/gstack-upgrade/SKILL.md.tmpl
+++ b/gstack-upgrade/SKILL.md.tmpl
@@ -125,12 +125,22 @@ Use the install type and directory detected in Step 2:
**For git installs** (global-git, local-git):
```bash
cd "$INSTALL_DIR"
+# Discard render-footprint dirt BEFORE stashing (#2569): pre-v1.67
+# gbrain-enabled installs ran gen:skill-docs:user IN PLACE, leaving
+# generated SKILL.md / sections/*.md files permanently modified. Stashing
+# that dirt poisons the stash: the post-upgrade `git stash pop` would
+# restore STALE generated markdown over the fresh checkout permanently.
+# These files are regenerable (setup re-renders brain-aware variants to
+# ~/.gstack/render), so discarding is lossless; anything else the user
+# changed still reaches the stash untouched. Same file classification as
+# migrations/v1.67.0.0.sh, which remains for manual git-pull flows.
+git checkout -- 'SKILL.md' '*/SKILL.md' '*/sections/*.md' 2>/dev/null || true
STASH_OUTPUT=$(git stash 2>&1)
git fetch origin
git reset --hard origin/main
./setup
```
-If `$STASH_OUTPUT` contains "Saved working directory", warn the user: "Note: local changes were stashed. Run `git stash pop` in the skill directory to restore them."
+If `$STASH_OUTPUT` contains "Saved working directory", warn the user: "Note: local changes were stashed (any modified generated SKILL.md/sections files were discarded first — they regenerate on setup). Run `git stash pop` in the skill directory to restore your own changes."
**For vendored installs** (vendored, vendored-global):
```bash
@@ -207,7 +217,10 @@ if [ -d "$MIGRATIONS_DIR" ]; then
# (simple string compare works for dotted versions with same segment count)
if [ "$OLD_VERSION" != "unknown" ] && [ "$(printf '%s\n%s' "$OLD_VERSION" "$m_ver" | sort -V | head -1)" = "$OLD_VERSION" ] && [ "$OLD_VERSION" != "$m_ver" ]; then
echo "Running migration $m_ver..."
- bash "$migration" || echo " Warning: migration $m_ver had errors (non-fatal)"
+ # GSTACK_INSTALL_DIR: migrations that clean the INSTALL (not just
+ # ~/.gstack state) default to ~/.claude/skills/gstack when unset —
+ # a repo-local install would silently no-op without this.
+ GSTACK_INSTALL_DIR="$INSTALL_DIR" bash "$migration" || echo " Warning: migration $m_ver had errors (non-fatal)"
fi
done
fi
@@ -217,6 +230,50 @@ Migrations are idempotent bash scripts in `gstack-upgrade/migrations/`. Each is
`v{VERSION}.sh` and runs only when upgrading from an older version. See CONTRIBUTING.md
for how to add new migrations.
+### Step 4.8: Stop any stale daemon (unconditional)
+
+A browse daemon started before the upgrade keeps serving the OLD binary's code
+until it is stopped — it survives `git reset --hard` and `./setup` because the
+running process holds the old executable (#2551). Always run this step, using
+the install directory detected in Step 2.
+
+```bash
+INSTALL_DIR_PLACEHOLDER="<install dir from Step 2>"
+NEW_HASH=$(cat "$INSTALL_DIR_PLACEHOLDER/browse/dist/.version" 2>/dev/null || echo "")
+_STATE_FILE="${BROWSE_STATE_FILE:-$(git rev-parse --show-toplevel 2>/dev/null || pwd)/.gstack/browse.json}"
+if [ -z "$NEW_HASH" ] || [ ! -f "$_STATE_FILE" ]; then
+ echo "DAEMON_CHECK=none (no state file or no fresh build hash)"
+else
+ DAEMON_PID=$(sed -n 's/.*"pid"[[:space:]]*:[[:space:]]*\([0-9][0-9]*\).*/\1/p' "$_STATE_FILE" | head -1)
+ DAEMON_PORT=$(sed -n 's/.*"port"[[:space:]]*:[[:space:]]*\([0-9][0-9]*\).*/\1/p' "$_STATE_FILE" | head -1)
+ OLD_HASH=$(sed -n 's/.*"binaryVersion"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$_STATE_FILE" | head -1)
+ if [ -z "$DAEMON_PID" ] || ! kill -0 "$DAEMON_PID" 2>/dev/null; then
+ echo "DAEMON_CHECK=dead (no live daemon to stop)"
+ elif [ "$OLD_HASH" = "$NEW_HASH" ]; then
+ echo "DAEMON_CHECK=current (daemon already runs the new binary)"
+ elif curl -fsS --max-time 2 "http://127.0.0.1:$DAEMON_PORT/health" 2>/dev/null | grep -q '"status":"healthy"'; then
+ echo "DAEMON_CHECK=stale-responsive pid=$DAEMON_PID hash=${OLD_HASH:-unknown} -> $NEW_HASH"
+ "$INSTALL_DIR_PLACEHOLDER/browse/dist/browse" stop && echo "DAEMON_STOPPED=yes"
+ else
+ echo "DAEMON_CHECK=stale-busy pid=$DAEMON_PID hash=${OLD_HASH:-unknown} -> $NEW_HASH"
+ fi
+fi
+```
+
+Replace `<install dir from Step 2>` with the actual install directory before
+running. Interpret the `DAEMON_CHECK` result:
+
+1. **`stale-responsive` + `DAEMON_STOPPED=yes`:** Tell the user "Stopped the
+ old browse daemon (binary {OLD_HASH} → {NEW_HASH}). The next browse command
+ starts a fresh daemon on the new binary."
+2. **`stale-busy`:** The daemon runs the old binary but is mid-work — DEFER to
+ it, never kill a busy daemon during upgrade. Tell the user: "A browse daemon
+ is still running the pre-upgrade binary ({OLD_HASH} → {NEW_HASH}) but is
+ busy right now. When it finishes, stop it with `browse stop` — or force it
+ immediately with `browse --force-restart stop` (loses that session's
+ tabs/cookies/logins)."
+3. **`none` / `dead` / `current`:** Nothing to do — say nothing.
+
### Step 5: Write marker + clear cache
```bash
diff --git a/gstack-upgrade/migrations/v1.67.0.0.sh b/gstack-upgrade/migrations/v1.67.0.0.sh
new file mode 100755
index 000000000..b8209e539
--- /dev/null
+++ b/gstack-upgrade/migrations/v1.67.0.0.sh
@@ -0,0 +1,73 @@
+#!/usr/bin/env bash
+# Migration: v1.67.0.0 — restore tracked files dirtied by the legacy in-place
+# gbrain render (#2569, F12).
+#
+# Why a migration: pre-v1.67, gbrain-enabled setups ran `gen:skill-docs:user
+# --host claude` IN PLACE inside the global install checkout
+# (~/.claude/skills/gstack), rewriting ~16 TRACKED SKILL.md files. The
+# checkout stayed permanently dirty, and every /gstack-upgrade `git stash`
+# saved a redundant snapshot of generated content — stashes that invite a
+# dangerous `git stash pop` of stale instruction markdown over a newer
+# version. v1.67 renders to an untracked out-dir (~/.gstack/render/claude)
+# instead, so this migration does the ONE-TIME cleanup of the legacy dirt:
+# `git checkout --` on the modified generated files.
+#
+# Restore scope is deliberately narrow: only UNSTAGED MODIFIED files whose
+# path is a SKILL.md or lives under a sections/ directory — the exact
+# footprint of the legacy render. Anything else a user changed by hand
+# (untracked files, staged work, non-generated edits) is left alone and
+# reported. setup's gbrain step re-renders the brain-aware variant into the
+# out-dir immediately after migrations run, so no capability is lost.
+#
+# Affected: global-git installs that ever ran ./setup or `gstack-config
+# gbrain-refresh` with gbrain detected, before v1.67.0.0.
+#
+# Idempotent: a clean checkout is a no-op. Non-fatal throughout.
+set -u
+
+INSTALL_DIR="${GSTACK_INSTALL_DIR:-$HOME/.claude/skills/gstack}"
+
+# Only operate on a real (non-symlink) git checkout that looks like gstack.
+[ -d "$INSTALL_DIR" ] || exit 0
+[ -L "$INSTALL_DIR" ] && exit 0
+[ -f "$INSTALL_DIR/VERSION" ] || exit 0
+git -C "$INSTALL_DIR" rev-parse --is-inside-work-tree >/dev/null 2>&1 || exit 0
+
+_DIRTY="$(git -C "$INSTALL_DIR" status --porcelain 2>/dev/null || true)"
+[ -n "$_DIRTY" ] || exit 0
+
+_RESTORED=0
+_LEFT=0
+while IFS= read -r _LINE; do
+ [ -n "$_LINE" ] || continue
+ _CODE="${_LINE:0:2}"
+ _PATH="${_LINE:3}"
+ # Legacy render footprint: unstaged modifications to generated markdown.
+ case "$_CODE" in
+ " M")
+ case "$_PATH" in
+ SKILL.md|*/SKILL.md|*/sections/*.md)
+ if git -C "$INSTALL_DIR" checkout -- "$_PATH" 2>/dev/null; then
+ _RESTORED=$((_RESTORED + 1))
+ else
+ _LEFT=$((_LEFT + 1))
+ fi
+ ;;
+ *) _LEFT=$((_LEFT + 1)) ;;
+ esac
+ ;;
+ *) _LEFT=$((_LEFT + 1)) ;;
+ esac
+done <<EOF_DIRTY
+$_DIRTY
+EOF_DIRTY
+
+if [ "$_RESTORED" -gt 0 ]; then
+ echo " v1.67.0.0: restored $_RESTORED tracked file(s) dirtied by the legacy in-place gbrain render (#2569)."
+ echo " Brain-aware blocks now render to ~/.gstack/render/claude — the checkout stays clean from here on."
+fi
+if [ "$_LEFT" -gt 0 ]; then
+ echo " v1.67.0.0: left $_LEFT non-render change(s) in $INSTALL_DIR untouched (not the legacy render footprint)."
+fi
+
+exit 0
diff --git a/health/SKILL.md b/health/SKILL.md
index cf1c3177c..890085f5a 100644
--- a/health/SKILL.md
+++ b/health/SKILL.md
@@ -110,9 +110,11 @@ else
fi
~/.claude/skills/gstack/bin/gstack-timeline-log '{"skill":"health","event":"started","branch":"'"$_BRANCH"'","session":"'"$_SESSION_ID"'"}' 2>/dev/null &
_HAS_ROUTING="no"
-if [ -f CLAUDE.md ] && grep -q "## Skill routing" CLAUDE.md 2>/dev/null; then
- _HAS_ROUTING="yes"
-fi
+for _RF in CLAUDE.md AGENTS.md; do
+ if [ -f "$_RF" ] && grep -q "## Skill routing" "$_RF" 2>/dev/null; then
+ _HAS_ROUTING="yes"
+ fi
+done
_ROUTING_DECLINED=$(~/.claude/skills/gstack/bin/gstack-config get routing_declined 2>/dev/null || echo "false")
echo "HAS_ROUTING: $_HAS_ROUTING"
echo "ROUTING_DECLINED: $_ROUTING_DECLINED"
@@ -506,10 +508,13 @@ _BRAIN_SYNC_MODE=$("$_BRAIN_CONFIG_BIN" get artifacts_sync_mode 2>/dev/null || e
# Detect remote-MCP mode (Path 4 of /setup-gbrain). Local artifacts sync is
# a no-op in remote mode; the brain server pulls from GitHub/GitLab on its
# own cadence. Read claude.json directly to keep this preamble fast (no
-# subprocess to claude CLI on every skill start).
+# subprocess to claude CLI on every skill start). Both registration scopes
+# are read (#2499): user scope, then the nearest-ancestor project scope.
_GBRAIN_MCP_MODE="none"
+_GBRAIN_MCP_ENTRY=""
if command -v jq >/dev/null 2>&1 && [ -f "$HOME/.claude.json" ]; then
- _GBRAIN_MCP_TYPE=$(jq -r '.mcpServers.gbrain.type // .mcpServers.gbrain.transport // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_ENTRY=$(jq -c --arg cwd "$PWD" '.mcpServers.gbrain // ((.projects // {}) | to_entries | map(select((.key as $k | $cwd == $k or ($cwd | startswith($k + "/"))) and ((try .value.mcpServers.gbrain catch null) != null))) | sort_by(.key | length) | last | .value.mcpServers.gbrain) // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_TYPE=$(printf '%s' "$_GBRAIN_MCP_ENTRY" | jq -r '.type // .transport // empty' 2>/dev/null)
case "$_GBRAIN_MCP_TYPE" in
url|http|sse) _GBRAIN_MCP_MODE="remote-http" ;;
stdio) _GBRAIN_MCP_MODE="local-stdio" ;;
@@ -530,6 +535,7 @@ if [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_DO_PULL=1
if [ -f "$_BRAIN_LAST_PULL_FILE" ]; then
_BRAIN_LAST=$(cat "$_BRAIN_LAST_PULL_FILE" 2>/dev/null || echo 0)
+ case "$_BRAIN_LAST" in ''|*[!0-9]*) _BRAIN_LAST=0 ;; esac
_BRAIN_AGE=$(( _BRAIN_NOW - _BRAIN_LAST ))
[ "$_BRAIN_AGE" -lt 86400 ] && _BRAIN_DO_PULL=0
fi
@@ -543,7 +549,7 @@ fi
if [ "$_GBRAIN_MCP_MODE" = "remote-http" ]; then
# Remote-MCP mode: local artifacts sync is a no-op (brain admin's server
# pulls from GitHub/GitLab). Show the user this is by design, not broken.
- _GBRAIN_HOST=$(jq -r '.mcpServers.gbrain.url // empty' "$HOME/.claude.json" 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|')
+ _GBRAIN_HOST=$(printf '%s' "${_GBRAIN_MCP_ENTRY:-}" | jq -r '.url // empty' 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|' | head -1 | tr -cd 'A-Za-z0-9._-')
echo "ARTIFACTS_SYNC: remote-mode (managed by brain server ${_GBRAIN_HOST:-remote})"
elif [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_QUEUE_DEPTH=0
@@ -628,8 +634,8 @@ eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)"
_PROJ="${GSTACK_HOME:-$HOME/.gstack}/projects/${SLUG:-unknown}"
if [ -d "$_PROJ" ]; then
echo "--- RECENT ARTIFACTS ---"
- find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs ls -t 2>/dev/null | head -3
- [ -f "$_PROJ/${_BRANCH}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/${_BRANCH}-reviews.jsonl" | tr -d ' ') entries"
+ find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3
+ [ -f "$_PROJ/${BRANCH:-unknown}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/${BRANCH:-unknown}-reviews.jsonl" | tr -d ' ') entries"
[ -f "$_PROJ/timeline.jsonl" ] && tail -5 "$_PROJ/timeline.jsonl"
if [ -f "$_PROJ/timeline.jsonl" ]; then
_LAST=$(grep "\"branch\":\"${_BRANCH}\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -1)
@@ -637,7 +643,7 @@ if [ -d "$_PROJ" ]; then
_RECENT_SKILLS=$(grep "\"branch\":\"${_BRANCH}\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -3 | grep -o '"skill":"[^"]*"' | sed 's/"skill":"//;s/"//' | tr '\n' ',')
[ -n "$_RECENT_SKILLS" ] && echo "RECENT_PATTERN: $_RECENT_SKILLS"
fi
- _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs ls -t 2>/dev/null | head -1)
+ _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs -r ls -t 2>/dev/null | head -1)
[ -n "$_LATEST_CP" ] && echo "LATEST_CHECKPOINT: $_LATEST_CP"
if [ -f "$_PROJ/decisions.active.json" ]; then
echo "--- ACTIVE DECISIONS (recent, scope-relevant) ---"
@@ -713,7 +719,7 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST
## Question Tuning (skip entirely if `QUESTION_TUNING: false`)
-Before each AskUserQuestion, choose `question_id` from `scripts/question-registry.ts` or `{skill}-{slug}`, then run `printf '%s' "<question summary>" | ~/.claude/skills/gstack/bin/gstack-question-preference --check "<id>" --summary-stdin` (piped summary feeds the one-way keyword net, #2024). `AUTO_DECIDE` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." `ASK_NORMALLY` means ask.
+Before each AskUserQuestion, choose `question_id` from `~/.claude/skills/gstack/scripts/question-registry.ts` or `{skill}-{slug}`, then run `printf '%s' "<question summary>" | ~/.claude/skills/gstack/bin/gstack-question-preference --check "<id>" --summary-stdin` (piped summary feeds the one-way keyword net, #2024). `AUTO_DECIDE` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." `ASK_NORMALLY` means ask.
**Embed the question_id as a marker in the question text** so hooks can identify it deterministically (plan-tune cathedral T14 / D18 progressive markers). Append `<gstack-qid:{question_id}>` somewhere in the rendered question (the leading line or trailing line is fine; the marker doesn't render visibly to the user when wrapped in HTML-style angle brackets, but the hook strips it). Without the marker the PreToolUse enforcement hook treats the AUQ as observed-only and never auto-decides — so always include it when the question matches a registered `question_id`.
diff --git a/hosts/claude/hooks/timeline-stop-hook b/hosts/claude/hooks/timeline-stop-hook
new file mode 100755
index 000000000..2beb36b74
--- /dev/null
+++ b/hosts/claude/hooks/timeline-stop-hook
@@ -0,0 +1,10 @@
+#!/usr/bin/env bash
+# Bash shim — Claude Code hooks run `command` strings via /bin/sh, so this
+# wrapper makes the TypeScript hook executable via bun. Settings.json
+# references this file directly.
+#
+# FAIL-OPEN (F5): a Stop-event telemetry repair must never block the session.
+# Every failure path — bun missing, script crash — still exits 0.
+HERE="$(cd "$(dirname "$0")" && pwd)" || exit 0
+bun "$HERE/timeline-stop-hook.ts" || true
+exit 0
diff --git a/hosts/claude/hooks/timeline-stop-hook.ts b/hosts/claude/hooks/timeline-stop-hook.ts
new file mode 100755
index 000000000..30fca9f8b
--- /dev/null
+++ b/hosts/claude/hooks/timeline-stop-hook.ts
@@ -0,0 +1,216 @@
+#!/usr/bin/env bun
+/**
+ * Stop hook: close dangling "started" timeline entries (#2553).
+ *
+ * The preamble writes {"skill":X,"event":"started",...} at every skill start;
+ * the completion write lives in prose at the END of the skill workflow and is
+ * unenforceable — an interrupted session, a context blowout, or an agent that
+ * simply stops leaves started > completed forever, and the leak is
+ * unrepairable after the fact. This hook runs on Claude Code's Stop event and
+ * appends event:"completed" (outcome "unknown", source "stop-hook") for every
+ * "started" entry in the project's timeline that has no matching "completed".
+ *
+ * FAIL-OPEN CONTRACT (F5) — a telemetry repair must never block a session:
+ * - ALWAYS exits 0, whatever happens (corrupt timeline, missing file, bad
+ * stdin, unreadable slug). Errors go to ~/.gstack/hook-errors.log,
+ * best-effort.
+ * - Internal time budget (~2s): work is bounded up front — the timeline is
+ * skipped entirely over a size cap, only the last TAIL_WINDOW_BYTES are
+ * read and parsed (P3: this hook runs on EVERY Stop event machine-wide,
+ * and a full read+parse scaled to the cap at ~100-300ms/turn), and the
+ * deadline is re-checked before the write. Claude Code's own hook
+ * timeout is the outer belt.
+ * - Append-only: never rewrites timeline.jsonl.
+ * - Tail-window semantics: a dangling "started" older than the last 256KB
+ * of appends belongs to a session long gone — beyond repair interest.
+ * A "completed" is always appended AFTER its "started", so any started
+ * inside the window has its completion inside the window too: the window
+ * can never fabricate a dangling entry, and idempotency holds.
+ *
+ * Correlation limits, on purpose: the preamble's session id is a shell-local
+ * "$$-epoch", not the Claude session id this hook receives, so entries can't
+ * be attributed to THIS session specifically. Closing every dangling entry in
+ * the project is the repair semantics #2553 asks for; a concurrent session
+ * mid-skill in the same project may get its entry closed early, which shows
+ * up as a traceable source:"stop-hook" completion rather than a silent leak.
+ */
+import * as fs from 'fs';
+import * as os from 'os';
+import * as path from 'path';
+import { runBin } from './spawn-bin';
+
+const DEADLINE_MS = 2000;
+const MAX_TIMELINE_BYTES = 10 * 1024 * 1024;
+const TAIL_WINDOW_BYTES = 256 * 1024;
+const startedAt = Date.now();
+
+/**
+ * Read only the last TAIL_WINDOW_BYTES of the timeline (P3). When the window
+ * starts mid-file, the first (partial) line is discarded — its entry is
+ * outside the window by definition. Throws on I/O errors; the caller owns
+ * the fail-open handling.
+ */
+function readTimelineTail(timelinePath: string, size: number): string {
+ const fd = fs.openSync(timelinePath, 'r');
+ try {
+ const offset = Math.max(0, size - TAIL_WINDOW_BYTES);
+ const length = size - offset;
+ const buf = Buffer.alloc(length);
+ const bytesRead = fs.readSync(fd, buf, 0, length, offset);
+ let text = buf.subarray(0, bytesRead).toString('utf8');
+ if (offset > 0) {
+ const firstNewline = text.indexOf('\n');
+ text = firstNewline === -1 ? '' : text.slice(firstNewline + 1);
+ }
+ return text;
+ } finally {
+ fs.closeSync(fd);
+ }
+}
+
+function stateRoot(): string {
+ return process.env.GSTACK_HOME || path.join(os.homedir(), '.gstack');
+}
+
+function logHookError(msg: string): void {
+ try {
+ const root = stateRoot();
+ fs.mkdirSync(root, { recursive: true });
+ fs.appendFileSync(
+ path.join(root, 'hook-errors.log'),
+ `${new Date().toISOString()} timeline-stop-hook: ${msg}\n`,
+ );
+ } catch {
+ // best-effort; never block the session because logging failed
+ }
+}
+
+interface TimelineEntry {
+ skill?: string;
+ event?: string;
+ session?: string;
+ branch?: string;
+ ts?: string;
+}
+
+function main(): void {
+ let cwd = process.cwd();
+ try {
+ const stdin = fs.readFileSync(0, 'utf8');
+ if (stdin.trim()) {
+ const payload = JSON.parse(stdin) as { cwd?: string };
+ if (payload.cwd && fs.existsSync(payload.cwd)) cwd = payload.cwd;
+ }
+ } catch {
+ // Bad/absent stdin: fall through with process.cwd() — repair is still valid.
+ }
+
+ // Resolve the project slug the same way the preamble did (GSTACK_PROJECT_SLUG
+ // override, project-root walk, remote-derived slug).
+ let slug = '';
+ try {
+ const r = runBin('gstack-slug', [], { cwd, encoding: 'utf8', timeout: DEADLINE_MS });
+ const m = (r.stdout ?? '').toString().match(/^SLUG=([A-Za-z0-9._-]+)$/m);
+ if (m) slug = m[1];
+ } catch {
+ // fall through
+ }
+ if (!slug) {
+ logHookError('could not resolve project slug — nothing repaired');
+ return;
+ }
+
+ const timelinePath = path.join(stateRoot(), 'projects', slug, 'timeline.jsonl');
+ let stat: fs.Stats;
+ try {
+ stat = fs.statSync(timelinePath);
+ } catch {
+ return; // no timeline — nothing to repair
+ }
+ if (stat.size === 0) return;
+ if (stat.size > MAX_TIMELINE_BYTES) {
+ logHookError(`timeline over size cap (${stat.size} bytes) — skipped (fail-open)`);
+ return;
+ }
+
+ let raw: string;
+ try {
+ raw = readTimelineTail(timelinePath, stat.size);
+ } catch (err) {
+ logHookError(`could not read timeline: ${err instanceof Error ? err.message : String(err)}`);
+ return;
+ }
+
+ // Corrupt LINES are skipped individually; a fully corrupt file repairs nothing.
+ //
+ // COUNT started vs completed per key rather than treating completed as a
+ // set: keys are not unique per run — legacy entries with no session field
+ // all share the bare-skill key, and the preamble's "$$-epoch" session ids
+ // can collide within the same second. With set semantics, a key where one
+ // run completed and another dangles was NEVER repaired (the lone
+ // completion masked every dangler forever). Closing the count DIFFERENCE
+ // repairs exactly the open runs and stays idempotent: the appended
+ // completions balance the counts, so the next Stop appends nothing.
+ const startedCount = new Map<string, number>();
+ const firstStarted = new Map<string, TimelineEntry>();
+ const completedCount = new Map<string, number>();
+ for (const line of raw.split('\n')) {
+ if (!line.trim()) continue;
+ let entry: TimelineEntry;
+ try {
+ entry = JSON.parse(line) as TimelineEntry;
+ } catch {
+ continue;
+ }
+ if (!entry || typeof entry.skill !== 'string') continue;
+ const key = `${entry.skill}\u0000${entry.session ?? ''}`;
+ if (entry.event === 'started') {
+ startedCount.set(key, (startedCount.get(key) ?? 0) + 1);
+ if (!firstStarted.has(key)) firstStarted.set(key, entry);
+ }
+ if (entry.event === 'completed') {
+ completedCount.set(key, (completedCount.get(key) ?? 0) + 1);
+ }
+ }
+
+ const dangling: Array<[string, TimelineEntry]> = [];
+ for (const [key, count] of startedCount) {
+ const open = count - (completedCount.get(key) ?? 0);
+ const entry = firstStarted.get(key);
+ if (!entry) continue;
+ for (let i = 0; i < open; i++) dangling.push([key, entry]);
+ }
+ if (dangling.length === 0) return;
+
+ if (Date.now() - startedAt > DEADLINE_MS) {
+ logHookError('internal 2s budget exhausted before write — skipped (fail-open)');
+ return;
+ }
+
+ const now = new Date().toISOString();
+ const lines = dangling
+ .map(([, entry]) =>
+ JSON.stringify({
+ skill: entry.skill,
+ event: 'completed',
+ ...(entry.branch ? { branch: entry.branch } : {}),
+ outcome: 'unknown',
+ source: 'stop-hook',
+ ...(entry.session ? { session: entry.session } : {}),
+ ts: now,
+ }),
+ )
+ .join('\n');
+ try {
+ fs.appendFileSync(timelinePath, lines + '\n');
+ } catch (err) {
+ logHookError(`could not append completions: ${err instanceof Error ? err.message : String(err)}`);
+ }
+}
+
+try {
+ main();
+} catch (err) {
+ logHookError(`unexpected: ${err instanceof Error ? (err.stack ?? err.message) : String(err)}`);
+}
+process.exit(0);
diff --git a/investigate/SKILL.md b/investigate/SKILL.md
index 2a7d241c9..abb4f158a 100644
--- a/investigate/SKILL.md
+++ b/investigate/SKILL.md
@@ -149,9 +149,11 @@ else
fi
~/.claude/skills/gstack/bin/gstack-timeline-log '{"skill":"investigate","event":"started","branch":"'"$_BRANCH"'","session":"'"$_SESSION_ID"'"}' 2>/dev/null &
_HAS_ROUTING="no"
-if [ -f CLAUDE.md ] && grep -q "## Skill routing" CLAUDE.md 2>/dev/null; then
- _HAS_ROUTING="yes"
-fi
+for _RF in CLAUDE.md AGENTS.md; do
+ if [ -f "$_RF" ] && grep -q "## Skill routing" "$_RF" 2>/dev/null; then
+ _HAS_ROUTING="yes"
+ fi
+done
_ROUTING_DECLINED=$(~/.claude/skills/gstack/bin/gstack-config get routing_declined 2>/dev/null || echo "false")
echo "HAS_ROUTING: $_HAS_ROUTING"
echo "ROUTING_DECLINED: $_ROUTING_DECLINED"
@@ -545,10 +547,13 @@ _BRAIN_SYNC_MODE=$("$_BRAIN_CONFIG_BIN" get artifacts_sync_mode 2>/dev/null || e
# Detect remote-MCP mode (Path 4 of /setup-gbrain). Local artifacts sync is
# a no-op in remote mode; the brain server pulls from GitHub/GitLab on its
# own cadence. Read claude.json directly to keep this preamble fast (no
-# subprocess to claude CLI on every skill start).
+# subprocess to claude CLI on every skill start). Both registration scopes
+# are read (#2499): user scope, then the nearest-ancestor project scope.
_GBRAIN_MCP_MODE="none"
+_GBRAIN_MCP_ENTRY=""
if command -v jq >/dev/null 2>&1 && [ -f "$HOME/.claude.json" ]; then
- _GBRAIN_MCP_TYPE=$(jq -r '.mcpServers.gbrain.type // .mcpServers.gbrain.transport // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_ENTRY=$(jq -c --arg cwd "$PWD" '.mcpServers.gbrain // ((.projects // {}) | to_entries | map(select((.key as $k | $cwd == $k or ($cwd | startswith($k + "/"))) and ((try .value.mcpServers.gbrain catch null) != null))) | sort_by(.key | length) | last | .value.mcpServers.gbrain) // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_TYPE=$(printf '%s' "$_GBRAIN_MCP_ENTRY" | jq -r '.type // .transport // empty' 2>/dev/null)
case "$_GBRAIN_MCP_TYPE" in
url|http|sse) _GBRAIN_MCP_MODE="remote-http" ;;
stdio) _GBRAIN_MCP_MODE="local-stdio" ;;
@@ -569,6 +574,7 @@ if [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_DO_PULL=1
if [ -f "$_BRAIN_LAST_PULL_FILE" ]; then
_BRAIN_LAST=$(cat "$_BRAIN_LAST_PULL_FILE" 2>/dev/null || echo 0)
+ case "$_BRAIN_LAST" in ''|*[!0-9]*) _BRAIN_LAST=0 ;; esac
_BRAIN_AGE=$(( _BRAIN_NOW - _BRAIN_LAST ))
[ "$_BRAIN_AGE" -lt 86400 ] && _BRAIN_DO_PULL=0
fi
@@ -582,7 +588,7 @@ fi
if [ "$_GBRAIN_MCP_MODE" = "remote-http" ]; then
# Remote-MCP mode: local artifacts sync is a no-op (brain admin's server
# pulls from GitHub/GitLab). Show the user this is by design, not broken.
- _GBRAIN_HOST=$(jq -r '.mcpServers.gbrain.url // empty' "$HOME/.claude.json" 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|')
+ _GBRAIN_HOST=$(printf '%s' "${_GBRAIN_MCP_ENTRY:-}" | jq -r '.url // empty' 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|' | head -1 | tr -cd 'A-Za-z0-9._-')
echo "ARTIFACTS_SYNC: remote-mode (managed by brain server ${_GBRAIN_HOST:-remote})"
elif [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_QUEUE_DEPTH=0
@@ -667,8 +673,8 @@ eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)"
_PROJ="${GSTACK_HOME:-$HOME/.gstack}/projects/${SLUG:-unknown}"
if [ -d "$_PROJ" ]; then
echo "--- RECENT ARTIFACTS ---"
- find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs ls -t 2>/dev/null | head -3
- [ -f "$_PROJ/${_BRANCH}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/${_BRANCH}-reviews.jsonl" | tr -d ' ') entries"
+ find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3
+ [ -f "$_PROJ/${BRANCH:-unknown}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/${BRANCH:-unknown}-reviews.jsonl" | tr -d ' ') entries"
[ -f "$_PROJ/timeline.jsonl" ] && tail -5 "$_PROJ/timeline.jsonl"
if [ -f "$_PROJ/timeline.jsonl" ]; then
_LAST=$(grep "\"branch\":\"${_BRANCH}\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -1)
@@ -676,7 +682,7 @@ if [ -d "$_PROJ" ]; then
_RECENT_SKILLS=$(grep "\"branch\":\"${_BRANCH}\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -3 | grep -o '"skill":"[^"]*"' | sed 's/"skill":"//;s/"//' | tr '\n' ',')
[ -n "$_RECENT_SKILLS" ] && echo "RECENT_PATTERN: $_RECENT_SKILLS"
fi
- _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs ls -t 2>/dev/null | head -1)
+ _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs -r ls -t 2>/dev/null | head -1)
[ -n "$_LATEST_CP" ] && echo "LATEST_CHECKPOINT: $_LATEST_CP"
if [ -f "$_PROJ/decisions.active.json" ]; then
echo "--- ACTIVE DECISIONS (recent, scope-relevant) ---"
@@ -752,7 +758,7 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST
## Question Tuning (skip entirely if `QUESTION_TUNING: false`)
-Before each AskUserQuestion, choose `question_id` from `scripts/question-registry.ts` or `{skill}-{slug}`, then run `printf '%s' "<question summary>" | ~/.claude/skills/gstack/bin/gstack-question-preference --check "<id>" --summary-stdin` (piped summary feeds the one-way keyword net, #2024). `AUTO_DECIDE` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." `ASK_NORMALLY` means ask.
+Before each AskUserQuestion, choose `question_id` from `~/.claude/skills/gstack/scripts/question-registry.ts` or `{skill}-{slug}`, then run `printf '%s' "<question summary>" | ~/.claude/skills/gstack/bin/gstack-question-preference --check "<id>" --summary-stdin` (piped summary feeds the one-way keyword net, #2024). `AUTO_DECIDE` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." `ASK_NORMALLY` means ask.
**Embed the question_id as a marker in the question text** so hooks can identify it deterministically (plan-tune cathedral T14 / D18 progressive markers). Append `<gstack-qid:{question_id}>` somewhere in the rendered question (the leading line or trailing line is fine; the marker doesn't render visibly to the user when wrapped in HTML-style angle brackets, but the hook strips it). Without the marker the PreToolUse enforcement hook treats the AUQ as observed-only and never auto-decides — so always include it when the question matches a registered `question_id`.
diff --git a/ios-clean/SKILL.md b/ios-clean/SKILL.md
index 1d73d8f7b..4964b2a94 100644
--- a/ios-clean/SKILL.md
+++ b/ios-clean/SKILL.md
@@ -112,9 +112,11 @@ else
fi
~/.claude/skills/gstack/bin/gstack-timeline-log '{"skill":"ios-clean","event":"started","branch":"'"$_BRANCH"'","session":"'"$_SESSION_ID"'"}' 2>/dev/null &
_HAS_ROUTING="no"
-if [ -f CLAUDE.md ] && grep -q "## Skill routing" CLAUDE.md 2>/dev/null; then
- _HAS_ROUTING="yes"
-fi
+for _RF in CLAUDE.md AGENTS.md; do
+ if [ -f "$_RF" ] && grep -q "## Skill routing" "$_RF" 2>/dev/null; then
+ _HAS_ROUTING="yes"
+ fi
+done
_ROUTING_DECLINED=$(~/.claude/skills/gstack/bin/gstack-config get routing_declined 2>/dev/null || echo "false")
echo "HAS_ROUTING: $_HAS_ROUTING"
echo "ROUTING_DECLINED: $_ROUTING_DECLINED"
@@ -508,10 +510,13 @@ _BRAIN_SYNC_MODE=$("$_BRAIN_CONFIG_BIN" get artifacts_sync_mode 2>/dev/null || e
# Detect remote-MCP mode (Path 4 of /setup-gbrain). Local artifacts sync is
# a no-op in remote mode; the brain server pulls from GitHub/GitLab on its
# own cadence. Read claude.json directly to keep this preamble fast (no
-# subprocess to claude CLI on every skill start).
+# subprocess to claude CLI on every skill start). Both registration scopes
+# are read (#2499): user scope, then the nearest-ancestor project scope.
_GBRAIN_MCP_MODE="none"
+_GBRAIN_MCP_ENTRY=""
if command -v jq >/dev/null 2>&1 && [ -f "$HOME/.claude.json" ]; then
- _GBRAIN_MCP_TYPE=$(jq -r '.mcpServers.gbrain.type // .mcpServers.gbrain.transport // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_ENTRY=$(jq -c --arg cwd "$PWD" '.mcpServers.gbrain // ((.projects // {}) | to_entries | map(select((.key as $k | $cwd == $k or ($cwd | startswith($k + "/"))) and ((try .value.mcpServers.gbrain catch null) != null))) | sort_by(.key | length) | last | .value.mcpServers.gbrain) // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_TYPE=$(printf '%s' "$_GBRAIN_MCP_ENTRY" | jq -r '.type // .transport // empty' 2>/dev/null)
case "$_GBRAIN_MCP_TYPE" in
url|http|sse) _GBRAIN_MCP_MODE="remote-http" ;;
stdio) _GBRAIN_MCP_MODE="local-stdio" ;;
@@ -532,6 +537,7 @@ if [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_DO_PULL=1
if [ -f "$_BRAIN_LAST_PULL_FILE" ]; then
_BRAIN_LAST=$(cat "$_BRAIN_LAST_PULL_FILE" 2>/dev/null || echo 0)
+ case "$_BRAIN_LAST" in ''|*[!0-9]*) _BRAIN_LAST=0 ;; esac
_BRAIN_AGE=$(( _BRAIN_NOW - _BRAIN_LAST ))
[ "$_BRAIN_AGE" -lt 86400 ] && _BRAIN_DO_PULL=0
fi
@@ -545,7 +551,7 @@ fi
if [ "$_GBRAIN_MCP_MODE" = "remote-http" ]; then
# Remote-MCP mode: local artifacts sync is a no-op (brain admin's server
# pulls from GitHub/GitLab). Show the user this is by design, not broken.
- _GBRAIN_HOST=$(jq -r '.mcpServers.gbrain.url // empty' "$HOME/.claude.json" 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|')
+ _GBRAIN_HOST=$(printf '%s' "${_GBRAIN_MCP_ENTRY:-}" | jq -r '.url // empty' 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|' | head -1 | tr -cd 'A-Za-z0-9._-')
echo "ARTIFACTS_SYNC: remote-mode (managed by brain server ${_GBRAIN_HOST:-remote})"
elif [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_QUEUE_DEPTH=0
@@ -630,8 +636,8 @@ eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)"
_PROJ="${GSTACK_HOME:-$HOME/.gstack}/projects/${SLUG:-unknown}"
if [ -d "$_PROJ" ]; then
echo "--- RECENT ARTIFACTS ---"
- find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs ls -t 2>/dev/null | head -3
- [ -f "$_PROJ/${_BRANCH}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/${_BRANCH}-reviews.jsonl" | tr -d ' ') entries"
+ find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3
+ [ -f "$_PROJ/${BRANCH:-unknown}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/${BRANCH:-unknown}-reviews.jsonl" | tr -d ' ') entries"
[ -f "$_PROJ/timeline.jsonl" ] && tail -5 "$_PROJ/timeline.jsonl"
if [ -f "$_PROJ/timeline.jsonl" ]; then
_LAST=$(grep "\"branch\":\"${_BRANCH}\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -1)
@@ -639,7 +645,7 @@ if [ -d "$_PROJ" ]; then
_RECENT_SKILLS=$(grep "\"branch\":\"${_BRANCH}\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -3 | grep -o '"skill":"[^"]*"' | sed 's/"skill":"//;s/"//' | tr '\n' ',')
[ -n "$_RECENT_SKILLS" ] && echo "RECENT_PATTERN: $_RECENT_SKILLS"
fi
- _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs ls -t 2>/dev/null | head -1)
+ _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs -r ls -t 2>/dev/null | head -1)
[ -n "$_LATEST_CP" ] && echo "LATEST_CHECKPOINT: $_LATEST_CP"
if [ -f "$_PROJ/decisions.active.json" ]; then
echo "--- ACTIVE DECISIONS (recent, scope-relevant) ---"
@@ -715,7 +721,7 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST
## Question Tuning (skip entirely if `QUESTION_TUNING: false`)
-Before each AskUserQuestion, choose `question_id` from `scripts/question-registry.ts` or `{skill}-{slug}`, then run `printf '%s' "<question summary>" | ~/.claude/skills/gstack/bin/gstack-question-preference --check "<id>" --summary-stdin` (piped summary feeds the one-way keyword net, #2024). `AUTO_DECIDE` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." `ASK_NORMALLY` means ask.
+Before each AskUserQuestion, choose `question_id` from `~/.claude/skills/gstack/scripts/question-registry.ts` or `{skill}-{slug}`, then run `printf '%s' "<question summary>" | ~/.claude/skills/gstack/bin/gstack-question-preference --check "<id>" --summary-stdin` (piped summary feeds the one-way keyword net, #2024). `AUTO_DECIDE` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." `ASK_NORMALLY` means ask.
**Embed the question_id as a marker in the question text** so hooks can identify it deterministically (plan-tune cathedral T14 / D18 progressive markers). Append `<gstack-qid:{question_id}>` somewhere in the rendered question (the leading line or trailing line is fine; the marker doesn't render visibly to the user when wrapped in HTML-style angle brackets, but the hook strips it). Without the marker the PreToolUse enforcement hook treats the AUQ as observed-only and never auto-decides — so always include it when the question matches a registered `question_id`.
diff --git a/ios-design-review/SKILL.md b/ios-design-review/SKILL.md
index 8cdc8a024..9d35d967a 100644
--- a/ios-design-review/SKILL.md
+++ b/ios-design-review/SKILL.md
@@ -114,9 +114,11 @@ else
fi
~/.claude/skills/gstack/bin/gstack-timeline-log '{"skill":"ios-design-review","event":"started","branch":"'"$_BRANCH"'","session":"'"$_SESSION_ID"'"}' 2>/dev/null &
_HAS_ROUTING="no"
-if [ -f CLAUDE.md ] && grep -q "## Skill routing" CLAUDE.md 2>/dev/null; then
- _HAS_ROUTING="yes"
-fi
+for _RF in CLAUDE.md AGENTS.md; do
+ if [ -f "$_RF" ] && grep -q "## Skill routing" "$_RF" 2>/dev/null; then
+ _HAS_ROUTING="yes"
+ fi
+done
_ROUTING_DECLINED=$(~/.claude/skills/gstack/bin/gstack-config get routing_declined 2>/dev/null || echo "false")
echo "HAS_ROUTING: $_HAS_ROUTING"
echo "ROUTING_DECLINED: $_ROUTING_DECLINED"
@@ -510,10 +512,13 @@ _BRAIN_SYNC_MODE=$("$_BRAIN_CONFIG_BIN" get artifacts_sync_mode 2>/dev/null || e
# Detect remote-MCP mode (Path 4 of /setup-gbrain). Local artifacts sync is
# a no-op in remote mode; the brain server pulls from GitHub/GitLab on its
# own cadence. Read claude.json directly to keep this preamble fast (no
-# subprocess to claude CLI on every skill start).
+# subprocess to claude CLI on every skill start). Both registration scopes
+# are read (#2499): user scope, then the nearest-ancestor project scope.
_GBRAIN_MCP_MODE="none"
+_GBRAIN_MCP_ENTRY=""
if command -v jq >/dev/null 2>&1 && [ -f "$HOME/.claude.json" ]; then
- _GBRAIN_MCP_TYPE=$(jq -r '.mcpServers.gbrain.type // .mcpServers.gbrain.transport // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_ENTRY=$(jq -c --arg cwd "$PWD" '.mcpServers.gbrain // ((.projects // {}) | to_entries | map(select((.key as $k | $cwd == $k or ($cwd | startswith($k + "/"))) and ((try .value.mcpServers.gbrain catch null) != null))) | sort_by(.key | length) | last | .value.mcpServers.gbrain) // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_TYPE=$(printf '%s' "$_GBRAIN_MCP_ENTRY" | jq -r '.type // .transport // empty' 2>/dev/null)
case "$_GBRAIN_MCP_TYPE" in
url|http|sse) _GBRAIN_MCP_MODE="remote-http" ;;
stdio) _GBRAIN_MCP_MODE="local-stdio" ;;
@@ -534,6 +539,7 @@ if [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_DO_PULL=1
if [ -f "$_BRAIN_LAST_PULL_FILE" ]; then
_BRAIN_LAST=$(cat "$_BRAIN_LAST_PULL_FILE" 2>/dev/null || echo 0)
+ case "$_BRAIN_LAST" in ''|*[!0-9]*) _BRAIN_LAST=0 ;; esac
_BRAIN_AGE=$(( _BRAIN_NOW - _BRAIN_LAST ))
[ "$_BRAIN_AGE" -lt 86400 ] && _BRAIN_DO_PULL=0
fi
@@ -547,7 +553,7 @@ fi
if [ "$_GBRAIN_MCP_MODE" = "remote-http" ]; then
# Remote-MCP mode: local artifacts sync is a no-op (brain admin's server
# pulls from GitHub/GitLab). Show the user this is by design, not broken.
- _GBRAIN_HOST=$(jq -r '.mcpServers.gbrain.url // empty' "$HOME/.claude.json" 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|')
+ _GBRAIN_HOST=$(printf '%s' "${_GBRAIN_MCP_ENTRY:-}" | jq -r '.url // empty' 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|' | head -1 | tr -cd 'A-Za-z0-9._-')
echo "ARTIFACTS_SYNC: remote-mode (managed by brain server ${_GBRAIN_HOST:-remote})"
elif [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_QUEUE_DEPTH=0
@@ -632,8 +638,8 @@ eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)"
_PROJ="${GSTACK_HOME:-$HOME/.gstack}/projects/${SLUG:-unknown}"
if [ -d "$_PROJ" ]; then
echo "--- RECENT ARTIFACTS ---"
- find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs ls -t 2>/dev/null | head -3
- [ -f "$_PROJ/${_BRANCH}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/${_BRANCH}-reviews.jsonl" | tr -d ' ') entries"
+ find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3
+ [ -f "$_PROJ/${BRANCH:-unknown}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/${BRANCH:-unknown}-reviews.jsonl" | tr -d ' ') entries"
[ -f "$_PROJ/timeline.jsonl" ] && tail -5 "$_PROJ/timeline.jsonl"
if [ -f "$_PROJ/timeline.jsonl" ]; then
_LAST=$(grep "\"branch\":\"${_BRANCH}\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -1)
@@ -641,7 +647,7 @@ if [ -d "$_PROJ" ]; then
_RECENT_SKILLS=$(grep "\"branch\":\"${_BRANCH}\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -3 | grep -o '"skill":"[^"]*"' | sed 's/"skill":"//;s/"//' | tr '\n' ',')
[ -n "$_RECENT_SKILLS" ] && echo "RECENT_PATTERN: $_RECENT_SKILLS"
fi
- _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs ls -t 2>/dev/null | head -1)
+ _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs -r ls -t 2>/dev/null | head -1)
[ -n "$_LATEST_CP" ] && echo "LATEST_CHECKPOINT: $_LATEST_CP"
if [ -f "$_PROJ/decisions.active.json" ]; then
echo "--- ACTIVE DECISIONS (recent, scope-relevant) ---"
@@ -717,7 +723,7 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST
## Question Tuning (skip entirely if `QUESTION_TUNING: false`)
-Before each AskUserQuestion, choose `question_id` from `scripts/question-registry.ts` or `{skill}-{slug}`, then run `printf '%s' "<question summary>" | ~/.claude/skills/gstack/bin/gstack-question-preference --check "<id>" --summary-stdin` (piped summary feeds the one-way keyword net, #2024). `AUTO_DECIDE` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." `ASK_NORMALLY` means ask.
+Before each AskUserQuestion, choose `question_id` from `~/.claude/skills/gstack/scripts/question-registry.ts` or `{skill}-{slug}`, then run `printf '%s' "<question summary>" | ~/.claude/skills/gstack/bin/gstack-question-preference --check "<id>" --summary-stdin` (piped summary feeds the one-way keyword net, #2024). `AUTO_DECIDE` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." `ASK_NORMALLY` means ask.
**Embed the question_id as a marker in the question text** so hooks can identify it deterministically (plan-tune cathedral T14 / D18 progressive markers). Append `<gstack-qid:{question_id}>` somewhere in the rendered question (the leading line or trailing line is fine; the marker doesn't render visibly to the user when wrapped in HTML-style angle brackets, but the hook strips it). Without the marker the PreToolUse enforcement hook treats the AUQ as observed-only and never auto-decides — so always include it when the question matches a registered `question_id`.
diff --git a/ios-fix/SKILL.md b/ios-fix/SKILL.md
index 6857d49af..777e9879e 100644
--- a/ios-fix/SKILL.md
+++ b/ios-fix/SKILL.md
@@ -115,9 +115,11 @@ else
fi
~/.claude/skills/gstack/bin/gstack-timeline-log '{"skill":"ios-fix","event":"started","branch":"'"$_BRANCH"'","session":"'"$_SESSION_ID"'"}' 2>/dev/null &
_HAS_ROUTING="no"
-if [ -f CLAUDE.md ] && grep -q "## Skill routing" CLAUDE.md 2>/dev/null; then
- _HAS_ROUTING="yes"
-fi
+for _RF in CLAUDE.md AGENTS.md; do
+ if [ -f "$_RF" ] && grep -q "## Skill routing" "$_RF" 2>/dev/null; then
+ _HAS_ROUTING="yes"
+ fi
+done
_ROUTING_DECLINED=$(~/.claude/skills/gstack/bin/gstack-config get routing_declined 2>/dev/null || echo "false")
echo "HAS_ROUTING: $_HAS_ROUTING"
echo "ROUTING_DECLINED: $_ROUTING_DECLINED"
@@ -511,10 +513,13 @@ _BRAIN_SYNC_MODE=$("$_BRAIN_CONFIG_BIN" get artifacts_sync_mode 2>/dev/null || e
# Detect remote-MCP mode (Path 4 of /setup-gbrain). Local artifacts sync is
# a no-op in remote mode; the brain server pulls from GitHub/GitLab on its
# own cadence. Read claude.json directly to keep this preamble fast (no
-# subprocess to claude CLI on every skill start).
+# subprocess to claude CLI on every skill start). Both registration scopes
+# are read (#2499): user scope, then the nearest-ancestor project scope.
_GBRAIN_MCP_MODE="none"
+_GBRAIN_MCP_ENTRY=""
if command -v jq >/dev/null 2>&1 && [ -f "$HOME/.claude.json" ]; then
- _GBRAIN_MCP_TYPE=$(jq -r '.mcpServers.gbrain.type // .mcpServers.gbrain.transport // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_ENTRY=$(jq -c --arg cwd "$PWD" '.mcpServers.gbrain // ((.projects // {}) | to_entries | map(select((.key as $k | $cwd == $k or ($cwd | startswith($k + "/"))) and ((try .value.mcpServers.gbrain catch null) != null))) | sort_by(.key | length) | last | .value.mcpServers.gbrain) // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_TYPE=$(printf '%s' "$_GBRAIN_MCP_ENTRY" | jq -r '.type // .transport // empty' 2>/dev/null)
case "$_GBRAIN_MCP_TYPE" in
url|http|sse) _GBRAIN_MCP_MODE="remote-http" ;;
stdio) _GBRAIN_MCP_MODE="local-stdio" ;;
@@ -535,6 +540,7 @@ if [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_DO_PULL=1
if [ -f "$_BRAIN_LAST_PULL_FILE" ]; then
_BRAIN_LAST=$(cat "$_BRAIN_LAST_PULL_FILE" 2>/dev/null || echo 0)
+ case "$_BRAIN_LAST" in ''|*[!0-9]*) _BRAIN_LAST=0 ;; esac
_BRAIN_AGE=$(( _BRAIN_NOW - _BRAIN_LAST ))
[ "$_BRAIN_AGE" -lt 86400 ] && _BRAIN_DO_PULL=0
fi
@@ -548,7 +554,7 @@ fi
if [ "$_GBRAIN_MCP_MODE" = "remote-http" ]; then
# Remote-MCP mode: local artifacts sync is a no-op (brain admin's server
# pulls from GitHub/GitLab). Show the user this is by design, not broken.
- _GBRAIN_HOST=$(jq -r '.mcpServers.gbrain.url // empty' "$HOME/.claude.json" 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|')
+ _GBRAIN_HOST=$(printf '%s' "${_GBRAIN_MCP_ENTRY:-}" | jq -r '.url // empty' 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|' | head -1 | tr -cd 'A-Za-z0-9._-')
echo "ARTIFACTS_SYNC: remote-mode (managed by brain server ${_GBRAIN_HOST:-remote})"
elif [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_QUEUE_DEPTH=0
@@ -633,8 +639,8 @@ eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)"
_PROJ="${GSTACK_HOME:-$HOME/.gstack}/projects/${SLUG:-unknown}"
if [ -d "$_PROJ" ]; then
echo "--- RECENT ARTIFACTS ---"
- find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs ls -t 2>/dev/null | head -3
- [ -f "$_PROJ/${_BRANCH}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/${_BRANCH}-reviews.jsonl" | tr -d ' ') entries"
+ find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3
+ [ -f "$_PROJ/${BRANCH:-unknown}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/${BRANCH:-unknown}-reviews.jsonl" | tr -d ' ') entries"
[ -f "$_PROJ/timeline.jsonl" ] && tail -5 "$_PROJ/timeline.jsonl"
if [ -f "$_PROJ/timeline.jsonl" ]; then
_LAST=$(grep "\"branch\":\"${_BRANCH}\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -1)
@@ -642,7 +648,7 @@ if [ -d "$_PROJ" ]; then
_RECENT_SKILLS=$(grep "\"branch\":\"${_BRANCH}\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -3 | grep -o '"skill":"[^"]*"' | sed 's/"skill":"//;s/"//' | tr '\n' ',')
[ -n "$_RECENT_SKILLS" ] && echo "RECENT_PATTERN: $_RECENT_SKILLS"
fi
- _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs ls -t 2>/dev/null | head -1)
+ _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs -r ls -t 2>/dev/null | head -1)
[ -n "$_LATEST_CP" ] && echo "LATEST_CHECKPOINT: $_LATEST_CP"
if [ -f "$_PROJ/decisions.active.json" ]; then
echo "--- ACTIVE DECISIONS (recent, scope-relevant) ---"
@@ -718,7 +724,7 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST
## Question Tuning (skip entirely if `QUESTION_TUNING: false`)
-Before each AskUserQuestion, choose `question_id` from `scripts/question-registry.ts` or `{skill}-{slug}`, then run `printf '%s' "<question summary>" | ~/.claude/skills/gstack/bin/gstack-question-preference --check "<id>" --summary-stdin` (piped summary feeds the one-way keyword net, #2024). `AUTO_DECIDE` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." `ASK_NORMALLY` means ask.
+Before each AskUserQuestion, choose `question_id` from `~/.claude/skills/gstack/scripts/question-registry.ts` or `{skill}-{slug}`, then run `printf '%s' "<question summary>" | ~/.claude/skills/gstack/bin/gstack-question-preference --check "<id>" --summary-stdin` (piped summary feeds the one-way keyword net, #2024). `AUTO_DECIDE` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." `ASK_NORMALLY` means ask.
**Embed the question_id as a marker in the question text** so hooks can identify it deterministically (plan-tune cathedral T14 / D18 progressive markers). Append `<gstack-qid:{question_id}>` somewhere in the rendered question (the leading line or trailing line is fine; the marker doesn't render visibly to the user when wrapped in HTML-style angle brackets, but the hook strips it). Without the marker the PreToolUse enforcement hook treats the AUQ as observed-only and never auto-decides — so always include it when the question matches a registered `question_id`.
diff --git a/ios-qa/SKILL.md b/ios-qa/SKILL.md
index 5540914be..2d9c29594 100644
--- a/ios-qa/SKILL.md
+++ b/ios-qa/SKILL.md
@@ -118,9 +118,11 @@ else
fi
~/.claude/skills/gstack/bin/gstack-timeline-log '{"skill":"ios-qa","event":"started","branch":"'"$_BRANCH"'","session":"'"$_SESSION_ID"'"}' 2>/dev/null &
_HAS_ROUTING="no"
-if [ -f CLAUDE.md ] && grep -q "## Skill routing" CLAUDE.md 2>/dev/null; then
- _HAS_ROUTING="yes"
-fi
+for _RF in CLAUDE.md AGENTS.md; do
+ if [ -f "$_RF" ] && grep -q "## Skill routing" "$_RF" 2>/dev/null; then
+ _HAS_ROUTING="yes"
+ fi
+done
_ROUTING_DECLINED=$(~/.claude/skills/gstack/bin/gstack-config get routing_declined 2>/dev/null || echo "false")
echo "HAS_ROUTING: $_HAS_ROUTING"
echo "ROUTING_DECLINED: $_ROUTING_DECLINED"
@@ -514,10 +516,13 @@ _BRAIN_SYNC_MODE=$("$_BRAIN_CONFIG_BIN" get artifacts_sync_mode 2>/dev/null || e
# Detect remote-MCP mode (Path 4 of /setup-gbrain). Local artifacts sync is
# a no-op in remote mode; the brain server pulls from GitHub/GitLab on its
# own cadence. Read claude.json directly to keep this preamble fast (no
-# subprocess to claude CLI on every skill start).
+# subprocess to claude CLI on every skill start). Both registration scopes
+# are read (#2499): user scope, then the nearest-ancestor project scope.
_GBRAIN_MCP_MODE="none"
+_GBRAIN_MCP_ENTRY=""
if command -v jq >/dev/null 2>&1 && [ -f "$HOME/.claude.json" ]; then
- _GBRAIN_MCP_TYPE=$(jq -r '.mcpServers.gbrain.type // .mcpServers.gbrain.transport // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_ENTRY=$(jq -c --arg cwd "$PWD" '.mcpServers.gbrain // ((.projects // {}) | to_entries | map(select((.key as $k | $cwd == $k or ($cwd | startswith($k + "/"))) and ((try .value.mcpServers.gbrain catch null) != null))) | sort_by(.key | length) | last | .value.mcpServers.gbrain) // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_TYPE=$(printf '%s' "$_GBRAIN_MCP_ENTRY" | jq -r '.type // .transport // empty' 2>/dev/null)
case "$_GBRAIN_MCP_TYPE" in
url|http|sse) _GBRAIN_MCP_MODE="remote-http" ;;
stdio) _GBRAIN_MCP_MODE="local-stdio" ;;
@@ -538,6 +543,7 @@ if [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_DO_PULL=1
if [ -f "$_BRAIN_LAST_PULL_FILE" ]; then
_BRAIN_LAST=$(cat "$_BRAIN_LAST_PULL_FILE" 2>/dev/null || echo 0)
+ case "$_BRAIN_LAST" in ''|*[!0-9]*) _BRAIN_LAST=0 ;; esac
_BRAIN_AGE=$(( _BRAIN_NOW - _BRAIN_LAST ))
[ "$_BRAIN_AGE" -lt 86400 ] && _BRAIN_DO_PULL=0
fi
@@ -551,7 +557,7 @@ fi
if [ "$_GBRAIN_MCP_MODE" = "remote-http" ]; then
# Remote-MCP mode: local artifacts sync is a no-op (brain admin's server
# pulls from GitHub/GitLab). Show the user this is by design, not broken.
- _GBRAIN_HOST=$(jq -r '.mcpServers.gbrain.url // empty' "$HOME/.claude.json" 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|')
+ _GBRAIN_HOST=$(printf '%s' "${_GBRAIN_MCP_ENTRY:-}" | jq -r '.url // empty' 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|' | head -1 | tr -cd 'A-Za-z0-9._-')
echo "ARTIFACTS_SYNC: remote-mode (managed by brain server ${_GBRAIN_HOST:-remote})"
elif [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_QUEUE_DEPTH=0
@@ -636,8 +642,8 @@ eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)"
_PROJ="${GSTACK_HOME:-$HOME/.gstack}/projects/${SLUG:-unknown}"
if [ -d "$_PROJ" ]; then
echo "--- RECENT ARTIFACTS ---"
- find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs ls -t 2>/dev/null | head -3
- [ -f "$_PROJ/${_BRANCH}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/${_BRANCH}-reviews.jsonl" | tr -d ' ') entries"
+ find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3
+ [ -f "$_PROJ/${BRANCH:-unknown}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/${BRANCH:-unknown}-reviews.jsonl" | tr -d ' ') entries"
[ -f "$_PROJ/timeline.jsonl" ] && tail -5 "$_PROJ/timeline.jsonl"
if [ -f "$_PROJ/timeline.jsonl" ]; then
_LAST=$(grep "\"branch\":\"${_BRANCH}\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -1)
@@ -645,7 +651,7 @@ if [ -d "$_PROJ" ]; then
_RECENT_SKILLS=$(grep "\"branch\":\"${_BRANCH}\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -3 | grep -o '"skill":"[^"]*"' | sed 's/"skill":"//;s/"//' | tr '\n' ',')
[ -n "$_RECENT_SKILLS" ] && echo "RECENT_PATTERN: $_RECENT_SKILLS"
fi
- _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs ls -t 2>/dev/null | head -1)
+ _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs -r ls -t 2>/dev/null | head -1)
[ -n "$_LATEST_CP" ] && echo "LATEST_CHECKPOINT: $_LATEST_CP"
if [ -f "$_PROJ/decisions.active.json" ]; then
echo "--- ACTIVE DECISIONS (recent, scope-relevant) ---"
@@ -721,7 +727,7 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST
## Question Tuning (skip entirely if `QUESTION_TUNING: false`)
-Before each AskUserQuestion, choose `question_id` from `scripts/question-registry.ts` or `{skill}-{slug}`, then run `printf '%s' "<question summary>" | ~/.claude/skills/gstack/bin/gstack-question-preference --check "<id>" --summary-stdin` (piped summary feeds the one-way keyword net, #2024). `AUTO_DECIDE` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." `ASK_NORMALLY` means ask.
+Before each AskUserQuestion, choose `question_id` from `~/.claude/skills/gstack/scripts/question-registry.ts` or `{skill}-{slug}`, then run `printf '%s' "<question summary>" | ~/.claude/skills/gstack/bin/gstack-question-preference --check "<id>" --summary-stdin` (piped summary feeds the one-way keyword net, #2024). `AUTO_DECIDE` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." `ASK_NORMALLY` means ask.
**Embed the question_id as a marker in the question text** so hooks can identify it deterministically (plan-tune cathedral T14 / D18 progressive markers). Append `<gstack-qid:{question_id}>` somewhere in the rendered question (the leading line or trailing line is fine; the marker doesn't render visibly to the user when wrapped in HTML-style angle brackets, but the hook strips it). Without the marker the PreToolUse enforcement hook treats the AUQ as observed-only and never auto-decides — so always include it when the question matches a registered `question_id`.
@@ -880,7 +886,20 @@ fi
## Phase 1: Read source, plan codegen
-1. Walk the app source (passed as `--source <dir>`) and identify all `@Observable`
+1. Before changing the app or replacing an installed build, verify that the
+ bridge is compatible with the project:
+ - The generator currently supports file-scope `@Observable` classes only;
+ `ObservableObject`, `@StateObject`, and other observation models do not
+ produce accessors.
+ - The documented dependency wiring assumes a SwiftPM app manifest. For an
+ `.xcodeproj` or `.xcworkspace`, do not invent package or target wiring.
+ If either requirement is unmet, stop the bridge bootstrap without modifying
+ the app. Preserve any installed production or TestFlight build. Prefer an
+ existing real-device XCUITest harness; when a separate QA build is needed,
+ use an isolated bundle identifier and non-production entitlements so it can
+ coexist with the production app. Report fixture-driven state, provider UI,
+ and actual external-provider success as distinct evidence tiers.
+2. Walk the app source (passed as `--source <dir>`) and identify all `@Observable`
classes. Note any property immediately preceded by the generator marker
comment `// @Snapshotable` — those are the snapshot-eligible fields. The
marker is a comment so it composes with the `@Observable` macro. Each
@@ -891,7 +910,7 @@ fi
Optional compositions. Keys must be unique across observable classes.
Codegen stops with a source diagnostic instead of emitting a broken or
lossy harness when any of these constraints is violated.
-2. Show the user the accessor list and ask whether to install the DebugBridge
+3. Show the user the accessor list and ask whether to install the DebugBridge
SPM dependency into their `Package.swift` (one AskUserQuestion).
## Phase 2: Bootstrap the device bridge
diff --git a/ios-qa/SKILL.md.tmpl b/ios-qa/SKILL.md.tmpl
index 78f9454b1..2e147c5ae 100644
--- a/ios-qa/SKILL.md.tmpl
+++ b/ios-qa/SKILL.md.tmpl
@@ -96,7 +96,20 @@ fi
## Phase 1: Read source, plan codegen
-1. Walk the app source (passed as `--source <dir>`) and identify all `@Observable`
+1. Before changing the app or replacing an installed build, verify that the
+ bridge is compatible with the project:
+ - The generator currently supports file-scope `@Observable` classes only;
+ `ObservableObject`, `@StateObject`, and other observation models do not
+ produce accessors.
+ - The documented dependency wiring assumes a SwiftPM app manifest. For an
+ `.xcodeproj` or `.xcworkspace`, do not invent package or target wiring.
+ If either requirement is unmet, stop the bridge bootstrap without modifying
+ the app. Preserve any installed production or TestFlight build. Prefer an
+ existing real-device XCUITest harness; when a separate QA build is needed,
+ use an isolated bundle identifier and non-production entitlements so it can
+ coexist with the production app. Report fixture-driven state, provider UI,
+ and actual external-provider success as distinct evidence tiers.
+2. Walk the app source (passed as `--source <dir>`) and identify all `@Observable`
classes. Note any property immediately preceded by the generator marker
comment `// @Snapshotable` — those are the snapshot-eligible fields. The
marker is a comment so it composes with the `@Observable` macro. Each
@@ -107,7 +120,7 @@ fi
Optional compositions. Keys must be unique across observable classes.
Codegen stops with a source diagnostic instead of emitting a broken or
lossy harness when any of these constraints is violated.
-2. Show the user the accessor list and ask whether to install the DebugBridge
+3. Show the user the accessor list and ask whether to install the DebugBridge
SPM dependency into their `Package.swift` (one AskUserQuestion).
## Phase 2: Bootstrap the device bridge
diff --git a/ios-qa/templates/Bridges.swift.template b/ios-qa/templates/Bridges.swift.template
index 4a91142de..74e227928 100644
--- a/ios-qa/templates/Bridges.swift.template
+++ b/ios-qa/templates/Bridges.swift.template
@@ -60,12 +60,13 @@ private func debugBridgeAccessibilityChildren(of element: NSObject) -> [NSObject
@MainActor
enum ScreenshotBridgeImpl {
- /// Capture a PNG of the active window. Uses UIGraphicsImageRenderer
+ /// Capture a PNG of the visible UI. Uses UIGraphicsImageRenderer
/// (modern API, replaces UIGraphicsBeginImageContext). Returns nil if
- /// no key window is available (e.g., app backgrounded).
+ /// no window is available (e.g., app backgrounded).
static func capturePNG() -> Data? {
- guard let scene = activeScene(), let window = activeKeyWindow(in: scene) else { return nil }
- let bounds = window.bounds
+ guard let scene = activeScene() else { return nil }
+ let windows = orderedWindows(in: scene)
+ guard let bounds = windows.first?.bounds else { return nil }
let format = UIGraphicsImageRendererFormat.default()
// /tap consumes UIKit window points. Render at 1x so screenshot pixels
// use that same coordinate space on 2x/3x devices.
@@ -75,24 +76,73 @@ enum ScreenshotBridgeImpl {
// drawHierarchy is the documented way to snapshot real UIKit
// layers including layer-backed views. afterScreenUpdates: false
// because we want the CURRENT visible state, not a forced layout.
- window.drawHierarchy(in: bounds, afterScreenUpdates: false)
+ //
+ // Back-to-front across every window: a UIMenu, alert or action
+ // sheet lives in its OWN window, so drawing only the key window
+ // silently drops it from the screenshot.
+ for window in windows.reversed() {
+ window.drawHierarchy(in: window.bounds, afterScreenUpdates: false)
+ }
}
return image.pngData()
}
- private static func activeScene() -> UIWindowScene? {
+ static func activeScene() -> UIWindowScene? {
UIApplication.shared.connectedScenes
.compactMap { $0 as? UIWindowScene }
.first { $0.activationState == .foregroundActive }
?? (UIApplication.shared.connectedScenes.first as? UIWindowScene)
}
- private static func activeKeyWindow(in scene: UIWindowScene) -> UIWindow? {
+ static func activeKeyWindow(in scene: UIWindowScene) -> UIWindow? {
let windows = scene.windows.filter { window in
!window.isHidden && !String(describing: type(of: window)).contains("PassThroughWindow")
}
return windows.first(where: { $0.isKeyWindow }) ?? windows.max(by: { $0.windowLevel < $1.windowLevel })
}
+
+ /// Visible windows, front-most first: higher `windowLevel` wins, and within
+ /// a level the later window sits on top. Menus, alerts and action sheets
+ /// get their own window, so `isKeyWindow` alone does not find them.
+ /// PassThroughWindow overlays stay filtered (same rule as activeKeyWindow).
+ static func orderedWindows(in scene: UIWindowScene) -> [UIWindow] {
+ scene.windows
+ .filter {
+ !$0.isHidden && $0.alpha > 0.01 && !$0.bounds.isEmpty
+ && !String(describing: type(of: $0)).contains("PassThroughWindow")
+ }
+ .enumerated()
+ .sorted {
+ ($0.element.windowLevel.rawValue, Double($0.offset))
+ > ($1.element.windowLevel.rawValue, Double($1.offset))
+ }
+ .map(\.element)
+ }
+
+ /// The window the user is actually touching — front-most, not merely key.
+ static func frontmostWindow() -> UIWindow? {
+ guard let scene = activeScene() else { return nil }
+ return orderedWindows(in: scene).first ?? activeKeyWindow(in: scene)
+ }
+
+ /// Roots to search, front-most first: for each window, the top-most
+ /// presented view controller's view before the window itself.
+ ///
+ /// Tree order is NOT front-most order. A presented sheet sits *after* the
+ /// screen it covers in `window.subviews`, so a walk rooted at the window
+ /// emits the covered screen first and a client taking the first match for a
+ /// label gets a control the user cannot reach.
+ static func searchRoots() -> [UIView] {
+ guard let scene = activeScene() else { return [] }
+ var roots: [UIView] = []
+ for window in orderedWindows(in: scene) {
+ var controller = window.rootViewController
+ while let presented = controller?.presentedViewController { controller = presented }
+ if let view = controller?.view, view !== window { roots.append(view) }
+ roots.append(window)
+ }
+ return roots
+ }
}
// MARK: - ElementsBridge implementation
@@ -103,19 +153,26 @@ enum ElementsBridgeImpl {
/// Each entry has frame (in window coords), accessibility label,
/// identifier, traits as a bitmask, and a parent path. Skips
/// non-accessible / hidden views.
+ /// Front-most content first, so a client taking the first match for a
+ /// label gets the element the user can actually reach — a presented view
+ /// is also reachable through its window, so the roots overlap by design
+ /// and the shared visited set emits each view once, at its front-most
+ /// position.
static func snapshot() -> [JSONDict] {
- guard let scene = activeScene(), let window = activeKeyWindow(in: scene) else { return [] }
var elements: [JSONDict] = []
var visited = Set<ObjectIdentifier>()
var remaining = 2_048
- collect(
- view: window,
- parentPath: "",
- window: window,
- visited: &visited,
- remaining: &remaining,
- into: &elements
- )
+ for root in ScreenshotBridgeImpl.searchRoots() {
+ guard let window = (root as? UIWindow) ?? root.window else { continue }
+ collect(
+ view: root,
+ parentPath: "",
+ window: window,
+ visited: &visited,
+ remaining: &remaining,
+ into: &elements
+ )
+ }
return elements
}
@@ -263,20 +320,6 @@ enum ElementsBridgeImpl {
}
}
}
-
- private static func activeScene() -> UIWindowScene? {
- UIApplication.shared.connectedScenes
- .compactMap { $0 as? UIWindowScene }
- .first { $0.activationState == .foregroundActive }
- ?? (UIApplication.shared.connectedScenes.first as? UIWindowScene)
- }
-
- private static func activeKeyWindow(in scene: UIWindowScene) -> UIWindow? {
- let windows = scene.windows.filter { window in
- !window.isHidden && !String(describing: type(of: window)).contains("PassThroughWindow")
- }
- return windows.first(where: { $0.isKeyWindow }) ?? windows.max(by: { $0.windowLevel < $1.windowLevel })
- }
}
// MARK: - MutationBridge implementation
@@ -301,7 +344,9 @@ enum MutationBridgeImpl {
guard let x = payload["x"] as? NSNumber,
let y = payload["y"] as? NSNumber else { return false }
let point = CGPoint(x: x.doubleValue, y: y.doubleValue)
- guard let scene = activeScene(), let window = activeKeyWindow(in: scene) else { return false }
+ // Front-most, not merely key: a menu/alert/sheet lives in its own
+ // window, and a tap aimed there must not land on the covered screen.
+ guard let window = ScreenshotBridgeImpl.frontmostWindow() else { return false }
if let element = findActivatableAXElement(at: point, in: window),
element.accessibilityActivate() {
return true
@@ -353,8 +398,10 @@ enum MutationBridgeImpl {
/// Set text on the first responder if it's a UITextField or UITextView.
private static func handleType(_ payload: JSONDict) -> Bool {
guard let text = payload["text"] as? String else { return false }
- guard let scene = activeScene(), let window = activeKeyWindow(in: scene) else { return false }
- guard let responder = findFirstResponder(in: window) else { return false }
+ // Search front-most roots first: the focused field in a presented
+ // sheet wins over a same-named field on the covered screen.
+ guard let responder = ScreenshotBridgeImpl.searchRoots()
+ .lazy.compactMap({ findFirstResponder(in: $0) }).first else { return false }
if let field = responder as? UITextField {
field.text = text
field.sendActions(for: .editingChanged)
@@ -379,8 +426,10 @@ enum MutationBridgeImpl {
let from = CGPoint(x: fx.doubleValue, y: fy.doubleValue)
let to = CGPoint(x: tx.doubleValue, y: ty.doubleValue)
- guard let scene = activeScene(), let window = activeKeyWindow(in: scene) else { return false }
- guard let hit = window.hitTest(from, with: nil) else { return false }
+ // Hit-test front-most roots first (sheet before covered screen).
+ guard let hit = ScreenshotBridgeImpl.searchRoots()
+ .lazy.compactMap({ $0.hitTest($0.convert(from, from: nil), with: nil) })
+ .first else { return false }
// Find the nearest enclosing UIScrollView.
var node: UIView? = hit
@@ -420,20 +469,6 @@ enum MutationBridgeImpl {
}
return nil
}
-
- private static func activeScene() -> UIWindowScene? {
- UIApplication.shared.connectedScenes
- .compactMap { $0 as? UIWindowScene }
- .first { $0.activationState == .foregroundActive }
- ?? (UIApplication.shared.connectedScenes.first as? UIWindowScene)
- }
-
- private static func activeKeyWindow(in scene: UIWindowScene) -> UIWindow? {
- let windows = scene.windows.filter { window in
- !window.isHidden && !String(describing: type(of: window)).contains("PassThroughWindow")
- }
- return windows.first(where: { $0.isKeyWindow }) ?? windows.max(by: { $0.windowLevel < $1.windowLevel })
- }
}
#endif // DEBUG && canImport(UIKit)
diff --git a/ios-qa/templates/DebugBridgeTouch.m.template b/ios-qa/templates/DebugBridgeTouch.m.template
index aa6954c6d..e82199467 100644
--- a/ios-qa/templates/DebugBridgeTouch.m.template
+++ b/ios-qa/templates/DebugBridgeTouch.m.template
@@ -20,7 +20,29 @@
#import "DebugBridgeTouch.h"
#import <TargetConditionals.h>
-#if TARGET_OS_IOS
+#if !defined(DEBUG)
+
+// RELEASE BUILD: this file deliberately emits NOTHING — no class, no symbols, no
+// private-API references. The header still declares the interface, which is inert
+// on its own; every consumer of DebugBridgeTouch is itself `#if DEBUG` guarded, so
+// nothing references it here and nothing fails to link.
+//
+// This guard was added because the comments at the top of this file and in the
+// header both PROMISED "DEBUG-only; never shipped to App Store" and "never link in
+// Release" — and nothing enforced it. Only `#if TARGET_OS_IOS` was tested, so a
+// Release build for iOS compiled the whole implementation in. Measured on a real
+// app (Seize Day, 2026-08-15), `nm -j` on a Release binary returned 15 DebugBridge
+// symbols including +[DebugBridgeTouch sendTapAtPoint:inWindow:], plus
+// IOHIDEventCreateDigitizer, AXSSetAutomationEnabled and IOKit.framework strings.
+// That is a Guideline 2.5.1 private-API exposure in a shippable binary.
+//
+// Package.swift's stated guard — `.when(configuration: .debug)` on the consuming
+// target's dependency — only exists for SwiftPM consumers. An app integrating this
+// as a local package inside an .xcodeproj cannot express it: Xcode's Filters column
+// in Frameworks/Libraries offers platform conditions only, never configuration. So
+// the guard has to live here, in the source, where it holds for every consumer.
+
+#elif TARGET_OS_IOS
#import <UIKit/UIKit.h>
#import <objc/runtime.h>
@@ -340,4 +362,4 @@ static id DBT_HitTestView(UIWindow *window, CGPoint point) {
}
@end
-#endif // TARGET_OS_IOS
+#endif // !DEBUG / TARGET_OS_IOS
diff --git a/ios-qa/templates/Package.swift.template b/ios-qa/templates/Package.swift.template
index 427a3399d..39100d637 100644
--- a/ios-qa/templates/Package.swift.template
+++ b/ios-qa/templates/Package.swift.template
@@ -12,9 +12,22 @@
// MutationBridge implementations. Depends on the other
// two.
//
-// The structural Release-build guard is the `.when(configuration: .debug)`
-// conditional on every consuming target's dependency. SwiftPM refuses to link
-// DebugBridge* in Release config.
+// Release-build guards, in order of reliability:
+//
+// 1. SOURCE. Every file is `#if DEBUG` guarded, including DebugBridgeTouch.m,
+// which holds regardless of how the package is integrated. This is the one
+// that actually protects you.
+// 2. `.when(configuration: .debug)` on the consuming target's dependency. This
+// works for SwiftPM consumers ONLY. An app integrating this as a local
+// package inside an .xcodeproj CANNOT express it — Xcode's Filters column in
+// Frameworks/Libraries offers platform conditions, never configuration — so
+// do not rely on it alone.
+//
+// Guard 1 was added 2026-08-15 after a measured failure: DebugBridgeTouch.m was
+// guarded only by `#if TARGET_OS_IOS`, so a Release iOS build of a real app linked
+// it, and `nm -j` returned 15 DebugBridge symbols plus IOHIDEventCreateDigitizer,
+// AXSSetAutomationEnabled and IOKit.framework strings. Guideline 2.5.1 exposure in
+// a shippable binary, with guard 2 present and doing nothing.
//
// CI invariant: `swift build -c release` + `nm -j build/Release/<binary>
// | grep -q DebugBridge && exit 1`.
@@ -43,6 +56,13 @@ let package = Package(
dependencies: [],
path: "Sources/DebugBridgeTouch",
publicHeadersPath: "include",
+ cSettings: [
+ // Explicit, because the source guard depends on it. SwiftPM's
+ // implicit DEBUG for C-family targets is not something to bet a
+ // private-API exposure on — the two Swift targets already declare
+ // it, and this target is the one that actually links private API.
+ .define("DEBUG", .when(configuration: .debug)),
+ ],
linkerSettings: [
// IOKit is loaded dynamically via dlopen at runtime (it's a
// private framework on iOS and can't be linked statically).
diff --git a/ios-sync/SKILL.md b/ios-sync/SKILL.md
index 0b1390c1c..d72446a10 100644
--- a/ios-sync/SKILL.md
+++ b/ios-sync/SKILL.md
@@ -112,9 +112,11 @@ else
fi
~/.claude/skills/gstack/bin/gstack-timeline-log '{"skill":"ios-sync","event":"started","branch":"'"$_BRANCH"'","session":"'"$_SESSION_ID"'"}' 2>/dev/null &
_HAS_ROUTING="no"
-if [ -f CLAUDE.md ] && grep -q "## Skill routing" CLAUDE.md 2>/dev/null; then
- _HAS_ROUTING="yes"
-fi
+for _RF in CLAUDE.md AGENTS.md; do
+ if [ -f "$_RF" ] && grep -q "## Skill routing" "$_RF" 2>/dev/null; then
+ _HAS_ROUTING="yes"
+ fi
+done
_ROUTING_DECLINED=$(~/.claude/skills/gstack/bin/gstack-config get routing_declined 2>/dev/null || echo "false")
echo "HAS_ROUTING: $_HAS_ROUTING"
echo "ROUTING_DECLINED: $_ROUTING_DECLINED"
@@ -508,10 +510,13 @@ _BRAIN_SYNC_MODE=$("$_BRAIN_CONFIG_BIN" get artifacts_sync_mode 2>/dev/null || e
# Detect remote-MCP mode (Path 4 of /setup-gbrain). Local artifacts sync is
# a no-op in remote mode; the brain server pulls from GitHub/GitLab on its
# own cadence. Read claude.json directly to keep this preamble fast (no
-# subprocess to claude CLI on every skill start).
+# subprocess to claude CLI on every skill start). Both registration scopes
+# are read (#2499): user scope, then the nearest-ancestor project scope.
_GBRAIN_MCP_MODE="none"
+_GBRAIN_MCP_ENTRY=""
if command -v jq >/dev/null 2>&1 && [ -f "$HOME/.claude.json" ]; then
- _GBRAIN_MCP_TYPE=$(jq -r '.mcpServers.gbrain.type // .mcpServers.gbrain.transport // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_ENTRY=$(jq -c --arg cwd "$PWD" '.mcpServers.gbrain // ((.projects // {}) | to_entries | map(select((.key as $k | $cwd == $k or ($cwd | startswith($k + "/"))) and ((try .value.mcpServers.gbrain catch null) != null))) | sort_by(.key | length) | last | .value.mcpServers.gbrain) // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_TYPE=$(printf '%s' "$_GBRAIN_MCP_ENTRY" | jq -r '.type // .transport // empty' 2>/dev/null)
case "$_GBRAIN_MCP_TYPE" in
url|http|sse) _GBRAIN_MCP_MODE="remote-http" ;;
stdio) _GBRAIN_MCP_MODE="local-stdio" ;;
@@ -532,6 +537,7 @@ if [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_DO_PULL=1
if [ -f "$_BRAIN_LAST_PULL_FILE" ]; then
_BRAIN_LAST=$(cat "$_BRAIN_LAST_PULL_FILE" 2>/dev/null || echo 0)
+ case "$_BRAIN_LAST" in ''|*[!0-9]*) _BRAIN_LAST=0 ;; esac
_BRAIN_AGE=$(( _BRAIN_NOW - _BRAIN_LAST ))
[ "$_BRAIN_AGE" -lt 86400 ] && _BRAIN_DO_PULL=0
fi
@@ -545,7 +551,7 @@ fi
if [ "$_GBRAIN_MCP_MODE" = "remote-http" ]; then
# Remote-MCP mode: local artifacts sync is a no-op (brain admin's server
# pulls from GitHub/GitLab). Show the user this is by design, not broken.
- _GBRAIN_HOST=$(jq -r '.mcpServers.gbrain.url // empty' "$HOME/.claude.json" 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|')
+ _GBRAIN_HOST=$(printf '%s' "${_GBRAIN_MCP_ENTRY:-}" | jq -r '.url // empty' 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|' | head -1 | tr -cd 'A-Za-z0-9._-')
echo "ARTIFACTS_SYNC: remote-mode (managed by brain server ${_GBRAIN_HOST:-remote})"
elif [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_QUEUE_DEPTH=0
@@ -630,8 +636,8 @@ eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)"
_PROJ="${GSTACK_HOME:-$HOME/.gstack}/projects/${SLUG:-unknown}"
if [ -d "$_PROJ" ]; then
echo "--- RECENT ARTIFACTS ---"
- find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs ls -t 2>/dev/null | head -3
- [ -f "$_PROJ/${_BRANCH}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/${_BRANCH}-reviews.jsonl" | tr -d ' ') entries"
+ find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3
+ [ -f "$_PROJ/${BRANCH:-unknown}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/${BRANCH:-unknown}-reviews.jsonl" | tr -d ' ') entries"
[ -f "$_PROJ/timeline.jsonl" ] && tail -5 "$_PROJ/timeline.jsonl"
if [ -f "$_PROJ/timeline.jsonl" ]; then
_LAST=$(grep "\"branch\":\"${_BRANCH}\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -1)
@@ -639,7 +645,7 @@ if [ -d "$_PROJ" ]; then
_RECENT_SKILLS=$(grep "\"branch\":\"${_BRANCH}\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -3 | grep -o '"skill":"[^"]*"' | sed 's/"skill":"//;s/"//' | tr '\n' ',')
[ -n "$_RECENT_SKILLS" ] && echo "RECENT_PATTERN: $_RECENT_SKILLS"
fi
- _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs ls -t 2>/dev/null | head -1)
+ _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs -r ls -t 2>/dev/null | head -1)
[ -n "$_LATEST_CP" ] && echo "LATEST_CHECKPOINT: $_LATEST_CP"
if [ -f "$_PROJ/decisions.active.json" ]; then
echo "--- ACTIVE DECISIONS (recent, scope-relevant) ---"
@@ -715,7 +721,7 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST
## Question Tuning (skip entirely if `QUESTION_TUNING: false`)
-Before each AskUserQuestion, choose `question_id` from `scripts/question-registry.ts` or `{skill}-{slug}`, then run `printf '%s' "<question summary>" | ~/.claude/skills/gstack/bin/gstack-question-preference --check "<id>" --summary-stdin` (piped summary feeds the one-way keyword net, #2024). `AUTO_DECIDE` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." `ASK_NORMALLY` means ask.
+Before each AskUserQuestion, choose `question_id` from `~/.claude/skills/gstack/scripts/question-registry.ts` or `{skill}-{slug}`, then run `printf '%s' "<question summary>" | ~/.claude/skills/gstack/bin/gstack-question-preference --check "<id>" --summary-stdin` (piped summary feeds the one-way keyword net, #2024). `AUTO_DECIDE` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." `ASK_NORMALLY` means ask.
**Embed the question_id as a marker in the question text** so hooks can identify it deterministically (plan-tune cathedral T14 / D18 progressive markers). Append `<gstack-qid:{question_id}>` somewhere in the rendered question (the leading line or trailing line is fine; the marker doesn't render visibly to the user when wrapped in HTML-style angle brackets, but the hook strips it). Without the marker the PreToolUse enforcement hook treats the AUQ as observed-only and never auto-decides — so always include it when the question matches a registered `question_id`.
diff --git a/land-and-deploy/SKILL.md b/land-and-deploy/SKILL.md
index 5edaa8296..5788526a6 100644
--- a/land-and-deploy/SKILL.md
+++ b/land-and-deploy/SKILL.md
@@ -107,9 +107,11 @@ else
fi
~/.claude/skills/gstack/bin/gstack-timeline-log '{"skill":"land-and-deploy","event":"started","branch":"'"$_BRANCH"'","session":"'"$_SESSION_ID"'"}' 2>/dev/null &
_HAS_ROUTING="no"
-if [ -f CLAUDE.md ] && grep -q "## Skill routing" CLAUDE.md 2>/dev/null; then
- _HAS_ROUTING="yes"
-fi
+for _RF in CLAUDE.md AGENTS.md; do
+ if [ -f "$_RF" ] && grep -q "## Skill routing" "$_RF" 2>/dev/null; then
+ _HAS_ROUTING="yes"
+ fi
+done
_ROUTING_DECLINED=$(~/.claude/skills/gstack/bin/gstack-config get routing_declined 2>/dev/null || echo "false")
echo "HAS_ROUTING: $_HAS_ROUTING"
echo "ROUTING_DECLINED: $_ROUTING_DECLINED"
@@ -503,10 +505,13 @@ _BRAIN_SYNC_MODE=$("$_BRAIN_CONFIG_BIN" get artifacts_sync_mode 2>/dev/null || e
# Detect remote-MCP mode (Path 4 of /setup-gbrain). Local artifacts sync is
# a no-op in remote mode; the brain server pulls from GitHub/GitLab on its
# own cadence. Read claude.json directly to keep this preamble fast (no
-# subprocess to claude CLI on every skill start).
+# subprocess to claude CLI on every skill start). Both registration scopes
+# are read (#2499): user scope, then the nearest-ancestor project scope.
_GBRAIN_MCP_MODE="none"
+_GBRAIN_MCP_ENTRY=""
if command -v jq >/dev/null 2>&1 && [ -f "$HOME/.claude.json" ]; then
- _GBRAIN_MCP_TYPE=$(jq -r '.mcpServers.gbrain.type // .mcpServers.gbrain.transport // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_ENTRY=$(jq -c --arg cwd "$PWD" '.mcpServers.gbrain // ((.projects // {}) | to_entries | map(select((.key as $k | $cwd == $k or ($cwd | startswith($k + "/"))) and ((try .value.mcpServers.gbrain catch null) != null))) | sort_by(.key | length) | last | .value.mcpServers.gbrain) // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_TYPE=$(printf '%s' "$_GBRAIN_MCP_ENTRY" | jq -r '.type // .transport // empty' 2>/dev/null)
case "$_GBRAIN_MCP_TYPE" in
url|http|sse) _GBRAIN_MCP_MODE="remote-http" ;;
stdio) _GBRAIN_MCP_MODE="local-stdio" ;;
@@ -527,6 +532,7 @@ if [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_DO_PULL=1
if [ -f "$_BRAIN_LAST_PULL_FILE" ]; then
_BRAIN_LAST=$(cat "$_BRAIN_LAST_PULL_FILE" 2>/dev/null || echo 0)
+ case "$_BRAIN_LAST" in ''|*[!0-9]*) _BRAIN_LAST=0 ;; esac
_BRAIN_AGE=$(( _BRAIN_NOW - _BRAIN_LAST ))
[ "$_BRAIN_AGE" -lt 86400 ] && _BRAIN_DO_PULL=0
fi
@@ -540,7 +546,7 @@ fi
if [ "$_GBRAIN_MCP_MODE" = "remote-http" ]; then
# Remote-MCP mode: local artifacts sync is a no-op (brain admin's server
# pulls from GitHub/GitLab). Show the user this is by design, not broken.
- _GBRAIN_HOST=$(jq -r '.mcpServers.gbrain.url // empty' "$HOME/.claude.json" 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|')
+ _GBRAIN_HOST=$(printf '%s' "${_GBRAIN_MCP_ENTRY:-}" | jq -r '.url // empty' 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|' | head -1 | tr -cd 'A-Za-z0-9._-')
echo "ARTIFACTS_SYNC: remote-mode (managed by brain server ${_GBRAIN_HOST:-remote})"
elif [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_QUEUE_DEPTH=0
@@ -625,8 +631,8 @@ eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)"
_PROJ="${GSTACK_HOME:-$HOME/.gstack}/projects/${SLUG:-unknown}"
if [ -d "$_PROJ" ]; then
echo "--- RECENT ARTIFACTS ---"
- find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs ls -t 2>/dev/null | head -3
- [ -f "$_PROJ/${_BRANCH}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/${_BRANCH}-reviews.jsonl" | tr -d ' ') entries"
+ find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3
+ [ -f "$_PROJ/${BRANCH:-unknown}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/${BRANCH:-unknown}-reviews.jsonl" | tr -d ' ') entries"
[ -f "$_PROJ/timeline.jsonl" ] && tail -5 "$_PROJ/timeline.jsonl"
if [ -f "$_PROJ/timeline.jsonl" ]; then
_LAST=$(grep "\"branch\":\"${_BRANCH}\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -1)
@@ -634,7 +640,7 @@ if [ -d "$_PROJ" ]; then
_RECENT_SKILLS=$(grep "\"branch\":\"${_BRANCH}\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -3 | grep -o '"skill":"[^"]*"' | sed 's/"skill":"//;s/"//' | tr '\n' ',')
[ -n "$_RECENT_SKILLS" ] && echo "RECENT_PATTERN: $_RECENT_SKILLS"
fi
- _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs ls -t 2>/dev/null | head -1)
+ _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs -r ls -t 2>/dev/null | head -1)
[ -n "$_LATEST_CP" ] && echo "LATEST_CHECKPOINT: $_LATEST_CP"
if [ -f "$_PROJ/decisions.active.json" ]; then
echo "--- ACTIVE DECISIONS (recent, scope-relevant) ---"
@@ -710,7 +716,7 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST
## Question Tuning (skip entirely if `QUESTION_TUNING: false`)
-Before each AskUserQuestion, choose `question_id` from `scripts/question-registry.ts` or `{skill}-{slug}`, then run `printf '%s' "<question summary>" | ~/.claude/skills/gstack/bin/gstack-question-preference --check "<id>" --summary-stdin` (piped summary feeds the one-way keyword net, #2024). `AUTO_DECIDE` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." `ASK_NORMALLY` means ask.
+Before each AskUserQuestion, choose `question_id` from `~/.claude/skills/gstack/scripts/question-registry.ts` or `{skill}-{slug}`, then run `printf '%s' "<question summary>" | ~/.claude/skills/gstack/bin/gstack-question-preference --check "<id>" --summary-stdin` (piped summary feeds the one-way keyword net, #2024). `AUTO_DECIDE` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." `ASK_NORMALLY` means ask.
**Embed the question_id as a marker in the question text** so hooks can identify it deterministically (plan-tune cathedral T14 / D18 progressive markers). Append `<gstack-qid:{question_id}>` somewhere in the rendered question (the leading line or trailing line is fine; the marker doesn't render visibly to the user when wrapped in HTML-style angle brackets, but the hook strips it). Without the marker the PreToolUse enforcement hook treats the AUQ as observed-only and never auto-decides — so always include it when the question matches a registered `question_id`.
diff --git a/landing-report/SKILL.md b/landing-report/SKILL.md
index 4995332ac..93db4f026 100644
--- a/landing-report/SKILL.md
+++ b/landing-report/SKILL.md
@@ -109,9 +109,11 @@ else
fi
~/.claude/skills/gstack/bin/gstack-timeline-log '{"skill":"landing-report","event":"started","branch":"'"$_BRANCH"'","session":"'"$_SESSION_ID"'"}' 2>/dev/null &
_HAS_ROUTING="no"
-if [ -f CLAUDE.md ] && grep -q "## Skill routing" CLAUDE.md 2>/dev/null; then
- _HAS_ROUTING="yes"
-fi
+for _RF in CLAUDE.md AGENTS.md; do
+ if [ -f "$_RF" ] && grep -q "## Skill routing" "$_RF" 2>/dev/null; then
+ _HAS_ROUTING="yes"
+ fi
+done
_ROUTING_DECLINED=$(~/.claude/skills/gstack/bin/gstack-config get routing_declined 2>/dev/null || echo "false")
echo "HAS_ROUTING: $_HAS_ROUTING"
echo "ROUTING_DECLINED: $_ROUTING_DECLINED"
@@ -505,10 +507,13 @@ _BRAIN_SYNC_MODE=$("$_BRAIN_CONFIG_BIN" get artifacts_sync_mode 2>/dev/null || e
# Detect remote-MCP mode (Path 4 of /setup-gbrain). Local artifacts sync is
# a no-op in remote mode; the brain server pulls from GitHub/GitLab on its
# own cadence. Read claude.json directly to keep this preamble fast (no
-# subprocess to claude CLI on every skill start).
+# subprocess to claude CLI on every skill start). Both registration scopes
+# are read (#2499): user scope, then the nearest-ancestor project scope.
_GBRAIN_MCP_MODE="none"
+_GBRAIN_MCP_ENTRY=""
if command -v jq >/dev/null 2>&1 && [ -f "$HOME/.claude.json" ]; then
- _GBRAIN_MCP_TYPE=$(jq -r '.mcpServers.gbrain.type // .mcpServers.gbrain.transport // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_ENTRY=$(jq -c --arg cwd "$PWD" '.mcpServers.gbrain // ((.projects // {}) | to_entries | map(select((.key as $k | $cwd == $k or ($cwd | startswith($k + "/"))) and ((try .value.mcpServers.gbrain catch null) != null))) | sort_by(.key | length) | last | .value.mcpServers.gbrain) // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_TYPE=$(printf '%s' "$_GBRAIN_MCP_ENTRY" | jq -r '.type // .transport // empty' 2>/dev/null)
case "$_GBRAIN_MCP_TYPE" in
url|http|sse) _GBRAIN_MCP_MODE="remote-http" ;;
stdio) _GBRAIN_MCP_MODE="local-stdio" ;;
@@ -529,6 +534,7 @@ if [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_DO_PULL=1
if [ -f "$_BRAIN_LAST_PULL_FILE" ]; then
_BRAIN_LAST=$(cat "$_BRAIN_LAST_PULL_FILE" 2>/dev/null || echo 0)
+ case "$_BRAIN_LAST" in ''|*[!0-9]*) _BRAIN_LAST=0 ;; esac
_BRAIN_AGE=$(( _BRAIN_NOW - _BRAIN_LAST ))
[ "$_BRAIN_AGE" -lt 86400 ] && _BRAIN_DO_PULL=0
fi
@@ -542,7 +548,7 @@ fi
if [ "$_GBRAIN_MCP_MODE" = "remote-http" ]; then
# Remote-MCP mode: local artifacts sync is a no-op (brain admin's server
# pulls from GitHub/GitLab). Show the user this is by design, not broken.
- _GBRAIN_HOST=$(jq -r '.mcpServers.gbrain.url // empty' "$HOME/.claude.json" 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|')
+ _GBRAIN_HOST=$(printf '%s' "${_GBRAIN_MCP_ENTRY:-}" | jq -r '.url // empty' 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|' | head -1 | tr -cd 'A-Za-z0-9._-')
echo "ARTIFACTS_SYNC: remote-mode (managed by brain server ${_GBRAIN_HOST:-remote})"
elif [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_QUEUE_DEPTH=0
@@ -627,8 +633,8 @@ eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)"
_PROJ="${GSTACK_HOME:-$HOME/.gstack}/projects/${SLUG:-unknown}"
if [ -d "$_PROJ" ]; then
echo "--- RECENT ARTIFACTS ---"
- find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs ls -t 2>/dev/null | head -3
- [ -f "$_PROJ/${_BRANCH}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/${_BRANCH}-reviews.jsonl" | tr -d ' ') entries"
+ find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3
+ [ -f "$_PROJ/${BRANCH:-unknown}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/${BRANCH:-unknown}-reviews.jsonl" | tr -d ' ') entries"
[ -f "$_PROJ/timeline.jsonl" ] && tail -5 "$_PROJ/timeline.jsonl"
if [ -f "$_PROJ/timeline.jsonl" ]; then
_LAST=$(grep "\"branch\":\"${_BRANCH}\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -1)
@@ -636,7 +642,7 @@ if [ -d "$_PROJ" ]; then
_RECENT_SKILLS=$(grep "\"branch\":\"${_BRANCH}\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -3 | grep -o '"skill":"[^"]*"' | sed 's/"skill":"//;s/"//' | tr '\n' ',')
[ -n "$_RECENT_SKILLS" ] && echo "RECENT_PATTERN: $_RECENT_SKILLS"
fi
- _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs ls -t 2>/dev/null | head -1)
+ _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs -r ls -t 2>/dev/null | head -1)
[ -n "$_LATEST_CP" ] && echo "LATEST_CHECKPOINT: $_LATEST_CP"
if [ -f "$_PROJ/decisions.active.json" ]; then
echo "--- ACTIVE DECISIONS (recent, scope-relevant) ---"
@@ -712,7 +718,7 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST
## Question Tuning (skip entirely if `QUESTION_TUNING: false`)
-Before each AskUserQuestion, choose `question_id` from `scripts/question-registry.ts` or `{skill}-{slug}`, then run `printf '%s' "<question summary>" | ~/.claude/skills/gstack/bin/gstack-question-preference --check "<id>" --summary-stdin` (piped summary feeds the one-way keyword net, #2024). `AUTO_DECIDE` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." `ASK_NORMALLY` means ask.
+Before each AskUserQuestion, choose `question_id` from `~/.claude/skills/gstack/scripts/question-registry.ts` or `{skill}-{slug}`, then run `printf '%s' "<question summary>" | ~/.claude/skills/gstack/bin/gstack-question-preference --check "<id>" --summary-stdin` (piped summary feeds the one-way keyword net, #2024). `AUTO_DECIDE` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." `ASK_NORMALLY` means ask.
**Embed the question_id as a marker in the question text** so hooks can identify it deterministically (plan-tune cathedral T14 / D18 progressive markers). Append `<gstack-qid:{question_id}>` somewhere in the rendered question (the leading line or trailing line is fine; the marker doesn't render visibly to the user when wrapped in HTML-style angle brackets, but the hook strips it). Without the marker the PreToolUse enforcement hook treats the AUQ as observed-only and never auto-decides — so always include it when the question matches a registered `question_id`.
diff --git a/learn/SKILL.md b/learn/SKILL.md
index 85c094c82..a0b1c69cb 100644
--- a/learn/SKILL.md
+++ b/learn/SKILL.md
@@ -110,9 +110,11 @@ else
fi
~/.claude/skills/gstack/bin/gstack-timeline-log '{"skill":"learn","event":"started","branch":"'"$_BRANCH"'","session":"'"$_SESSION_ID"'"}' 2>/dev/null &
_HAS_ROUTING="no"
-if [ -f CLAUDE.md ] && grep -q "## Skill routing" CLAUDE.md 2>/dev/null; then
- _HAS_ROUTING="yes"
-fi
+for _RF in CLAUDE.md AGENTS.md; do
+ if [ -f "$_RF" ] && grep -q "## Skill routing" "$_RF" 2>/dev/null; then
+ _HAS_ROUTING="yes"
+ fi
+done
_ROUTING_DECLINED=$(~/.claude/skills/gstack/bin/gstack-config get routing_declined 2>/dev/null || echo "false")
echo "HAS_ROUTING: $_HAS_ROUTING"
echo "ROUTING_DECLINED: $_ROUTING_DECLINED"
@@ -506,10 +508,13 @@ _BRAIN_SYNC_MODE=$("$_BRAIN_CONFIG_BIN" get artifacts_sync_mode 2>/dev/null || e
# Detect remote-MCP mode (Path 4 of /setup-gbrain). Local artifacts sync is
# a no-op in remote mode; the brain server pulls from GitHub/GitLab on its
# own cadence. Read claude.json directly to keep this preamble fast (no
-# subprocess to claude CLI on every skill start).
+# subprocess to claude CLI on every skill start). Both registration scopes
+# are read (#2499): user scope, then the nearest-ancestor project scope.
_GBRAIN_MCP_MODE="none"
+_GBRAIN_MCP_ENTRY=""
if command -v jq >/dev/null 2>&1 && [ -f "$HOME/.claude.json" ]; then
- _GBRAIN_MCP_TYPE=$(jq -r '.mcpServers.gbrain.type // .mcpServers.gbrain.transport // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_ENTRY=$(jq -c --arg cwd "$PWD" '.mcpServers.gbrain // ((.projects // {}) | to_entries | map(select((.key as $k | $cwd == $k or ($cwd | startswith($k + "/"))) and ((try .value.mcpServers.gbrain catch null) != null))) | sort_by(.key | length) | last | .value.mcpServers.gbrain) // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_TYPE=$(printf '%s' "$_GBRAIN_MCP_ENTRY" | jq -r '.type // .transport // empty' 2>/dev/null)
case "$_GBRAIN_MCP_TYPE" in
url|http|sse) _GBRAIN_MCP_MODE="remote-http" ;;
stdio) _GBRAIN_MCP_MODE="local-stdio" ;;
@@ -530,6 +535,7 @@ if [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_DO_PULL=1
if [ -f "$_BRAIN_LAST_PULL_FILE" ]; then
_BRAIN_LAST=$(cat "$_BRAIN_LAST_PULL_FILE" 2>/dev/null || echo 0)
+ case "$_BRAIN_LAST" in ''|*[!0-9]*) _BRAIN_LAST=0 ;; esac
_BRAIN_AGE=$(( _BRAIN_NOW - _BRAIN_LAST ))
[ "$_BRAIN_AGE" -lt 86400 ] && _BRAIN_DO_PULL=0
fi
@@ -543,7 +549,7 @@ fi
if [ "$_GBRAIN_MCP_MODE" = "remote-http" ]; then
# Remote-MCP mode: local artifacts sync is a no-op (brain admin's server
# pulls from GitHub/GitLab). Show the user this is by design, not broken.
- _GBRAIN_HOST=$(jq -r '.mcpServers.gbrain.url // empty' "$HOME/.claude.json" 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|')
+ _GBRAIN_HOST=$(printf '%s' "${_GBRAIN_MCP_ENTRY:-}" | jq -r '.url // empty' 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|' | head -1 | tr -cd 'A-Za-z0-9._-')
echo "ARTIFACTS_SYNC: remote-mode (managed by brain server ${_GBRAIN_HOST:-remote})"
elif [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_QUEUE_DEPTH=0
@@ -628,8 +634,8 @@ eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)"
_PROJ="${GSTACK_HOME:-$HOME/.gstack}/projects/${SLUG:-unknown}"
if [ -d "$_PROJ" ]; then
echo "--- RECENT ARTIFACTS ---"
- find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs ls -t 2>/dev/null | head -3
- [ -f "$_PROJ/${_BRANCH}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/${_BRANCH}-reviews.jsonl" | tr -d ' ') entries"
+ find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3
+ [ -f "$_PROJ/${BRANCH:-unknown}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/${BRANCH:-unknown}-reviews.jsonl" | tr -d ' ') entries"
[ -f "$_PROJ/timeline.jsonl" ] && tail -5 "$_PROJ/timeline.jsonl"
if [ -f "$_PROJ/timeline.jsonl" ]; then
_LAST=$(grep "\"branch\":\"${_BRANCH}\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -1)
@@ -637,7 +643,7 @@ if [ -d "$_PROJ" ]; then
_RECENT_SKILLS=$(grep "\"branch\":\"${_BRANCH}\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -3 | grep -o '"skill":"[^"]*"' | sed 's/"skill":"//;s/"//' | tr '\n' ',')
[ -n "$_RECENT_SKILLS" ] && echo "RECENT_PATTERN: $_RECENT_SKILLS"
fi
- _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs ls -t 2>/dev/null | head -1)
+ _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs -r ls -t 2>/dev/null | head -1)
[ -n "$_LATEST_CP" ] && echo "LATEST_CHECKPOINT: $_LATEST_CP"
if [ -f "$_PROJ/decisions.active.json" ]; then
echo "--- ACTIVE DECISIONS (recent, scope-relevant) ---"
@@ -713,7 +719,7 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST
## Question Tuning (skip entirely if `QUESTION_TUNING: false`)
-Before each AskUserQuestion, choose `question_id` from `scripts/question-registry.ts` or `{skill}-{slug}`, then run `printf '%s' "<question summary>" | ~/.claude/skills/gstack/bin/gstack-question-preference --check "<id>" --summary-stdin` (piped summary feeds the one-way keyword net, #2024). `AUTO_DECIDE` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." `ASK_NORMALLY` means ask.
+Before each AskUserQuestion, choose `question_id` from `~/.claude/skills/gstack/scripts/question-registry.ts` or `{skill}-{slug}`, then run `printf '%s' "<question summary>" | ~/.claude/skills/gstack/bin/gstack-question-preference --check "<id>" --summary-stdin` (piped summary feeds the one-way keyword net, #2024). `AUTO_DECIDE` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." `ASK_NORMALLY` means ask.
**Embed the question_id as a marker in the question text** so hooks can identify it deterministically (plan-tune cathedral T14 / D18 progressive markers). Append `<gstack-qid:{question_id}>` somewhere in the rendered question (the leading line or trailing line is fine; the marker doesn't render visibly to the user when wrapped in HTML-style angle brackets, but the hook strips it). Without the marker the PreToolUse enforcement hook treats the AUQ as observed-only and never auto-decides — so always include it when the question matches a registered `question_id`.
diff --git a/lib/bin-context.ts b/lib/bin-context.ts
index faa1c65a2..28021b56a 100644
--- a/lib/bin-context.ts
+++ b/lib/bin-context.ts
@@ -6,12 +6,102 @@
*/
import { spawnSync } from "child_process";
+import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "fs";
+import { homedir } from "os";
+import { basename, join } from "path";
-/** Resolve the project slug via the `gstack-slug` helper (parses `SLUG=...`). */
+/** Keep the slug inside the [a-zA-Z0-9._-] alphabet gstack-slug promises (`tr -cd`). */
+function sanitizeSlug(s: string): string {
+ return s.replace(/[^a-zA-Z0-9._-]/g, "");
+}
+
+/**
+ * A Windows path in the MSYS form git-bash's `pwd` reports:
+ * `C:\Users\j\foo` → `/c/Users/j/foo`. gstack-slug keys its cache on THAT form
+ * (`tr '/' '_'`), so a native lookup must reproduce it exactly or it misses the very
+ * entry gstack-slug wrote and silently re-derives instead of staying consistent.
+ * Exported for the cache-key test; non-Windows paths pass through unchanged.
+ */
+export function toMsysPath(p: string): string {
+ const drive = p.match(/^([A-Za-z]):[\\/]/);
+ const body = (drive ? p.slice(2) : p).replace(/\\/g, "/");
+ return drive ? `/${drive[1].toLowerCase()}${body}` : body;
+}
+
+/**
+ * Native port of bin/gstack-slug's resolution order, used when that script cannot be
+ * spawned (see resolveSlug). Same three steps, same alphabet, same cache file — so
+ * this and the shell path always agree. They must: the bins WRITE using this, while
+ * the Context Recovery preamble READS using the script.
+ */
+export function slugFromEnvironment(gstackHome?: string, cwd: string = process.cwd()): string {
+ const home = gstackHome || process.env.GSTACK_HOME || join(homedir(), ".gstack");
+ const cacheDir = join(home, "slug-cache");
+ const cacheFile = join(cacheDir, toMsysPath(cwd).replace(/\//g, "_"));
+
+ let slug = "";
+ // 1. cached slug wins (guarantees consistency across sessions)
+ if (existsSync(cacheFile)) {
+ try {
+ slug = sanitizeSlug(readFileSync(cacheFile, "utf-8").trim());
+ } catch {
+ slug = "";
+ }
+ }
+ // 2. else derive from the git remote: [:/]<owner>/<repo>[.git] → owner-repo
+ if (!slug) {
+ const r = spawnSync("git", ["remote", "get-url", "origin"], { encoding: "utf-8", cwd });
+ const m = (r.stdout || "").trim().match(/[:/]([^/]+\/[^/]+?)(?:\.git)?$/);
+ if (m) slug = sanitizeSlug(m[1].replace(/\//g, "-"));
+ }
+ // 3. else the directory name
+ if (!slug) slug = sanitizeSlug(basename(cwd));
+ if (!slug) return "unknown";
+
+ // 4. cache it, as gstack-slug does — atomic, and failures stay silent (`|| true`)
+ try {
+ mkdirSync(cacheDir, { recursive: true });
+ const tmp = `${cacheFile}.tmp.${process.pid}`;
+ writeFileSync(tmp, slug, "utf-8");
+ renameSync(tmp, cacheFile);
+ } catch {
+ // best-effort cache; a miss only costs a re-derive on the next call
+ }
+ return slug;
+}
+
+/** Windows cannot exec an extensionless `#!/usr/bin/env bash` script (no shebang, no
+ * PATHEXT match for an explicit path), so gstack-slug spawns ENOENT there. */
+export const NEEDS_NATIVE_SLUG_ON_WINDOWS = process.platform === "win32";
+
+/**
+ * Resolve the project slug via the `gstack-slug` helper (parses `SLUG=...`).
+ *
+ * On Windows that spawn fails ENOENT (see NEEDS_NATIVE_SLUG_ON_WINDOWS) and `r.stdout`
+ * is undefined — the same class of hazard as the gbrain shim spawns in lib/gbrain-exec.ts
+ * (#1731). Returning the literal "unknown" filed every decision under
+ * ~/.gstack/projects/unknown/ — one bucket shared by every project on the machine —
+ * while the bash-side Context Recovery preamble resolved the real slug, found no
+ * decisions.active.json there, and skipped through a bare `if [ -f … ]` with no else.
+ *
+ * Nothing failed, for ten days: BOTH decision bins (log and search) missed identically,
+ * so writes and searches stayed consistent with each other, and the only component that
+ * resolved correctly was silent by design.
+ *
+ * `shell: true` is NOT the fix here, unlike #1731: cmd.exe cannot run a bash script
+ * either. Nor is re-spawning through `bash` — on Windows that frequently resolves to
+ * WSL, whose $HOME and /mnt/c paths yield a different slug AND a different cache
+ * directory, trading one split store for another.
+ *
+ * POSIX behaviour is unchanged: the fallback is win32-only, where the previous result
+ * was unconditionally wrong and so has nothing to regress.
+ */
export function resolveSlug(slugBinPath: string): string {
const r = spawnSync(slugBinPath, { encoding: "utf-8" });
const m = (r.stdout || "").match(/^SLUG=(.+)$/m);
- return m ? m[1].trim() : "unknown";
+ if (m) return m[1].trim();
+ if (NEEDS_NATIVE_SLUG_ON_WINDOWS) return slugFromEnvironment();
+ return "unknown";
}
/** Current git branch, or undefined on detached HEAD / outside a repo. */
diff --git a/lib/gbrain-exec.ts b/lib/gbrain-exec.ts
index 0cb1ddc57..a7d32dea7 100644
--- a/lib/gbrain-exec.ts
+++ b/lib/gbrain-exec.ts
@@ -21,10 +21,12 @@
* spawn. This is the central bug the helper exists to prevent
* regressing on.
*
- * 3. **`GBRAIN_HOME` honored consistently.** Other gstack helpers
- * (`detectEngineTier`) already honor `GBRAIN_HOME`. `buildGbrainEnv`
- * reads from `${GBRAIN_HOME:-$HOME/.gbrain}/config.json` so all
- * gstack-side gbrain calls agree on which config file matters.
+ * 3. **`GBRAIN_HOME` honored consistently — with gbrain's own semantics
+ * (#2521).** gbrain's configDir() treats `GBRAIN_HOME` as a PARENT
+ * directory and always appends `.gbrain` itself (GBRAIN_HOME=/tmp/x
+ * → /tmp/x/.gbrain/config.json). Every gstack-side read goes through
+ * `gbrainConfigDir()` below so gstack and gbrain agree on which
+ * config file matters.
*
* **Escape hatch:** `GSTACK_RESPECT_ENV_DATABASE_URL=1` returns the
* caller's env unchanged. Use only when the brain intentionally lives in
@@ -75,8 +77,21 @@ export function isTransactionModePooler(url: string): boolean {
}
/**
- * Build an env dict with DATABASE_URL seeded from
- * `${GBRAIN_HOME:-$HOME/.gbrain}/config.json`. Returns the base env
+ * gbrain's config directory, matching gbrain's own configDir() contract
+ * (#2521): `GBRAIN_HOME` is a PARENT directory — gbrain always appends
+ * `.gbrain` itself, so GBRAIN_HOME=/tmp/x reads /tmp/x/.gbrain/config.json.
+ * Unset → ~/.gbrain. Every gstack-side gbrain-config read MUST resolve
+ * through this helper, or gstack classifies engine status from a file
+ * gbrain never reads.
+ */
+export function gbrainConfigDir(env: NodeJS.ProcessEnv = process.env): string {
+ if (env.GBRAIN_HOME) return join(env.GBRAIN_HOME, ".gbrain");
+ return join(env.HOME || homedir(), ".gbrain");
+}
+
+/**
+ * Build an env dict with DATABASE_URL seeded from gbrain's config.json
+ * (resolved via `gbrainConfigDir`). Returns the base env
* unchanged when:
* - `GSTACK_RESPECT_ENV_DATABASE_URL=1` (intentional opt-out),
* - the config file is missing or unparseable,
@@ -98,9 +113,7 @@ export function buildGbrainEnv(opts: BuildGbrainEnvOptions = {}): NodeJS.Process
const out: NodeJS.ProcessEnv = { ...baseEnv };
if (baseEnv.GSTACK_RESPECT_ENV_DATABASE_URL === "1") return out;
- const homeBase = baseEnv.HOME || homedir();
- const gbrainHome = baseEnv.GBRAIN_HOME || join(homeBase, ".gbrain");
- const configPath = join(gbrainHome, "config.json");
+ const configPath = join(gbrainConfigDir(baseEnv), "config.json");
if (!existsSync(configPath)) return out;
let cfg: GbrainConfig = {};
@@ -136,6 +149,93 @@ export function buildGbrainEnv(opts: BuildGbrainEnvOptions = {}): NodeJS.Process
*/
export const NEEDS_SHELL_ON_WINDOWS = process.platform === "win32";
+/** Where Git for Windows puts bash, most-specific first. */
+const WINDOWS_BASH_CANDIDATES = [
+ "C:\\Program Files\\Git\\bin\\bash.exe",
+ "C:\\Program Files\\Git\\usr\\bin\\bash.exe",
+ "C:\\Program Files (x86)\\Git\\bin\\bash.exe",
+];
+
+export interface ScriptInvocation {
+ cmd: string;
+ argv: string[];
+ /** Always false: we resolve the interpreter ourselves rather than via cmd.exe. */
+ shell: false;
+}
+
+/**
+ * How to invoke a **bash shebang script** (`gstack-brain-sync`) on this platform.
+ *
+ * POSIX execs it directly — the shebang does the work. Windows cannot, and
+ * `shell: true` does NOT rescue it: that routes through cmd.exe, which resolves
+ * `.cmd`/`.bat` via PATHEXT but has no concept of a shebang, so an
+ * extension-less bash script comes back as *"is not recognized as an internal
+ * or external command"*. This is why #1731's `shell: NEEDS_SHELL_ON_WINDOWS`
+ * fix genuinely cured the `gbrain.cmd` shim while leaving the brain-sync stage
+ * failing on **every** run on Windows. The two cases look identical and are not:
+ * a `.cmd` shim needs a shell, a shebang script needs an interpreter.
+ *
+ * The consequence was quiet rather than loud. `artifacts_sync_mode` defaults to
+ * pushing curated artifacts to git, so a Windows user's learnings accumulated in
+ * `~/.gstack` and were never committed, while `/sync-gbrain` printed one red
+ * line among four green ones.
+ *
+ * Git for Windows' bash is preferred over a bare `bash` on PATH because
+ * WindowsApps ships a `bash.exe` that is the WSL launcher; if it wins PATH
+ * order it interprets `C:\...` as a Linux path and the script never sees the
+ * repo. `GSTACK_BASH` overrides everything for unusual installs.
+ *
+ * Returns `null` when no bash can be found, so the caller can say so plainly
+ * instead of surfacing a spawn error nobody can act on.
+ */
+export function bashScriptInvocation(
+ scriptPath: string,
+ args: string[],
+ opts: { platform?: string; exists?: (p: string) => boolean; env?: NodeJS.ProcessEnv } = {},
+): ScriptInvocation | null {
+ const platform = opts.platform ?? process.platform;
+ if (platform !== "win32") return { cmd: scriptPath, argv: args, shell: false };
+
+ const exists = opts.exists ?? existsSync;
+ const env = opts.env ?? process.env;
+
+ const override = env.GSTACK_BASH?.trim();
+ const candidates = [...(override ? [override] : []), ...WINDOWS_BASH_CANDIDATES];
+ const bash = candidates.find((p) => exists(p));
+ if (!bash) return null;
+
+ // Forward slashes: bash treats backslashes as escapes, so a Windows path
+ // passed verbatim loses its separators.
+ return { cmd: bash, argv: [scriptPath.replace(/\\/g, "/"), ...args], shell: false };
+}
+
+/**
+ * Quote one argument for cmd.exe's re-parse (#2471). With `shell: true` on
+ * Windows, Node/Bun JOIN the argv into a single cmd.exe string WITHOUT
+ * quoting, so any argument containing a space — the default
+ * `C:\Users\First Last\repo` home layout — splits into two arguments and the
+ * gbrain call silently targets the wrong path. Pass-through for the safe
+ * charset; everything else is double-quoted with embedded quotes doubled
+ * (cmd.exe's escape). POSIX callers never see this (shell is false there).
+ */
+export function windowsShellQuote(arg: string): string {
+ if (arg !== "" && /^[A-Za-z0-9_\-.:\\/=,@+]+$/.test(arg)) return arg;
+ return '"' + arg.replace(/"/g, '""') + '"';
+}
+
+/**
+ * The single seam for building a gbrain CLI invocation (#2471). Every
+ * spawnSync/execFileSync of the `gbrain` shim must construct its
+ * (cmd, argv, shell) triple here so the Windows quoting fix lives in exactly
+ * one place — a direct spawn of the literal "gbrain" string with a shell
+ * flag reopens the space-in-path split this exists to close.
+ */
+export function gbrainInvocation(args: string[]): { cmd: string; argv: string[]; shell: boolean } {
+ return NEEDS_SHELL_ON_WINDOWS
+ ? { cmd: "gbrain", argv: args.map(windowsShellQuote), shell: true }
+ : { cmd: "gbrain", argv: args, shell: false };
+}
+
export interface SpawnGbrainOptions {
/** Timeout in milliseconds. Defaults to 30s. */
timeout?: number;
@@ -159,13 +259,14 @@ export interface SpawnGbrainOptions {
* `stderr` exactly as they would with `spawnSync` directly.
*/
export function spawnGbrain(args: string[], opts: SpawnGbrainOptions = {}): SpawnSyncReturns<string> {
- return spawnSync("gbrain", args, {
+ const inv = gbrainInvocation(args);
+ return spawnSync(inv.cmd, inv.argv, {
encoding: "utf-8",
timeout: opts.timeout ?? 30_000,
cwd: opts.cwd,
stdio: opts.stdio || ["ignore", "pipe", "pipe"],
env: buildGbrainEnv({ baseEnv: opts.baseEnv, announce: opts.announce }),
- shell: NEEDS_SHELL_ON_WINDOWS, // #1731: gbrain is a .cmd shim on Windows
+ shell: inv.shell, // #1731: gbrain is a .cmd shim on Windows (+#2471 quoting)
});
}
@@ -194,11 +295,12 @@ export function spawnGbrainAsync(
args: string[],
opts: { stdio?: SpawnOptions["stdio"]; cwd?: string; baseEnv?: NodeJS.ProcessEnv } = {},
): ChildProcess {
- return spawn("gbrain", args, {
+ const inv = gbrainInvocation(args);
+ return spawn(inv.cmd, inv.argv, {
stdio: opts.stdio || ["ignore", "pipe", "pipe"],
cwd: opts.cwd,
env: buildGbrainEnv({ baseEnv: opts.baseEnv, announce: false }),
- shell: NEEDS_SHELL_ON_WINDOWS, // #1731: gbrain is a .cmd shim on Windows
+ shell: inv.shell, // #1731: gbrain is a .cmd shim on Windows (+#2471 quoting)
});
}
@@ -207,12 +309,13 @@ export function spawnGbrainAsync(
* for callers that want to surface gbrain's stderr as the error message.
*/
export function execGbrainText(args: string[], opts: SpawnGbrainOptions = {}): string {
- return execFileSync("gbrain", args, {
+ const inv = gbrainInvocation(args);
+ return execFileSync(inv.cmd, inv.argv, {
encoding: "utf-8",
timeout: opts.timeout ?? 30_000,
cwd: opts.cwd,
stdio: opts.stdio || ["ignore", "pipe", "pipe"],
env: buildGbrainEnv({ baseEnv: opts.baseEnv, announce: opts.announce }),
- shell: NEEDS_SHELL_ON_WINDOWS, // #1731: gbrain is a .cmd shim on Windows
+ shell: inv.shell, // #1731: gbrain is a .cmd shim on Windows (+#2471 quoting)
});
}
diff --git a/lib/gbrain-guards.ts b/lib/gbrain-guards.ts
index e983de260..1c46b4ad4 100644
--- a/lib/gbrain-guards.ts
+++ b/lib/gbrain-guards.ts
@@ -36,7 +36,9 @@ import { execGbrainJson, execGbrainText, NEEDS_SHELL_ON_WINDOWS } from "./gbrain
import { parseSourcesList, type GbrainSourceRow } from "./gbrain-sources";
export function gbrainHome(env: NodeJS.ProcessEnv = process.env): string {
- return env.GBRAIN_HOME || join(homedir(), ".gbrain");
+ // #2521: GBRAIN_HOME is a PARENT dir per gbrain's configDir() contract —
+ // gbrain appends `.gbrain` itself, so gstack must too.
+ return env.GBRAIN_HOME ? join(env.GBRAIN_HOME, ".gbrain") : join(homedir(), ".gbrain");
}
/**
diff --git a/lib/gbrain-local-status.ts b/lib/gbrain-local-status.ts
index a421b281f..ec2b115e1 100644
--- a/lib/gbrain-local-status.ts
+++ b/lib/gbrain-local-status.ts
@@ -24,12 +24,14 @@
* Timeout → probe exceeded GSTACK_GBRAIN_PROBE_TIMEOUT_MS (default 15s) with no
* recognized error — engine is likely healthy but slow (e.g. a cold
* pooler connection, #1964). Consumers treat this as usable.
- * Thin-client → config carries gbrain's remote_mcp marker (#2051): NO local
- * engine by design; queries go to a remote-HTTP MCP brain. Usable
- * for brain-aware prose gates; sync stages that need a LOCAL engine
- * (code/memory/dream) skip. Remote reachability is verified at USE
- * time (gbrain calls degrade gracefully), never by a classifier
- * network probe — that's the #1964 pathology.
+ * Thin-client → config carries gbrain's remote_mcp marker (#2051), OR the
+ * agent host's MCP registration is remote-HTTP-only (#2520 — bearer
+ * installs via `gbrain connect --token` never get the marker): NO
+ * local engine by design; queries go to a remote-HTTP MCP brain.
+ * Usable for brain-aware prose gates; sync stages that need a LOCAL
+ * engine (code/memory/dream) skip. Remote reachability is verified
+ * at USE time (gbrain calls degrade gracefully), never by a
+ * classifier network probe — that's the #1964 pathology.
* Ok → DB reachable, sources list returned valid JSON.
*/
@@ -46,7 +48,7 @@ import {
import { atomicWriteSync } from "./fs-atomic";
import { homedir } from "os";
import { dirname, join } from "path";
-import { buildGbrainEnv, NEEDS_SHELL_ON_WINDOWS } from "./gbrain-exec";
+import { buildGbrainEnv, gbrainConfigDir, NEEDS_SHELL_ON_WINDOWS } from "./gbrain-exec";
export type LocalEngineStatus =
| "ok"
@@ -120,11 +122,84 @@ export function cacheFilePath(): string {
);
}
-/** Honors GBRAIN_HOME (codex D11) — same resolution as buildGbrainEnv. */
+/**
+ * Honors GBRAIN_HOME (codex D11) with gbrain's own configDir() semantics
+ * (#2521): GBRAIN_HOME is a parent dir, `.gbrain` is appended. Same
+ * resolution as buildGbrainEnv — both route through gbrainConfigDir.
+ */
function gbrainConfigPath(env?: NodeJS.ProcessEnv): string {
const e = env ?? process.env;
- const gbrainHome = e.GBRAIN_HOME || join(userHome(e), ".gbrain");
- return join(gbrainHome, "config.json");
+ return join(gbrainConfigDir(e), "config.json");
+}
+
+/**
+ * Bearer-token thin-client evidence (#2520). `gbrain connect <url> --token`
+ * registers a remote-HTTP MCP server with the agent host but never writes
+ * gbrain's remote_mcp marker into config.json — that marker is OAuth-only,
+ * written by `gbrain init --mcp-only`. So the config-file marker check misses
+ * bearer installs entirely: they fall through to the local probe, which fails
+ * against the dead-or-absent local engine and lands on missing-config /
+ * broken-db / broken-config / engine-locked, silently suppressing brain
+ * blocks for a fully-working remote brain.
+ *
+ * Evidence read: ~/.claude.json MCP registrations — user scope AND project
+ * scope (project-scoped registrations are otherwise invisible, #2499).
+ * File-read only: no subprocess, no network (a classifier network probe is
+ * the #1964 pathology). Returns true only when a gbrain registration is
+ * remote-HTTP AND no gbrain registration is local-stdio — a local-stdio
+ * entry means the user runs a local engine (possibly alongside a remote one,
+ * e.g. federation), and local-engine statuses like engine-locked must keep
+ * their precise meaning there.
+ */
+export function hasRemoteOnlyGbrainMcp(env?: NodeJS.ProcessEnv): boolean {
+ interface McpEntry {
+ type?: string;
+ transport?: string;
+ command?: string;
+ url?: string;
+ }
+ let cj: unknown;
+ try {
+ cj = JSON.parse(readFileSync(join(userHome(env), ".claude.json"), "utf-8"));
+ } catch {
+ return false;
+ }
+ // Same classification rules as gstack-gbrain-detect's detectMcpMode tier 3,
+ // including the #2051 name generalization (gbrain, gbrain-remote, gbrain_work).
+ const classify = (entry: McpEntry): "remote" | "local" | null => {
+ const mtype = entry.type || entry.transport || "";
+ if (mtype === "url" || mtype === "http" || mtype === "sse") return "remote";
+ if (mtype === "stdio") return "local";
+ if (entry.url) return "remote";
+ if (entry.command) return "local";
+ return null;
+ };
+ let sawRemote = false;
+ let sawLocal = false;
+ const scan = (servers: unknown): void => {
+ if (!servers || typeof servers !== "object") return;
+ for (const [name, entry] of Object.entries(servers as Record<string, McpEntry>)) {
+ if (!entry || typeof entry !== "object") continue;
+ const isGbrainName = /^gbrain([-_][\w-]*)?$/.test(name);
+ const cmdMentionsGbrain =
+ typeof entry.command === "string" && /\bgbrain\b/.test(entry.command);
+ if (!isGbrainName && !cmdMentionsGbrain) continue;
+ const c = classify(entry);
+ if (c === "remote") sawRemote = true;
+ if (c === "local") sawLocal = true;
+ }
+ };
+ const root = cj as {
+ mcpServers?: unknown;
+ projects?: Record<string, { mcpServers?: unknown }>;
+ } | null;
+ scan(root?.mcpServers);
+ if (root?.projects && typeof root.projects === "object") {
+ for (const proj of Object.values(root.projects)) {
+ if (proj && typeof proj === "object") scan(proj.mcpServers);
+ }
+ }
+ return sawRemote && !sawLocal;
}
function configuredEngine(env?: NodeJS.ProcessEnv): "pglite" | "postgres" | null {
@@ -146,6 +221,10 @@ function hashPath(p: string): string {
* call share one fork-exec (~200ms saved per skill preamble).
*/
const _gbrainBinCache = new Map<string, string | null>();
+// On Windows the shim is `gbrain.cmd` → `bun run cli.ts`; a cold spawn can
+// exceed 2s, and a false negative here poisons the 60s status cache with
+// "no-cli". Give the shim headroom; POSIX keeps the tight timeout.
+const VERSION_PROBE_TIMEOUT_MS = NEEDS_SHELL_ON_WINDOWS ? 10_000 : 2_000;
export function resolveGbrainBin(env?: NodeJS.ProcessEnv): string | null {
const e = env ?? process.env;
const key = e.PATH || "";
@@ -154,7 +233,7 @@ export function resolveGbrainBin(env?: NodeJS.ProcessEnv): string | null {
try {
execFileSync("gbrain", ["--version"], {
encoding: "utf-8",
- timeout: 2_000,
+ timeout: VERSION_PROBE_TIMEOUT_MS,
stdio: ["ignore", "ignore", "ignore"],
env: e,
shell: NEEDS_SHELL_ON_WINDOWS, // #1731: gbrain is a .cmd shim on Windows
@@ -177,7 +256,7 @@ export function readGbrainVersion(env?: NodeJS.ProcessEnv): string {
try {
const out = execFileSync("gbrain", ["--version"], {
encoding: "utf-8",
- timeout: 2_000,
+ timeout: VERSION_PROBE_TIMEOUT_MS,
stdio: ["ignore", "pipe", "ignore"],
env: e,
shell: NEEDS_SHELL_ON_WINDOWS, // #1731: gbrain is a .cmd shim on Windows
@@ -271,8 +350,12 @@ function freshClassify(env?: NodeJS.ProcessEnv): LocalEngineStatus {
const gbrainBin = resolveGbrainBin(env);
if (!gbrainBin) return "no-cli";
- // 2. Config file present?
- if (!existsSync(gbrainConfigPath(env))) return "missing-config";
+ // 2. Config file present? A bearer thin client (#2520) may never have run
+ // a local init, so config.json can be absent while the remote-HTTP MCP
+ // registration IS the user's brain.
+ if (!existsSync(gbrainConfigPath(env))) {
+ return hasRemoteOnlyGbrainMcp(env) ? "thin-client" : "missing-config";
+ }
// 2.5 Thin client? gbrain's own marker (mirrors gbrain isThinClient():
// truthy remote_mcp in config). A thin client has NO local engine — gbrain
@@ -329,28 +412,45 @@ function freshClassify(env?: NodeJS.ProcessEnv): LocalEngineStatus {
// couldn't read — gbrain's dispatch guard says e.g. "`gbrain sources` is
// not routable ... (thin-client of <url>)"), then the more specific
// DB-unreachable signal.
- if (/thin[- ]client/i.test(stderr)) return "thin-client";
- if (stderr.includes("Cannot connect to database")) return "broken-db";
- if (stderr.includes("config.json")) return "broken-config";
-
- // PGLite is single-process. A long-lived `gbrain serve` can own the
- // embedded database, causing the CLI to finish with its own exit 124 and
- // "connect timed out" message. This is neither our watchdog timeout nor
- // evidence that the valid config is malformed (#2194).
- if (stderr.includes("connect timed out") || e.status === 124) {
- return configuredEngine(env) === "pglite" ? "engine-locked" : "broken-db";
- }
+ const raw = ((): LocalEngineStatus => {
+ if (/thin[- ]client/i.test(stderr)) return "thin-client";
+ if (stderr.includes("Cannot connect to database")) return "broken-db";
+ if (stderr.includes("config.json")) return "broken-config";
- // Probe killed by the timeout with no recognized error: the engine is
- // most likely healthy but slow (cold pooler connections measured at
- // 6.9-10.7s in #1964). Don't tell the user their config is malformed.
- if (e.killed === true || e.signal === "SIGTERM" || e.code === "ETIMEDOUT") {
- return "timeout";
- }
+ // PGLite is single-process. A long-lived `gbrain serve` can own the
+ // embedded database, causing the CLI to finish with its own exit 124 and
+ // "connect timed out" message. This is neither our watchdog timeout nor
+ // evidence that the valid config is malformed (#2194).
+ if (stderr.includes("connect timed out") || e.status === 124) {
+ return configuredEngine(env) === "pglite" ? "engine-locked" : "broken-db";
+ }
+
+ // Probe killed by the timeout with no recognized error: the engine is
+ // most likely healthy but slow (cold pooler connections measured at
+ // 6.9-10.7s in #1964). Don't tell the user their config is malformed.
+ if (e.killed === true || e.signal === "SIGTERM" || e.code === "ETIMEDOUT") {
+ return "timeout";
+ }
- // Defensive default per codex #8: unrecognized failures classify as
- // broken-config so the user sees the raw stderr surfaced upstream.
- return "broken-config";
+ // Defensive default per codex #8: unrecognized failures classify as
+ // broken-config so the user sees the raw stderr surfaced upstream.
+ return "broken-config";
+ })();
+
+ // #2520 bearer-token fallback: the local probe failed, but the user's
+ // only gbrain MCP registration is remote-HTTP — the dead-or-locked local
+ // engine is not their brain (typical shape: a leftover local config plus
+ // `gbrain connect --token`). Reclassify as thin-client so brain blocks
+ // stay rendered and sync's local stages skip with the accurate "nothing
+ // to do locally" message. "timeout" is deliberately excluded: it already
+ // counts as usable and may be a genuinely healthy slow LOCAL engine.
+ if (
+ (raw === "broken-db" || raw === "broken-config" || raw === "engine-locked") &&
+ hasRemoteOnlyGbrainMcp(env)
+ ) {
+ return "thin-client";
+ }
+ return raw;
}
}
diff --git a/lib/gbrain-sources.ts b/lib/gbrain-sources.ts
index 826e905ac..34b42319c 100644
--- a/lib/gbrain-sources.ts
+++ b/lib/gbrain-sources.ts
@@ -12,7 +12,7 @@
import { execFileSync, spawnSync } from "child_process";
import { realpathSync } from "fs";
import { withErrorContext } from "./gstack-memory-helpers";
-import { execGbrainJson, NEEDS_SHELL_ON_WINDOWS } from "./gbrain-exec";
+import { execGbrainJson, gbrainInvocation } from "./gbrain-exec";
import {
detectAutopilot,
decideSourceRemove,
@@ -117,12 +117,13 @@ function samePath(registered: string | undefined, requested: string): boolean {
export function probeSource(id: string, env?: NodeJS.ProcessEnv): SourceState {
let stdout: string;
try {
- stdout = execFileSync("gbrain", ["sources", "list", "--json"], {
+ const inv = gbrainInvocation(["sources", "list", "--json"]);
+ stdout = execFileSync(inv.cmd, inv.argv, {
encoding: "utf-8",
timeout: 30_000,
stdio: ["ignore", "pipe", "pipe"],
env,
- shell: NEEDS_SHELL_ON_WINDOWS, // #1731: gbrain is a .cmd shim on Windows
+ shell: inv.shell, // #1731: gbrain is a .cmd shim on Windows (+#2471 quoting)
});
} catch (err) {
const e = err as NodeJS.ErrnoException & { stderr?: Buffer };
@@ -224,29 +225,28 @@ export async function ensureSourceRegistered(
throw new Error(`refusing drift re-register of ${id}: ${decision.reason}`);
}
- const rm = spawnSync(
- "gbrain",
- ["sources", "remove", id, "--yes", "--confirm-destructive", ...decision.extraArgs],
- {
- encoding: "utf-8",
- timeout: 30_000,
- env,
- shell: NEEDS_SHELL_ON_WINDOWS, // #1731: gbrain is a .cmd shim on Windows
- },
- );
+ const rmInv = gbrainInvocation(["sources", "remove", id, "--yes", "--confirm-destructive", ...decision.extraArgs]);
+ const rm = spawnSync(rmInv.cmd, rmInv.argv, {
+ encoding: "utf-8",
+ timeout: 30_000,
+ env,
+ shell: rmInv.shell, // #1731: gbrain is a .cmd shim on Windows (+#2471 quoting)
+ });
if (rm.status !== 0) {
throw new Error(`gbrain sources remove ${id} failed: ${rm.stderr || rm.stdout || `exit ${rm.status}`}`);
}
}
- // Add.
+ // Add. `path` is a user repo path — the #2471 space-in-path victim; the
+ // invocation seam quotes it for cmd.exe's re-parse.
const addArgs = ["sources", "add", id, "--path", path];
if (federated) addArgs.push("--federated");
- const add = spawnSync("gbrain", addArgs, {
+ const addInv = gbrainInvocation(addArgs);
+ const add = spawnSync(addInv.cmd, addInv.argv, {
encoding: "utf-8",
timeout: 30_000,
env,
- shell: NEEDS_SHELL_ON_WINDOWS, // #1731: gbrain is a .cmd shim on Windows
+ shell: addInv.shell, // #1731: gbrain is a .cmd shim on Windows (+#2471 quoting)
});
if (add.status !== 0) {
throw new Error(`gbrain sources add ${id} failed: ${add.stderr || add.stdout || `exit ${add.status}`}`);
@@ -267,12 +267,13 @@ export async function ensureSourceRegistered(
export function sourcePageCount(id: string, env?: NodeJS.ProcessEnv): number | null {
let stdout: string;
try {
- stdout = execFileSync("gbrain", ["sources", "list", "--json"], {
+ const inv = gbrainInvocation(["sources", "list", "--json"]);
+ stdout = execFileSync(inv.cmd, inv.argv, {
encoding: "utf-8",
timeout: 30_000,
stdio: ["ignore", "pipe", "pipe"],
env,
- shell: NEEDS_SHELL_ON_WINDOWS, // #1731: gbrain is a .cmd shim on Windows
+ shell: inv.shell, // #1731: gbrain is a .cmd shim on Windows (+#2471 quoting)
});
} catch {
return null;
diff --git a/lib/gstack-memory-helpers.ts b/lib/gstack-memory-helpers.ts
index cca8515a1..91a786665 100644
--- a/lib/gstack-memory-helpers.ts
+++ b/lib/gstack-memory-helpers.ts
@@ -19,6 +19,7 @@
import { existsSync, readFileSync, writeFileSync, mkdirSync, statSync } from "fs";
import { appendJsonl } from "./jsonl-store";
+import { gbrainConfigDir } from "./gbrain-exec";
import { dirname, join } from "path";
import { execFileSync } from "child_process";
import { homedir } from "os";
@@ -256,12 +257,13 @@ export function detectEngineTier(): EngineDetect {
}
// Returns gbrain's config.json path, honoring GBRAIN_HOME env var with a
-// fallback to ~/.gbrain. gbrain >=0.25 dropped the top-level `engine` field
+// fallback to ~/.gbrain. Resolution matches gbrain's own configDir()
+// contract (#2521): GBRAIN_HOME is a parent dir, `.gbrain` is appended.
+// gbrain >=0.25 dropped the top-level `engine` field
// from doctor output, so this file is the only reliable source for engine
// detection on that version. See #1415.
function gbrainConfigPath(): string {
- const root = process.env.GBRAIN_HOME || join(homedir(), ".gbrain");
- return join(root, "config.json");
+ return join(gbrainConfigDir(process.env), "config.json");
}
// Best-effort JSONL append to ~/.gstack/.gbrain-errors.jsonl. Never throws.
diff --git a/lib/redact-patterns.ts b/lib/redact-patterns.ts
index 45a730c1a..b447e59cd 100644
--- a/lib/redact-patterns.ts
+++ b/lib/redact-patterns.ts
@@ -108,6 +108,39 @@ export function shannonEntropy(s: string): number {
return h;
}
+// env.kv name-shape calibration: the regex's zero-or-more-prefix net matches
+// ANY identifier ending in a credential suffix, so `cacheKey:`, `sortKey:`,
+// `partitionKey:`, `hotkey:`, even `monkey:` with an 8+-char entropic value
+// all hit a MEDIUM confirm prompt — a gate that cries wolf gets ignored.
+// A matched name only counts when its shape is credential-semantic:
+// (i) suffix separated from the prefix by _ / - / . (api_key, x-access-key,
+// AUTH.TOKEN)
+// (ii) the whole name IS the bare suffix (key:, token:)
+// (iii) the name is ALL-CAPS env style (APIKEY=, MY_APIKEY=)
+// (iv) a lowercase/camel compound whose prefix ends in a credential word
+// (apiKey, authToken, clientSecret, stripeApiKey) — cacheKey/sortKey/
+// monkey have no credential prefix and are rejected.
+const ENV_KV_NAME =
+ /^[ \t]*(?:export[ \t]+)?["']?([A-Za-z0-9_.-]*?(?:KEY|TOKEN|SECRET|PASSWORD|PASSWD|CREDENTIALS?|DSN|AUTH|COOKIE|SESSION|PRIVATE))["']?[ \t]*[:=]/i;
+const ENV_KV_SUFFIX =
+ /(KEY|TOKEN|SECRET|PASSWORD|PASSWD|CREDENTIALS?|DSN|AUTH|COOKIE|SESSION|PRIVATE)$/i;
+const ENV_KV_CRED_PREFIX =
+ /(api|auth|access|secret|private|app|client|server|master|admin|signing|encryption|session|csrf|jwt|oauth|bearer)$/i;
+
+/** True when the full env.kv match starts with a credential-shaped name. */
+export function isCredentialShapedEnvName(fullMatch: string): boolean {
+ const nameMatch = ENV_KV_NAME.exec(fullMatch);
+ if (!nameMatch) return false;
+ const name = nameMatch[1];
+ const suffixMatch = ENV_KV_SUFFIX.exec(name);
+ if (!suffixMatch) return false;
+ const prefix = name.slice(0, name.length - suffixMatch[1].length);
+ if (prefix === "") return true; // (ii) bare suffix
+ if (/[_.\-]$/.test(prefix)) return true; // (i) separator before suffix
+ if (!/[a-z]/.test(name)) return true; // (iii) ALL-CAPS env style
+ return ENV_KV_CRED_PREFIX.test(prefix); // (iv) credential-semantic compound
+}
+
/** True when an IPv4 string is a public address (not RFC1918/loopback/etc). */
export function isPublicIPv4(ip: string): boolean {
const m = ip.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);
@@ -168,6 +201,58 @@ function looksLikeCompactTimestamp(span: string): boolean {
);
}
+/** Context window for pairing a normalized parcel ID with its punctuated form. */
+const PARCEL_CONTEXT_CHARS = 400;
+
+/**
+ * County tax-map parcel ID (APN). Ohio's dominant form is NN-NNNNNNN.NNN, and
+ * some counties use a hyphen before the 3-4 digit suffix instead of a dot.
+ */
+const PARCEL_PUNCT_RE = /\b\d{2}-\d{4,8}[.\-]\d{3,4}\b/g;
+
+/**
+ * A parcel ID reads as a national-format phone number to pii.phone.e164 — the
+ * same collision class as the digit-only UUID that `insideUuid` already guards.
+ * Land/title repos carry these by the hundred, so the false positives are not
+ * incidental: they arrive on every branch that touches title, and a guardrail
+ * that cries wolf on the domain's primary identifier trains people to wave the
+ * warning through, which is how a real HIGH finding eventually gets ignored.
+ *
+ * Deliberately narrow, in two tiers:
+ *
+ * 1. The DOTTED form is exempt on its own shape. No phone convention places a
+ * dot before a trailing 3-4 digit group after a 4-8 digit middle, so this
+ * cannot swallow a real number. The hyphen-only variants (22-0001-000) are
+ * NOT exempted by shape — those genuinely are phone-shaped.
+ *
+ * 2. A DIGITS-ONLY span is phone-shaped in isolation, so it earns the exemption
+ * only by evidence: it must be the exact digit-normalization of a punctuated
+ * parcel ID within the surrounding window. Fixtures and marts always carry
+ * the pair ({parcel_id: "12-3456789.000", norm: "123456789000"}), and a bare
+ * phone number has no such twin nearby — so this reads the document's own
+ * evidence rather than guessing from digits.
+ */
+export function looksLikeParcelId(span: string, match: RegExpExecArray): boolean {
+ if (/^\d{2}-\d{4,8}\.\d{3,4}$/.test(span)) return true;
+ if (!/^\d{10,14}$/.test(span)) return false;
+
+ const input = match.input ?? "";
+ const spanStartInMatch = match[1] !== undefined ? match[0].indexOf(match[1]) : 0;
+ const spanStart = match.index + Math.max(0, spanStartInMatch);
+ const spanEnd = spanStart + span.length;
+ const window = input.slice(
+ Math.max(0, spanStart - PARCEL_CONTEXT_CHARS),
+ spanEnd + PARCEL_CONTEXT_CHARS,
+ );
+
+ PARCEL_PUNCT_RE.lastIndex = 0;
+ let p: RegExpExecArray | null;
+ while ((p = PARCEL_PUNCT_RE.exec(window)) !== null) {
+ if (p[0].replace(/\D/g, "") === span) return true;
+ }
+ return false;
+}
+
// ── Placeholder suppression (per-matched-span, NOT per-line) ─────────────────
/**
@@ -504,10 +589,26 @@ export const PATTERNS: RedactPattern[] = [
id: "env.kv",
tier: "MEDIUM",
category: "secret",
- description: "Env-style SECRET assignment with high-entropy value",
- regex: /^[ \t]*(?:export[ \t]+)?[A-Z][A-Z0-9_]*(?:KEY|TOKEN|SECRET|PASSWORD|PASSWD|CREDENTIALS?|DSN|AUTH|COOKIE|SESSION|PRIVATE)[ \t]*=[ \t]*['"]?([^\s'"]{8,})['"]?/,
- // Only fire on high-entropy values — kills `FOO_KEY=changeme` FPs.
- validate: (span) =>
+ description: "Secret-named assignment (env/YAML/JSON) with high-entropy value",
+ // #1946 gap 3: the original shape required an UPPERCASE name and an `=`
+ // assignment, so `api_key=…`, `apiKey: "…"`, and `password: …` (YAML/JSON
+ // colon form) produced NO finding at all — a detection fail-open on the
+ // most common config shapes. Now case-insensitive with `:` or `=`
+ // assignment and optional quotes around the key (JSON). Still MEDIUM and
+ // entropy-gated: this is the calibrated generic net, not a blocker.
+ // The name part is `[A-Za-z0-9_.-]*` + suffix (zero-or-more prefix, not
+ // one-or-more): a mandatory first char would swallow the suffix's own
+ // first letter and bare names like `password:` / `key:` would never match.
+ // The wide net is then calibrated by isCredentialShapedEnvName in
+ // validate — without it, any identifier that merely ENDS in a suffix
+ // (cacheKey:, sortKey:, monkey:) fires a MEDIUM confirm on entropic
+ // values. The value must stay capture group 1 (the engine masks group 1),
+ // so name-shape checking lives in validate, not in a second group.
+ regex: /^[ \t]*(?:export[ \t]+)?["']?[A-Za-z0-9_.-]*(?:KEY|TOKEN|SECRET|PASSWORD|PASSWD|CREDENTIALS?|DSN|AUTH|COOKIE|SESSION|PRIVATE)["']?[ \t]*[:=][ \t]*["']?([^\s'"]{8,})["']?/i,
+ // Only fire on credential-shaped names with high-entropy values — kills
+ // `FOO_KEY=changeme` and `cacheKey: <entropic-id>` FPs.
+ validate: (span, match) =>
+ isCredentialShapedEnvName(match[0]) &&
!isPlaceholderSpan(span) &&
!/^\$\{?[A-Za-z_]/.test(span) &&
shannonEntropy(span) >= 3.0,
@@ -549,11 +650,13 @@ export const PATTERNS: RedactPattern[] = [
regex: /(?<![\w.])(\+?[1-9]\d{0,2}[ \-.]?\(?\d{2,4}\)?[ \-.]?\d{3,4}[ \-.]?\d{3,4})(?![\w.])/,
autoRedactable: true,
redactToken: "<REDACTED-PHONE>",
- // A digit-only UUID's hyphen groups read as national phone formatting.
+ // A digit-only UUID's hyphen groups read as national phone formatting, and
+ // so does a county tax-map parcel ID (see looksLikeParcelId).
validate: (span, match) =>
!insideUuid(match) &&
span.replace(/\D/g, "").length >= 10 &&
- !looksLikeCompactTimestamp(span),
+ !looksLikeCompactTimestamp(span) &&
+ !looksLikeParcelId(span, match),
},
{
id: "pii.ssn",
diff --git a/lib/version-source.ts b/lib/version-source.ts
new file mode 100644
index 000000000..17a745131
--- /dev/null
+++ b/lib/version-source.ts
@@ -0,0 +1,130 @@
+// version-source — where a repo's version lives, and how wide it is.
+//
+// gstack's native shape is a plain-text VERSION file at the repo root holding a
+// 4-digit MAJOR.MINOR.PATCH.MICRO — and for gstack itself that file STAYS the
+// source of truth (decision pinned in the v1.67 fix-wave plan: package.json is
+// a translated mirror, never the authority). This module exists for the two
+// real-world shapes that did not fit and both failed CLOSED in a way that
+// silently disabled /ship's version tooling (#2501):
+//
+// 1. The version's home is a package.json — often not at the root (a monorepo
+// whose frontend/package.json is the single source of truth because the
+// build injects it). The --version-path / .gstack/version-path pin already
+// let you point anywhere, but the readers treated the target as raw text,
+// so a JSON file was whitespace-stripped into `{"name":"frontend",...` and
+// every version read came back as the 0.0.0.0 fallback — including rival
+// PRs' claims fetched through the GitHub Contents API, which were then
+// dropped as "malformed".
+// 2. The version is 3-digit semver. parseVersion() required exactly four
+// components, so gstack-next-version exited 2 ("could not parse base
+// version") on every invocation — and that CLI *is* the queue-collision
+// check, so /ship fell through to its documented "offline" path of naive
+// local arithmetic. Two branches cut from the same base then pick the same
+// version, and git merges that without a conflict because both sides set
+// one line to identical text. The duplicate slot ships silently.
+//
+// Both are handled here rather than in each CLI so the two agree by construction.
+//
+// Detection is by shape, not configuration: a version-path ending in .json is
+// read as JSON (.version), anything else as trimmed text; a version string with
+// three components stays three components through bumping and formatting. A
+// repo with a root VERSION file and 4-digit versions sees no behaviour change.
+//
+// Re-derived from PR #2501 by @YiftahR.
+
+export type Version = [number, number, number, number];
+export type VersionWidth = 3 | 4;
+export type Bump = "major" | "minor" | "patch" | "micro";
+
+/** Parse 3- or 4-component versions. 3-digit pads to [a,b,c,0] so comparison stays uniform. */
+export function parseVersion(s: string): Version | null {
+ const m = s.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:\.(\d+))?$/);
+ if (!m) return null;
+ return [Number(m[1]), Number(m[2]), Number(m[3]), Number(m[4] ?? 0)];
+}
+
+/** How many components the string actually had — what to format back out as. */
+export function versionWidth(s: string): VersionWidth {
+ return /^\d+\.\d+\.\d+\.\d+$/.test(s.trim()) ? 4 : 3;
+}
+
+export function fmtVersion(v: Version, width: VersionWidth = 4): string {
+ return v.slice(0, width).join(".");
+}
+
+export function cmpVersion(a: Version, b: Version): number {
+ for (let i = 0; i < 4; i++) {
+ if (a[i] !== b[i]) return a[i] - b[i];
+ }
+ return 0;
+}
+
+/**
+ * Bump one level. In a 3-digit repo there is no MICRO component to move, so
+ * `micro` is carried out as a PATCH: /ship auto-picks MICRO by default, and
+ * erroring there would make it unusable in every 3-digit repo — a silent no-op
+ * would be worse still, since the caller would then write back the version it
+ * started with and claim a taken slot.
+ */
+export function bumpVersion(v: Version, level: Bump, width: VersionWidth = 4): Version {
+ const effective: Bump = width === 3 && level === "micro" ? "patch" : level;
+ switch (effective) {
+ case "major":
+ return [v[0] + 1, 0, 0, 0];
+ case "minor":
+ return [v[0], v[1] + 1, 0, 0];
+ case "patch":
+ return [v[0], v[1], v[2] + 1, 0];
+ case "micro":
+ return [v[0], v[1], v[2], v[3] + 1];
+ }
+}
+
+/** True when the effective bump differs from the one asked for (so callers can say so). */
+export function bumpWasCoerced(level: Bump, width: VersionWidth): boolean {
+ return width === 3 && level === "micro";
+}
+
+/**
+ * The npm-valid form of a gstack version. npm's semver is 3-component and
+ * rejects a fourth, so the 4-digit MAJOR.MINOR.PATCH.MICRO truncates to
+ * MAJOR.MINOR.PATCH; 3-digit versions pass through unchanged. Per the
+ * version-tooling end-state spec (v1.67 fix-wave plan, decision 11): the
+ * manifest mirror always carries this form, and VERSION stays the 4-digit
+ * source of truth.
+ */
+export function npmVersion(version: string): string {
+ return version.trim().split(".").slice(0, 3).join(".");
+}
+
+/** A version-path pointing at a .json is read as JSON, not as raw text. */
+export function isJsonVersionPath(versionPath: string): boolean {
+ return /\.json$/i.test(versionPath.trim());
+}
+
+/**
+ * Pull the version out of whatever the version-path resolves to. `text` is the
+ * file's contents from anywhere — local read, `git show`, or a base64-decoded
+ * API response — so every reader agrees on interpretation. Returns "" when
+ * there is no usable version, which callers map to their own fallback.
+ */
+export function extractVersion(text: string, versionPath: string): string {
+ if (!isJsonVersionPath(versionPath)) return text.replace(/[\r\n\s]/g, "");
+ try {
+ const parsed = JSON.parse(text) as { version?: unknown };
+ return typeof parsed?.version === "string" ? parsed.version.trim() : "";
+ } catch {
+ return "";
+ }
+}
+
+/**
+ * Write a version back into a JSON file, preserving the rest of it. Deliberately
+ * key-order-preserving (JSON.parse/stringify keeps insertion order) and 2-space
+ * indented with a trailing newline, matching what package managers write.
+ */
+export function setVersionInJson(raw: string, version: string): string {
+ const parsed = JSON.parse(raw) as Record<string, unknown>;
+ parsed.version = version;
+ return JSON.stringify(parsed, null, 2) + "\n";
+}
diff --git a/make-pdf/SKILL.md b/make-pdf/SKILL.md
index 1e181760c..9fbe62c8e 100644
--- a/make-pdf/SKILL.md
+++ b/make-pdf/SKILL.md
@@ -109,9 +109,11 @@ else
fi
~/.claude/skills/gstack/bin/gstack-timeline-log '{"skill":"make-pdf","event":"started","branch":"'"$_BRANCH"'","session":"'"$_SESSION_ID"'"}' 2>/dev/null &
_HAS_ROUTING="no"
-if [ -f CLAUDE.md ] && grep -q "## Skill routing" CLAUDE.md 2>/dev/null; then
- _HAS_ROUTING="yes"
-fi
+for _RF in CLAUDE.md AGENTS.md; do
+ if [ -f "$_RF" ] && grep -q "## Skill routing" "$_RF" 2>/dev/null; then
+ _HAS_ROUTING="yes"
+ fi
+done
_ROUTING_DECLINED=$(~/.claude/skills/gstack/bin/gstack-config get routing_declined 2>/dev/null || echo "false")
echo "HAS_ROUTING: $_HAS_ROUTING"
echo "ROUTING_DECLINED: $_ROUTING_DECLINED"
@@ -416,10 +418,13 @@ _BRAIN_SYNC_MODE=$("$_BRAIN_CONFIG_BIN" get artifacts_sync_mode 2>/dev/null || e
# Detect remote-MCP mode (Path 4 of /setup-gbrain). Local artifacts sync is
# a no-op in remote mode; the brain server pulls from GitHub/GitLab on its
# own cadence. Read claude.json directly to keep this preamble fast (no
-# subprocess to claude CLI on every skill start).
+# subprocess to claude CLI on every skill start). Both registration scopes
+# are read (#2499): user scope, then the nearest-ancestor project scope.
_GBRAIN_MCP_MODE="none"
+_GBRAIN_MCP_ENTRY=""
if command -v jq >/dev/null 2>&1 && [ -f "$HOME/.claude.json" ]; then
- _GBRAIN_MCP_TYPE=$(jq -r '.mcpServers.gbrain.type // .mcpServers.gbrain.transport // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_ENTRY=$(jq -c --arg cwd "$PWD" '.mcpServers.gbrain // ((.projects // {}) | to_entries | map(select((.key as $k | $cwd == $k or ($cwd | startswith($k + "/"))) and ((try .value.mcpServers.gbrain catch null) != null))) | sort_by(.key | length) | last | .value.mcpServers.gbrain) // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_TYPE=$(printf '%s' "$_GBRAIN_MCP_ENTRY" | jq -r '.type // .transport // empty' 2>/dev/null)
case "$_GBRAIN_MCP_TYPE" in
url|http|sse) _GBRAIN_MCP_MODE="remote-http" ;;
stdio) _GBRAIN_MCP_MODE="local-stdio" ;;
@@ -440,6 +445,7 @@ if [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_DO_PULL=1
if [ -f "$_BRAIN_LAST_PULL_FILE" ]; then
_BRAIN_LAST=$(cat "$_BRAIN_LAST_PULL_FILE" 2>/dev/null || echo 0)
+ case "$_BRAIN_LAST" in ''|*[!0-9]*) _BRAIN_LAST=0 ;; esac
_BRAIN_AGE=$(( _BRAIN_NOW - _BRAIN_LAST ))
[ "$_BRAIN_AGE" -lt 86400 ] && _BRAIN_DO_PULL=0
fi
@@ -453,7 +459,7 @@ fi
if [ "$_GBRAIN_MCP_MODE" = "remote-http" ]; then
# Remote-MCP mode: local artifacts sync is a no-op (brain admin's server
# pulls from GitHub/GitLab). Show the user this is by design, not broken.
- _GBRAIN_HOST=$(jq -r '.mcpServers.gbrain.url // empty' "$HOME/.claude.json" 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|')
+ _GBRAIN_HOST=$(printf '%s' "${_GBRAIN_MCP_ENTRY:-}" | jq -r '.url // empty' 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|' | head -1 | tr -cd 'A-Za-z0-9._-')
echo "ARTIFACTS_SYNC: remote-mode (managed by brain server ${_GBRAIN_HOST:-remote})"
elif [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_QUEUE_DEPTH=0
diff --git a/make-pdf/src/cli.ts b/make-pdf/src/cli.ts
index 988e20444..642e8a7a5 100644
--- a/make-pdf/src/cli.ts
+++ b/make-pdf/src/cli.ts
@@ -20,7 +20,20 @@ interface ParsedArgs {
flags: Record<string, string | boolean>;
}
-function parseArgs(argv: string[]): ParsedArgs {
+/**
+ * Flags that never take a value (#2514). The parser used to treat ANY
+ * following non-flag token as the flag's value, so the skill's own
+ * documented usage — `$P generate --cover --toc essay.md essay.pdf` — worked
+ * only by luck of flag adjacency, while `$P generate --toc essay.md` ate
+ * `essay.md` as --toc's value and failed with "missing input".
+ */
+export const BOOLEAN_FLAGS = new Set([
+ "cover", "toc", "no-chapter-breaks", "confidential", "no-confidential",
+ "page-numbers", "no-page-numbers", "tagged", "no-tagged",
+ "outline", "no-outline", "quiet", "verbose", "allow-network", "strict",
+]);
+
+export function parseArgs(argv: string[]): ParsedArgs {
const args = argv.slice(2);
if (args.length === 0) {
printUsage();
@@ -37,7 +50,7 @@ function parseArgs(argv: string[]): ParsedArgs {
if (a.startsWith("--")) {
const key = a.slice(2);
const next = args[i + 1];
- if (next !== undefined && !next.startsWith("--")) {
+ if (!BOOLEAN_FLAGS.has(key) && next !== undefined && !next.startsWith("--")) {
flags[key] = next;
i++;
} else {
@@ -272,4 +285,7 @@ async function main(): Promise<void> {
}
}
-main();
+// Guarded so tests can import parseArgs/BOOLEAN_FLAGS without running the CLI.
+if (import.meta.main) {
+ main();
+}
diff --git a/make-pdf/test/cli-args.test.ts b/make-pdf/test/cli-args.test.ts
new file mode 100644
index 000000000..2479e7720
--- /dev/null
+++ b/make-pdf/test/cli-args.test.ts
@@ -0,0 +1,94 @@
+/**
+ * #2514: boolean flags (--toc, --cover, ...) must never swallow the next
+ * positional argument. The parser treated ANY following non-flag token as a
+ * flag value, so `$P generate --toc essay.md` ate essay.md as --toc's value
+ * and the skill's own documented invocations failed with "missing input".
+ */
+
+import { describe, test, expect } from "bun:test";
+import * as fs from "fs";
+import * as path from "path";
+import { parseArgs, BOOLEAN_FLAGS } from "../src/cli";
+import { COMMANDS } from "../src/commands";
+
+// parseArgs slices argv from index 2 (node/bun + script path).
+const parse = (...args: string[]) => parseArgs(["bun", "cli.ts", ...args]);
+
+describe("#2514 boolean flags do not swallow positionals", () => {
+ test("--toc before the input keeps the input positional", () => {
+ const r = parse("generate", "--toc", "essay.md");
+ expect(r.command).toBe("generate");
+ expect(r.flags.toc).toBe(true);
+ expect(r.positional).toEqual(["essay.md"]);
+ });
+
+ test("the skill's documented usage parses: --cover --toc essay.md essay.pdf", () => {
+ const r = parse("generate", "--cover", "--toc", "essay.md", "essay.pdf");
+ expect(r.flags.cover).toBe(true);
+ expect(r.flags.toc).toBe(true);
+ expect(r.positional).toEqual(["essay.md", "essay.pdf"]);
+ });
+
+ test("value flags still consume their value", () => {
+ const r = parse("generate", "--watermark", "DRAFT", "memo.md");
+ expect(r.flags.watermark).toBe("DRAFT");
+ expect(r.positional).toEqual(["memo.md"]);
+ });
+
+ test("--to consumes its format value", () => {
+ const r = parse("generate", "--to", "html", "doc.md");
+ expect(r.flags.to).toBe("html");
+ expect(r.positional).toEqual(["doc.md"]);
+ });
+
+ test("every boolean read in cli.ts is covered by the set (derived, not hardcoded)", () => {
+ // The original guard hardcoded six names, so --strict and --confidential
+ // shipped outside the set and still swallowed the next positional — the
+ // exact #2514 failure. Derive the list from the source's own boolean
+ // reads instead: `f.name === true` / `f["some-name"] === true` direct
+ // reads, plus booleanFlag("name", ...) pairs which read BOTH name and
+ // no-name. A new boolean read now fails this test until it joins the set.
+ const src = fs.readFileSync(path.join(import.meta.dir, "..", "src", "cli.ts"), "utf-8");
+ const derived = new Set<string>();
+ for (const m of src.matchAll(/\bf\.([a-zA-Z][\w-]*) === true/g)) derived.add(m[1]);
+ for (const m of src.matchAll(/\bf\["([\w-]+)"\] === true/g)) derived.add(m[1]);
+ for (const m of src.matchAll(/booleanFlag\("([\w-]+)"/g)) {
+ derived.add(m[1]);
+ derived.add(`no-${m[1]}`);
+ }
+ expect(derived.size).toBeGreaterThanOrEqual(6); // regex went blind if this drops
+ for (const f of derived) {
+ expect(BOOLEAN_FLAGS.has(f), `boolean read '--${f}' is missing from BOOLEAN_FLAGS`).toBe(true);
+ }
+ });
+
+ test("--strict does not swallow the input (the documented CI-mode flag, #2514)", () => {
+ const r = parse("generate", "--strict", "essay.md");
+ expect(r.flags.strict).toBe(true);
+ expect(r.positional).toEqual(["essay.md"]);
+ });
+
+ test("--no-confidential and --confidential both stay valueless", () => {
+ const a = parse("generate", "--no-confidential", "memo.md");
+ expect(a.flags["no-confidential"]).toBe(true);
+ expect(a.positional).toEqual(["memo.md"]);
+ const b = parse("generate", "--confidential", "memo.md");
+ expect(b.flags.confidential).toBe(true);
+ expect(b.positional).toEqual(["memo.md"]);
+ });
+
+ test("structural (T4): every --no-* flag in the commands.ts registry is boolean", () => {
+ // A --no-* flag is a negation — it never takes a value. A new one added
+ // to the registry but missed in BOOLEAN_FLAGS silently re-opens #2514
+ // (it would swallow the next positional). Derived from the registry, so
+ // this cannot rot as commands grow.
+ const missing: string[] = [];
+ for (const [cmd, spec] of COMMANDS) {
+ for (const flag of spec.flags ?? []) {
+ if (!/^--no-/.test(flag)) continue;
+ if (!BOOLEAN_FLAGS.has(flag.replace(/^--/, ""))) missing.push(`${cmd}: ${flag}`);
+ }
+ }
+ expect(missing).toEqual([]);
+ });
+});
diff --git a/office-hours/SKILL.md b/office-hours/SKILL.md
index 9c7dc5cad..978d473d8 100644
--- a/office-hours/SKILL.md
+++ b/office-hours/SKILL.md
@@ -145,9 +145,11 @@ else
fi
~/.claude/skills/gstack/bin/gstack-timeline-log '{"skill":"office-hours","event":"started","branch":"'"$_BRANCH"'","session":"'"$_SESSION_ID"'"}' 2>/dev/null &
_HAS_ROUTING="no"
-if [ -f CLAUDE.md ] && grep -q "## Skill routing" CLAUDE.md 2>/dev/null; then
- _HAS_ROUTING="yes"
-fi
+for _RF in CLAUDE.md AGENTS.md; do
+ if [ -f "$_RF" ] && grep -q "## Skill routing" "$_RF" 2>/dev/null; then
+ _HAS_ROUTING="yes"
+ fi
+done
_ROUTING_DECLINED=$(~/.claude/skills/gstack/bin/gstack-config get routing_declined 2>/dev/null || echo "false")
echo "HAS_ROUTING: $_HAS_ROUTING"
echo "ROUTING_DECLINED: $_ROUTING_DECLINED"
@@ -541,10 +543,13 @@ _BRAIN_SYNC_MODE=$("$_BRAIN_CONFIG_BIN" get artifacts_sync_mode 2>/dev/null || e
# Detect remote-MCP mode (Path 4 of /setup-gbrain). Local artifacts sync is
# a no-op in remote mode; the brain server pulls from GitHub/GitLab on its
# own cadence. Read claude.json directly to keep this preamble fast (no
-# subprocess to claude CLI on every skill start).
+# subprocess to claude CLI on every skill start). Both registration scopes
+# are read (#2499): user scope, then the nearest-ancestor project scope.
_GBRAIN_MCP_MODE="none"
+_GBRAIN_MCP_ENTRY=""
if command -v jq >/dev/null 2>&1 && [ -f "$HOME/.claude.json" ]; then
- _GBRAIN_MCP_TYPE=$(jq -r '.mcpServers.gbrain.type // .mcpServers.gbrain.transport // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_ENTRY=$(jq -c --arg cwd "$PWD" '.mcpServers.gbrain // ((.projects // {}) | to_entries | map(select((.key as $k | $cwd == $k or ($cwd | startswith($k + "/"))) and ((try .value.mcpServers.gbrain catch null) != null))) | sort_by(.key | length) | last | .value.mcpServers.gbrain) // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_TYPE=$(printf '%s' "$_GBRAIN_MCP_ENTRY" | jq -r '.type // .transport // empty' 2>/dev/null)
case "$_GBRAIN_MCP_TYPE" in
url|http|sse) _GBRAIN_MCP_MODE="remote-http" ;;
stdio) _GBRAIN_MCP_MODE="local-stdio" ;;
@@ -565,6 +570,7 @@ if [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_DO_PULL=1
if [ -f "$_BRAIN_LAST_PULL_FILE" ]; then
_BRAIN_LAST=$(cat "$_BRAIN_LAST_PULL_FILE" 2>/dev/null || echo 0)
+ case "$_BRAIN_LAST" in ''|*[!0-9]*) _BRAIN_LAST=0 ;; esac
_BRAIN_AGE=$(( _BRAIN_NOW - _BRAIN_LAST ))
[ "$_BRAIN_AGE" -lt 86400 ] && _BRAIN_DO_PULL=0
fi
@@ -578,7 +584,7 @@ fi
if [ "$_GBRAIN_MCP_MODE" = "remote-http" ]; then
# Remote-MCP mode: local artifacts sync is a no-op (brain admin's server
# pulls from GitHub/GitLab). Show the user this is by design, not broken.
- _GBRAIN_HOST=$(jq -r '.mcpServers.gbrain.url // empty' "$HOME/.claude.json" 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|')
+ _GBRAIN_HOST=$(printf '%s' "${_GBRAIN_MCP_ENTRY:-}" | jq -r '.url // empty' 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|' | head -1 | tr -cd 'A-Za-z0-9._-')
echo "ARTIFACTS_SYNC: remote-mode (managed by brain server ${_GBRAIN_HOST:-remote})"
elif [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_QUEUE_DEPTH=0
@@ -663,8 +669,8 @@ eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)"
_PROJ="${GSTACK_HOME:-$HOME/.gstack}/projects/${SLUG:-unknown}"
if [ -d "$_PROJ" ]; then
echo "--- RECENT ARTIFACTS ---"
- find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs ls -t 2>/dev/null | head -3
- [ -f "$_PROJ/${_BRANCH}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/${_BRANCH}-reviews.jsonl" | tr -d ' ') entries"
+ find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3
+ [ -f "$_PROJ/${BRANCH:-unknown}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/${BRANCH:-unknown}-reviews.jsonl" | tr -d ' ') entries"
[ -f "$_PROJ/timeline.jsonl" ] && tail -5 "$_PROJ/timeline.jsonl"
if [ -f "$_PROJ/timeline.jsonl" ]; then
_LAST=$(grep "\"branch\":\"${_BRANCH}\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -1)
@@ -672,7 +678,7 @@ if [ -d "$_PROJ" ]; then
_RECENT_SKILLS=$(grep "\"branch\":\"${_BRANCH}\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -3 | grep -o '"skill":"[^"]*"' | sed 's/"skill":"//;s/"//' | tr '\n' ',')
[ -n "$_RECENT_SKILLS" ] && echo "RECENT_PATTERN: $_RECENT_SKILLS"
fi
- _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs ls -t 2>/dev/null | head -1)
+ _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs -r ls -t 2>/dev/null | head -1)
[ -n "$_LATEST_CP" ] && echo "LATEST_CHECKPOINT: $_LATEST_CP"
if [ -f "$_PROJ/decisions.active.json" ]; then
echo "--- ACTIVE DECISIONS (recent, scope-relevant) ---"
@@ -748,7 +754,7 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST
## Question Tuning (skip entirely if `QUESTION_TUNING: false`)
-Before each AskUserQuestion, choose `question_id` from `scripts/question-registry.ts` or `{skill}-{slug}`, then run `printf '%s' "<question summary>" | ~/.claude/skills/gstack/bin/gstack-question-preference --check "<id>" --summary-stdin` (piped summary feeds the one-way keyword net, #2024). `AUTO_DECIDE` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." `ASK_NORMALLY` means ask.
+Before each AskUserQuestion, choose `question_id` from `~/.claude/skills/gstack/scripts/question-registry.ts` or `{skill}-{slug}`, then run `printf '%s' "<question summary>" | ~/.claude/skills/gstack/bin/gstack-question-preference --check "<id>" --summary-stdin` (piped summary feeds the one-way keyword net, #2024). `AUTO_DECIDE` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." `ASK_NORMALLY` means ask.
**Embed the question_id as a marker in the question text** so hooks can identify it deterministically (plan-tune cathedral T14 / D18 progressive markers). Append `<gstack-qid:{question_id}>` somewhere in the rendered question (the leading line or trailing line is fine; the marker doesn't render visibly to the user when wrapped in HTML-style angle brackets, but the hook strips it). Without the marker the PreToolUse enforcement hook treats the AUQ as observed-only and never auto-decides — so always include it when the question matches a registered `question_id`.
@@ -1371,7 +1377,7 @@ Then add the context block and mode-appropriate instructions:
```bash
TMPERR_OH=$(mktemp /tmp/codex-oh-err-XXXXXXXX)
_REPO_ROOT=$(git rev-parse --show-toplevel) || { echo "ERROR: not in a git repo" >&2; exit 1; }
-codex exec "$(cat "$CODEX_PROMPT_FILE")" -C "$_REPO_ROOT" -s read-only -c 'model_reasoning_effort="high"' --enable web_search_cached < /dev/null 2>"$TMPERR_OH"
+codex exec "$(cat "$CODEX_PROMPT_FILE")" -C "$_REPO_ROOT" -s read-only -c 'model_reasoning_effort="high"' -c 'web_search="cached"' < /dev/null 2>"$TMPERR_OH"
```
Use a 5-minute timeout (`timeout: 300000`). After the command completes, read stderr:
@@ -1621,7 +1627,7 @@ If user chooses A, launch both voices simultaneously:
```bash
TMPERR_SKETCH=$(mktemp /tmp/codex-sketch-XXXXXXXX)
_REPO_ROOT=$(git rev-parse --show-toplevel) || { echo "ERROR: not in a git repo" >&2; exit 1; }
-codex exec "For this product approach, provide: a visual thesis (one sentence — mood, material, energy), a content plan (hero → support → detail → CTA), and 2 interaction ideas that change page feel. Apply beautiful defaults: composition-first, brand-first, cardless, poster not document. Be opinionated." -C "$_REPO_ROOT" -s read-only -c 'model_reasoning_effort="medium"' --enable web_search_cached < /dev/null 2>"$TMPERR_SKETCH"
+codex exec "For this product approach, provide: a visual thesis (one sentence — mood, material, energy), a content plan (hero → support → detail → CTA), and 2 interaction ideas that change page feel. Apply beautiful defaults: composition-first, brand-first, cardless, poster not document. Be opinionated." -C "$_REPO_ROOT" -s read-only -c 'model_reasoning_effort="medium"' -c 'web_search="cached"' < /dev/null 2>"$TMPERR_SKETCH"
```
Use a 5-minute timeout (`timeout: 300000`). After completion: `cat "$TMPERR_SKETCH" && rm -f "$TMPERR_SKETCH"`
diff --git a/open-gstack-browser/SKILL.md b/open-gstack-browser/SKILL.md
index 6d05a6723..956a748ef 100644
--- a/open-gstack-browser/SKILL.md
+++ b/open-gstack-browser/SKILL.md
@@ -108,9 +108,11 @@ else
fi
~/.claude/skills/gstack/bin/gstack-timeline-log '{"skill":"open-gstack-browser","event":"started","branch":"'"$_BRANCH"'","session":"'"$_SESSION_ID"'"}' 2>/dev/null &
_HAS_ROUTING="no"
-if [ -f CLAUDE.md ] && grep -q "## Skill routing" CLAUDE.md 2>/dev/null; then
- _HAS_ROUTING="yes"
-fi
+for _RF in CLAUDE.md AGENTS.md; do
+ if [ -f "$_RF" ] && grep -q "## Skill routing" "$_RF" 2>/dev/null; then
+ _HAS_ROUTING="yes"
+ fi
+done
_ROUTING_DECLINED=$(~/.claude/skills/gstack/bin/gstack-config get routing_declined 2>/dev/null || echo "false")
echo "HAS_ROUTING: $_HAS_ROUTING"
echo "ROUTING_DECLINED: $_ROUTING_DECLINED"
@@ -379,10 +381,13 @@ _BRAIN_SYNC_MODE=$("$_BRAIN_CONFIG_BIN" get artifacts_sync_mode 2>/dev/null || e
# Detect remote-MCP mode (Path 4 of /setup-gbrain). Local artifacts sync is
# a no-op in remote mode; the brain server pulls from GitHub/GitLab on its
# own cadence. Read claude.json directly to keep this preamble fast (no
-# subprocess to claude CLI on every skill start).
+# subprocess to claude CLI on every skill start). Both registration scopes
+# are read (#2499): user scope, then the nearest-ancestor project scope.
_GBRAIN_MCP_MODE="none"
+_GBRAIN_MCP_ENTRY=""
if command -v jq >/dev/null 2>&1 && [ -f "$HOME/.claude.json" ]; then
- _GBRAIN_MCP_TYPE=$(jq -r '.mcpServers.gbrain.type // .mcpServers.gbrain.transport // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_ENTRY=$(jq -c --arg cwd "$PWD" '.mcpServers.gbrain // ((.projects // {}) | to_entries | map(select((.key as $k | $cwd == $k or ($cwd | startswith($k + "/"))) and ((try .value.mcpServers.gbrain catch null) != null))) | sort_by(.key | length) | last | .value.mcpServers.gbrain) // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_TYPE=$(printf '%s' "$_GBRAIN_MCP_ENTRY" | jq -r '.type // .transport // empty' 2>/dev/null)
case "$_GBRAIN_MCP_TYPE" in
url|http|sse) _GBRAIN_MCP_MODE="remote-http" ;;
stdio) _GBRAIN_MCP_MODE="local-stdio" ;;
@@ -403,6 +408,7 @@ if [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_DO_PULL=1
if [ -f "$_BRAIN_LAST_PULL_FILE" ]; then
_BRAIN_LAST=$(cat "$_BRAIN_LAST_PULL_FILE" 2>/dev/null || echo 0)
+ case "$_BRAIN_LAST" in ''|*[!0-9]*) _BRAIN_LAST=0 ;; esac
_BRAIN_AGE=$(( _BRAIN_NOW - _BRAIN_LAST ))
[ "$_BRAIN_AGE" -lt 86400 ] && _BRAIN_DO_PULL=0
fi
@@ -416,7 +422,7 @@ fi
if [ "$_GBRAIN_MCP_MODE" = "remote-http" ]; then
# Remote-MCP mode: local artifacts sync is a no-op (brain admin's server
# pulls from GitHub/GitLab). Show the user this is by design, not broken.
- _GBRAIN_HOST=$(jq -r '.mcpServers.gbrain.url // empty' "$HOME/.claude.json" 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|')
+ _GBRAIN_HOST=$(printf '%s' "${_GBRAIN_MCP_ENTRY:-}" | jq -r '.url // empty' 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|' | head -1 | tr -cd 'A-Za-z0-9._-')
echo "ARTIFACTS_SYNC: remote-mode (managed by brain server ${_GBRAIN_HOST:-remote})"
elif [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_QUEUE_DEPTH=0
diff --git a/package.json b/package.json
index d5f090712..ba1baeae3 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "gstack",
- "version": "1.66.1.0",
+ "version": "1.67.0",
"description": "Garry's Stack — Claude Code skills + fast headless browser. One repo, one install, entire AI engineering workflow.",
"license": "MIT",
"type": "module",
@@ -51,14 +51,14 @@
"slop:diff": "bun run scripts/slop-diff.ts"
},
"dependencies": {
- "@huggingface/transformers": "^4.1.0",
+ "@huggingface/transformers": "^4.2.0",
"@ngrok/ngrok": "^1.7.0",
+ "cross-spawn": "^7.0.6",
"diff": "^9.0.0",
"html-to-docx": "1.8.0",
- "marked": "^18.0.2",
- "playwright": "^1.58.2",
- "puppeteer-core": "^24.40.0",
- "socks": "^2.8.8"
+ "marked": "^18.0.9",
+ "playwright": "^1.62.1",
+ "socks": "^2.8.9"
},
"engines": {
"bun": ">=1.0.0"
@@ -80,6 +80,9 @@
"xterm-addon-fit": "^0.8.0"
},
"overrides": {
- "basic-ftp": "5.3.1"
+ "adm-zip": "^0.6.0"
+ },
+ "patchedDependencies": {
}
}
diff --git a/pair-agent/SKILL.md b/pair-agent/SKILL.md
index 63f301c72..3436a5d62 100644
--- a/pair-agent/SKILL.md
+++ b/pair-agent/SKILL.md
@@ -110,9 +110,11 @@ else
fi
~/.claude/skills/gstack/bin/gstack-timeline-log '{"skill":"pair-agent","event":"started","branch":"'"$_BRANCH"'","session":"'"$_SESSION_ID"'"}' 2>/dev/null &
_HAS_ROUTING="no"
-if [ -f CLAUDE.md ] && grep -q "## Skill routing" CLAUDE.md 2>/dev/null; then
- _HAS_ROUTING="yes"
-fi
+for _RF in CLAUDE.md AGENTS.md; do
+ if [ -f "$_RF" ] && grep -q "## Skill routing" "$_RF" 2>/dev/null; then
+ _HAS_ROUTING="yes"
+ fi
+done
_ROUTING_DECLINED=$(~/.claude/skills/gstack/bin/gstack-config get routing_declined 2>/dev/null || echo "false")
echo "HAS_ROUTING: $_HAS_ROUTING"
echo "ROUTING_DECLINED: $_ROUTING_DECLINED"
@@ -506,10 +508,13 @@ _BRAIN_SYNC_MODE=$("$_BRAIN_CONFIG_BIN" get artifacts_sync_mode 2>/dev/null || e
# Detect remote-MCP mode (Path 4 of /setup-gbrain). Local artifacts sync is
# a no-op in remote mode; the brain server pulls from GitHub/GitLab on its
# own cadence. Read claude.json directly to keep this preamble fast (no
-# subprocess to claude CLI on every skill start).
+# subprocess to claude CLI on every skill start). Both registration scopes
+# are read (#2499): user scope, then the nearest-ancestor project scope.
_GBRAIN_MCP_MODE="none"
+_GBRAIN_MCP_ENTRY=""
if command -v jq >/dev/null 2>&1 && [ -f "$HOME/.claude.json" ]; then
- _GBRAIN_MCP_TYPE=$(jq -r '.mcpServers.gbrain.type // .mcpServers.gbrain.transport // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_ENTRY=$(jq -c --arg cwd "$PWD" '.mcpServers.gbrain // ((.projects // {}) | to_entries | map(select((.key as $k | $cwd == $k or ($cwd | startswith($k + "/"))) and ((try .value.mcpServers.gbrain catch null) != null))) | sort_by(.key | length) | last | .value.mcpServers.gbrain) // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_TYPE=$(printf '%s' "$_GBRAIN_MCP_ENTRY" | jq -r '.type // .transport // empty' 2>/dev/null)
case "$_GBRAIN_MCP_TYPE" in
url|http|sse) _GBRAIN_MCP_MODE="remote-http" ;;
stdio) _GBRAIN_MCP_MODE="local-stdio" ;;
@@ -530,6 +535,7 @@ if [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_DO_PULL=1
if [ -f "$_BRAIN_LAST_PULL_FILE" ]; then
_BRAIN_LAST=$(cat "$_BRAIN_LAST_PULL_FILE" 2>/dev/null || echo 0)
+ case "$_BRAIN_LAST" in ''|*[!0-9]*) _BRAIN_LAST=0 ;; esac
_BRAIN_AGE=$(( _BRAIN_NOW - _BRAIN_LAST ))
[ "$_BRAIN_AGE" -lt 86400 ] && _BRAIN_DO_PULL=0
fi
@@ -543,7 +549,7 @@ fi
if [ "$_GBRAIN_MCP_MODE" = "remote-http" ]; then
# Remote-MCP mode: local artifacts sync is a no-op (brain admin's server
# pulls from GitHub/GitLab). Show the user this is by design, not broken.
- _GBRAIN_HOST=$(jq -r '.mcpServers.gbrain.url // empty' "$HOME/.claude.json" 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|')
+ _GBRAIN_HOST=$(printf '%s' "${_GBRAIN_MCP_ENTRY:-}" | jq -r '.url // empty' 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|' | head -1 | tr -cd 'A-Za-z0-9._-')
echo "ARTIFACTS_SYNC: remote-mode (managed by brain server ${_GBRAIN_HOST:-remote})"
elif [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_QUEUE_DEPTH=0
@@ -628,8 +634,8 @@ eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)"
_PROJ="${GSTACK_HOME:-$HOME/.gstack}/projects/${SLUG:-unknown}"
if [ -d "$_PROJ" ]; then
echo "--- RECENT ARTIFACTS ---"
- find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs ls -t 2>/dev/null | head -3
- [ -f "$_PROJ/${_BRANCH}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/${_BRANCH}-reviews.jsonl" | tr -d ' ') entries"
+ find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3
+ [ -f "$_PROJ/${BRANCH:-unknown}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/${BRANCH:-unknown}-reviews.jsonl" | tr -d ' ') entries"
[ -f "$_PROJ/timeline.jsonl" ] && tail -5 "$_PROJ/timeline.jsonl"
if [ -f "$_PROJ/timeline.jsonl" ]; then
_LAST=$(grep "\"branch\":\"${_BRANCH}\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -1)
@@ -637,7 +643,7 @@ if [ -d "$_PROJ" ]; then
_RECENT_SKILLS=$(grep "\"branch\":\"${_BRANCH}\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -3 | grep -o '"skill":"[^"]*"' | sed 's/"skill":"//;s/"//' | tr '\n' ',')
[ -n "$_RECENT_SKILLS" ] && echo "RECENT_PATTERN: $_RECENT_SKILLS"
fi
- _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs ls -t 2>/dev/null | head -1)
+ _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs -r ls -t 2>/dev/null | head -1)
[ -n "$_LATEST_CP" ] && echo "LATEST_CHECKPOINT: $_LATEST_CP"
if [ -f "$_PROJ/decisions.active.json" ]; then
echo "--- ACTIVE DECISIONS (recent, scope-relevant) ---"
@@ -713,7 +719,7 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST
## Question Tuning (skip entirely if `QUESTION_TUNING: false`)
-Before each AskUserQuestion, choose `question_id` from `scripts/question-registry.ts` or `{skill}-{slug}`, then run `printf '%s' "<question summary>" | ~/.claude/skills/gstack/bin/gstack-question-preference --check "<id>" --summary-stdin` (piped summary feeds the one-way keyword net, #2024). `AUTO_DECIDE` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." `ASK_NORMALLY` means ask.
+Before each AskUserQuestion, choose `question_id` from `~/.claude/skills/gstack/scripts/question-registry.ts` or `{skill}-{slug}`, then run `printf '%s' "<question summary>" | ~/.claude/skills/gstack/bin/gstack-question-preference --check "<id>" --summary-stdin` (piped summary feeds the one-way keyword net, #2024). `AUTO_DECIDE` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." `ASK_NORMALLY` means ask.
**Embed the question_id as a marker in the question text** so hooks can identify it deterministically (plan-tune cathedral T14 / D18 progressive markers). Append `<gstack-qid:{question_id}>` somewhere in the rendered question (the leading line or trailing line is fine; the marker doesn't render visibly to the user when wrapped in HTML-style angle brackets, but the hook strips it). Without the marker the PreToolUse enforcement hook treats the AUQ as observed-only and never auto-decides — so always include it when the question matches a registered `question_id`.
diff --git a/patches/[email protected] b/patches/[email protected]
new file mode 100644
index 000000000..b270adbdb
--- /dev/null
+++ b/patches/[email protected]
@@ -0,0 +1,24 @@
+diff --git a/lib/coreBundle.js b/lib/coreBundle.js
+index d9041dd0f009072511a7d808dec83121ff29e127..e5c72c452c98f1c64038c5f24ac5805fbc99151f 100644
+--- a/lib/coreBundle.js
++++ b/lib/coreBundle.js
+@@ -8906,6 +8906,10 @@ async function launchProcess(options) {
+ env: options.env,
+ cwd: options.cwd,
+ shell: options.shell,
++ // gstack patch (#2160/#1989): Node defaults windowsHide to false for
++ // child_process.spawn, so browser children could flash a console window
++ // on Windows. Playwright never needs the child's window shown.
++ windowsHide: true,
+ stdio
+ };
+ const spawnedProcess = childProcess.spawn(options.command, options.args || [], spawnOptions);
+@@ -8985,7 +8989,7 @@ async function launchProcess(options) {
+ options.log(`[pid=${spawnedProcess.pid}] <will force kill>`);
+ try {
+ if (process.platform === "win32") {
+- const taskkillProcess = childProcess.spawnSync(`taskkill /pid ${spawnedProcess.pid} /T /F`, { shell: true });
++ const taskkillProcess = childProcess.spawnSync(`taskkill /pid ${spawnedProcess.pid} /T /F`, { shell: true, windowsHide: true });
+ const [stdout2, stderr2] = [taskkillProcess.stdout.toString(), taskkillProcess.stderr.toString()];
+ if (stdout2)
+ options.log(`[pid=${spawnedProcess.pid}] taskkill stdout: ${stdout2}`);
diff --git a/plan-ceo-review/SKILL.md b/plan-ceo-review/SKILL.md
index 65dd790e1..07fde001c 100644
--- a/plan-ceo-review/SKILL.md
+++ b/plan-ceo-review/SKILL.md
@@ -139,9 +139,11 @@ else
fi
~/.claude/skills/gstack/bin/gstack-timeline-log '{"skill":"plan-ceo-review","event":"started","branch":"'"$_BRANCH"'","session":"'"$_SESSION_ID"'"}' 2>/dev/null &
_HAS_ROUTING="no"
-if [ -f CLAUDE.md ] && grep -q "## Skill routing" CLAUDE.md 2>/dev/null; then
- _HAS_ROUTING="yes"
-fi
+for _RF in CLAUDE.md AGENTS.md; do
+ if [ -f "$_RF" ] && grep -q "## Skill routing" "$_RF" 2>/dev/null; then
+ _HAS_ROUTING="yes"
+ fi
+done
_ROUTING_DECLINED=$(~/.claude/skills/gstack/bin/gstack-config get routing_declined 2>/dev/null || echo "false")
echo "HAS_ROUTING: $_HAS_ROUTING"
echo "ROUTING_DECLINED: $_ROUTING_DECLINED"
@@ -535,10 +537,13 @@ _BRAIN_SYNC_MODE=$("$_BRAIN_CONFIG_BIN" get artifacts_sync_mode 2>/dev/null || e
# Detect remote-MCP mode (Path 4 of /setup-gbrain). Local artifacts sync is
# a no-op in remote mode; the brain server pulls from GitHub/GitLab on its
# own cadence. Read claude.json directly to keep this preamble fast (no
-# subprocess to claude CLI on every skill start).
+# subprocess to claude CLI on every skill start). Both registration scopes
+# are read (#2499): user scope, then the nearest-ancestor project scope.
_GBRAIN_MCP_MODE="none"
+_GBRAIN_MCP_ENTRY=""
if command -v jq >/dev/null 2>&1 && [ -f "$HOME/.claude.json" ]; then
- _GBRAIN_MCP_TYPE=$(jq -r '.mcpServers.gbrain.type // .mcpServers.gbrain.transport // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_ENTRY=$(jq -c --arg cwd "$PWD" '.mcpServers.gbrain // ((.projects // {}) | to_entries | map(select((.key as $k | $cwd == $k or ($cwd | startswith($k + "/"))) and ((try .value.mcpServers.gbrain catch null) != null))) | sort_by(.key | length) | last | .value.mcpServers.gbrain) // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_TYPE=$(printf '%s' "$_GBRAIN_MCP_ENTRY" | jq -r '.type // .transport // empty' 2>/dev/null)
case "$_GBRAIN_MCP_TYPE" in
url|http|sse) _GBRAIN_MCP_MODE="remote-http" ;;
stdio) _GBRAIN_MCP_MODE="local-stdio" ;;
@@ -559,6 +564,7 @@ if [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_DO_PULL=1
if [ -f "$_BRAIN_LAST_PULL_FILE" ]; then
_BRAIN_LAST=$(cat "$_BRAIN_LAST_PULL_FILE" 2>/dev/null || echo 0)
+ case "$_BRAIN_LAST" in ''|*[!0-9]*) _BRAIN_LAST=0 ;; esac
_BRAIN_AGE=$(( _BRAIN_NOW - _BRAIN_LAST ))
[ "$_BRAIN_AGE" -lt 86400 ] && _BRAIN_DO_PULL=0
fi
@@ -572,7 +578,7 @@ fi
if [ "$_GBRAIN_MCP_MODE" = "remote-http" ]; then
# Remote-MCP mode: local artifacts sync is a no-op (brain admin's server
# pulls from GitHub/GitLab). Show the user this is by design, not broken.
- _GBRAIN_HOST=$(jq -r '.mcpServers.gbrain.url // empty' "$HOME/.claude.json" 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|')
+ _GBRAIN_HOST=$(printf '%s' "${_GBRAIN_MCP_ENTRY:-}" | jq -r '.url // empty' 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|' | head -1 | tr -cd 'A-Za-z0-9._-')
echo "ARTIFACTS_SYNC: remote-mode (managed by brain server ${_GBRAIN_HOST:-remote})"
elif [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_QUEUE_DEPTH=0
@@ -657,8 +663,8 @@ eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)"
_PROJ="${GSTACK_HOME:-$HOME/.gstack}/projects/${SLUG:-unknown}"
if [ -d "$_PROJ" ]; then
echo "--- RECENT ARTIFACTS ---"
- find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs ls -t 2>/dev/null | head -3
- [ -f "$_PROJ/${_BRANCH}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/${_BRANCH}-reviews.jsonl" | tr -d ' ') entries"
+ find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3
+ [ -f "$_PROJ/${BRANCH:-unknown}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/${BRANCH:-unknown}-reviews.jsonl" | tr -d ' ') entries"
[ -f "$_PROJ/timeline.jsonl" ] && tail -5 "$_PROJ/timeline.jsonl"
if [ -f "$_PROJ/timeline.jsonl" ]; then
_LAST=$(grep "\"branch\":\"${_BRANCH}\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -1)
@@ -666,7 +672,7 @@ if [ -d "$_PROJ" ]; then
_RECENT_SKILLS=$(grep "\"branch\":\"${_BRANCH}\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -3 | grep -o '"skill":"[^"]*"' | sed 's/"skill":"//;s/"//' | tr '\n' ',')
[ -n "$_RECENT_SKILLS" ] && echo "RECENT_PATTERN: $_RECENT_SKILLS"
fi
- _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs ls -t 2>/dev/null | head -1)
+ _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs -r ls -t 2>/dev/null | head -1)
[ -n "$_LATEST_CP" ] && echo "LATEST_CHECKPOINT: $_LATEST_CP"
if [ -f "$_PROJ/decisions.active.json" ]; then
echo "--- ACTIVE DECISIONS (recent, scope-relevant) ---"
@@ -742,7 +748,7 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST
## Question Tuning (skip entirely if `QUESTION_TUNING: false`)
-Before each AskUserQuestion, choose `question_id` from `scripts/question-registry.ts` or `{skill}-{slug}`, then run `printf '%s' "<question summary>" | ~/.claude/skills/gstack/bin/gstack-question-preference --check "<id>" --summary-stdin` (piped summary feeds the one-way keyword net, #2024). `AUTO_DECIDE` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." `ASK_NORMALLY` means ask.
+Before each AskUserQuestion, choose `question_id` from `~/.claude/skills/gstack/scripts/question-registry.ts` or `{skill}-{slug}`, then run `printf '%s' "<question summary>" | ~/.claude/skills/gstack/bin/gstack-question-preference --check "<id>" --summary-stdin` (piped summary feeds the one-way keyword net, #2024). `AUTO_DECIDE` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." `ASK_NORMALLY` means ask.
**Embed the question_id as a marker in the question text** so hooks can identify it deterministically (plan-tune cathedral T14 / D18 progressive markers). Append `<gstack-qid:{question_id}>` somewhere in the rendered question (the leading line or trailing line is fine; the marker doesn't render visibly to the user when wrapped in HTML-style angle brackets, but the hook strips it). Without the marker the PreToolUse enforcement hook treats the AUQ as observed-only and never auto-decides — so always include it when the question matches a registered `question_id`.
diff --git a/plan-ceo-review/sections/review-sections.md b/plan-ceo-review/sections/review-sections.md
index d35dcf019..7193cdeb5 100644
--- a/plan-ceo-review/sections/review-sections.md
+++ b/plan-ceo-review/sections/review-sections.md
@@ -270,10 +270,20 @@ _CODEX_CFG=$(~/.claude/skills/gstack/bin/gstack-config get codex_reviews 2>/dev/
source ~/.claude/skills/gstack/bin/gstack-codex-probe 2>/dev/null || true
if [ "$_CODEX_CFG" = "disabled" ]; then
_CODEX_MODE="disabled"
+# Running-under-Codex presence probe (#2519): a live Codex session exports
+# CODEX_THREAD_ID / CODEX_SANDBOX into every shell it spawns (verified
+# against a live `codex exec 'env | grep -i codex'` capture, codex 0.147.0).
+# Nested codex spawns from inside a Codex host multiply token burn
+# (observed: one /review = 15M tokens). GSTACK_FORCE_CODEX_REVIEW=1 forces
+# the nested passes anyway.
+elif [ "${GSTACK_FORCE_CODEX_REVIEW:-0}" != "1" ] && { [ -n "${CODEX_THREAD_ID:-}" ] || [ -n "${CODEX_SANDBOX:-}" ]; }; then
+ _CODEX_MODE="under_codex"
elif ! command -v codex >/dev/null 2>&1; then
_CODEX_MODE="not_installed"; _gstack_codex_log_event "codex_cli_missing" 2>/dev/null || true
elif ! _gstack_codex_auth_probe >/dev/null 2>&1; then
_CODEX_MODE="not_authed"; _gstack_codex_log_event "codex_auth_failed" 2>/dev/null || true
+elif ! _gstack_codex_model_probe; then
+ _CODEX_MODE="model_unusable"
else
_CODEX_MODE="ready"; _gstack_codex_version_check 2>/dev/null || true
fi
@@ -283,7 +293,9 @@ echo "CODEX_MODE: $_CODEX_MODE"
Branch on the echoed `CODEX_MODE`:
- **`disabled`** — the user turned Codex reviews off (`codex_reviews=disabled`). Skip this section entirely; do NOT fall back to a Claude subagent — disabled means no extra review step. Print: "Codex review skipped (codex_reviews disabled). Re-enable: `gstack-config set codex_reviews enabled`."
- **`not_installed`** — Codex CLI absent. Print: "Codex not installed — using Claude subagent. Install for cross-model coverage: `npm install -g @openai/codex`." Fall back to the Claude subagent path.
+- **`under_codex`** — this session is already running INSIDE a Codex host, so spawning codex again is the same model reviewing itself at multiplied token cost (#2519). Print exactly one line: "[running under Codex — nested codex passes skipped; set GSTACK_FORCE_CODEX_REVIEW=1 to force]" and skip the codex invocations below; run the section's free in-host pass instead if it defines one.
- **`not_authed`** — installed but no credentials. Print: "Codex installed but not authenticated — using Claude subagent. Run `codex login` or set `$CODEX_API_KEY`." Fall back to the Claude subagent path.
+- **`model_unusable`** — authed but the account cannot use its configured model (#2477: HTTP 400 on every call, usually a stale `model =` pin in `~/.codex/config.toml`). Relay the probe's HINT lines, tell the user the one-line fix (update the pin; `[notice.model_migrations]` names the replacement), and fall back to the Claude subagent path. The ~10s round trip is cached for 1h; timeouts fail open to `ready`.
- **`ready`** — run the Codex pass below.
When the mode is `ready`, `not_installed`, or `not_authed`, print one line so the off-switch
@@ -315,7 +327,7 @@ THE PLAN:
```bash
TMPERR_PV=$(mktemp /tmp/codex-planreview-XXXXXXXX)
_REPO_ROOT=$(git rev-parse --show-toplevel) || { echo "ERROR: not in a git repo" >&2; exit 1; }
-codex exec "<prompt>" -C "$_REPO_ROOT" -s read-only -c 'model_reasoning_effort="high"' --enable web_search_cached < /dev/null 2>"$TMPERR_PV"
+codex exec "<prompt>" -C "$_REPO_ROOT" -s read-only -c 'model_reasoning_effort="high"' -c 'web_search="cached"' < /dev/null 2>"$TMPERR_PV"
```
Use a 5-minute timeout (`timeout: 300000`). After the command completes, read stderr:
diff --git a/plan-design-review/SKILL.md b/plan-design-review/SKILL.md
index 853609247..fca490d0f 100644
--- a/plan-design-review/SKILL.md
+++ b/plan-design-review/SKILL.md
@@ -111,9 +111,11 @@ else
fi
~/.claude/skills/gstack/bin/gstack-timeline-log '{"skill":"plan-design-review","event":"started","branch":"'"$_BRANCH"'","session":"'"$_SESSION_ID"'"}' 2>/dev/null &
_HAS_ROUTING="no"
-if [ -f CLAUDE.md ] && grep -q "## Skill routing" CLAUDE.md 2>/dev/null; then
- _HAS_ROUTING="yes"
-fi
+for _RF in CLAUDE.md AGENTS.md; do
+ if [ -f "$_RF" ] && grep -q "## Skill routing" "$_RF" 2>/dev/null; then
+ _HAS_ROUTING="yes"
+ fi
+done
_ROUTING_DECLINED=$(~/.claude/skills/gstack/bin/gstack-config get routing_declined 2>/dev/null || echo "false")
echo "HAS_ROUTING: $_HAS_ROUTING"
echo "ROUTING_DECLINED: $_ROUTING_DECLINED"
@@ -507,10 +509,13 @@ _BRAIN_SYNC_MODE=$("$_BRAIN_CONFIG_BIN" get artifacts_sync_mode 2>/dev/null || e
# Detect remote-MCP mode (Path 4 of /setup-gbrain). Local artifacts sync is
# a no-op in remote mode; the brain server pulls from GitHub/GitLab on its
# own cadence. Read claude.json directly to keep this preamble fast (no
-# subprocess to claude CLI on every skill start).
+# subprocess to claude CLI on every skill start). Both registration scopes
+# are read (#2499): user scope, then the nearest-ancestor project scope.
_GBRAIN_MCP_MODE="none"
+_GBRAIN_MCP_ENTRY=""
if command -v jq >/dev/null 2>&1 && [ -f "$HOME/.claude.json" ]; then
- _GBRAIN_MCP_TYPE=$(jq -r '.mcpServers.gbrain.type // .mcpServers.gbrain.transport // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_ENTRY=$(jq -c --arg cwd "$PWD" '.mcpServers.gbrain // ((.projects // {}) | to_entries | map(select((.key as $k | $cwd == $k or ($cwd | startswith($k + "/"))) and ((try .value.mcpServers.gbrain catch null) != null))) | sort_by(.key | length) | last | .value.mcpServers.gbrain) // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_TYPE=$(printf '%s' "$_GBRAIN_MCP_ENTRY" | jq -r '.type // .transport // empty' 2>/dev/null)
case "$_GBRAIN_MCP_TYPE" in
url|http|sse) _GBRAIN_MCP_MODE="remote-http" ;;
stdio) _GBRAIN_MCP_MODE="local-stdio" ;;
@@ -531,6 +536,7 @@ if [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_DO_PULL=1
if [ -f "$_BRAIN_LAST_PULL_FILE" ]; then
_BRAIN_LAST=$(cat "$_BRAIN_LAST_PULL_FILE" 2>/dev/null || echo 0)
+ case "$_BRAIN_LAST" in ''|*[!0-9]*) _BRAIN_LAST=0 ;; esac
_BRAIN_AGE=$(( _BRAIN_NOW - _BRAIN_LAST ))
[ "$_BRAIN_AGE" -lt 86400 ] && _BRAIN_DO_PULL=0
fi
@@ -544,7 +550,7 @@ fi
if [ "$_GBRAIN_MCP_MODE" = "remote-http" ]; then
# Remote-MCP mode: local artifacts sync is a no-op (brain admin's server
# pulls from GitHub/GitLab). Show the user this is by design, not broken.
- _GBRAIN_HOST=$(jq -r '.mcpServers.gbrain.url // empty' "$HOME/.claude.json" 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|')
+ _GBRAIN_HOST=$(printf '%s' "${_GBRAIN_MCP_ENTRY:-}" | jq -r '.url // empty' 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|' | head -1 | tr -cd 'A-Za-z0-9._-')
echo "ARTIFACTS_SYNC: remote-mode (managed by brain server ${_GBRAIN_HOST:-remote})"
elif [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_QUEUE_DEPTH=0
@@ -629,8 +635,8 @@ eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)"
_PROJ="${GSTACK_HOME:-$HOME/.gstack}/projects/${SLUG:-unknown}"
if [ -d "$_PROJ" ]; then
echo "--- RECENT ARTIFACTS ---"
- find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs ls -t 2>/dev/null | head -3
- [ -f "$_PROJ/${_BRANCH}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/${_BRANCH}-reviews.jsonl" | tr -d ' ') entries"
+ find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3
+ [ -f "$_PROJ/${BRANCH:-unknown}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/${BRANCH:-unknown}-reviews.jsonl" | tr -d ' ') entries"
[ -f "$_PROJ/timeline.jsonl" ] && tail -5 "$_PROJ/timeline.jsonl"
if [ -f "$_PROJ/timeline.jsonl" ]; then
_LAST=$(grep "\"branch\":\"${_BRANCH}\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -1)
@@ -638,7 +644,7 @@ if [ -d "$_PROJ" ]; then
_RECENT_SKILLS=$(grep "\"branch\":\"${_BRANCH}\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -3 | grep -o '"skill":"[^"]*"' | sed 's/"skill":"//;s/"//' | tr '\n' ',')
[ -n "$_RECENT_SKILLS" ] && echo "RECENT_PATTERN: $_RECENT_SKILLS"
fi
- _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs ls -t 2>/dev/null | head -1)
+ _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs -r ls -t 2>/dev/null | head -1)
[ -n "$_LATEST_CP" ] && echo "LATEST_CHECKPOINT: $_LATEST_CP"
if [ -f "$_PROJ/decisions.active.json" ]; then
echo "--- ACTIVE DECISIONS (recent, scope-relevant) ---"
@@ -714,7 +720,7 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST
## Question Tuning (skip entirely if `QUESTION_TUNING: false`)
-Before each AskUserQuestion, choose `question_id` from `scripts/question-registry.ts` or `{skill}-{slug}`, then run `printf '%s' "<question summary>" | ~/.claude/skills/gstack/bin/gstack-question-preference --check "<id>" --summary-stdin` (piped summary feeds the one-way keyword net, #2024). `AUTO_DECIDE` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." `ASK_NORMALLY` means ask.
+Before each AskUserQuestion, choose `question_id` from `~/.claude/skills/gstack/scripts/question-registry.ts` or `{skill}-{slug}`, then run `printf '%s' "<question summary>" | ~/.claude/skills/gstack/bin/gstack-question-preference --check "<id>" --summary-stdin` (piped summary feeds the one-way keyword net, #2024). `AUTO_DECIDE` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." `ASK_NORMALLY` means ask.
**Embed the question_id as a marker in the question text** so hooks can identify it deterministically (plan-tune cathedral T14 / D18 progressive markers). Append `<gstack-qid:{question_id}>` somewhere in the rendered question (the leading line or trailing line is fine; the marker doesn't render visibly to the user when wrapped in HTML-style angle brackets, but the hook strips it). Without the marker the PreToolUse enforcement hook treats the AUQ as observed-only and never auto-decides — so always include it when the question matches a registered `question_id`.
@@ -1405,7 +1411,7 @@ HARD RULES — first classify as MARKETING/LANDING PAGE vs APP UI vs HYBRID, the
- APP UI: Calm surface hierarchy, dense but readable, utility language, minimal chrome
- UNIVERSAL: CSS variables for colors, no default font stacks, one job per section, cards earn existence
-For each finding: what's wrong, what will happen if it ships unresolved, and the specific fix. Be opinionated. No hedging." -C "$_REPO_ROOT" -s read-only -c 'model_reasoning_effort="high"' --enable web_search_cached < /dev/null 2>"$TMPERR_DESIGN"
+For each finding: what's wrong, what will happen if it ships unresolved, and the specific fix. Be opinionated. No hedging." -C "$_REPO_ROOT" -s read-only -c 'model_reasoning_effort="high"' -c 'web_search="cached"' < /dev/null 2>"$TMPERR_DESIGN"
```
Use a 5-minute timeout (`timeout: 300000`). After the command completes, read stderr:
```bash
diff --git a/plan-devex-review/SKILL.md b/plan-devex-review/SKILL.md
index 9dc9d8b05..71d6835e2 100644
--- a/plan-devex-review/SKILL.md
+++ b/plan-devex-review/SKILL.md
@@ -117,9 +117,11 @@ else
fi
~/.claude/skills/gstack/bin/gstack-timeline-log '{"skill":"plan-devex-review","event":"started","branch":"'"$_BRANCH"'","session":"'"$_SESSION_ID"'"}' 2>/dev/null &
_HAS_ROUTING="no"
-if [ -f CLAUDE.md ] && grep -q "## Skill routing" CLAUDE.md 2>/dev/null; then
- _HAS_ROUTING="yes"
-fi
+for _RF in CLAUDE.md AGENTS.md; do
+ if [ -f "$_RF" ] && grep -q "## Skill routing" "$_RF" 2>/dev/null; then
+ _HAS_ROUTING="yes"
+ fi
+done
_ROUTING_DECLINED=$(~/.claude/skills/gstack/bin/gstack-config get routing_declined 2>/dev/null || echo "false")
echo "HAS_ROUTING: $_HAS_ROUTING"
echo "ROUTING_DECLINED: $_ROUTING_DECLINED"
@@ -513,10 +515,13 @@ _BRAIN_SYNC_MODE=$("$_BRAIN_CONFIG_BIN" get artifacts_sync_mode 2>/dev/null || e
# Detect remote-MCP mode (Path 4 of /setup-gbrain). Local artifacts sync is
# a no-op in remote mode; the brain server pulls from GitHub/GitLab on its
# own cadence. Read claude.json directly to keep this preamble fast (no
-# subprocess to claude CLI on every skill start).
+# subprocess to claude CLI on every skill start). Both registration scopes
+# are read (#2499): user scope, then the nearest-ancestor project scope.
_GBRAIN_MCP_MODE="none"
+_GBRAIN_MCP_ENTRY=""
if command -v jq >/dev/null 2>&1 && [ -f "$HOME/.claude.json" ]; then
- _GBRAIN_MCP_TYPE=$(jq -r '.mcpServers.gbrain.type // .mcpServers.gbrain.transport // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_ENTRY=$(jq -c --arg cwd "$PWD" '.mcpServers.gbrain // ((.projects // {}) | to_entries | map(select((.key as $k | $cwd == $k or ($cwd | startswith($k + "/"))) and ((try .value.mcpServers.gbrain catch null) != null))) | sort_by(.key | length) | last | .value.mcpServers.gbrain) // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_TYPE=$(printf '%s' "$_GBRAIN_MCP_ENTRY" | jq -r '.type // .transport // empty' 2>/dev/null)
case "$_GBRAIN_MCP_TYPE" in
url|http|sse) _GBRAIN_MCP_MODE="remote-http" ;;
stdio) _GBRAIN_MCP_MODE="local-stdio" ;;
@@ -537,6 +542,7 @@ if [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_DO_PULL=1
if [ -f "$_BRAIN_LAST_PULL_FILE" ]; then
_BRAIN_LAST=$(cat "$_BRAIN_LAST_PULL_FILE" 2>/dev/null || echo 0)
+ case "$_BRAIN_LAST" in ''|*[!0-9]*) _BRAIN_LAST=0 ;; esac
_BRAIN_AGE=$(( _BRAIN_NOW - _BRAIN_LAST ))
[ "$_BRAIN_AGE" -lt 86400 ] && _BRAIN_DO_PULL=0
fi
@@ -550,7 +556,7 @@ fi
if [ "$_GBRAIN_MCP_MODE" = "remote-http" ]; then
# Remote-MCP mode: local artifacts sync is a no-op (brain admin's server
# pulls from GitHub/GitLab). Show the user this is by design, not broken.
- _GBRAIN_HOST=$(jq -r '.mcpServers.gbrain.url // empty' "$HOME/.claude.json" 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|')
+ _GBRAIN_HOST=$(printf '%s' "${_GBRAIN_MCP_ENTRY:-}" | jq -r '.url // empty' 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|' | head -1 | tr -cd 'A-Za-z0-9._-')
echo "ARTIFACTS_SYNC: remote-mode (managed by brain server ${_GBRAIN_HOST:-remote})"
elif [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_QUEUE_DEPTH=0
@@ -635,8 +641,8 @@ eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)"
_PROJ="${GSTACK_HOME:-$HOME/.gstack}/projects/${SLUG:-unknown}"
if [ -d "$_PROJ" ]; then
echo "--- RECENT ARTIFACTS ---"
- find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs ls -t 2>/dev/null | head -3
- [ -f "$_PROJ/${_BRANCH}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/${_BRANCH}-reviews.jsonl" | tr -d ' ') entries"
+ find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3
+ [ -f "$_PROJ/${BRANCH:-unknown}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/${BRANCH:-unknown}-reviews.jsonl" | tr -d ' ') entries"
[ -f "$_PROJ/timeline.jsonl" ] && tail -5 "$_PROJ/timeline.jsonl"
if [ -f "$_PROJ/timeline.jsonl" ]; then
_LAST=$(grep "\"branch\":\"${_BRANCH}\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -1)
@@ -644,7 +650,7 @@ if [ -d "$_PROJ" ]; then
_RECENT_SKILLS=$(grep "\"branch\":\"${_BRANCH}\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -3 | grep -o '"skill":"[^"]*"' | sed 's/"skill":"//;s/"//' | tr '\n' ',')
[ -n "$_RECENT_SKILLS" ] && echo "RECENT_PATTERN: $_RECENT_SKILLS"
fi
- _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs ls -t 2>/dev/null | head -1)
+ _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs -r ls -t 2>/dev/null | head -1)
[ -n "$_LATEST_CP" ] && echo "LATEST_CHECKPOINT: $_LATEST_CP"
if [ -f "$_PROJ/decisions.active.json" ]; then
echo "--- ACTIVE DECISIONS (recent, scope-relevant) ---"
@@ -720,7 +726,7 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST
## Question Tuning (skip entirely if `QUESTION_TUNING: false`)
-Before each AskUserQuestion, choose `question_id` from `scripts/question-registry.ts` or `{skill}-{slug}`, then run `printf '%s' "<question summary>" | ~/.claude/skills/gstack/bin/gstack-question-preference --check "<id>" --summary-stdin` (piped summary feeds the one-way keyword net, #2024). `AUTO_DECIDE` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." `ASK_NORMALLY` means ask.
+Before each AskUserQuestion, choose `question_id` from `~/.claude/skills/gstack/scripts/question-registry.ts` or `{skill}-{slug}`, then run `printf '%s' "<question summary>" | ~/.claude/skills/gstack/bin/gstack-question-preference --check "<id>" --summary-stdin` (piped summary feeds the one-way keyword net, #2024). `AUTO_DECIDE` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." `ASK_NORMALLY` means ask.
**Embed the question_id as a marker in the question text** so hooks can identify it deterministically (plan-tune cathedral T14 / D18 progressive markers). Append `<gstack-qid:{question_id}>` somewhere in the rendered question (the leading line or trailing line is fine; the marker doesn't render visibly to the user when wrapped in HTML-style angle brackets, but the hook strips it). Without the marker the PreToolUse enforcement hook treats the AUQ as observed-only and never auto-decides — so always include it when the question matches a registered `question_id`.
diff --git a/plan-devex-review/sections/review-sections.md b/plan-devex-review/sections/review-sections.md
index b57d72868..2a5cfa517 100644
--- a/plan-devex-review/sections/review-sections.md
+++ b/plan-devex-review/sections/review-sections.md
@@ -256,10 +256,20 @@ _CODEX_CFG=$(~/.claude/skills/gstack/bin/gstack-config get codex_reviews 2>/dev/
source ~/.claude/skills/gstack/bin/gstack-codex-probe 2>/dev/null || true
if [ "$_CODEX_CFG" = "disabled" ]; then
_CODEX_MODE="disabled"
+# Running-under-Codex presence probe (#2519): a live Codex session exports
+# CODEX_THREAD_ID / CODEX_SANDBOX into every shell it spawns (verified
+# against a live `codex exec 'env | grep -i codex'` capture, codex 0.147.0).
+# Nested codex spawns from inside a Codex host multiply token burn
+# (observed: one /review = 15M tokens). GSTACK_FORCE_CODEX_REVIEW=1 forces
+# the nested passes anyway.
+elif [ "${GSTACK_FORCE_CODEX_REVIEW:-0}" != "1" ] && { [ -n "${CODEX_THREAD_ID:-}" ] || [ -n "${CODEX_SANDBOX:-}" ]; }; then
+ _CODEX_MODE="under_codex"
elif ! command -v codex >/dev/null 2>&1; then
_CODEX_MODE="not_installed"; _gstack_codex_log_event "codex_cli_missing" 2>/dev/null || true
elif ! _gstack_codex_auth_probe >/dev/null 2>&1; then
_CODEX_MODE="not_authed"; _gstack_codex_log_event "codex_auth_failed" 2>/dev/null || true
+elif ! _gstack_codex_model_probe; then
+ _CODEX_MODE="model_unusable"
else
_CODEX_MODE="ready"; _gstack_codex_version_check 2>/dev/null || true
fi
@@ -269,7 +279,9 @@ echo "CODEX_MODE: $_CODEX_MODE"
Branch on the echoed `CODEX_MODE`:
- **`disabled`** — the user turned Codex reviews off (`codex_reviews=disabled`). Skip this section entirely; do NOT fall back to a Claude subagent — disabled means no extra review step. Print: "Codex review skipped (codex_reviews disabled). Re-enable: `gstack-config set codex_reviews enabled`."
- **`not_installed`** — Codex CLI absent. Print: "Codex not installed — using Claude subagent. Install for cross-model coverage: `npm install -g @openai/codex`." Fall back to the Claude subagent path.
+- **`under_codex`** — this session is already running INSIDE a Codex host, so spawning codex again is the same model reviewing itself at multiplied token cost (#2519). Print exactly one line: "[running under Codex — nested codex passes skipped; set GSTACK_FORCE_CODEX_REVIEW=1 to force]" and skip the codex invocations below; run the section's free in-host pass instead if it defines one.
- **`not_authed`** — installed but no credentials. Print: "Codex installed but not authenticated — using Claude subagent. Run `codex login` or set `$CODEX_API_KEY`." Fall back to the Claude subagent path.
+- **`model_unusable`** — authed but the account cannot use its configured model (#2477: HTTP 400 on every call, usually a stale `model =` pin in `~/.codex/config.toml`). Relay the probe's HINT lines, tell the user the one-line fix (update the pin; `[notice.model_migrations]` names the replacement), and fall back to the Claude subagent path. The ~10s round trip is cached for 1h; timeouts fail open to `ready`.
- **`ready`** — run the Codex pass below.
When the mode is `ready`, `not_installed`, or `not_authed`, print one line so the off-switch
@@ -301,7 +313,7 @@ THE PLAN:
```bash
TMPERR_PV=$(mktemp /tmp/codex-planreview-XXXXXXXX)
_REPO_ROOT=$(git rev-parse --show-toplevel) || { echo "ERROR: not in a git repo" >&2; exit 1; }
-codex exec "<prompt>" -C "$_REPO_ROOT" -s read-only -c 'model_reasoning_effort="high"' --enable web_search_cached < /dev/null 2>"$TMPERR_PV"
+codex exec "<prompt>" -C "$_REPO_ROOT" -s read-only -c 'model_reasoning_effort="high"' -c 'web_search="cached"' < /dev/null 2>"$TMPERR_PV"
```
Use a 5-minute timeout (`timeout: 300000`). After the command completes, read stderr:
diff --git a/plan-eng-review/SKILL.md b/plan-eng-review/SKILL.md
index 8672c9464..4c2f1fc48 100644
--- a/plan-eng-review/SKILL.md
+++ b/plan-eng-review/SKILL.md
@@ -115,9 +115,11 @@ else
fi
~/.claude/skills/gstack/bin/gstack-timeline-log '{"skill":"plan-eng-review","event":"started","branch":"'"$_BRANCH"'","session":"'"$_SESSION_ID"'"}' 2>/dev/null &
_HAS_ROUTING="no"
-if [ -f CLAUDE.md ] && grep -q "## Skill routing" CLAUDE.md 2>/dev/null; then
- _HAS_ROUTING="yes"
-fi
+for _RF in CLAUDE.md AGENTS.md; do
+ if [ -f "$_RF" ] && grep -q "## Skill routing" "$_RF" 2>/dev/null; then
+ _HAS_ROUTING="yes"
+ fi
+done
_ROUTING_DECLINED=$(~/.claude/skills/gstack/bin/gstack-config get routing_declined 2>/dev/null || echo "false")
echo "HAS_ROUTING: $_HAS_ROUTING"
echo "ROUTING_DECLINED: $_ROUTING_DECLINED"
@@ -511,10 +513,13 @@ _BRAIN_SYNC_MODE=$("$_BRAIN_CONFIG_BIN" get artifacts_sync_mode 2>/dev/null || e
# Detect remote-MCP mode (Path 4 of /setup-gbrain). Local artifacts sync is
# a no-op in remote mode; the brain server pulls from GitHub/GitLab on its
# own cadence. Read claude.json directly to keep this preamble fast (no
-# subprocess to claude CLI on every skill start).
+# subprocess to claude CLI on every skill start). Both registration scopes
+# are read (#2499): user scope, then the nearest-ancestor project scope.
_GBRAIN_MCP_MODE="none"
+_GBRAIN_MCP_ENTRY=""
if command -v jq >/dev/null 2>&1 && [ -f "$HOME/.claude.json" ]; then
- _GBRAIN_MCP_TYPE=$(jq -r '.mcpServers.gbrain.type // .mcpServers.gbrain.transport // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_ENTRY=$(jq -c --arg cwd "$PWD" '.mcpServers.gbrain // ((.projects // {}) | to_entries | map(select((.key as $k | $cwd == $k or ($cwd | startswith($k + "/"))) and ((try .value.mcpServers.gbrain catch null) != null))) | sort_by(.key | length) | last | .value.mcpServers.gbrain) // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_TYPE=$(printf '%s' "$_GBRAIN_MCP_ENTRY" | jq -r '.type // .transport // empty' 2>/dev/null)
case "$_GBRAIN_MCP_TYPE" in
url|http|sse) _GBRAIN_MCP_MODE="remote-http" ;;
stdio) _GBRAIN_MCP_MODE="local-stdio" ;;
@@ -535,6 +540,7 @@ if [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_DO_PULL=1
if [ -f "$_BRAIN_LAST_PULL_FILE" ]; then
_BRAIN_LAST=$(cat "$_BRAIN_LAST_PULL_FILE" 2>/dev/null || echo 0)
+ case "$_BRAIN_LAST" in ''|*[!0-9]*) _BRAIN_LAST=0 ;; esac
_BRAIN_AGE=$(( _BRAIN_NOW - _BRAIN_LAST ))
[ "$_BRAIN_AGE" -lt 86400 ] && _BRAIN_DO_PULL=0
fi
@@ -548,7 +554,7 @@ fi
if [ "$_GBRAIN_MCP_MODE" = "remote-http" ]; then
# Remote-MCP mode: local artifacts sync is a no-op (brain admin's server
# pulls from GitHub/GitLab). Show the user this is by design, not broken.
- _GBRAIN_HOST=$(jq -r '.mcpServers.gbrain.url // empty' "$HOME/.claude.json" 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|')
+ _GBRAIN_HOST=$(printf '%s' "${_GBRAIN_MCP_ENTRY:-}" | jq -r '.url // empty' 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|' | head -1 | tr -cd 'A-Za-z0-9._-')
echo "ARTIFACTS_SYNC: remote-mode (managed by brain server ${_GBRAIN_HOST:-remote})"
elif [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_QUEUE_DEPTH=0
@@ -633,8 +639,8 @@ eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)"
_PROJ="${GSTACK_HOME:-$HOME/.gstack}/projects/${SLUG:-unknown}"
if [ -d "$_PROJ" ]; then
echo "--- RECENT ARTIFACTS ---"
- find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs ls -t 2>/dev/null | head -3
- [ -f "$_PROJ/${_BRANCH}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/${_BRANCH}-reviews.jsonl" | tr -d ' ') entries"
+ find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3
+ [ -f "$_PROJ/${BRANCH:-unknown}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/${BRANCH:-unknown}-reviews.jsonl" | tr -d ' ') entries"
[ -f "$_PROJ/timeline.jsonl" ] && tail -5 "$_PROJ/timeline.jsonl"
if [ -f "$_PROJ/timeline.jsonl" ]; then
_LAST=$(grep "\"branch\":\"${_BRANCH}\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -1)
@@ -642,7 +648,7 @@ if [ -d "$_PROJ" ]; then
_RECENT_SKILLS=$(grep "\"branch\":\"${_BRANCH}\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -3 | grep -o '"skill":"[^"]*"' | sed 's/"skill":"//;s/"//' | tr '\n' ',')
[ -n "$_RECENT_SKILLS" ] && echo "RECENT_PATTERN: $_RECENT_SKILLS"
fi
- _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs ls -t 2>/dev/null | head -1)
+ _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs -r ls -t 2>/dev/null | head -1)
[ -n "$_LATEST_CP" ] && echo "LATEST_CHECKPOINT: $_LATEST_CP"
if [ -f "$_PROJ/decisions.active.json" ]; then
echo "--- ACTIVE DECISIONS (recent, scope-relevant) ---"
@@ -718,7 +724,7 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST
## Question Tuning (skip entirely if `QUESTION_TUNING: false`)
-Before each AskUserQuestion, choose `question_id` from `scripts/question-registry.ts` or `{skill}-{slug}`, then run `printf '%s' "<question summary>" | ~/.claude/skills/gstack/bin/gstack-question-preference --check "<id>" --summary-stdin` (piped summary feeds the one-way keyword net, #2024). `AUTO_DECIDE` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." `ASK_NORMALLY` means ask.
+Before each AskUserQuestion, choose `question_id` from `~/.claude/skills/gstack/scripts/question-registry.ts` or `{skill}-{slug}`, then run `printf '%s' "<question summary>" | ~/.claude/skills/gstack/bin/gstack-question-preference --check "<id>" --summary-stdin` (piped summary feeds the one-way keyword net, #2024). `AUTO_DECIDE` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." `ASK_NORMALLY` means ask.
**Embed the question_id as a marker in the question text** so hooks can identify it deterministically (plan-tune cathedral T14 / D18 progressive markers). Append `<gstack-qid:{question_id}>` somewhere in the rendered question (the leading line or trailing line is fine; the marker doesn't render visibly to the user when wrapped in HTML-style angle brackets, but the hook strips it). Without the marker the PreToolUse enforcement hook treats the AUQ as observed-only and never auto-decides — so always include it when the question matches a registered `question_id`.
diff --git a/plan-eng-review/sections/review-sections.md b/plan-eng-review/sections/review-sections.md
index 9b65ba812..d1d125cff 100644
--- a/plan-eng-review/sections/review-sections.md
+++ b/plan-eng-review/sections/review-sections.md
@@ -351,10 +351,20 @@ _CODEX_CFG=$(~/.claude/skills/gstack/bin/gstack-config get codex_reviews 2>/dev/
source ~/.claude/skills/gstack/bin/gstack-codex-probe 2>/dev/null || true
if [ "$_CODEX_CFG" = "disabled" ]; then
_CODEX_MODE="disabled"
+# Running-under-Codex presence probe (#2519): a live Codex session exports
+# CODEX_THREAD_ID / CODEX_SANDBOX into every shell it spawns (verified
+# against a live `codex exec 'env | grep -i codex'` capture, codex 0.147.0).
+# Nested codex spawns from inside a Codex host multiply token burn
+# (observed: one /review = 15M tokens). GSTACK_FORCE_CODEX_REVIEW=1 forces
+# the nested passes anyway.
+elif [ "${GSTACK_FORCE_CODEX_REVIEW:-0}" != "1" ] && { [ -n "${CODEX_THREAD_ID:-}" ] || [ -n "${CODEX_SANDBOX:-}" ]; }; then
+ _CODEX_MODE="under_codex"
elif ! command -v codex >/dev/null 2>&1; then
_CODEX_MODE="not_installed"; _gstack_codex_log_event "codex_cli_missing" 2>/dev/null || true
elif ! _gstack_codex_auth_probe >/dev/null 2>&1; then
_CODEX_MODE="not_authed"; _gstack_codex_log_event "codex_auth_failed" 2>/dev/null || true
+elif ! _gstack_codex_model_probe; then
+ _CODEX_MODE="model_unusable"
else
_CODEX_MODE="ready"; _gstack_codex_version_check 2>/dev/null || true
fi
@@ -364,7 +374,9 @@ echo "CODEX_MODE: $_CODEX_MODE"
Branch on the echoed `CODEX_MODE`:
- **`disabled`** — the user turned Codex reviews off (`codex_reviews=disabled`). Skip this section entirely; do NOT fall back to a Claude subagent — disabled means no extra review step. Print: "Codex review skipped (codex_reviews disabled). Re-enable: `gstack-config set codex_reviews enabled`."
- **`not_installed`** — Codex CLI absent. Print: "Codex not installed — using Claude subagent. Install for cross-model coverage: `npm install -g @openai/codex`." Fall back to the Claude subagent path.
+- **`under_codex`** — this session is already running INSIDE a Codex host, so spawning codex again is the same model reviewing itself at multiplied token cost (#2519). Print exactly one line: "[running under Codex — nested codex passes skipped; set GSTACK_FORCE_CODEX_REVIEW=1 to force]" and skip the codex invocations below; run the section's free in-host pass instead if it defines one.
- **`not_authed`** — installed but no credentials. Print: "Codex installed but not authenticated — using Claude subagent. Run `codex login` or set `$CODEX_API_KEY`." Fall back to the Claude subagent path.
+- **`model_unusable`** — authed but the account cannot use its configured model (#2477: HTTP 400 on every call, usually a stale `model =` pin in `~/.codex/config.toml`). Relay the probe's HINT lines, tell the user the one-line fix (update the pin; `[notice.model_migrations]` names the replacement), and fall back to the Claude subagent path. The ~10s round trip is cached for 1h; timeouts fail open to `ready`.
- **`ready`** — run the Codex pass below.
When the mode is `ready`, `not_installed`, or `not_authed`, print one line so the off-switch
@@ -396,7 +408,7 @@ THE PLAN:
```bash
TMPERR_PV=$(mktemp /tmp/codex-planreview-XXXXXXXX)
_REPO_ROOT=$(git rev-parse --show-toplevel) || { echo "ERROR: not in a git repo" >&2; exit 1; }
-codex exec "<prompt>" -C "$_REPO_ROOT" -s read-only -c 'model_reasoning_effort="high"' --enable web_search_cached < /dev/null 2>"$TMPERR_PV"
+codex exec "<prompt>" -C "$_REPO_ROOT" -s read-only -c 'model_reasoning_effort="high"' -c 'web_search="cached"' < /dev/null 2>"$TMPERR_PV"
```
Use a 5-minute timeout (`timeout: 300000`). After the command completes, read stderr:
diff --git a/plan-tune/SKILL.md b/plan-tune/SKILL.md
index 7f3656d1a..65197b783 100644
--- a/plan-tune/SKILL.md
+++ b/plan-tune/SKILL.md
@@ -120,9 +120,11 @@ else
fi
~/.claude/skills/gstack/bin/gstack-timeline-log '{"skill":"plan-tune","event":"started","branch":"'"$_BRANCH"'","session":"'"$_SESSION_ID"'"}' 2>/dev/null &
_HAS_ROUTING="no"
-if [ -f CLAUDE.md ] && grep -q "## Skill routing" CLAUDE.md 2>/dev/null; then
- _HAS_ROUTING="yes"
-fi
+for _RF in CLAUDE.md AGENTS.md; do
+ if [ -f "$_RF" ] && grep -q "## Skill routing" "$_RF" 2>/dev/null; then
+ _HAS_ROUTING="yes"
+ fi
+done
_ROUTING_DECLINED=$(~/.claude/skills/gstack/bin/gstack-config get routing_declined 2>/dev/null || echo "false")
echo "HAS_ROUTING: $_HAS_ROUTING"
echo "ROUTING_DECLINED: $_ROUTING_DECLINED"
@@ -516,10 +518,13 @@ _BRAIN_SYNC_MODE=$("$_BRAIN_CONFIG_BIN" get artifacts_sync_mode 2>/dev/null || e
# Detect remote-MCP mode (Path 4 of /setup-gbrain). Local artifacts sync is
# a no-op in remote mode; the brain server pulls from GitHub/GitLab on its
# own cadence. Read claude.json directly to keep this preamble fast (no
-# subprocess to claude CLI on every skill start).
+# subprocess to claude CLI on every skill start). Both registration scopes
+# are read (#2499): user scope, then the nearest-ancestor project scope.
_GBRAIN_MCP_MODE="none"
+_GBRAIN_MCP_ENTRY=""
if command -v jq >/dev/null 2>&1 && [ -f "$HOME/.claude.json" ]; then
- _GBRAIN_MCP_TYPE=$(jq -r '.mcpServers.gbrain.type // .mcpServers.gbrain.transport // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_ENTRY=$(jq -c --arg cwd "$PWD" '.mcpServers.gbrain // ((.projects // {}) | to_entries | map(select((.key as $k | $cwd == $k or ($cwd | startswith($k + "/"))) and ((try .value.mcpServers.gbrain catch null) != null))) | sort_by(.key | length) | last | .value.mcpServers.gbrain) // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_TYPE=$(printf '%s' "$_GBRAIN_MCP_ENTRY" | jq -r '.type // .transport // empty' 2>/dev/null)
case "$_GBRAIN_MCP_TYPE" in
url|http|sse) _GBRAIN_MCP_MODE="remote-http" ;;
stdio) _GBRAIN_MCP_MODE="local-stdio" ;;
@@ -540,6 +545,7 @@ if [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_DO_PULL=1
if [ -f "$_BRAIN_LAST_PULL_FILE" ]; then
_BRAIN_LAST=$(cat "$_BRAIN_LAST_PULL_FILE" 2>/dev/null || echo 0)
+ case "$_BRAIN_LAST" in ''|*[!0-9]*) _BRAIN_LAST=0 ;; esac
_BRAIN_AGE=$(( _BRAIN_NOW - _BRAIN_LAST ))
[ "$_BRAIN_AGE" -lt 86400 ] && _BRAIN_DO_PULL=0
fi
@@ -553,7 +559,7 @@ fi
if [ "$_GBRAIN_MCP_MODE" = "remote-http" ]; then
# Remote-MCP mode: local artifacts sync is a no-op (brain admin's server
# pulls from GitHub/GitLab). Show the user this is by design, not broken.
- _GBRAIN_HOST=$(jq -r '.mcpServers.gbrain.url // empty' "$HOME/.claude.json" 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|')
+ _GBRAIN_HOST=$(printf '%s' "${_GBRAIN_MCP_ENTRY:-}" | jq -r '.url // empty' 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|' | head -1 | tr -cd 'A-Za-z0-9._-')
echo "ARTIFACTS_SYNC: remote-mode (managed by brain server ${_GBRAIN_HOST:-remote})"
elif [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_QUEUE_DEPTH=0
@@ -638,8 +644,8 @@ eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)"
_PROJ="${GSTACK_HOME:-$HOME/.gstack}/projects/${SLUG:-unknown}"
if [ -d "$_PROJ" ]; then
echo "--- RECENT ARTIFACTS ---"
- find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs ls -t 2>/dev/null | head -3
- [ -f "$_PROJ/${_BRANCH}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/${_BRANCH}-reviews.jsonl" | tr -d ' ') entries"
+ find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3
+ [ -f "$_PROJ/${BRANCH:-unknown}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/${BRANCH:-unknown}-reviews.jsonl" | tr -d ' ') entries"
[ -f "$_PROJ/timeline.jsonl" ] && tail -5 "$_PROJ/timeline.jsonl"
if [ -f "$_PROJ/timeline.jsonl" ]; then
_LAST=$(grep "\"branch\":\"${_BRANCH}\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -1)
@@ -647,7 +653,7 @@ if [ -d "$_PROJ" ]; then
_RECENT_SKILLS=$(grep "\"branch\":\"${_BRANCH}\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -3 | grep -o '"skill":"[^"]*"' | sed 's/"skill":"//;s/"//' | tr '\n' ',')
[ -n "$_RECENT_SKILLS" ] && echo "RECENT_PATTERN: $_RECENT_SKILLS"
fi
- _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs ls -t 2>/dev/null | head -1)
+ _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs -r ls -t 2>/dev/null | head -1)
[ -n "$_LATEST_CP" ] && echo "LATEST_CHECKPOINT: $_LATEST_CP"
if [ -f "$_PROJ/decisions.active.json" ]; then
echo "--- ACTIVE DECISIONS (recent, scope-relevant) ---"
@@ -723,7 +729,7 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST
## Question Tuning (skip entirely if `QUESTION_TUNING: false`)
-Before each AskUserQuestion, choose `question_id` from `scripts/question-registry.ts` or `{skill}-{slug}`, then run `printf '%s' "<question summary>" | ~/.claude/skills/gstack/bin/gstack-question-preference --check "<id>" --summary-stdin` (piped summary feeds the one-way keyword net, #2024). `AUTO_DECIDE` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." `ASK_NORMALLY` means ask.
+Before each AskUserQuestion, choose `question_id` from `~/.claude/skills/gstack/scripts/question-registry.ts` or `{skill}-{slug}`, then run `printf '%s' "<question summary>" | ~/.claude/skills/gstack/bin/gstack-question-preference --check "<id>" --summary-stdin` (piped summary feeds the one-way keyword net, #2024). `AUTO_DECIDE` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." `ASK_NORMALLY` means ask.
**Embed the question_id as a marker in the question text** so hooks can identify it deterministically (plan-tune cathedral T14 / D18 progressive markers). Append `<gstack-qid:{question_id}>` somewhere in the rendered question (the leading line or trailing line is fine; the marker doesn't render visibly to the user when wrapped in HTML-style angle brackets, but the hook strips it). Without the marker the PreToolUse enforcement hook treats the AUQ as observed-only and never auto-decides — so always include it when the question matches a registered `question_id`.
diff --git a/qa-only/SKILL.md b/qa-only/SKILL.md
index 1d58adcc7..bea258ee8 100644
--- a/qa-only/SKILL.md
+++ b/qa-only/SKILL.md
@@ -110,9 +110,11 @@ else
fi
~/.claude/skills/gstack/bin/gstack-timeline-log '{"skill":"qa-only","event":"started","branch":"'"$_BRANCH"'","session":"'"$_SESSION_ID"'"}' 2>/dev/null &
_HAS_ROUTING="no"
-if [ -f CLAUDE.md ] && grep -q "## Skill routing" CLAUDE.md 2>/dev/null; then
- _HAS_ROUTING="yes"
-fi
+for _RF in CLAUDE.md AGENTS.md; do
+ if [ -f "$_RF" ] && grep -q "## Skill routing" "$_RF" 2>/dev/null; then
+ _HAS_ROUTING="yes"
+ fi
+done
_ROUTING_DECLINED=$(~/.claude/skills/gstack/bin/gstack-config get routing_declined 2>/dev/null || echo "false")
echo "HAS_ROUTING: $_HAS_ROUTING"
echo "ROUTING_DECLINED: $_ROUTING_DECLINED"
@@ -506,10 +508,13 @@ _BRAIN_SYNC_MODE=$("$_BRAIN_CONFIG_BIN" get artifacts_sync_mode 2>/dev/null || e
# Detect remote-MCP mode (Path 4 of /setup-gbrain). Local artifacts sync is
# a no-op in remote mode; the brain server pulls from GitHub/GitLab on its
# own cadence. Read claude.json directly to keep this preamble fast (no
-# subprocess to claude CLI on every skill start).
+# subprocess to claude CLI on every skill start). Both registration scopes
+# are read (#2499): user scope, then the nearest-ancestor project scope.
_GBRAIN_MCP_MODE="none"
+_GBRAIN_MCP_ENTRY=""
if command -v jq >/dev/null 2>&1 && [ -f "$HOME/.claude.json" ]; then
- _GBRAIN_MCP_TYPE=$(jq -r '.mcpServers.gbrain.type // .mcpServers.gbrain.transport // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_ENTRY=$(jq -c --arg cwd "$PWD" '.mcpServers.gbrain // ((.projects // {}) | to_entries | map(select((.key as $k | $cwd == $k or ($cwd | startswith($k + "/"))) and ((try .value.mcpServers.gbrain catch null) != null))) | sort_by(.key | length) | last | .value.mcpServers.gbrain) // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_TYPE=$(printf '%s' "$_GBRAIN_MCP_ENTRY" | jq -r '.type // .transport // empty' 2>/dev/null)
case "$_GBRAIN_MCP_TYPE" in
url|http|sse) _GBRAIN_MCP_MODE="remote-http" ;;
stdio) _GBRAIN_MCP_MODE="local-stdio" ;;
@@ -530,6 +535,7 @@ if [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_DO_PULL=1
if [ -f "$_BRAIN_LAST_PULL_FILE" ]; then
_BRAIN_LAST=$(cat "$_BRAIN_LAST_PULL_FILE" 2>/dev/null || echo 0)
+ case "$_BRAIN_LAST" in ''|*[!0-9]*) _BRAIN_LAST=0 ;; esac
_BRAIN_AGE=$(( _BRAIN_NOW - _BRAIN_LAST ))
[ "$_BRAIN_AGE" -lt 86400 ] && _BRAIN_DO_PULL=0
fi
@@ -543,7 +549,7 @@ fi
if [ "$_GBRAIN_MCP_MODE" = "remote-http" ]; then
# Remote-MCP mode: local artifacts sync is a no-op (brain admin's server
# pulls from GitHub/GitLab). Show the user this is by design, not broken.
- _GBRAIN_HOST=$(jq -r '.mcpServers.gbrain.url // empty' "$HOME/.claude.json" 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|')
+ _GBRAIN_HOST=$(printf '%s' "${_GBRAIN_MCP_ENTRY:-}" | jq -r '.url // empty' 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|' | head -1 | tr -cd 'A-Za-z0-9._-')
echo "ARTIFACTS_SYNC: remote-mode (managed by brain server ${_GBRAIN_HOST:-remote})"
elif [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_QUEUE_DEPTH=0
@@ -628,8 +634,8 @@ eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)"
_PROJ="${GSTACK_HOME:-$HOME/.gstack}/projects/${SLUG:-unknown}"
if [ -d "$_PROJ" ]; then
echo "--- RECENT ARTIFACTS ---"
- find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs ls -t 2>/dev/null | head -3
- [ -f "$_PROJ/${_BRANCH}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/${_BRANCH}-reviews.jsonl" | tr -d ' ') entries"
+ find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3
+ [ -f "$_PROJ/${BRANCH:-unknown}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/${BRANCH:-unknown}-reviews.jsonl" | tr -d ' ') entries"
[ -f "$_PROJ/timeline.jsonl" ] && tail -5 "$_PROJ/timeline.jsonl"
if [ -f "$_PROJ/timeline.jsonl" ]; then
_LAST=$(grep "\"branch\":\"${_BRANCH}\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -1)
@@ -637,7 +643,7 @@ if [ -d "$_PROJ" ]; then
_RECENT_SKILLS=$(grep "\"branch\":\"${_BRANCH}\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -3 | grep -o '"skill":"[^"]*"' | sed 's/"skill":"//;s/"//' | tr '\n' ',')
[ -n "$_RECENT_SKILLS" ] && echo "RECENT_PATTERN: $_RECENT_SKILLS"
fi
- _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs ls -t 2>/dev/null | head -1)
+ _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs -r ls -t 2>/dev/null | head -1)
[ -n "$_LATEST_CP" ] && echo "LATEST_CHECKPOINT: $_LATEST_CP"
if [ -f "$_PROJ/decisions.active.json" ]; then
echo "--- ACTIVE DECISIONS (recent, scope-relevant) ---"
@@ -713,7 +719,7 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST
## Question Tuning (skip entirely if `QUESTION_TUNING: false`)
-Before each AskUserQuestion, choose `question_id` from `scripts/question-registry.ts` or `{skill}-{slug}`, then run `printf '%s' "<question summary>" | ~/.claude/skills/gstack/bin/gstack-question-preference --check "<id>" --summary-stdin` (piped summary feeds the one-way keyword net, #2024). `AUTO_DECIDE` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." `ASK_NORMALLY` means ask.
+Before each AskUserQuestion, choose `question_id` from `~/.claude/skills/gstack/scripts/question-registry.ts` or `{skill}-{slug}`, then run `printf '%s' "<question summary>" | ~/.claude/skills/gstack/bin/gstack-question-preference --check "<id>" --summary-stdin` (piped summary feeds the one-way keyword net, #2024). `AUTO_DECIDE` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." `ASK_NORMALLY` means ask.
**Embed the question_id as a marker in the question text** so hooks can identify it deterministically (plan-tune cathedral T14 / D18 progressive markers). Append `<gstack-qid:{question_id}>` somewhere in the rendered question (the leading line or trailing line is fine; the marker doesn't render visibly to the user when wrapped in HTML-style angle brackets, but the hook strips it). Without the marker the PreToolUse enforcement hook treats the AUQ as observed-only and never auto-decides — so always include it when the question matches a registered `question_id`.
diff --git a/qa/SKILL.md b/qa/SKILL.md
index ce3633067..5a0e4d4b2 100644
--- a/qa/SKILL.md
+++ b/qa/SKILL.md
@@ -116,9 +116,11 @@ else
fi
~/.claude/skills/gstack/bin/gstack-timeline-log '{"skill":"qa","event":"started","branch":"'"$_BRANCH"'","session":"'"$_SESSION_ID"'"}' 2>/dev/null &
_HAS_ROUTING="no"
-if [ -f CLAUDE.md ] && grep -q "## Skill routing" CLAUDE.md 2>/dev/null; then
- _HAS_ROUTING="yes"
-fi
+for _RF in CLAUDE.md AGENTS.md; do
+ if [ -f "$_RF" ] && grep -q "## Skill routing" "$_RF" 2>/dev/null; then
+ _HAS_ROUTING="yes"
+ fi
+done
_ROUTING_DECLINED=$(~/.claude/skills/gstack/bin/gstack-config get routing_declined 2>/dev/null || echo "false")
echo "HAS_ROUTING: $_HAS_ROUTING"
echo "ROUTING_DECLINED: $_ROUTING_DECLINED"
@@ -512,10 +514,13 @@ _BRAIN_SYNC_MODE=$("$_BRAIN_CONFIG_BIN" get artifacts_sync_mode 2>/dev/null || e
# Detect remote-MCP mode (Path 4 of /setup-gbrain). Local artifacts sync is
# a no-op in remote mode; the brain server pulls from GitHub/GitLab on its
# own cadence. Read claude.json directly to keep this preamble fast (no
-# subprocess to claude CLI on every skill start).
+# subprocess to claude CLI on every skill start). Both registration scopes
+# are read (#2499): user scope, then the nearest-ancestor project scope.
_GBRAIN_MCP_MODE="none"
+_GBRAIN_MCP_ENTRY=""
if command -v jq >/dev/null 2>&1 && [ -f "$HOME/.claude.json" ]; then
- _GBRAIN_MCP_TYPE=$(jq -r '.mcpServers.gbrain.type // .mcpServers.gbrain.transport // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_ENTRY=$(jq -c --arg cwd "$PWD" '.mcpServers.gbrain // ((.projects // {}) | to_entries | map(select((.key as $k | $cwd == $k or ($cwd | startswith($k + "/"))) and ((try .value.mcpServers.gbrain catch null) != null))) | sort_by(.key | length) | last | .value.mcpServers.gbrain) // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_TYPE=$(printf '%s' "$_GBRAIN_MCP_ENTRY" | jq -r '.type // .transport // empty' 2>/dev/null)
case "$_GBRAIN_MCP_TYPE" in
url|http|sse) _GBRAIN_MCP_MODE="remote-http" ;;
stdio) _GBRAIN_MCP_MODE="local-stdio" ;;
@@ -536,6 +541,7 @@ if [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_DO_PULL=1
if [ -f "$_BRAIN_LAST_PULL_FILE" ]; then
_BRAIN_LAST=$(cat "$_BRAIN_LAST_PULL_FILE" 2>/dev/null || echo 0)
+ case "$_BRAIN_LAST" in ''|*[!0-9]*) _BRAIN_LAST=0 ;; esac
_BRAIN_AGE=$(( _BRAIN_NOW - _BRAIN_LAST ))
[ "$_BRAIN_AGE" -lt 86400 ] && _BRAIN_DO_PULL=0
fi
@@ -549,7 +555,7 @@ fi
if [ "$_GBRAIN_MCP_MODE" = "remote-http" ]; then
# Remote-MCP mode: local artifacts sync is a no-op (brain admin's server
# pulls from GitHub/GitLab). Show the user this is by design, not broken.
- _GBRAIN_HOST=$(jq -r '.mcpServers.gbrain.url // empty' "$HOME/.claude.json" 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|')
+ _GBRAIN_HOST=$(printf '%s' "${_GBRAIN_MCP_ENTRY:-}" | jq -r '.url // empty' 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|' | head -1 | tr -cd 'A-Za-z0-9._-')
echo "ARTIFACTS_SYNC: remote-mode (managed by brain server ${_GBRAIN_HOST:-remote})"
elif [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_QUEUE_DEPTH=0
@@ -634,8 +640,8 @@ eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)"
_PROJ="${GSTACK_HOME:-$HOME/.gstack}/projects/${SLUG:-unknown}"
if [ -d "$_PROJ" ]; then
echo "--- RECENT ARTIFACTS ---"
- find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs ls -t 2>/dev/null | head -3
- [ -f "$_PROJ/${_BRANCH}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/${_BRANCH}-reviews.jsonl" | tr -d ' ') entries"
+ find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3
+ [ -f "$_PROJ/${BRANCH:-unknown}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/${BRANCH:-unknown}-reviews.jsonl" | tr -d ' ') entries"
[ -f "$_PROJ/timeline.jsonl" ] && tail -5 "$_PROJ/timeline.jsonl"
if [ -f "$_PROJ/timeline.jsonl" ]; then
_LAST=$(grep "\"branch\":\"${_BRANCH}\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -1)
@@ -643,7 +649,7 @@ if [ -d "$_PROJ" ]; then
_RECENT_SKILLS=$(grep "\"branch\":\"${_BRANCH}\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -3 | grep -o '"skill":"[^"]*"' | sed 's/"skill":"//;s/"//' | tr '\n' ',')
[ -n "$_RECENT_SKILLS" ] && echo "RECENT_PATTERN: $_RECENT_SKILLS"
fi
- _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs ls -t 2>/dev/null | head -1)
+ _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs -r ls -t 2>/dev/null | head -1)
[ -n "$_LATEST_CP" ] && echo "LATEST_CHECKPOINT: $_LATEST_CP"
if [ -f "$_PROJ/decisions.active.json" ]; then
echo "--- ACTIVE DECISIONS (recent, scope-relevant) ---"
@@ -719,7 +725,7 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST
## Question Tuning (skip entirely if `QUESTION_TUNING: false`)
-Before each AskUserQuestion, choose `question_id` from `scripts/question-registry.ts` or `{skill}-{slug}`, then run `printf '%s' "<question summary>" | ~/.claude/skills/gstack/bin/gstack-question-preference --check "<id>" --summary-stdin` (piped summary feeds the one-way keyword net, #2024). `AUTO_DECIDE` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." `ASK_NORMALLY` means ask.
+Before each AskUserQuestion, choose `question_id` from `~/.claude/skills/gstack/scripts/question-registry.ts` or `{skill}-{slug}`, then run `printf '%s' "<question summary>" | ~/.claude/skills/gstack/bin/gstack-question-preference --check "<id>" --summary-stdin` (piped summary feeds the one-way keyword net, #2024). `AUTO_DECIDE` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." `ASK_NORMALLY` means ask.
**Embed the question_id as a marker in the question text** so hooks can identify it deterministically (plan-tune cathedral T14 / D18 progressive markers). Append `<gstack-qid:{question_id}>` somewhere in the rendered question (the leading line or trailing line is fine; the marker doesn't render visibly to the user when wrapped in HTML-style angle brackets, but the hook strips it). Without the marker the PreToolUse enforcement hook treats the AUQ as observed-only and never auto-decides — so always include it when the question matches a registered `question_id`.
diff --git a/retro/SKILL.md b/retro/SKILL.md
index 03f3898dd..896e37516 100644
--- a/retro/SKILL.md
+++ b/retro/SKILL.md
@@ -18,7 +18,10 @@ gbrain:
context_queries:
- id: prior-retros
kind: filesystem
- glob: "~/.gstack/projects/{repo_slug}/retros/*.md"
+ # #2552: /retro writes .context/retros/*.json (repo-local; see the save
+ # step below) — the old ~/.gstack/.../retros/*.md glob matched a
+ # directory and extension nothing ever writes, so this query was dead.
+ glob: ".context/retros/*.json"
sort: mtime_desc
limit: 5
render_as: "## Prior retros for this project"
@@ -127,9 +130,11 @@ else
fi
~/.claude/skills/gstack/bin/gstack-timeline-log '{"skill":"retro","event":"started","branch":"'"$_BRANCH"'","session":"'"$_SESSION_ID"'"}' 2>/dev/null &
_HAS_ROUTING="no"
-if [ -f CLAUDE.md ] && grep -q "## Skill routing" CLAUDE.md 2>/dev/null; then
- _HAS_ROUTING="yes"
-fi
+for _RF in CLAUDE.md AGENTS.md; do
+ if [ -f "$_RF" ] && grep -q "## Skill routing" "$_RF" 2>/dev/null; then
+ _HAS_ROUTING="yes"
+ fi
+done
_ROUTING_DECLINED=$(~/.claude/skills/gstack/bin/gstack-config get routing_declined 2>/dev/null || echo "false")
echo "HAS_ROUTING: $_HAS_ROUTING"
echo "ROUTING_DECLINED: $_ROUTING_DECLINED"
@@ -523,10 +528,13 @@ _BRAIN_SYNC_MODE=$("$_BRAIN_CONFIG_BIN" get artifacts_sync_mode 2>/dev/null || e
# Detect remote-MCP mode (Path 4 of /setup-gbrain). Local artifacts sync is
# a no-op in remote mode; the brain server pulls from GitHub/GitLab on its
# own cadence. Read claude.json directly to keep this preamble fast (no
-# subprocess to claude CLI on every skill start).
+# subprocess to claude CLI on every skill start). Both registration scopes
+# are read (#2499): user scope, then the nearest-ancestor project scope.
_GBRAIN_MCP_MODE="none"
+_GBRAIN_MCP_ENTRY=""
if command -v jq >/dev/null 2>&1 && [ -f "$HOME/.claude.json" ]; then
- _GBRAIN_MCP_TYPE=$(jq -r '.mcpServers.gbrain.type // .mcpServers.gbrain.transport // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_ENTRY=$(jq -c --arg cwd "$PWD" '.mcpServers.gbrain // ((.projects // {}) | to_entries | map(select((.key as $k | $cwd == $k or ($cwd | startswith($k + "/"))) and ((try .value.mcpServers.gbrain catch null) != null))) | sort_by(.key | length) | last | .value.mcpServers.gbrain) // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_TYPE=$(printf '%s' "$_GBRAIN_MCP_ENTRY" | jq -r '.type // .transport // empty' 2>/dev/null)
case "$_GBRAIN_MCP_TYPE" in
url|http|sse) _GBRAIN_MCP_MODE="remote-http" ;;
stdio) _GBRAIN_MCP_MODE="local-stdio" ;;
@@ -547,6 +555,7 @@ if [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_DO_PULL=1
if [ -f "$_BRAIN_LAST_PULL_FILE" ]; then
_BRAIN_LAST=$(cat "$_BRAIN_LAST_PULL_FILE" 2>/dev/null || echo 0)
+ case "$_BRAIN_LAST" in ''|*[!0-9]*) _BRAIN_LAST=0 ;; esac
_BRAIN_AGE=$(( _BRAIN_NOW - _BRAIN_LAST ))
[ "$_BRAIN_AGE" -lt 86400 ] && _BRAIN_DO_PULL=0
fi
@@ -560,7 +569,7 @@ fi
if [ "$_GBRAIN_MCP_MODE" = "remote-http" ]; then
# Remote-MCP mode: local artifacts sync is a no-op (brain admin's server
# pulls from GitHub/GitLab). Show the user this is by design, not broken.
- _GBRAIN_HOST=$(jq -r '.mcpServers.gbrain.url // empty' "$HOME/.claude.json" 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|')
+ _GBRAIN_HOST=$(printf '%s' "${_GBRAIN_MCP_ENTRY:-}" | jq -r '.url // empty' 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|' | head -1 | tr -cd 'A-Za-z0-9._-')
echo "ARTIFACTS_SYNC: remote-mode (managed by brain server ${_GBRAIN_HOST:-remote})"
elif [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_QUEUE_DEPTH=0
@@ -645,8 +654,8 @@ eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)"
_PROJ="${GSTACK_HOME:-$HOME/.gstack}/projects/${SLUG:-unknown}"
if [ -d "$_PROJ" ]; then
echo "--- RECENT ARTIFACTS ---"
- find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs ls -t 2>/dev/null | head -3
- [ -f "$_PROJ/${_BRANCH}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/${_BRANCH}-reviews.jsonl" | tr -d ' ') entries"
+ find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3
+ [ -f "$_PROJ/${BRANCH:-unknown}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/${BRANCH:-unknown}-reviews.jsonl" | tr -d ' ') entries"
[ -f "$_PROJ/timeline.jsonl" ] && tail -5 "$_PROJ/timeline.jsonl"
if [ -f "$_PROJ/timeline.jsonl" ]; then
_LAST=$(grep "\"branch\":\"${_BRANCH}\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -1)
@@ -654,7 +663,7 @@ if [ -d "$_PROJ" ]; then
_RECENT_SKILLS=$(grep "\"branch\":\"${_BRANCH}\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -3 | grep -o '"skill":"[^"]*"' | sed 's/"skill":"//;s/"//' | tr '\n' ',')
[ -n "$_RECENT_SKILLS" ] && echo "RECENT_PATTERN: $_RECENT_SKILLS"
fi
- _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs ls -t 2>/dev/null | head -1)
+ _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs -r ls -t 2>/dev/null | head -1)
[ -n "$_LATEST_CP" ] && echo "LATEST_CHECKPOINT: $_LATEST_CP"
if [ -f "$_PROJ/decisions.active.json" ]; then
echo "--- ACTIVE DECISIONS (recent, scope-relevant) ---"
@@ -730,7 +739,7 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST
## Question Tuning (skip entirely if `QUESTION_TUNING: false`)
-Before each AskUserQuestion, choose `question_id` from `scripts/question-registry.ts` or `{skill}-{slug}`, then run `printf '%s' "<question summary>" | ~/.claude/skills/gstack/bin/gstack-question-preference --check "<id>" --summary-stdin` (piped summary feeds the one-way keyword net, #2024). `AUTO_DECIDE` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." `ASK_NORMALLY` means ask.
+Before each AskUserQuestion, choose `question_id` from `~/.claude/skills/gstack/scripts/question-registry.ts` or `{skill}-{slug}`, then run `printf '%s' "<question summary>" | ~/.claude/skills/gstack/bin/gstack-question-preference --check "<id>" --summary-stdin` (piped summary feeds the one-way keyword net, #2024). `AUTO_DECIDE` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." `ASK_NORMALLY` means ask.
**Embed the question_id as a marker in the question text** so hooks can identify it deterministically (plan-tune cathedral T14 / D18 progressive markers). Append `<gstack-qid:{question_id}>` somewhere in the rendered question (the leading line or trailing line is fine; the marker doesn't render visibly to the user when wrapped in HTML-style angle brackets, but the hook strips it). Without the marker the PreToolUse enforcement hook treats the AUQ as observed-only and never auto-decides — so always include it when the question matches a registered `question_id`.
diff --git a/retro/SKILL.md.tmpl b/retro/SKILL.md.tmpl
index b60e0c3f3..338feb531 100644
--- a/retro/SKILL.md.tmpl
+++ b/retro/SKILL.md.tmpl
@@ -23,7 +23,10 @@ gbrain:
context_queries:
- id: prior-retros
kind: filesystem
- glob: "~/.gstack/projects/{repo_slug}/retros/*.md"
+ # #2552: /retro writes .context/retros/*.json (repo-local; see the save
+ # step below) — the old ~/.gstack/.../retros/*.md glob matched a
+ # directory and extension nothing ever writes, so this query was dead.
+ glob: ".context/retros/*.json"
sort: mtime_desc
limit: 5
render_as: "## Prior retros for this project"
diff --git a/review/SKILL.md b/review/SKILL.md
index 184229ccd..7c46c9fc6 100644
--- a/review/SKILL.md
+++ b/review/SKILL.md
@@ -112,9 +112,11 @@ else
fi
~/.claude/skills/gstack/bin/gstack-timeline-log '{"skill":"review","event":"started","branch":"'"$_BRANCH"'","session":"'"$_SESSION_ID"'"}' 2>/dev/null &
_HAS_ROUTING="no"
-if [ -f CLAUDE.md ] && grep -q "## Skill routing" CLAUDE.md 2>/dev/null; then
- _HAS_ROUTING="yes"
-fi
+for _RF in CLAUDE.md AGENTS.md; do
+ if [ -f "$_RF" ] && grep -q "## Skill routing" "$_RF" 2>/dev/null; then
+ _HAS_ROUTING="yes"
+ fi
+done
_ROUTING_DECLINED=$(~/.claude/skills/gstack/bin/gstack-config get routing_declined 2>/dev/null || echo "false")
echo "HAS_ROUTING: $_HAS_ROUTING"
echo "ROUTING_DECLINED: $_ROUTING_DECLINED"
@@ -508,10 +510,13 @@ _BRAIN_SYNC_MODE=$("$_BRAIN_CONFIG_BIN" get artifacts_sync_mode 2>/dev/null || e
# Detect remote-MCP mode (Path 4 of /setup-gbrain). Local artifacts sync is
# a no-op in remote mode; the brain server pulls from GitHub/GitLab on its
# own cadence. Read claude.json directly to keep this preamble fast (no
-# subprocess to claude CLI on every skill start).
+# subprocess to claude CLI on every skill start). Both registration scopes
+# are read (#2499): user scope, then the nearest-ancestor project scope.
_GBRAIN_MCP_MODE="none"
+_GBRAIN_MCP_ENTRY=""
if command -v jq >/dev/null 2>&1 && [ -f "$HOME/.claude.json" ]; then
- _GBRAIN_MCP_TYPE=$(jq -r '.mcpServers.gbrain.type // .mcpServers.gbrain.transport // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_ENTRY=$(jq -c --arg cwd "$PWD" '.mcpServers.gbrain // ((.projects // {}) | to_entries | map(select((.key as $k | $cwd == $k or ($cwd | startswith($k + "/"))) and ((try .value.mcpServers.gbrain catch null) != null))) | sort_by(.key | length) | last | .value.mcpServers.gbrain) // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_TYPE=$(printf '%s' "$_GBRAIN_MCP_ENTRY" | jq -r '.type // .transport // empty' 2>/dev/null)
case "$_GBRAIN_MCP_TYPE" in
url|http|sse) _GBRAIN_MCP_MODE="remote-http" ;;
stdio) _GBRAIN_MCP_MODE="local-stdio" ;;
@@ -532,6 +537,7 @@ if [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_DO_PULL=1
if [ -f "$_BRAIN_LAST_PULL_FILE" ]; then
_BRAIN_LAST=$(cat "$_BRAIN_LAST_PULL_FILE" 2>/dev/null || echo 0)
+ case "$_BRAIN_LAST" in ''|*[!0-9]*) _BRAIN_LAST=0 ;; esac
_BRAIN_AGE=$(( _BRAIN_NOW - _BRAIN_LAST ))
[ "$_BRAIN_AGE" -lt 86400 ] && _BRAIN_DO_PULL=0
fi
@@ -545,7 +551,7 @@ fi
if [ "$_GBRAIN_MCP_MODE" = "remote-http" ]; then
# Remote-MCP mode: local artifacts sync is a no-op (brain admin's server
# pulls from GitHub/GitLab). Show the user this is by design, not broken.
- _GBRAIN_HOST=$(jq -r '.mcpServers.gbrain.url // empty' "$HOME/.claude.json" 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|')
+ _GBRAIN_HOST=$(printf '%s' "${_GBRAIN_MCP_ENTRY:-}" | jq -r '.url // empty' 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|' | head -1 | tr -cd 'A-Za-z0-9._-')
echo "ARTIFACTS_SYNC: remote-mode (managed by brain server ${_GBRAIN_HOST:-remote})"
elif [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_QUEUE_DEPTH=0
@@ -630,8 +636,8 @@ eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)"
_PROJ="${GSTACK_HOME:-$HOME/.gstack}/projects/${SLUG:-unknown}"
if [ -d "$_PROJ" ]; then
echo "--- RECENT ARTIFACTS ---"
- find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs ls -t 2>/dev/null | head -3
- [ -f "$_PROJ/${_BRANCH}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/${_BRANCH}-reviews.jsonl" | tr -d ' ') entries"
+ find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3
+ [ -f "$_PROJ/${BRANCH:-unknown}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/${BRANCH:-unknown}-reviews.jsonl" | tr -d ' ') entries"
[ -f "$_PROJ/timeline.jsonl" ] && tail -5 "$_PROJ/timeline.jsonl"
if [ -f "$_PROJ/timeline.jsonl" ]; then
_LAST=$(grep "\"branch\":\"${_BRANCH}\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -1)
@@ -639,7 +645,7 @@ if [ -d "$_PROJ" ]; then
_RECENT_SKILLS=$(grep "\"branch\":\"${_BRANCH}\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -3 | grep -o '"skill":"[^"]*"' | sed 's/"skill":"//;s/"//' | tr '\n' ',')
[ -n "$_RECENT_SKILLS" ] && echo "RECENT_PATTERN: $_RECENT_SKILLS"
fi
- _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs ls -t 2>/dev/null | head -1)
+ _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs -r ls -t 2>/dev/null | head -1)
[ -n "$_LATEST_CP" ] && echo "LATEST_CHECKPOINT: $_LATEST_CP"
if [ -f "$_PROJ/decisions.active.json" ]; then
echo "--- ACTIVE DECISIONS (recent, scope-relevant) ---"
@@ -715,7 +721,7 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST
## Question Tuning (skip entirely if `QUESTION_TUNING: false`)
-Before each AskUserQuestion, choose `question_id` from `scripts/question-registry.ts` or `{skill}-{slug}`, then run `printf '%s' "<question summary>" | ~/.claude/skills/gstack/bin/gstack-question-preference --check "<id>" --summary-stdin` (piped summary feeds the one-way keyword net, #2024). `AUTO_DECIDE` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." `ASK_NORMALLY` means ask.
+Before each AskUserQuestion, choose `question_id` from `~/.claude/skills/gstack/scripts/question-registry.ts` or `{skill}-{slug}`, then run `printf '%s' "<question summary>" | ~/.claude/skills/gstack/bin/gstack-question-preference --check "<id>" --summary-stdin` (piped summary feeds the one-way keyword net, #2024). `AUTO_DECIDE` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." `ASK_NORMALLY` means ask.
**Embed the question_id as a marker in the question text** so hooks can identify it deterministically (plan-tune cathedral T14 / D18 progressive markers). Append `<gstack-qid:{question_id}>` somewhere in the rendered question (the leading line or trailing line is fine; the marker doesn't render visibly to the user when wrapped in HTML-style angle brackets, but the hook strips it). Without the marker the PreToolUse enforcement hook treats the AUQ as observed-only and never auto-decides — so always include it when the question matches a registered `question_id`.
@@ -908,7 +914,7 @@ Before reviewing code quality, check: **did they build what was requested — no
```bash
setopt +o nomatch 2>/dev/null || true # zsh compat
-BRANCH=$(git branch --show-current 2>/dev/null | tr '/' '-')
+BRANCH=$(git branch --show-current 2>/dev/null | tr '/' '-' | tr -cd 'a-zA-Z0-9._-')
REPO=$(basename "$(git rev-parse --show-toplevel 2>/dev/null)")
# Compute project slug for ~/.gstack/projects/ lookup
_PLAN_SLUG=$(git remote get-url origin 2>/dev/null | sed 's|.*[:/]\([^/]*/[^/]*\)\.git$|\1|;s|.*[:/]\([^/]*/[^/]*\)$|\1|' | tr '/' '-' | tr -cd 'a-zA-Z0-9._-') || true
@@ -918,7 +924,7 @@ for PLAN_DIR in "$HOME/.gstack/projects/$_PLAN_SLUG" "$HOME/.claude/plans" "$HOM
[ -d "$PLAN_DIR" ] || continue
PLAN=$(ls -t "$PLAN_DIR"/*.md 2>/dev/null | xargs grep -l "$BRANCH" 2>/dev/null | head -1)
[ -z "$PLAN" ] && PLAN=$(ls -t "$PLAN_DIR"/*.md 2>/dev/null | xargs grep -l "$REPO" 2>/dev/null | head -1)
- [ -z "$PLAN" ] && PLAN=$(find "$PLAN_DIR" -name '*.md' -mmin -1440 -maxdepth 1 2>/dev/null | xargs ls -t 2>/dev/null | head -1)
+ [ -z "$PLAN" ] && PLAN=$(find "$PLAN_DIR" -name '*.md' -mmin -1440 -maxdepth 1 2>/dev/null | xargs -r ls -t 2>/dev/null | head -1)
[ -n "$PLAN" ] && break
done
[ -n "$PLAN" ] && echo "PLAN_FILE: $PLAN" || echo "NO_PLAN_FILE"
@@ -1675,10 +1681,20 @@ _CODEX_CFG=$(~/.claude/skills/gstack/bin/gstack-config get codex_reviews 2>/dev/
source ~/.claude/skills/gstack/bin/gstack-codex-probe 2>/dev/null || true
if [ "$_CODEX_CFG" = "disabled" ]; then
_CODEX_MODE="disabled"
+# Running-under-Codex presence probe (#2519): a live Codex session exports
+# CODEX_THREAD_ID / CODEX_SANDBOX into every shell it spawns (verified
+# against a live `codex exec 'env | grep -i codex'` capture, codex 0.147.0).
+# Nested codex spawns from inside a Codex host multiply token burn
+# (observed: one /review = 15M tokens). GSTACK_FORCE_CODEX_REVIEW=1 forces
+# the nested passes anyway.
+elif [ "${GSTACK_FORCE_CODEX_REVIEW:-0}" != "1" ] && { [ -n "${CODEX_THREAD_ID:-}" ] || [ -n "${CODEX_SANDBOX:-}" ]; }; then
+ _CODEX_MODE="under_codex"
elif ! command -v codex >/dev/null 2>&1; then
_CODEX_MODE="not_installed"; _gstack_codex_log_event "codex_cli_missing" 2>/dev/null || true
elif ! _gstack_codex_auth_probe >/dev/null 2>&1; then
_CODEX_MODE="not_authed"; _gstack_codex_log_event "codex_auth_failed" 2>/dev/null || true
+elif ! _gstack_codex_model_probe; then
+ _CODEX_MODE="model_unusable"
else
_CODEX_MODE="ready"; _gstack_codex_version_check 2>/dev/null || true
fi
@@ -1688,7 +1704,9 @@ echo "CODEX_MODE: $_CODEX_MODE"
Branch on the echoed `CODEX_MODE`:
- **`disabled`** — the user turned Codex reviews off (`codex_reviews=disabled`). Skip the Codex passes only; the Claude adversarial subagent below STILL runs (it is free and fast). Print: "Codex passes skipped (codex_reviews disabled) — running Claude adversarial only."
- **`not_installed`** — Codex CLI absent. Print: "Codex not installed — using Claude subagent. Install for cross-model coverage: `npm install -g @openai/codex`." Fall back to the Claude subagent path.
+- **`under_codex`** — this session is already running INSIDE a Codex host, so spawning codex again is the same model reviewing itself at multiplied token cost (#2519). Print exactly one line: "[running under Codex — nested codex passes skipped; set GSTACK_FORCE_CODEX_REVIEW=1 to force]" and skip the codex invocations below; run the section's free in-host pass instead if it defines one.
- **`not_authed`** — installed but no credentials. Print: "Codex installed but not authenticated — using Claude subagent. Run `codex login` or set `$CODEX_API_KEY`." Fall back to the Claude subagent path.
+- **`model_unusable`** — authed but the account cannot use its configured model (#2477: HTTP 400 on every call, usually a stale `model =` pin in `~/.codex/config.toml`). Relay the probe's HINT lines, tell the user the one-line fix (update the pin; `[notice.model_migrations]` names the replacement), and fall back to the Claude subagent path. The ~10s round trip is cached for 1h; timeouts fail open to `ready`.
- **`ready`** — run the Codex pass below.
For this diff-review path, `CODEX_MODE: disabled` means skip the Codex passes ONLY — the
@@ -1728,7 +1746,7 @@ _REPO_ROOT=$(git rev-parse --show-toplevel) || { echo "ERROR: not in a git repo"
# here. It defines _gstack_codex_timeout_wrapper (gtimeout -> timeout ->
# unwrapped fallback), added in #1056 but never wired into this call site.
source ~/.claude/skills/gstack/bin/gstack-codex-probe 2>/dev/null || true
-_gstack_codex_timeout_wrapper 540 codex exec "IMPORTANT: Do NOT read or execute any files under ~/.claude/, ~/.agents/, .claude/skills/, or agents/. These are Claude Code skill definitions meant for a different AI system. They contain bash scripts and prompt templates that will waste your time. Ignore them completely. Do NOT modify agents/openai.yaml. Stay focused on the repository code only.\n\nReview the changes on this branch against the base branch. Run DIFF_BASE=$(git merge-base origin/<base> HEAD) && git diff "$DIFF_BASE" to see the diff. Your job is to find ways this code will fail in production. Think like an attacker and a chaos engineer. Find edge cases, race conditions, security holes, resource leaks, failure modes, and silent data corruption paths. Be adversarial. Be thorough. No compliments — just the problems. End your output with ONE line in the canonical format `Recommendation: <action> because <one-line reason naming the most exploitable finding>`. Generic reasons like 'because it's safer' do not qualify; the reason must point to a specific finding or no-fix rationale." -C "$_REPO_ROOT" -s read-only -c 'model_reasoning_effort="high"' --enable web_search_cached < /dev/null 2>"$TMPERR_ADV"
+_gstack_codex_timeout_wrapper 540 codex exec "IMPORTANT: Do NOT read or execute any files under ~/.claude/, ~/.agents/, .claude/skills/, or agents/. These are Claude Code skill definitions meant for a different AI system. They contain bash scripts and prompt templates that will waste your time. Ignore them completely. Do NOT modify agents/openai.yaml. Stay focused on the repository code only.\n\nReview the changes on this branch against the base branch. Run DIFF_BASE=$(git merge-base origin/<base> HEAD) && git diff "$DIFF_BASE" to see the diff. Your job is to find ways this code will fail in production. Think like an attacker and a chaos engineer. Find edge cases, race conditions, security holes, resource leaks, failure modes, and silent data corruption paths. Be adversarial. Be thorough. No compliments — just the problems. End your output with ONE line in the canonical format `Recommendation: <action> because <one-line reason naming the most exploitable finding>`. Generic reasons like 'because it's safer' do not qualify; the reason must point to a specific finding or no-fix rationale." -C "$_REPO_ROOT" -s read-only -c 'model_reasoning_effort="high"' -c 'web_search="cached"' < /dev/null 2>"$TMPERR_ADV"
```
Set the Bash tool's `timeout` parameter to `600000` (10 minutes). It sits ABOVE the 540s wrapper deliberately, so the wrapper fires first and a stall surfaces as a diagnosable exit 124 instead of a harness kill that returns nothing. The wrapper resolves `gtimeout`, then `timeout`, then runs unwrapped, so it is safe on a macOS without coreutils. After the command completes, read stderr:
@@ -1761,7 +1779,7 @@ cd "$_REPO_ROOT"
# here. It defines _gstack_codex_timeout_wrapper (gtimeout -> timeout ->
# unwrapped fallback), added in #1056 but never wired into this call site.
source ~/.claude/skills/gstack/bin/gstack-codex-probe 2>/dev/null || true
-_gstack_codex_timeout_wrapper 540 codex review --base <base> -c 'model_reasoning_effort="high"' --enable web_search_cached < /dev/null 2>"$TMPERR"
+_gstack_codex_timeout_wrapper 540 codex review --base <base> -c 'model_reasoning_effort="high"' -c 'web_search="cached"' < /dev/null 2>"$TMPERR"
```
**No prompt argument.** `--base` is what scopes the review, and the positional `[PROMPT]` is mutually exclusive with it — passing both fails at argv parsing. Do NOT "fix" that error by dropping `--base` and keeping the prompt: a prompt-only `codex review` silently falls back to the **uncommitted working-tree** scope (`git status --short; git diff`), so it reviews the wrong changes and reports "no changes" on a clean tree. Prompt text describing the diff range does not change what the CLI feeds the reviewer. Unlike the adversarial pass above, which uses `codex exec` and really does run the git command it's told to, this path gets a pre-computed diff from the CLI — which is also why it needs no filesystem boundary.
diff --git a/scrape/SKILL.md b/scrape/SKILL.md
index 8f73d1cbe..1b202d66f 100644
--- a/scrape/SKILL.md
+++ b/scrape/SKILL.md
@@ -109,9 +109,11 @@ else
fi
~/.claude/skills/gstack/bin/gstack-timeline-log '{"skill":"scrape","event":"started","branch":"'"$_BRANCH"'","session":"'"$_SESSION_ID"'"}' 2>/dev/null &
_HAS_ROUTING="no"
-if [ -f CLAUDE.md ] && grep -q "## Skill routing" CLAUDE.md 2>/dev/null; then
- _HAS_ROUTING="yes"
-fi
+for _RF in CLAUDE.md AGENTS.md; do
+ if [ -f "$_RF" ] && grep -q "## Skill routing" "$_RF" 2>/dev/null; then
+ _HAS_ROUTING="yes"
+ fi
+done
_ROUTING_DECLINED=$(~/.claude/skills/gstack/bin/gstack-config get routing_declined 2>/dev/null || echo "false")
echo "HAS_ROUTING: $_HAS_ROUTING"
echo "ROUTING_DECLINED: $_ROUTING_DECLINED"
@@ -380,10 +382,13 @@ _BRAIN_SYNC_MODE=$("$_BRAIN_CONFIG_BIN" get artifacts_sync_mode 2>/dev/null || e
# Detect remote-MCP mode (Path 4 of /setup-gbrain). Local artifacts sync is
# a no-op in remote mode; the brain server pulls from GitHub/GitLab on its
# own cadence. Read claude.json directly to keep this preamble fast (no
-# subprocess to claude CLI on every skill start).
+# subprocess to claude CLI on every skill start). Both registration scopes
+# are read (#2499): user scope, then the nearest-ancestor project scope.
_GBRAIN_MCP_MODE="none"
+_GBRAIN_MCP_ENTRY=""
if command -v jq >/dev/null 2>&1 && [ -f "$HOME/.claude.json" ]; then
- _GBRAIN_MCP_TYPE=$(jq -r '.mcpServers.gbrain.type // .mcpServers.gbrain.transport // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_ENTRY=$(jq -c --arg cwd "$PWD" '.mcpServers.gbrain // ((.projects // {}) | to_entries | map(select((.key as $k | $cwd == $k or ($cwd | startswith($k + "/"))) and ((try .value.mcpServers.gbrain catch null) != null))) | sort_by(.key | length) | last | .value.mcpServers.gbrain) // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_TYPE=$(printf '%s' "$_GBRAIN_MCP_ENTRY" | jq -r '.type // .transport // empty' 2>/dev/null)
case "$_GBRAIN_MCP_TYPE" in
url|http|sse) _GBRAIN_MCP_MODE="remote-http" ;;
stdio) _GBRAIN_MCP_MODE="local-stdio" ;;
@@ -404,6 +409,7 @@ if [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_DO_PULL=1
if [ -f "$_BRAIN_LAST_PULL_FILE" ]; then
_BRAIN_LAST=$(cat "$_BRAIN_LAST_PULL_FILE" 2>/dev/null || echo 0)
+ case "$_BRAIN_LAST" in ''|*[!0-9]*) _BRAIN_LAST=0 ;; esac
_BRAIN_AGE=$(( _BRAIN_NOW - _BRAIN_LAST ))
[ "$_BRAIN_AGE" -lt 86400 ] && _BRAIN_DO_PULL=0
fi
@@ -417,7 +423,7 @@ fi
if [ "$_GBRAIN_MCP_MODE" = "remote-http" ]; then
# Remote-MCP mode: local artifacts sync is a no-op (brain admin's server
# pulls from GitHub/GitLab). Show the user this is by design, not broken.
- _GBRAIN_HOST=$(jq -r '.mcpServers.gbrain.url // empty' "$HOME/.claude.json" 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|')
+ _GBRAIN_HOST=$(printf '%s' "${_GBRAIN_MCP_ENTRY:-}" | jq -r '.url // empty' 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|' | head -1 | tr -cd 'A-Za-z0-9._-')
echo "ARTIFACTS_SYNC: remote-mode (managed by brain server ${_GBRAIN_HOST:-remote})"
elif [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_QUEUE_DEPTH=0
diff --git a/scripts/gen-skill-docs.ts b/scripts/gen-skill-docs.ts
index b348c5162..9596466f6 100644
--- a/scripts/gen-skill-docs.ts
+++ b/scripts/gen-skill-docs.ts
@@ -44,14 +44,14 @@ function loadGbrainOverride(): { detected: boolean } {
try {
const json = JSON.parse(fs.readFileSync(detectionPath, 'utf-8')) as { gbrain_local_status?: string };
// "timeout" = slow-but-healthy engine (#1964); "thin-client" = remote-HTTP
- // MCP brain with no local engine by design (#2051). Both usable — same
- // treatment as "ok", matching gstack-gbrain-detect --is-ok.
- return {
- detected:
- json.gbrain_local_status === 'ok' ||
- json.gbrain_local_status === 'timeout' ||
- json.gbrain_local_status === 'thin-client',
- };
+ // MCP brain with no local engine by design (#2051); "engine-locked" = same
+ // class (#2456): PGLite is single-writer, so a live `gbrain serve` (e.g.
+ // an MCP server) owns the embedded DB — gbrain is installed and healthy,
+ // a legitimate holder has the lock, so a transient lock must not silently
+ // strip brain blocks from every SKILL.md. All usable — same treatment as
+ // "ok", matching gstack-gbrain-detect --is-ok.
+ const USABLE = ['ok', 'timeout', 'thin-client', 'engine-locked'];
+ return { detected: USABLE.includes(json.gbrain_local_status ?? '') };
} catch {
return { detected: false };
}
@@ -413,6 +413,7 @@ export function toYamlInlineScalar(s: string): string {
s !== s.trim() || // leading/trailing whitespace
/:(\s|$)/.test(s) || // "foo: bar" / trailing colon → mapping ambiguity
/\s#/.test(s) || // " #" → inline comment
+ /\.\.\./.test(s) || // "..." → document-end marker; strict parsers reject mid-scalar (catalog-trim truncation appends it)
/^[\s>|&*!%@`"'#,\[\]{}?-]/.test(s); // leading YAML indicator char
return needsQuote ? JSON.stringify(s) : s;
}
@@ -667,12 +668,32 @@ function applyHostRewrites(content: string, hostConfig: HostConfig): string {
* unresolved. Extracted so SKILL.md and section templates resolve through the
* exact same path — a security/sanitization fix to one can't miss the other.
*/
+/**
+ * A second {{PREAMBLE}} in one template re-expands the entire ~12K-token
+ * preamble mid-document (#2508/#2362 — a PROSE mention of the macro in
+ * spec/SKILL.md.tmpl expanded it a second time, +43KB per /spec load).
+ * Resolution is context-blind, so any second occurrence — code fence, prose,
+ * anywhere — is a generation error, never intentional. Throw at render time
+ * so the mistake cannot reach a generated SKILL.md again.
+ */
+export function assertSinglePreamble(tmplContent: string, relTmplPath: string): void {
+ const count = (tmplContent.match(/\{\{PREAMBLE\}\}/g) || []).length;
+ if (count > 1) {
+ throw new Error(
+ `${relTmplPath} contains {{PREAMBLE}} ${count} times — a template may reference it `
+ + `at most once (each occurrence expands the full preamble; see #2508/#2362). `
+ + `Refer to "the preamble" in prose instead of the macro.`,
+ );
+ }
+}
+
function resolvePlaceholders(
tmplContent: string,
ctx: TemplateContext,
hostConfig: HostConfig,
relTmplPath: string,
): string {
+ assertSinglePreamble(tmplContent, relTmplPath);
// effectiveSuppressedResolvers() honors --respect-detection: when gbrain is
// detected locally, GBRAIN_* resolvers un-suppress. Shared by SKILL.md and
// section generation so both paths get the same gbrain-aware behavior.
diff --git a/scripts/resolvers/constants.ts b/scripts/resolvers/constants.ts
index b75db21cf..5d2b967ea 100644
--- a/scripts/resolvers/constants.ts
+++ b/scripts/resolvers/constants.ts
@@ -44,6 +44,26 @@ export const OPENAI_LITMUS_CHECKS = [
'Would design feel premium with all decorative shadows removed?',
];
+/**
+ * Web-search flag for every codex invocation (#2525).
+ *
+ * codex >=0.144 deprecated the legacy `--enable`-based web_search_cached
+ * spelling (web search is on by default; the deprecation notice says to set
+ * `web_search` to "live", "indexed", "cached", or "disabled" at the top
+ * level), and `--enable <FEATURE>` now means `-c features.<name>=true`
+ * (verified on 0.147.0), so the legacy spelling is headed for hard
+ * rejection. This is the ONE source
+ * of truth: resolvers interpolate it directly and templates reference it via
+ * the {{CODEX_WEB_SEARCH_FLAG}} token — never write the flag inline.
+ *
+ * Semantics note: unlike the legacy flag (which yielded to an existing
+ * top-level `web_search` in config.toml), the -c form explicitly overrides
+ * it. Deliberate: gstack wants deterministic cached search for review
+ * invocations. Native `codex review` disables web search regardless of
+ * configuration, so on that path the flag is a harmless no-op.
+ */
+export const CODEX_WEB_SEARCH_FLAG = `-c 'web_search="cached"'`;
+
/**
* Shared Codex error handling block for resolver output.
* Used by ADVERSARIAL_STEP, CODEX_PLAN_REVIEW, CODEX_SECOND_OPINION,
@@ -98,10 +118,20 @@ _CODEX_CFG=$(~/.claude/skills/gstack/bin/gstack-config get codex_reviews 2>/dev/
source ~/.claude/skills/gstack/bin/gstack-codex-probe 2>/dev/null || true
if [ "$_CODEX_CFG" = "disabled" ]; then
${m}="disabled"
+# Running-under-Codex presence probe (#2519): a live Codex session exports
+# CODEX_THREAD_ID / CODEX_SANDBOX into every shell it spawns (verified
+# against a live \`codex exec 'env | grep -i codex'\` capture, codex 0.147.0).
+# Nested codex spawns from inside a Codex host multiply token burn
+# (observed: one /review = 15M tokens). GSTACK_FORCE_CODEX_REVIEW=1 forces
+# the nested passes anyway.
+elif [ "\${GSTACK_FORCE_CODEX_REVIEW:-0}" != "1" ] && { [ -n "\${CODEX_THREAD_ID:-}" ] || [ -n "\${CODEX_SANDBOX:-}" ]; }; then
+ ${m}="under_codex"
elif ! command -v codex >/dev/null 2>&1; then
${m}="not_installed"; _gstack_codex_log_event "codex_cli_missing" 2>/dev/null || true
elif ! _gstack_codex_auth_probe >/dev/null 2>&1; then
${m}="not_authed"; _gstack_codex_log_event "codex_auth_failed" 2>/dev/null || true
+elif ! _gstack_codex_model_probe; then
+ ${m}="model_unusable"
else
${m}="ready"; _gstack_codex_version_check 2>/dev/null || true
fi
@@ -111,6 +141,8 @@ echo "CODEX_MODE: $${m}"
Branch on the echoed \`CODEX_MODE\`:
- **\`disabled\`** — the user turned Codex reviews off (\`codex_reviews=disabled\`). ${disabledLine}
- **\`not_installed\`** — Codex CLI absent. Print: "Codex not installed — using Claude subagent. Install for cross-model coverage: \`npm install -g @openai/codex\`." Fall back to the Claude subagent path.
+- **\`under_codex\`** — this session is already running INSIDE a Codex host, so spawning codex again is the same model reviewing itself at multiplied token cost (#2519). Print exactly one line: "[running under Codex — nested codex passes skipped; set GSTACK_FORCE_CODEX_REVIEW=1 to force]" and skip the codex invocations below; run the section's free in-host pass instead if it defines one.
- **\`not_authed\`** — installed but no credentials. Print: "Codex installed but not authenticated — using Claude subagent. Run \`codex login\` or set \`$CODEX_API_KEY\`." Fall back to the Claude subagent path.
+- **\`model_unusable\`** — authed but the account cannot use its configured model (#2477: HTTP 400 on every call, usually a stale \`model =\` pin in \`~/.codex/config.toml\`). Relay the probe's HINT lines, tell the user the one-line fix (update the pin; \`[notice.model_migrations]\` names the replacement), and fall back to the Claude subagent path. The ~10s round trip is cached for 1h; timeouts fail open to \`ready\`.
- **\`ready\`** — run the Codex pass below.`;
}
diff --git a/scripts/resolvers/design.ts b/scripts/resolvers/design.ts
index a6200145e..c272bc769 100644
--- a/scripts/resolvers/design.ts
+++ b/scripts/resolvers/design.ts
@@ -1,5 +1,5 @@
import { type TemplateContext, toShellPath } from './types';
-import { AI_SLOP_BLACKLIST, OPENAI_HARD_REJECTIONS, OPENAI_LITMUS_CHECKS } from './constants';
+import { AI_SLOP_BLACKLIST, OPENAI_HARD_REJECTIONS, OPENAI_LITMUS_CHECKS, CODEX_WEB_SEARCH_FLAG } from './constants';
export function generateDesignReviewLite(ctx: TemplateContext): string {
const litmusList = OPENAI_LITMUS_CHECKS.map((item, i) => `${i + 1}. ${item}`).join(' ');
@@ -18,7 +18,7 @@ If Codex is available, run a lightweight design check on the diff:
\`\`\`bash
TMPERR_DRL=$(mktemp /tmp/codex-drl-XXXXXXXX)
_REPO_ROOT=$(git rev-parse --show-toplevel) || { echo "ERROR: not in a git repo" >&2; exit 1; }
-codex exec "Review the git diff on this branch. Run 7 litmus checks (YES/NO each): ${litmusList} Flag any hard rejections: ${rejectionList} 5 most important design findings only. Reference file:line." -C "$_REPO_ROOT" -s read-only -c 'model_reasoning_effort="high"' --enable web_search_cached < /dev/null 2>"$TMPERR_DRL"
+codex exec "Review the git diff on this branch. Run 7 litmus checks (YES/NO each): ${litmusList} Flag any hard rejections: ${rejectionList} 5 most important design findings only. Reference file:line." -C "$_REPO_ROOT" -s read-only -c 'model_reasoning_effort="high"' ${CODEX_WEB_SEARCH_FLAG} < /dev/null 2>"$TMPERR_DRL"
\`\`\`
Use a 5-minute timeout (\`timeout: 300000\`). After the command completes, read stderr:
@@ -527,7 +527,7 @@ If user chooses A, launch both voices simultaneously:
\`\`\`bash
TMPERR_SKETCH=$(mktemp /tmp/codex-sketch-XXXXXXXX)
_REPO_ROOT=$(git rev-parse --show-toplevel) || { echo "ERROR: not in a git repo" >&2; exit 1; }
-codex exec "For this product approach, provide: a visual thesis (one sentence — mood, material, energy), a content plan (hero → support → detail → CTA), and 2 interaction ideas that change page feel. Apply beautiful defaults: composition-first, brand-first, cardless, poster not document. Be opinionated." -C "$_REPO_ROOT" -s read-only -c 'model_reasoning_effort="medium"' --enable web_search_cached < /dev/null 2>"$TMPERR_SKETCH"
+codex exec "For this product approach, provide: a visual thesis (one sentence — mood, material, energy), a content plan (hero → support → detail → CTA), and 2 interaction ideas that change page feel. Apply beautiful defaults: composition-first, brand-first, cardless, poster not document. Be opinionated." -C "$_REPO_ROOT" -s read-only -c 'model_reasoning_effort="medium"' ${CODEX_WEB_SEARCH_FLAG} < /dev/null 2>"$TMPERR_SKETCH"
\`\`\`
Use a 5-minute timeout (\`timeout: 300000\`). After completion: \`cat "$TMPERR_SKETCH" && rm -f "$TMPERR_SKETCH"\`
@@ -697,7 +697,7 @@ command -v codex >/dev/null 2>&1 && echo "CODEX_AVAILABLE" || echo "CODEX_NOT_AV
\`\`\`bash
TMPERR_DESIGN=$(mktemp /tmp/codex-design-XXXXXXXX)
_REPO_ROOT=$(git rev-parse --show-toplevel) || { echo "ERROR: not in a git repo" >&2; exit 1; }
-codex exec "${escapedCodexPrompt}" -C "$_REPO_ROOT" -s read-only -c 'model_reasoning_effort="${reasoningEffort}"' --enable web_search_cached < /dev/null 2>"$TMPERR_DESIGN"
+codex exec "${escapedCodexPrompt}" -C "$_REPO_ROOT" -s read-only -c 'model_reasoning_effort="${reasoningEffort}"' ${CODEX_WEB_SEARCH_FLAG} < /dev/null 2>"$TMPERR_DESIGN"
\`\`\`
Use a 5-minute timeout (\`timeout: 300000\`). After the command completes, read stderr:
\`\`\`bash
diff --git a/scripts/resolvers/index.ts b/scripts/resolvers/index.ts
index fce4bc6b7..98c7dfdda 100644
--- a/scripts/resolvers/index.ts
+++ b/scripts/resolvers/index.ts
@@ -23,7 +23,7 @@ import { generateCommandReference, generateSnapshotFlags, generateBrowseSetup }
import { generateDesignMethodology, generateDesignHardRules, generateDesignOutsideVoices, generateDesignReviewLite, generateDesignSketch, generateDesignSetup, generateDesignMockup, generateDesignShotgunLoop, generateTasteProfile, generateUXPrinciples } from './design';
import { generateTestBootstrap, generateTestCoverageAuditPlan, generateTestCoverageAuditShip } from './testing';
import { generateReviewDashboard, generatePlanFileReviewReport, generateExitPlanModeGate, generateAntiShortcutClause, generateSpecReviewLoop, generateBenefitsFrom, generateCodexSecondOpinion, generateAdversarialStep, generateCodexPlanReview, generateCodexDocReview, generatePlanCompletionAuditShip, generatePlanCompletionAuditReview, generatePlanVerificationExec, generateScopeDrift, generateCrossReviewDedup } from './review';
-import { generateSlugEval, generateSlugSetup, generateBaseBranchDetect, generateDeployBootstrap, generateQAMethodology, generateCoAuthorTrailer, generateChangelogWorkflow } from './utility';
+import { generateSlugEval, generateSlugSetup, generateBaseBranchDetect, generateDeployBootstrap, generateQAMethodology, generateCoAuthorTrailer, generateChangelogWorkflow, generateCodexWebSearchFlag } from './utility';
import { generateLearningsSearch, generateLearningsLog } from './learnings';
import { generateConfidenceCalibration } from './confidence';
import { generateInvokeSkill } from './composition';
@@ -39,6 +39,7 @@ import { generateDesignDocDiscovery } from './design-doc-discovery';
export const RESOLVERS: Record<string, ResolverFn> = {
SLUG_EVAL: generateSlugEval,
SLUG_SETUP: generateSlugSetup,
+ CODEX_WEB_SEARCH_FLAG: generateCodexWebSearchFlag,
REDACT_INVOCATION_BLOCK: generateRedactInvocationBlock,
THIRD_PARTY_ACTIONS: generateThirdPartyActions,
DESIGN_DOC_DISCOVERY: generateDesignDocDiscovery,
diff --git a/scripts/resolvers/preamble/generate-brain-sync-block.ts b/scripts/resolvers/preamble/generate-brain-sync-block.ts
index bbd18c2bc..ae1ab5778 100644
--- a/scripts/resolvers/preamble/generate-brain-sync-block.ts
+++ b/scripts/resolvers/preamble/generate-brain-sync-block.ts
@@ -30,6 +30,27 @@
import type { TemplateContext } from '../types';
import { quoteSafePath } from '../types';
+/**
+ * Shared jq sub-expression resolving the gbrain MCP registration entry
+ * (#2499). Claude Code registers MCP servers at TWO scopes in
+ * ~/.claude.json: user scope (.mcpServers.gbrain) and project scope
+ * (.projects["/abs/path"].mcpServers.gbrain — what `claude mcp add`
+ * WITHOUT --scope user writes). Reading only user scope makes a correctly
+ * configured project-scoped brain invisible: brain-aware blocks suppress,
+ * remote-mode sync is never recognised, nothing errors.
+ *
+ * Resolution order: user scope first, then the nearest-ancestor project
+ * entry for $PWD that actually carries a gbrain server (longest matching
+ * key with a path-boundary check, so nested repos pick their own
+ * registration, /a/repo never matches /a/repo2, and a nested project
+ * WITHOUT gbrain doesn't shadow its parent's registration). The emitted
+ * bash resolves the entry ONCE into _GBRAIN_MCP_ENTRY (compact JSON) and
+ * extracts fields from that variable — one jq parse of claude.json per
+ * skill start, and the long expression appears once per rendered SKILL.md.
+ */
+const GBRAIN_MCP_ENTRY_JQ =
+ '.mcpServers.gbrain // ((.projects // {}) | to_entries | map(select((.key as $k | $cwd == $k or ($cwd | startswith($k + "/"))) and ((try .value.mcpServers.gbrain catch null) != null))) | sort_by(.key | length) | last | .value.mcpServers.gbrain) // empty';
+
export function generateBrainSyncBlock(ctx: TemplateContext): string {
const isBrainHost = ctx.host === 'gbrain' || ctx.host === 'hermes';
return `## Artifacts Sync (skill start)
@@ -79,10 +100,13 @@ _BRAIN_SYNC_MODE=$("$_BRAIN_CONFIG_BIN" get artifacts_sync_mode 2>/dev/null || e
# Detect remote-MCP mode (Path 4 of /setup-gbrain). Local artifacts sync is
# a no-op in remote mode; the brain server pulls from GitHub/GitLab on its
# own cadence. Read claude.json directly to keep this preamble fast (no
-# subprocess to claude CLI on every skill start).
+# subprocess to claude CLI on every skill start). Both registration scopes
+# are read (#2499): user scope, then the nearest-ancestor project scope.
_GBRAIN_MCP_MODE="none"
+_GBRAIN_MCP_ENTRY=""
if command -v jq >/dev/null 2>&1 && [ -f "$HOME/.claude.json" ]; then
- _GBRAIN_MCP_TYPE=$(jq -r '.mcpServers.gbrain.type // .mcpServers.gbrain.transport // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_ENTRY=$(jq -c --arg cwd "$PWD" '${GBRAIN_MCP_ENTRY_JQ}' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_TYPE=$(printf '%s' "$_GBRAIN_MCP_ENTRY" | jq -r '.type // .transport // empty' 2>/dev/null)
case "$_GBRAIN_MCP_TYPE" in
url|http|sse) _GBRAIN_MCP_MODE="remote-http" ;;
stdio) _GBRAIN_MCP_MODE="local-stdio" ;;
@@ -103,6 +127,7 @@ if [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_DO_PULL=1
if [ -f "$_BRAIN_LAST_PULL_FILE" ]; then
_BRAIN_LAST=$(cat "$_BRAIN_LAST_PULL_FILE" 2>/dev/null || echo 0)
+ case "$_BRAIN_LAST" in ''|*[!0-9]*) _BRAIN_LAST=0 ;; esac
_BRAIN_AGE=$(( _BRAIN_NOW - _BRAIN_LAST ))
[ "$_BRAIN_AGE" -lt 86400 ] && _BRAIN_DO_PULL=0
fi
@@ -116,7 +141,7 @@ fi
if [ "$_GBRAIN_MCP_MODE" = "remote-http" ]; then
# Remote-MCP mode: local artifacts sync is a no-op (brain admin's server
# pulls from GitHub/GitLab). Show the user this is by design, not broken.
- _GBRAIN_HOST=$(jq -r '.mcpServers.gbrain.url // empty' "$HOME/.claude.json" 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\\1|')
+ _GBRAIN_HOST=$(printf '%s' "\${_GBRAIN_MCP_ENTRY:-}" | jq -r '.url // empty' 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\\1|' | head -1 | tr -cd 'A-Za-z0-9._-')
echo "ARTIFACTS_SYNC: remote-mode (managed by brain server \${_GBRAIN_HOST:-remote})"
elif [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_QUEUE_DEPTH=0
diff --git a/scripts/resolvers/preamble/generate-context-recovery.ts b/scripts/resolvers/preamble/generate-context-recovery.ts
index 46403b688..5894a8aea 100644
--- a/scripts/resolvers/preamble/generate-context-recovery.ts
+++ b/scripts/resolvers/preamble/generate-context-recovery.ts
@@ -3,6 +3,12 @@ import type { TemplateContext } from '../types';
export function generateContextRecovery(ctx: TemplateContext): string {
const binDir = ctx.paths.binDir; // env-var hosts already resolve to $GSTACK_BIN via types.ts
+ // Branch-form discipline (#2550/#1851): FILE-PATH positions use $BRANCH —
+ // the canonical slug form the gstack-slug eval on the first line sets
+ // (tr '/' '-' then tr -cd 'a-zA-Z0-9._-', matching what gstack-review-log
+ // WRITES). The timeline.jsonl greps keep raw $_BRANCH because the timeline
+ // writer (preamble's gstack-timeline-log call) stores the raw branch in the
+ // "branch" field — slugging the reader there would break matching.
return `## Context Recovery
At session start or after compaction, recover recent project context.
@@ -12,8 +18,8 @@ eval "$(${binDir}/gstack-slug 2>/dev/null)"
_PROJ="\${GSTACK_HOME:-$HOME/.gstack}/projects/\${SLUG:-unknown}"
if [ -d "$_PROJ" ]; then
echo "--- RECENT ARTIFACTS ---"
- find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs ls -t 2>/dev/null | head -3
- [ -f "$_PROJ/\${_BRANCH}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/\${_BRANCH}-reviews.jsonl" | tr -d ' ') entries"
+ find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3
+ [ -f "$_PROJ/\${BRANCH:-unknown}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/\${BRANCH:-unknown}-reviews.jsonl" | tr -d ' ') entries"
[ -f "$_PROJ/timeline.jsonl" ] && tail -5 "$_PROJ/timeline.jsonl"
if [ -f "$_PROJ/timeline.jsonl" ]; then
_LAST=$(grep "\\"branch\\":\\"\${_BRANCH}\\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -1)
@@ -21,7 +27,7 @@ if [ -d "$_PROJ" ]; then
_RECENT_SKILLS=$(grep "\\"branch\\":\\"\${_BRANCH}\\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -3 | grep -o '"skill":"[^"]*"' | sed 's/"skill":"//;s/"//' | tr '\\n' ',')
[ -n "$_RECENT_SKILLS" ] && echo "RECENT_PATTERN: $_RECENT_SKILLS"
fi
- _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs ls -t 2>/dev/null | head -1)
+ _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs -r ls -t 2>/dev/null | head -1)
[ -n "$_LATEST_CP" ] && echo "LATEST_CHECKPOINT: $_LATEST_CP"
if [ -f "$_PROJ/decisions.active.json" ]; then
echo "--- ACTIVE DECISIONS (recent, scope-relevant) ---"
diff --git a/scripts/resolvers/preamble/generate-preamble-bash.ts b/scripts/resolvers/preamble/generate-preamble-bash.ts
index 13ef420ca..e133b5d76 100644
--- a/scripts/resolvers/preamble/generate-preamble-bash.ts
+++ b/scripts/resolvers/preamble/generate-preamble-bash.ts
@@ -96,9 +96,11 @@ else
fi
${ctx.paths.binDir}/gstack-timeline-log '{"skill":"${ctx.skillName}","event":"started","branch":"'"$_BRANCH"'","session":"'"$_SESSION_ID"'"}' 2>/dev/null &
_HAS_ROUTING="no"
-if [ -f CLAUDE.md ] && grep -q "## Skill routing" CLAUDE.md 2>/dev/null; then
- _HAS_ROUTING="yes"
-fi
+for _RF in CLAUDE.md AGENTS.md; do
+ if [ -f "$_RF" ] && grep -q "## Skill routing" "$_RF" 2>/dev/null; then
+ _HAS_ROUTING="yes"
+ fi
+done
_ROUTING_DECLINED=$(${ctx.paths.binDir}/gstack-config get routing_declined 2>/dev/null || echo "false")
echo "HAS_ROUTING: $_HAS_ROUTING"
echo "ROUTING_DECLINED: $_ROUTING_DECLINED"
diff --git a/scripts/resolvers/question-tuning.ts b/scripts/resolvers/question-tuning.ts
index 5fefc5585..68dc218ff 100644
--- a/scripts/resolvers/question-tuning.ts
+++ b/scripts/resolvers/question-tuning.ts
@@ -20,9 +20,14 @@ function binDir(ctx: TemplateContext): string {
*/
export function generateQuestionTuning(ctx: TemplateContext): string {
const bin = binDir(ctx);
+ // Registry path must be interpolated absolute like ${bin} is (#2489): agents
+ // run with cwd in the USER'S project, where a relative
+ // `scripts/question-registry.ts` never resolves — the lookup silently fails
+ // and every question_id gets fabricated via the {skill}-{slug} fallback.
+ const registry = `${ctx.paths.skillRoot}/scripts/question-registry.ts`;
return `## Question Tuning (skip entirely if \`QUESTION_TUNING: false\`)
-Before each AskUserQuestion, choose \`question_id\` from \`scripts/question-registry.ts\` or \`{skill}-{slug}\`, then run \`printf '%s' "<question summary>" | ${bin}/gstack-question-preference --check "<id>" --summary-stdin\` (piped summary feeds the one-way keyword net, #2024). \`AUTO_DECIDE\` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." \`ASK_NORMALLY\` means ask.
+Before each AskUserQuestion, choose \`question_id\` from \`${registry}\` or \`{skill}-{slug}\`, then run \`printf '%s' "<question summary>" | ${bin}/gstack-question-preference --check "<id>" --summary-stdin\` (piped summary feeds the one-way keyword net, #2024). \`AUTO_DECIDE\` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." \`ASK_NORMALLY\` means ask.
**Embed the question_id as a marker in the question text** so hooks can identify it deterministically (plan-tune cathedral T14 / D18 progressive markers). Append \`<gstack-qid:{question_id}>\` somewhere in the rendered question (the leading line or trailing line is fine; the marker doesn't render visibly to the user when wrapped in HTML-style angle brackets, but the hook strips it). Without the marker the PreToolUse enforcement hook treats the AUQ as observed-only and never auto-decides — so always include it when the question matches a registered \`question_id\`.
diff --git a/scripts/resolvers/review.ts b/scripts/resolvers/review.ts
index 187534443..240ea2919 100644
--- a/scripts/resolvers/review.ts
+++ b/scripts/resolvers/review.ts
@@ -14,7 +14,7 @@
*/
import type { TemplateContext } from './types';
import { generateInvokeSkill } from './composition';
-import { codexPreflight, codexErrorHandling } from './constants';
+import { codexPreflight, codexErrorHandling, CODEX_WEB_SEARCH_FLAG } from './constants';
import { DESIGN_DOC_DISCOVERY_BLOCK } from './design-doc-discovery';
import { getHostConfig } from '../../hosts/index';
@@ -368,7 +368,7 @@ Then add the context block and mode-appropriate instructions:
\`\`\`bash
TMPERR_OH=$(mktemp /tmp/codex-oh-err-XXXXXXXX)
_REPO_ROOT=$(git rev-parse --show-toplevel) || { echo "ERROR: not in a git repo" >&2; exit 1; }
-codex exec "$(cat "$CODEX_PROMPT_FILE")" -C "$_REPO_ROOT" -s read-only -c 'model_reasoning_effort="high"' --enable web_search_cached < /dev/null 2>"$TMPERR_OH"
+codex exec "$(cat "$CODEX_PROMPT_FILE")" -C "$_REPO_ROOT" -s read-only -c 'model_reasoning_effort="high"' ${CODEX_WEB_SEARCH_FLAG} < /dev/null 2>"$TMPERR_OH"
\`\`\`
Use a 5-minute timeout (\`timeout: 300000\`). After the command completes, read stderr:
@@ -532,7 +532,7 @@ _REPO_ROOT=$(git rev-parse --show-toplevel) || { echo "ERROR: not in a git repo"
# here. It defines _gstack_codex_timeout_wrapper (gtimeout -> timeout ->
# unwrapped fallback), added in #1056 but never wired into this call site.
source ~/.claude/skills/gstack/bin/gstack-codex-probe 2>/dev/null || true
-_gstack_codex_timeout_wrapper 540 codex exec "${CODEX_BOUNDARY}Review the changes on this branch against the base branch. Run DIFF_BASE=$(git merge-base origin/<base> HEAD) && git diff "$DIFF_BASE" to see the diff. Your job is to find ways this code will fail in production. Think like an attacker and a chaos engineer. Find edge cases, race conditions, security holes, resource leaks, failure modes, and silent data corruption paths. Be adversarial. Be thorough. No compliments — just the problems. End your output with ONE line in the canonical format \`Recommendation: <action> because <one-line reason naming the most exploitable finding>\`. Generic reasons like 'because it's safer' do not qualify; the reason must point to a specific finding or no-fix rationale." -C "$_REPO_ROOT" -s read-only -c 'model_reasoning_effort="high"' --enable web_search_cached < /dev/null 2>"$TMPERR_ADV"
+_gstack_codex_timeout_wrapper 540 codex exec "${CODEX_BOUNDARY}Review the changes on this branch against the base branch. Run DIFF_BASE=$(git merge-base origin/<base> HEAD) && git diff "$DIFF_BASE" to see the diff. Your job is to find ways this code will fail in production. Think like an attacker and a chaos engineer. Find edge cases, race conditions, security holes, resource leaks, failure modes, and silent data corruption paths. Be adversarial. Be thorough. No compliments — just the problems. End your output with ONE line in the canonical format \`Recommendation: <action> because <one-line reason naming the most exploitable finding>\`. Generic reasons like 'because it's safer' do not qualify; the reason must point to a specific finding or no-fix rationale." -C "$_REPO_ROOT" -s read-only -c 'model_reasoning_effort="high"' ${CODEX_WEB_SEARCH_FLAG} < /dev/null 2>"$TMPERR_ADV"
\`\`\`
Set the Bash tool's \`timeout\` parameter to \`600000\` (10 minutes). It sits ABOVE the 540s wrapper deliberately, so the wrapper fires first and a stall surfaces as a diagnosable exit 124 instead of a harness kill that returns nothing. The wrapper resolves \`gtimeout\`, then \`timeout\`, then runs unwrapped, so it is safe on a macOS without coreutils. After the command completes, read stderr:
@@ -565,7 +565,7 @@ cd "$_REPO_ROOT"
# here. It defines _gstack_codex_timeout_wrapper (gtimeout -> timeout ->
# unwrapped fallback), added in #1056 but never wired into this call site.
source ~/.claude/skills/gstack/bin/gstack-codex-probe 2>/dev/null || true
-_gstack_codex_timeout_wrapper 540 codex review --base <base> -c 'model_reasoning_effort="high"' --enable web_search_cached < /dev/null 2>"$TMPERR"
+_gstack_codex_timeout_wrapper 540 codex review --base <base> -c 'model_reasoning_effort="high"' ${CODEX_WEB_SEARCH_FLAG} < /dev/null 2>"$TMPERR"
\`\`\`
**No prompt argument.** \`--base\` is what scopes the review, and the positional \`[PROMPT]\` is mutually exclusive with it — passing both fails at argv parsing. Do NOT "fix" that error by dropping \`--base\` and keeping the prompt: a prompt-only \`codex review\` silently falls back to the **uncommitted working-tree** scope (\`git status --short; git diff\`), so it reviews the wrong changes and reports "no changes" on a clean tree. Prompt text describing the diff range does not change what the CLI feeds the reviewer. Unlike the adversarial pass above, which uses \`codex exec\` and really does run the git command it's told to, this path gets a pre-computed diff from the CLI — which is also why it needs no filesystem boundary.
@@ -666,7 +666,7 @@ THE PLAN:
\`\`\`bash
TMPERR_PV=$(mktemp /tmp/codex-planreview-XXXXXXXX)
_REPO_ROOT=$(git rev-parse --show-toplevel) || { echo "ERROR: not in a git repo" >&2; exit 1; }
-codex exec "<prompt>" -C "$_REPO_ROOT" -s read-only -c 'model_reasoning_effort="high"' --enable web_search_cached < /dev/null 2>"$TMPERR_PV"
+codex exec "<prompt>" -C "$_REPO_ROOT" -s read-only -c 'model_reasoning_effort="high"' ${CODEX_WEB_SEARCH_FLAG} < /dev/null 2>"$TMPERR_PV"
\`\`\`
Use a 5-minute timeout (\`timeout: 300000\`). After the command completes, read stderr:
@@ -801,7 +801,7 @@ THE DOCS AND DIFF: <list the touched doc paths>"
\`\`\`bash
TMPERR_DOC=$(mktemp /tmp/codex-docreview-XXXXXXXX)
_REPO_ROOT=$(git rev-parse --show-toplevel) || { echo "ERROR: not in a git repo" >&2; exit 1; }
-codex exec "<prompt>" -C "$_REPO_ROOT" -s read-only -c 'model_reasoning_effort="high"' --enable web_search_cached < /dev/null 2>"$TMPERR_DOC"
+codex exec "<prompt>" -C "$_REPO_ROOT" -s read-only -c 'model_reasoning_effort="high"' ${CODEX_WEB_SEARCH_FLAG} < /dev/null 2>"$TMPERR_DOC"
\`\`\`
Use a 5-minute timeout (\`timeout: 300000\`). After the command completes, read stderr:
@@ -857,7 +857,7 @@ function generatePlanFileDiscovery(): string {
\`\`\`bash
setopt +o nomatch 2>/dev/null || true # zsh compat
-BRANCH=$(git branch --show-current 2>/dev/null | tr '/' '-')
+BRANCH=$(git branch --show-current 2>/dev/null | tr '/' '-' | tr -cd 'a-zA-Z0-9._-')
REPO=$(basename "$(git rev-parse --show-toplevel 2>/dev/null)")
# Compute project slug for ~/.gstack/projects/ lookup
_PLAN_SLUG=$(git remote get-url origin 2>/dev/null | sed 's|.*[:/]\\([^/]*/[^/]*\\)\\.git$|\\1|;s|.*[:/]\\([^/]*/[^/]*\\)$|\\1|' | tr '/' '-' | tr -cd 'a-zA-Z0-9._-') || true
@@ -867,7 +867,7 @@ for PLAN_DIR in "$HOME/.gstack/projects/$_PLAN_SLUG" "$HOME/.claude/plans" "$HOM
[ -d "$PLAN_DIR" ] || continue
PLAN=$(ls -t "$PLAN_DIR"/*.md 2>/dev/null | xargs grep -l "$BRANCH" 2>/dev/null | head -1)
[ -z "$PLAN" ] && PLAN=$(ls -t "$PLAN_DIR"/*.md 2>/dev/null | xargs grep -l "$REPO" 2>/dev/null | head -1)
- [ -z "$PLAN" ] && PLAN=$(find "$PLAN_DIR" -name '*.md' -mmin -1440 -maxdepth 1 2>/dev/null | xargs ls -t 2>/dev/null | head -1)
+ [ -z "$PLAN" ] && PLAN=$(find "$PLAN_DIR" -name '*.md' -mmin -1440 -maxdepth 1 2>/dev/null | xargs -r ls -t 2>/dev/null | head -1)
[ -n "$PLAN" ] && break
done
[ -n "$PLAN" ] && echo "PLAN_FILE: $PLAN" || echo "NO_PLAN_FILE"
diff --git a/scripts/resolvers/utility.ts b/scripts/resolvers/utility.ts
index 560a73c45..74e364cf1 100644
--- a/scripts/resolvers/utility.ts
+++ b/scripts/resolvers/utility.ts
@@ -1,4 +1,14 @@
import type { TemplateContext } from './types';
+import { CODEX_WEB_SEARCH_FLAG } from './constants';
+
+/**
+ * {{CODEX_WEB_SEARCH_FLAG}} — the non-deprecated codex web-search flag
+ * (#2525). Templates with inline codex invocations reference this token so
+ * the flag has exactly one source of truth (scripts/resolvers/constants.ts).
+ */
+export function generateCodexWebSearchFlag(_ctx: TemplateContext): string {
+ return CODEX_WEB_SEARCH_FLAG;
+}
export function generateSlugEval(ctx: TemplateContext): string {
return `eval "$(${ctx.paths.binDir}/gstack-slug 2>/dev/null)"`;
diff --git a/scripts/test-free-shards.ts b/scripts/test-free-shards.ts
index 386b25a29..140eac361 100755
--- a/scripts/test-free-shards.ts
+++ b/scripts/test-free-shards.ts
@@ -169,6 +169,10 @@ export const KNOWN_WINDOWS_INCOMPATIBLE: Array<{ file: string; reason: string }>
// seven POSIX-bound files the content patterns cannot see (their
// POSIX-ness is what they TEST, or arrives via a variable). Receipts:
// PR #2593 windows-free-tests run 31918591602.
+ {
+ file: 'test/codex-under-codex-detection.test.ts',
+ reason: 'drives the rendered preflight bash under a hardcoded POSIX PATH (/usr/bin:/bin) — bash is unreachable through that PATH on Windows, so every case sees empty output (v1.67 windows lane run 95234224148)',
+ },
{
file: 'test/regression-pr1169-build-app-sed.test.ts',
reason: 'tests sed escape sequences in build-app.sh — sed/bash are the subject under test',
@@ -255,6 +259,26 @@ export const KNOWN_WINDOWS_INCOMPATIBLE: Array<{ file: string; reason: string }>
// pattern hit is a false positive — the point of these files is Windows
// coverage, so auto-excluding them defeats the regression tests they carry.
const KNOWN_WINDOWS_SAFE: Array<{ file: string; reason: string }> = [
+ {
+ file: 'test/setup-windows-rerun-refresh.test.ts',
+ // Trips the "spawns bin/ shebang script" pattern via path.join(..., 'bin',
+ // 'tool.sh') fixture paths, but every spawn goes through spawnSync('bash',
+ // ['-c', ...]) — Git Bash executes it fine on windows-latest. This file IS
+ // the #2444 Windows regression coverage (IS_WINDOWS=1 copy-refresh path);
+ // excluding it here would keep the bug class unexercised on the one
+ // platform it bites.
+ reason: 'bin/ hits are fixture path segments; spawns bash explicitly — the IS_WINDOWS=1 refresh path must run on windows-latest',
+ },
+ {
+ file: 'test/uninstall-windows-copies.test.ts',
+ // Trips the "spawns bin/ shebang script" pattern via the
+ // path.join(ROOT, 'bin', 'gstack-uninstall') constant, but the script is
+ // always spawned through spawnSync('bash', [UNINSTALL, ...]). This file
+ // carries the #2563 Windows real-dir-copy uninstall coverage — the bug
+ // ONLY reproduces on the copy install shape windows-latest exercises.
+ // The symlink-shape describe block self-skips on win32.
+ reason: 'bin/ hit is a bash-spawned script path; #2563 real-dir uninstall coverage must run on windows-latest',
+ },
{
file: 'browse/test/file-permissions.test.ts',
// Trips the POSIX-mode-bitmask pattern, but every `mode & 0o777` assertion
@@ -355,6 +379,10 @@ export const TREE_MUTATING: Record<string, string> = {
'test/skill-validation.test.ts': 'regenerates .agents/ (codex host) artifacts in place (3 sites)',
'test/gbrain-detection-override.test.ts':
'regenerates SKILL.md in place with --respect-detection (gbrain variant), then git-restores — readers see inflated skeletons mid-window',
+ 'test/host-config.test.ts':
+ 'golden tests read .agents/.factory artifacts produced by gen-skill-docs.test.ts, and its beforeAll generates them when missing (#2532) — must not race the parallel readers or run before the mutators window',
+ 'test/catalog-trim.test.ts':
+ 'imports scripts/gen-skill-docs.ts, whose top-level body regenerates the full claude host at import time (71 files; idempotent on a fresh tree, but a stale tree gets rewritten mid-window) — same hazard class as #2532',
// Ratchet readers (measure the tree; need it quiet):
'test/parity-suite.test.ts': 'RATCHET READER — parity caps measure live SKILL.md/section bytes',
'test/skill-size-budget.test.ts': 'RATCHET READER — per-skill and corpus size budgets measure the live tree',
diff --git a/setup b/setup
index 51be8f13a..a17e5c22c 100755
--- a/setup
+++ b/setup
@@ -58,6 +58,8 @@ FACTORY_SKILLS="$HOME/.factory/skills"
FACTORY_GSTACK="$FACTORY_SKILLS/gstack"
OPENCODE_SKILLS="$HOME/.config/opencode/skills"
OPENCODE_GSTACK="$OPENCODE_SKILLS/gstack"
+CURSOR_SKILLS="$HOME/.cursor/skills"
+CURSOR_GSTACK="$CURSOR_SKILLS/gstack"
IS_WINDOWS=0
case "$(uname -s)" in
@@ -102,6 +104,53 @@ _link_or_copy() {
fi
}
+# ─── Ownership gates for the Windows refresh bypass (#2444 → #2142) ─────────
+# On Windows a refresh means rm -rf + re-copy (_link_or_copy). The host
+# skills dirs are SHARED namespaces (~/.codex/skills, ~/.factory/skills,
+# ~/.cursor/skills, ...), so a gstack* glob name can collide with a user's
+# OWN real directory (e.g. ~/.cursor/skills/gstack-notes) — deleting it on
+# every ./setup re-run is silent data loss. Mirror of bin/gstack-uninstall's
+# provenance gate (#2563): an existing REAL skill dir may only be replaced
+# when its SKILL.md carries the generated banner. Missing targets and
+# symlinks always pass (replacing a link never destroys content); non-dir
+# targets pass (file targets live inside gstack-owned roots).
+_owned_for_windows_refresh() {
+ local dst="$1"
+ if [ ! -e "$dst" ] && [ ! -L "$dst" ]; then return 0; fi
+ if [ -L "$dst" ]; then return 0; fi
+ if [ ! -d "$dst" ]; then return 0; fi
+ grep -q '<!-- AUTO-GENERATED from' "$dst/SKILL.md" 2>/dev/null
+}
+
+# A sidecar/runtime ROOT (…/skills/gstack) is provably USER-owned when it is
+# a real dir whose SKILL.md exists but lacks the generated banner — a
+# hand-written skill squatting on the canonical name. The sidecar installers
+# skip it entirely rather than write into (or wipe) someone else's skill.
+# A root with NO SKILL.md stays presumed ours: it is the documented gstack
+# install location and old/partial installs legitimately look like that.
+_sidecar_root_user_owned() {
+ local root="$1"
+ [ -d "$root" ] || return 1
+ [ -L "$root" ] && return 1
+ [ -f "$root/SKILL.md" ] || return 1
+ ! grep -q '<!-- AUTO-GENERATED from' "$root/SKILL.md" 2>/dev/null
+}
+
+# Swap a freshly-rendered tmp dir into the live render location (#2569
+# hardening). Installed skills SYMLINK into the live dir, so it is only ever
+# replaced AFTER a successful render — a failed render leaves the previous
+# render (and every link into it) fully intact. Keep in sync with
+# bin/gstack-config's _swap_in_render (same contract, both pinned by
+# test/user-render-out-dir-install.test.ts).
+_swap_in_render() {
+ local render_dir="$1" render_tmp="$2"
+ local render_old="$render_dir.old.$$"
+ rm -rf "$render_old"
+ if [ -e "$render_dir" ] || [ -L "$render_dir" ]; then mv "$render_dir" "$render_old"; fi
+ mv "$render_tmp" "$render_dir"
+ rm -rf "$render_old"
+}
+
_WINDOWS_COPY_NOTE_PRINTED=0
_print_windows_copy_note_once() {
if [ "$IS_WINDOWS" -eq 1 ] && [ "$_WINDOWS_COPY_NOTE_PRINTED" -eq 0 ]; then
@@ -239,14 +288,19 @@ INSTALL_CODEX=0
INSTALL_KIRO=0
INSTALL_FACTORY=0
INSTALL_OPENCODE=0
+INSTALL_CURSOR=0
if [ "$HOST" = "auto" ]; then
command -v claude >/dev/null 2>&1 && INSTALL_CLAUDE=1
command -v codex >/dev/null 2>&1 && INSTALL_CODEX=1
command -v kiro-cli >/dev/null 2>&1 && INSTALL_KIRO=1
command -v droid >/dev/null 2>&1 && INSTALL_FACTORY=1
command -v opencode >/dev/null 2>&1 && INSTALL_OPENCODE=1
+ # Cursor's `cursor` CLI shim isn't always on PATH; ~/.cursor is the
+ # reliable footprint of an installed Cursor IDE.
+ command -v cursor >/dev/null 2>&1 && INSTALL_CURSOR=1
+ [ -d "$HOME/.cursor" ] && INSTALL_CURSOR=1
# If none found, default to claude
- if [ "$INSTALL_CLAUDE" -eq 0 ] && [ "$INSTALL_CODEX" -eq 0 ] && [ "$INSTALL_KIRO" -eq 0 ] && [ "$INSTALL_FACTORY" -eq 0 ] && [ "$INSTALL_OPENCODE" -eq 0 ]; then
+ if [ "$INSTALL_CLAUDE" -eq 0 ] && [ "$INSTALL_CODEX" -eq 0 ] && [ "$INSTALL_KIRO" -eq 0 ] && [ "$INSTALL_FACTORY" -eq 0 ] && [ "$INSTALL_OPENCODE" -eq 0 ] && [ "$INSTALL_CURSOR" -eq 0 ]; then
INSTALL_CLAUDE=1
fi
elif [ "$HOST" = "claude" ]; then
@@ -259,6 +313,8 @@ elif [ "$HOST" = "factory" ]; then
INSTALL_FACTORY=1
elif [ "$HOST" = "opencode" ]; then
INSTALL_OPENCODE=1
+elif [ "$HOST" = "cursor" ]; then
+ INSTALL_CURSOR=1
fi
migrate_direct_codex_install() {
@@ -351,6 +407,24 @@ ensure_playwright_browser() {
_wait_with_deadline $! 90
}
+# P0 #2554: a macOS XProtect definition update can start SIGKILLing the
+# Chromium revision the lockfile pins, which surfaces here as a failed launch
+# probe. Clear com.apple.quarantine on the Playwright cache bundles ONLY —
+# never a GSTACK_CHROMIUM_PATH bundle (that belongs to the wrapper/embedder;
+# same scope contract as browse's probePoisonedChromiumBundle) — so the
+# reinstall below produces a launchable browser. Best-effort and macOS-only.
+_clear_playwright_quarantine() {
+ [ "$(uname -s)" = "Darwin" ] || return 0
+ local cache_root="${PLAYWRIGHT_BROWSERS_PATH:-$HOME/Library/Caches/ms-playwright}"
+ [ -d "$cache_root" ] || return 0
+ local d
+ for d in "$cache_root"/chromium-* "$cache_root"/chromium_headless_shell-*; do
+ [ -d "$d" ] || continue
+ echo " clearing com.apple.quarantine on $(basename "$d") (XProtect self-heal, #2554)" >&2
+ xattr -dr com.apple.quarantine "$d" 2>/dev/null || true
+ done
+}
+
# Ensure a color-emoji font is installed (Linux only).
#
# Chromium renders emoji code points as .notdef "tofu" (▯) when no color-emoji
@@ -593,6 +667,16 @@ if [ "$INSTALL_OPENCODE" -eq 1 ] && [ "$NEEDS_BUILD" -eq 0 ]; then
)
fi
+# 1e. Generate .cursor/ Cursor skill docs
+if [ "$INSTALL_CURSOR" -eq 1 ] && [ "$NEEDS_BUILD" -eq 0 ]; then
+ log "Generating .cursor/ skill docs..."
+ (
+ cd "$SOURCE_GSTACK_DIR"
+ bun_cmd install --frozen-lockfile 2>/dev/null || bun_cmd install
+ bun_cmd run gen:skill-docs --host cursor
+ )
+fi
+
# 2. Ensure Playwright's Chromium is available
# Detect Ubuntu 26.04: Playwright does not yet ship a native chromium build for
# ubuntu26.04-x64. Override the platform to ubuntu24.04-x64 so the installer
@@ -610,6 +694,10 @@ fi
if ! ensure_playwright_browser; then
echo "Installing Playwright Chromium..."
+ # XProtect self-heal (#2554): the probe failure may be the OS killing the
+ # cached Chromium, not a missing install. Clear quarantine on the Playwright
+ # cache bundles before reinstalling so the fresh fetch launches clean.
+ _clear_playwright_quarantine
_PW_LOCK="${TMPDIR:-/tmp}/gstack-playwright-install.lock"
# Stale-lock self-heal: a SIGKILL'd prior setup leaves the lock dir behind
# forever (mkdir mutexes have no owner). If the recorded holder PID is dead,
@@ -694,6 +782,51 @@ fi
# 3. Ensure ~/.gstack global state directory exists
mkdir -p "$HOME/.gstack/projects"
+# ─── Helper: link a skill's runtime assets into its installed dir ────────────
+# Installs EVERY runtime asset a skill ships next to its SKILL.md (#2317,
+# #2454): review/checklist.md + specialists/, qa/templates + references,
+# gstack-upgrade/migrations, careful/bin, freeze/bin, sections/, etc.
+# Exclusion list rather than inclusion list (F7) so a new asset file is
+# installed by default instead of silently dropped:
+# - SKILL.md linked separately by the caller (name-aware)
+# - node_modules dependency trees, never a runtime read
+# - dist compiled binaries; skills reference them repo-anchored
+# (~/.claude/skills/gstack/browse/dist/...), never
+# alias-relative, and fresh clones haven't built them
+# - test test fixtures
+# - *.tmpl generator sources; the generated file is the asset
+# - hidden files excluded by the glob (no dotglob)
+# Shared so any flattened-skill installer can reuse it (the Claude path is
+# the first consumer; codex/factory/opencode install from generated trees).
+_link_skill_runtime_assets() {
+ local src_dir="$1"
+ local dst_dir="$2"
+ local asset asset_name
+ for asset in "$src_dir"/*; do
+ [ -e "$asset" ] || continue # empty-glob guard
+ asset_name="$(basename "$asset")"
+ case "$asset_name" in
+ SKILL.md|node_modules|dist|test|*.tmpl) continue ;;
+ esac
+ # Refresh unconditionally: rm the old entry (symlink OR real copy — the
+ # Windows install pattern) so re-runs after `git pull` pick up changes.
+ if [ -e "$dst_dir/$asset_name" ] || [ -L "$dst_dir/$asset_name" ]; then
+ rm -rf "$dst_dir/$asset_name"
+ fi
+ _link_or_copy "$asset" "$dst_dir/$asset_name"
+ # P5: the exclusion list above filters DIRECT children only, but the
+ # Windows cp -R copy sweeps NESTED gitignored build output too (concrete:
+ # ios-qa/scripts/gen-accessors-tool/.build is 252MB). Prune post-copy —
+ # a rendered skill install is never a build root, so nested
+ # node_modules/.build/dist are dead weight. ONLY here: the generic
+ # _link_or_copy stays untouched because runtime roots (browse/, design/)
+ # intentionally copy their dist/ binaries.
+ if [ "$IS_WINDOWS" -eq 1 ] && [ -d "$dst_dir/$asset_name" ] && [ ! -L "$dst_dir/$asset_name" ]; then
+ find "$dst_dir/$asset_name" -type d \( -name node_modules -o -name .build -o -name dist \) -prune -exec rm -rf {} + 2>/dev/null || true
+ fi
+ done
+}
+
# ─── Helper: link Claude skill subdirectories into a skills parent directory ──
# Creates real directories (not symlinks) at the top level with a SKILL.md symlink
# inside. This ensures Claude discovers them as top-level skills, not nested under
@@ -731,15 +864,26 @@ link_claude_skill_dirs() {
mkdir -p "$target"
# Validate target isn't a symlink before creating the link
if [ -L "$target/SKILL.md" ]; then rm "$target/SKILL.md"; fi
- _link_or_copy "$gstack_dir/$dir_name/SKILL.md" "$target/SKILL.md"
- # Link the sections/ subdir for carved skills (v2 plan T9). The prefixed
- # Claude skill dir otherwise holds only SKILL.md, so a runtime
- # "Read sections/<name>.md" 404s. Route through _link_or_copy so Windows
- # gets a fresh copy (and re-copies on every ./setup, refreshing staleness).
- if [ -d "$gstack_dir/$dir_name/sections" ]; then
- if [ -e "$target/sections" ] || [ -L "$target/sections" ]; then rm -rf "$target/sections"; fi
- _link_or_copy "$gstack_dir/$dir_name/sections" "$target/sections"
+ # #2569: prefer a rendered :user variant when present. gbrain installs
+ # render brain-aware SKILL.md into ${GSTACK_HOME}/render/claude via
+ # gen:skill-docs --out-dir instead of dirtying the tracked source
+ # checkout; when a render exists for this skill, serve it. The rendered
+ # file's section-base paths point into the render dir, so section reads
+ # resolve there too.
+ _skill_md_src="$gstack_dir/$dir_name/SKILL.md"
+ _render_dir="${GSTACK_USER_RENDER_DIR:-${GSTACK_HOME:-$HOME/.gstack}/render/claude}"
+ if [ -f "$_render_dir/$dir_name/SKILL.md" ]; then
+ _skill_md_src="$_render_dir/$dir_name/SKILL.md"
fi
+ _link_or_copy "$_skill_md_src" "$target/SKILL.md"
+ # Link every runtime asset the skill ships next to its SKILL.md (#2317,
+ # #2454): sections/ for carved skills, review's checklist.md +
+ # specialists/, qa's templates/ + references/, gstack-upgrade's
+ # migrations/, careful/freeze's bin/, ... Without this, only SKILL.md
+ # landed and /review 404'd at "Read .claude/skills/review/checklist.md"
+ # on every fresh Claude install. Routes through _link_or_copy so Windows
+ # gets real copies refreshed on every ./setup.
+ _link_skill_runtime_assets "$gstack_dir/$dir_name" "$target"
linked+=("$link_name")
fi
done
@@ -749,24 +893,44 @@ link_claude_skill_dirs() {
fi
}
+# ─── Helper: install an alias SKILL.md as a rewritten COPY ───────────────────
+# Alias dirs (_gstack-command, connect-chrome) must NOT symlink the canonical
+# SKILL.md: the alias then carries the canonical frontmatter name:, Claude Code
+# sees two skills with the same name, and drops the ENTIRE personal-skills set
+# (#2511, #2201). Copy-then-rewrite instead: sed reads the SOURCE and writes a
+# fresh copy with name: set to the alias. It must never edit through an
+# existing symlink — that would rewrite the generated source file itself.
+# NOTE: every alias name passed to this helper (_gstack-command,
+# connect-chrome, gstack-connect-chrome) is hardcoded in the _INVENTORY seed
+# list in bin/gstack-uninstall — keep the two sites in sync when adding or
+# renaming an alias, or uninstall will refuse to delete the new alias dir.
+_install_alias_skill_md() {
+ local src_skill_md="$1"
+ local dst_dir="$2"
+ local alias_name="$3"
+ [ -f "$src_skill_md" ] || return 0
+ # Old installs left the alias as a whole-dir symlink — replace it.
+ if [ -L "$dst_dir" ]; then rm -f "$dst_dir"; fi
+ mkdir -p "$dst_dir"
+ # Remove any prior symlinked SKILL.md so the redirect below cannot write
+ # through it into the generated source.
+ rm -f "$dst_dir/SKILL.md"
+ sed "1,/^---\$/ s/^name:[[:space:]].*/name: $alias_name/" "$src_skill_md" > "$dst_dir/SKILL.md"
+}
+
# Claude Code skips the repo-shaped ~/.claude/skills/gstack directory when
# building the user-facing slash-command list. Keep the repo path for runtime
-# assets, and add a separate thin wrapper whose frontmatter name remains
-# `gstack` so `/gstack` can autocomplete.
+# assets, and add a separate thin wrapper. Its frontmatter name is rewritten to
+# `_gstack-command` (the dir name) so it never collides with the canonical
+# `gstack` name (#2511).
link_claude_root_skill_alias() {
local gstack_dir="$1"
local skills_dir="$2"
local target="$skills_dir/_gstack-command"
[ -f "$gstack_dir/SKILL.md" ] || return 0
- if [ -L "$target" ]; then
- rm -f "$target"
- fi
- mkdir -p "$target"
- if [ -L "$target/SKILL.md" ]; then rm "$target/SKILL.md"; fi
- _link_or_copy "$gstack_dir/SKILL.md" "$target/SKILL.md"
+ _install_alias_skill_md "$gstack_dir/SKILL.md" "$target" "_gstack-command"
echo " linked root skill alias: gstack"
- _print_windows_copy_note_once
}
# ─── Helper: remove old unprefixed Claude skill entries ───────────────────────
@@ -891,9 +1055,19 @@ link_codex_skill_dirs() {
[ "$skill_name" = "gstack" ] && continue
target="$skills_dir/$skill_name"
# Create or update symlink
- if [ -L "$target" ] || [ ! -e "$target" ]; then
- _link_or_copy "$skill_dir" "$target"
- linked+=("$skill_name")
+ # #2444: on Windows the installed target is a REAL directory copy, so
+ # the symlink-or-missing guard skipped every re-run and SKILL.md never
+ # refreshed after `git pull`. IS_WINDOWS bypasses the guard —
+ # _link_or_copy rm -rf's the destination first, refreshing the copy.
+ # #2142: a real dir may only be replaced when it is provably ours
+ # (_owned_for_windows_refresh), never a user's own colliding dir.
+ if [ "$IS_WINDOWS" -eq 1 ] || [ -L "$target" ] || [ ! -e "$target" ]; then
+ if _owned_for_windows_refresh "$target"; then
+ _link_or_copy "$skill_dir" "$target"
+ linked+=("$skill_name")
+ else
+ echo " left in place (existing dir not gstack-managed — no generated banner): $target" >&2
+ fi
fi
fi
done
@@ -909,6 +1083,13 @@ link_codex_skill_dirs() {
create_agents_sidecar() {
local repo_root="$1"
local agents_gstack="$repo_root/.agents/skills/gstack"
+ # #2142: a hand-written skill squatting on the canonical name is the
+ # user's — never write into it (the Windows branch would rm -rf its
+ # subdirs on every re-run).
+ if _sidecar_root_user_owned "$agents_gstack"; then
+ echo " left in place (existing dir not gstack-managed — no generated banner): $agents_gstack" >&2
+ return 0
+ fi
mkdir -p "$agents_gstack"
# Sidecar directories that skills reference at runtime. bin scripts import
@@ -917,7 +1098,9 @@ create_agents_sidecar() {
local src="$SOURCE_GSTACK_DIR/$asset"
local dst="$agents_gstack/$asset"
if [ -d "$src" ] || [ -f "$src" ]; then
- if [ -L "$dst" ] || [ ! -e "$dst" ]; then
+ # #2444: IS_WINDOWS bypass — real-dir copies never match -L, so re-runs
+ # skipped the refresh. _link_or_copy rm -rf's the destination first.
+ if [ "$IS_WINDOWS" -eq 1 ] || [ -L "$dst" ] || [ ! -e "$dst" ]; then
_link_or_copy "$src" "$dst"
fi
fi
@@ -928,7 +1111,9 @@ create_agents_sidecar() {
local src="$SOURCE_GSTACK_DIR/$file"
local dst="$agents_gstack/$file"
if [ -f "$src" ]; then
- if [ -L "$dst" ] || [ ! -e "$dst" ]; then
+ # #2444: IS_WINDOWS bypass — real-dir copies never match -L, so re-runs
+ # skipped the refresh. _link_or_copy rm -rf's the destination first.
+ if [ "$IS_WINDOWS" -eq 1 ] || [ -L "$dst" ] || [ ! -e "$dst" ]; then
_link_or_copy "$src" "$dst"
fi
fi
@@ -979,6 +1164,13 @@ create_codex_runtime_root() {
if [ -f "$agents_dir/gstack-upgrade/SKILL.md" ]; then
_link_or_copy "$agents_dir/gstack-upgrade/SKILL.md" "$codex_gstack/gstack-upgrade/SKILL.md"
fi
+ # plan-eng-review's inline office-hours step reads
+ # $GSTACK_ROOT/office-hours/SKILL.md (#2449) — install the codex-rendered
+ # variant there so the documented path exists.
+ if [ -f "${agents_dir}/gstack-office-hours/SKILL.md" ]; then
+ mkdir -p "${codex_gstack}/office-hours"
+ _link_or_copy "${agents_dir}/gstack-office-hours/SKILL.md" "${codex_gstack}/office-hours/SKILL.md"
+ fi
# Review runtime assets (individual files, NOT the whole review/ dir which has SKILL.md)
for f in checklist.md design-checklist.md greptile-triage.md TODOS-format.md; do
if [ -f "$gstack_dir/review/$f" ]; then
@@ -1027,6 +1219,13 @@ create_factory_runtime_root() {
if [ -f "$factory_dir/gstack-upgrade/SKILL.md" ]; then
_link_or_copy "$factory_dir/gstack-upgrade/SKILL.md" "$factory_gstack/gstack-upgrade/SKILL.md"
fi
+ # plan-eng-review's inline office-hours step reads
+ # $GSTACK_ROOT/office-hours/SKILL.md (#2449) — install the factory-rendered
+ # variant there so the documented path exists.
+ if [ -f "${factory_dir}/gstack-office-hours/SKILL.md" ]; then
+ mkdir -p "${factory_gstack}/office-hours"
+ _link_or_copy "${factory_dir}/gstack-office-hours/SKILL.md" "${factory_gstack}/office-hours/SKILL.md"
+ fi
for f in checklist.md design-checklist.md greptile-triage.md TODOS-format.md; do
if [ -f "$gstack_dir/review/$f" ]; then
_link_or_copy "$gstack_dir/review/$f" "$factory_gstack/review/$f"
@@ -1076,6 +1275,13 @@ create_opencode_runtime_root() {
if [ -f "$opencode_dir/gstack-upgrade/SKILL.md" ]; then
_link_or_copy "$opencode_dir/gstack-upgrade/SKILL.md" "$opencode_gstack/gstack-upgrade/SKILL.md"
fi
+ # plan-eng-review's inline office-hours step reads
+ # $GSTACK_ROOT/office-hours/SKILL.md (#2449) — install the opencode-rendered
+ # variant there so the documented path exists.
+ if [ -f "${opencode_dir}/gstack-office-hours/SKILL.md" ]; then
+ mkdir -p "${opencode_gstack}/office-hours"
+ _link_or_copy "${opencode_dir}/gstack-office-hours/SKILL.md" "${opencode_gstack}/office-hours/SKILL.md"
+ fi
for f in checklist.md design-checklist.md greptile-triage.md TODOS-format.md; do
if [ -f "$gstack_dir/review/$f" ]; then
_link_or_copy "$gstack_dir/review/$f" "$opencode_gstack/review/$f"
@@ -1124,9 +1330,19 @@ link_factory_skill_dirs() {
skill_name="$(basename "$skill_dir")"
[ "$skill_name" = "gstack" ] && continue
target="$skills_dir/$skill_name"
- if [ -L "$target" ] || [ ! -e "$target" ]; then
- _link_or_copy "$skill_dir" "$target"
- linked+=("$skill_name")
+ # #2444: on Windows the installed target is a REAL directory copy, so
+ # the symlink-or-missing guard skipped every re-run and SKILL.md never
+ # refreshed after `git pull`. IS_WINDOWS bypasses the guard —
+ # _link_or_copy rm -rf's the destination first, refreshing the copy.
+ # #2142: a real dir may only be replaced when it is provably ours
+ # (_owned_for_windows_refresh), never a user's own colliding dir.
+ if [ "$IS_WINDOWS" -eq 1 ] || [ -L "$target" ] || [ ! -e "$target" ]; then
+ if _owned_for_windows_refresh "$target"; then
+ _link_or_copy "$skill_dir" "$target"
+ linked+=("$skill_name")
+ else
+ echo " left in place (existing dir not gstack-managed — no generated banner): $target" >&2
+ fi
fi
fi
done
@@ -1156,9 +1372,174 @@ link_opencode_skill_dirs() {
skill_name="$(basename "$skill_dir")"
[ "$skill_name" = "gstack" ] && continue
target="$skills_dir/$skill_name"
- if [ -L "$target" ] || [ ! -e "$target" ]; then
- _link_or_copy "$skill_dir" "$target"
- linked+=("$skill_name")
+ # #2444: on Windows the installed target is a REAL directory copy, so
+ # the symlink-or-missing guard skipped every re-run and SKILL.md never
+ # refreshed after `git pull`. IS_WINDOWS bypasses the guard —
+ # _link_or_copy rm -rf's the destination first, refreshing the copy.
+ # #2142: a real dir may only be replaced when it is provably ours
+ # (_owned_for_windows_refresh), never a user's own colliding dir.
+ if [ "$IS_WINDOWS" -eq 1 ] || [ -L "$target" ] || [ ! -e "$target" ]; then
+ if _owned_for_windows_refresh "$target"; then
+ _link_or_copy "$skill_dir" "$target"
+ linked+=("$skill_name")
+ else
+ echo " left in place (existing dir not gstack-managed — no generated banner): $target" >&2
+ fi
+ fi
+ fi
+ done
+ if [ ${#linked[@]} -gt 0 ]; then
+ echo " linked skills: ${linked[*]}"
+ fi
+}
+
+# ─── Helper: create a minimal ~/.cursor/skills/gstack runtime root ──────────
+# Cursor scans ~/.cursor/skills. Same shape as the Codex/Factory/OpenCode
+# runtime roots: root SKILL.md from the generated tree + runtime assets only.
+# Contributed by @szsunyuan (PR #2547), re-derived onto the current installers.
+create_cursor_runtime_root() {
+ local gstack_dir="$1"
+ local cursor_gstack="$2"
+ local cursor_dir="$gstack_dir/.cursor/skills"
+ local generated_root="$cursor_dir/gstack"
+
+ if [ -L "$cursor_gstack" ]; then
+ rm -f "$cursor_gstack"
+ elif _sidecar_root_user_owned "$cursor_gstack"; then
+ # #2142: a hand-written skill squatting on the canonical name is the
+ # user's — never wipe it to make room for the runtime root.
+ echo " left in place (existing dir not gstack-managed — no generated banner): $cursor_gstack" >&2
+ return 0
+ elif [ -d "$cursor_gstack" ] && [ "$cursor_gstack" != "$gstack_dir" ] && [ "$cursor_gstack" != "$generated_root" ]; then
+ rm -rf "$cursor_gstack"
+ fi
+
+ mkdir -p "$cursor_gstack" "$cursor_gstack/browse" "$cursor_gstack/gstack-upgrade" "$cursor_gstack/review"
+
+ if [ -f "$cursor_dir/gstack/SKILL.md" ]; then
+ _link_or_copy "$cursor_dir/gstack/SKILL.md" "$cursor_gstack/SKILL.md"
+ fi
+ # bin scripts import shared modules via ../lib — bin and lib travel together.
+ if [ -d "$gstack_dir/bin" ]; then
+ _link_or_copy "$gstack_dir/bin" "$cursor_gstack/bin"
+ fi
+ if [ -d "$gstack_dir/lib" ]; then
+ _link_or_copy "$gstack_dir/lib" "$cursor_gstack/lib"
+ fi
+ if [ -d "$gstack_dir/browse/dist" ]; then
+ _link_or_copy "$gstack_dir/browse/dist" "$cursor_gstack/browse/dist"
+ fi
+ if [ -d "$gstack_dir/browse/bin" ]; then
+ _link_or_copy "$gstack_dir/browse/bin" "$cursor_gstack/browse/bin"
+ fi
+ if [ -f "$cursor_dir/gstack-upgrade/SKILL.md" ]; then
+ _link_or_copy "$cursor_dir/gstack-upgrade/SKILL.md" "$cursor_gstack/gstack-upgrade/SKILL.md"
+ fi
+ # Review runtime assets — the cursor host config ships the lean pair.
+ for f in checklist.md TODOS-format.md; do
+ if [ -f "$gstack_dir/review/$f" ]; then
+ _link_or_copy "$gstack_dir/review/$f" "$cursor_gstack/review/$f"
+ fi
+ done
+ if [ -f "$gstack_dir/ETHOS.md" ]; then
+ _link_or_copy "$gstack_dir/ETHOS.md" "$cursor_gstack/ETHOS.md"
+ fi
+ # supabase/config.sh — required by gstack-telemetry-sync to resolve GSTACK_SUPABASE_URL
+ if [ -f "$gstack_dir/supabase/config.sh" ]; then
+ mkdir -p "$cursor_gstack/supabase"
+ _link_or_copy "$gstack_dir/supabase/config.sh" "$cursor_gstack/supabase/config.sh"
+ fi
+}
+
+# Plant runtime assets into the repo-local generated skill dir so in-repo
+# GSTACK_ROOT (preamble prefers $_ROOT/.cursor/skills/gstack) has bin/.
+# NEVER wipe this directory — it holds the generated SKILL.md files.
+create_cursor_sidecar() {
+ local repo_root="$1"
+ local cursor_gstack="$repo_root/.cursor/skills/gstack"
+ local cursor_dir="$repo_root/.cursor/skills"
+
+ # #2142: same user-ownership gate as create_agents_sidecar — but the
+ # generated tree's own root (cursor_dir/gstack carries the banner) always
+ # passes, so normal installs refresh as before.
+ if _sidecar_root_user_owned "$cursor_gstack"; then
+ echo " left in place (existing dir not gstack-managed — no generated banner): $cursor_gstack" >&2
+ return 0
+ fi
+
+ mkdir -p "$cursor_gstack" "$cursor_gstack/browse" "$cursor_gstack/gstack-upgrade" "$cursor_gstack/review"
+
+ if [ -d "$repo_root/bin" ]; then
+ if [ "$IS_WINDOWS" -eq 1 ] || [ -L "$cursor_gstack/bin" ] || [ ! -e "$cursor_gstack/bin" ]; then
+ _link_or_copy "$repo_root/bin" "$cursor_gstack/bin"
+ fi
+ fi
+ if [ -d "$repo_root/lib" ]; then
+ if [ "$IS_WINDOWS" -eq 1 ] || [ -L "$cursor_gstack/lib" ] || [ ! -e "$cursor_gstack/lib" ]; then
+ _link_or_copy "$repo_root/lib" "$cursor_gstack/lib"
+ fi
+ fi
+ if [ -d "$repo_root/browse/dist" ]; then
+ if [ "$IS_WINDOWS" -eq 1 ] || [ -L "$cursor_gstack/browse/dist" ] || [ ! -e "$cursor_gstack/browse/dist" ]; then
+ _link_or_copy "$repo_root/browse/dist" "$cursor_gstack/browse/dist"
+ fi
+ fi
+ if [ -d "$repo_root/browse/bin" ]; then
+ if [ "$IS_WINDOWS" -eq 1 ] || [ -L "$cursor_gstack/browse/bin" ] || [ ! -e "$cursor_gstack/browse/bin" ]; then
+ _link_or_copy "$repo_root/browse/bin" "$cursor_gstack/browse/bin"
+ fi
+ fi
+ if [ -f "$cursor_dir/gstack-upgrade/SKILL.md" ]; then
+ if [ "$IS_WINDOWS" -eq 1 ] || [ -L "$cursor_gstack/gstack-upgrade/SKILL.md" ] || [ ! -e "$cursor_gstack/gstack-upgrade/SKILL.md" ]; then
+ _link_or_copy "$cursor_dir/gstack-upgrade/SKILL.md" "$cursor_gstack/gstack-upgrade/SKILL.md"
+ fi
+ fi
+ for f in checklist.md TODOS-format.md; do
+ if [ -f "$repo_root/review/$f" ]; then
+ if [ "$IS_WINDOWS" -eq 1 ] || [ -L "$cursor_gstack/review/$f" ] || [ ! -e "$cursor_gstack/review/$f" ]; then
+ _link_or_copy "$repo_root/review/$f" "$cursor_gstack/review/$f"
+ fi
+ fi
+ done
+ if [ -f "$repo_root/ETHOS.md" ]; then
+ if [ "$IS_WINDOWS" -eq 1 ] || [ -L "$cursor_gstack/ETHOS.md" ] || [ ! -e "$cursor_gstack/ETHOS.md" ]; then
+ _link_or_copy "$repo_root/ETHOS.md" "$cursor_gstack/ETHOS.md"
+ fi
+ fi
+}
+
+link_cursor_skill_dirs() {
+ local gstack_dir="$1"
+ local skills_dir="$2"
+ local cursor_dir="$gstack_dir/.cursor/skills"
+ local linked=()
+
+ if [ ! -d "$cursor_dir" ]; then
+ echo " Generating .cursor/ skill docs..."
+ ( cd "$gstack_dir" && bun_cmd run gen:skill-docs --host cursor )
+ fi
+
+ if [ ! -d "$cursor_dir" ]; then
+ echo " warning: .cursor/skills/ generation failed — run 'bun run gen:skill-docs --host cursor' manually" >&2
+ return 1
+ fi
+
+ for skill_dir in "$cursor_dir"/gstack*/; do
+ if [ -f "$skill_dir/SKILL.md" ]; then
+ skill_name="$(basename "$skill_dir")"
+ [ "$skill_name" = "gstack" ] && continue
+ target="$skills_dir/$skill_name"
+ # #2444: IS_WINDOWS bypass — real-dir copies never match -L, so re-runs
+ # skipped the refresh. Only replace a symlink, a missing path, or a
+ # PROVABLY gstack-managed real dir; never a user's own Cursor skill
+ # dir that merely starts with gstack (#2142).
+ if [ "$IS_WINDOWS" -eq 1 ] || [ -L "$target" ] || [ ! -e "$target" ]; then
+ if _owned_for_windows_refresh "$target"; then
+ _link_or_copy "$skill_dir" "$target"
+ linked+=("$skill_name")
+ else
+ echo " left in place (existing dir not gstack-managed — no generated banner): $target" >&2
+ fi
fi
fi
done
@@ -1188,6 +1569,7 @@ if [ "$INSTALL_CLAUDE" -eq 1 ]; then
"$SOURCE_GSTACK_DIR/bin/gstack-patch-names" "$SOURCE_GSTACK_DIR" "$SKILL_PREFIX"
link_claude_skill_dirs "$SOURCE_GSTACK_DIR" "$INSTALL_SKILLS_DIR"
link_claude_root_skill_alias "$SOURCE_GSTACK_DIR" "$INSTALL_SKILLS_DIR"
+ _CLAUDE_SKILLS_LINKED=1
# Self-healing: re-run gstack-relink to ensure name: fields and directory
# names are consistent with the config. This catches cases where an interrupted
# setup, stale git state, or gen:skill-docs left name: fields out of sync.
@@ -1196,13 +1578,16 @@ if [ "$INSTALL_CLAUDE" -eq 1 ]; then
GSTACK_SKILLS_DIR="$INSTALL_SKILLS_DIR" GSTACK_INSTALL_DIR="$SOURCE_GSTACK_DIR" "$GSTACK_RELINK" >/dev/null 2>&1 || true
fi
# Backwards-compat alias: /connect-chrome → /open-gstack-browser
+ # Rewritten copy, not a symlink: a symlinked alias re-serves the canonical
+ # name: open-gstack-browser, so one of the two silently shadows the other
+ # (#2201) — and duplicate names can drop the whole skill set (#2511).
_OGB_LINK="$INSTALL_SKILLS_DIR/connect-chrome"
+ _OGB_ALIAS_NAME="connect-chrome"
if [ "$SKILL_PREFIX" -eq 1 ]; then
_OGB_LINK="$INSTALL_SKILLS_DIR/gstack-connect-chrome"
+ _OGB_ALIAS_NAME="gstack-connect-chrome"
fi
- if [ -L "$_OGB_LINK" ] || [ ! -e "$_OGB_LINK" ]; then
- _link_or_copy "gstack/open-gstack-browser" "$_OGB_LINK"
- fi
+ _install_alias_skill_md "$SOURCE_GSTACK_DIR/open-gstack-browser/SKILL.md" "$_OGB_LINK" "$_OGB_ALIAS_NAME"
if [ "$LOCAL_INSTALL" -eq 1 ]; then
log "gstack ready (project-local)."
log " skills: $INSTALL_SKILLS_DIR"
@@ -1260,17 +1645,22 @@ if [ "$INSTALL_CLAUDE" -eq 1 ]; then
"$SOURCE_GSTACK_DIR/bin/gstack-patch-names" "$SOURCE_GSTACK_DIR" "$SKILL_PREFIX"
link_claude_skill_dirs "$SOURCE_GSTACK_DIR" "$INSTALL_SKILLS_DIR"
link_claude_root_skill_alias "$SOURCE_GSTACK_DIR" "$INSTALL_SKILLS_DIR"
+ _CLAUDE_SKILLS_LINKED=1
GSTACK_RELINK="$SOURCE_GSTACK_DIR/bin/gstack-relink"
if [ -x "$GSTACK_RELINK" ]; then
GSTACK_SKILLS_DIR="$INSTALL_SKILLS_DIR" GSTACK_INSTALL_DIR="$SOURCE_GSTACK_DIR" "$GSTACK_RELINK" >/dev/null 2>&1 || true
fi
+ # Rewritten copy, not a symlink: a symlinked alias re-serves the
+ # canonical name: open-gstack-browser, so one of the two silently
+ # shadows the other (#2201) — and duplicate names can drop the whole
+ # skill set (#2511).
_OGB_LINK="$INSTALL_SKILLS_DIR/connect-chrome"
+ _OGB_ALIAS_NAME="connect-chrome"
if [ "$SKILL_PREFIX" -eq 1 ]; then
_OGB_LINK="$INSTALL_SKILLS_DIR/gstack-connect-chrome"
+ _OGB_ALIAS_NAME="gstack-connect-chrome"
fi
- if [ -L "$_OGB_LINK" ] || [ ! -e "$_OGB_LINK" ]; then
- _link_or_copy "gstack/open-gstack-browser" "$_OGB_LINK"
- fi
+ _install_alias_skill_md "$SOURCE_GSTACK_DIR/open-gstack-browser/SKILL.md" "$_OGB_LINK" "$_OGB_ALIAS_NAME"
log "gstack ready (claude)."
log " browse: $BROWSE_BIN"
fi
@@ -1394,6 +1784,19 @@ if [ "$INSTALL_OPENCODE" -eq 1 ]; then
echo " opencode skills: $OPENCODE_SKILLS"
fi
+# 6d. Install for Cursor
+if [ "$INSTALL_CURSOR" -eq 1 ]; then
+ mkdir -p "$CURSOR_SKILLS"
+ create_cursor_runtime_root "$SOURCE_GSTACK_DIR" "$CURSOR_GSTACK"
+ # Link before sidecar. Sidecar mkdir -p creates .cursor/skills/gstack, which
+ # would make link_cursor_skill_dirs' "[ ! -d generated ]" gen fallback a no-op.
+ link_cursor_skill_dirs "$SOURCE_GSTACK_DIR" "$CURSOR_SKILLS"
+ create_cursor_sidecar "$SOURCE_GSTACK_DIR"
+ echo "gstack ready (cursor)."
+ echo " browse: $BROWSE_BIN"
+ echo " cursor skills: $CURSOR_SKILLS"
+fi
+
# 7. Create .agents/ sidecar symlinks for the real Codex skill target.
# The root Codex skill ends up pointing at $SOURCE_GSTACK_DIR/.agents/skills/gstack,
# so the runtime assets must live there for both global and repo-local installs.
@@ -1418,7 +1821,11 @@ if [ -d "$MIGRATIONS_DIR" ] && [ "$CURRENT_VERSION" != "unknown" ] && [ "$LAST_S
if [ "$(printf '%s\n%s' "$LAST_SETUP_VERSION" "$m_ver" | sort -V | head -1)" = "$LAST_SETUP_VERSION" ] && [ "$LAST_SETUP_VERSION" != "$m_ver" ] \
&& [ "$(printf '%s\n%s' "$m_ver" "$CURRENT_VERSION" | sort -V | tail -1)" = "$CURRENT_VERSION" ]; then
echo " running migration $m_ver..."
- bash "$migration" || echo " warning: migration $m_ver had errors (non-fatal)"
+ # GSTACK_INSTALL_DIR: migrations that clean the INSTALL (not just
+ # ~/.gstack state) default to ~/.claude/skills/gstack when unset —
+ # a repo-local ./setup would silently no-op them against the wrong
+ # tree without this.
+ GSTACK_INSTALL_DIR="$SOURCE_GSTACK_DIR" bash "$migration" || echo " warning: migration $m_ver had errors (non-fatal)"
fi
done
fi
@@ -1485,24 +1892,27 @@ if [ "$NO_TEAM_MODE" -eq 1 ]; then
log "Team mode disabled: auto-update hook removed."
fi
-# ─── GBrain detection + conditional SKILL.md regen ──────────────────────
+# ─── GBrain detection + conditional SKILL.md render ─────────────────────
#
# Detect whether gbrain is installed and persist the result to
# ~/.gstack/gbrain-detection.json so gen-skill-docs can decide whether to
# render GBRAIN_CONTEXT_LOAD and GBRAIN_SAVE_RESULTS blocks. If detected,
-# regenerate the Claude-host SKILL.md files with the un-suppressed
-# (compressed) brain-aware blocks via `bun run gen:skill-docs:user`.
+# render the Claude-host :user variant (un-suppressed brain-aware blocks)
+# into an UNTRACKED out-dir — ${GSTACK_HOME}/render/claude — and repoint the
+# installed skills at it (#2569). The old in-place render wrote into TRACKED
+# files of the install checkout, so a global-git install stayed permanently
+# dirty and every upgrade stashed 16 files of generated dirt.
#
-# If gbrain is not detected, the canonical no-gbrain SKILL.md files
-# (which were just generated above by `gen:skill-docs --host claude` if
-# applicable, or which are checked in) stay as-is. Zero token overhead
-# for non-gbrain users.
+# If gbrain is not detected, the canonical no-gbrain SKILL.md files stay
+# as-is (zero token overhead) and any stale render dir is removed so it
+# can't shadow canonical files on the next relink.
#
# Users who install gbrain after running ./setup should re-run setup OR
-# call `gstack-config gbrain-refresh` + `bun run gen:skill-docs:user`.
+# call `gstack-config gbrain-refresh`.
DETECT_BIN="$SOURCE_GSTACK_DIR/bin/gstack-gbrain-detect"
GBRAIN_STATE_DIR="${GSTACK_HOME:-$HOME/.gstack}"
DETECTION_FILE="$GBRAIN_STATE_DIR/gbrain-detection.json"
+_GSTACK_RENDER_DIR="${GSTACK_USER_RENDER_DIR:-$GBRAIN_STATE_DIR/render/claude}"
# PID-unique tmp so concurrent setups (parallel Conductor workspaces) can't
# clobber each other's in-flight detection write.
DETECTION_TMP="$DETECTION_FILE.$$.tmp"
@@ -1515,28 +1925,52 @@ if [ -x "$DETECT_BIN" ]; then
# all gate on the same check instead of re-grepping the JSON.
if "$DETECT_BIN" --is-ok 2>/dev/null; then
if [ -n "${GSTACK_SKIP_GBRAIN_REGEN:-}" ]; then
- # Dev/source tree (set by bin/dev-setup): never regenerate tracked
- # SKILL.md in place — that dirties checked-in source. Detection is
- # still persisted above; the dev workspace renders the :user variant
- # into an untracked dir, and other projects get blocks via
- # `gstack-config gbrain-refresh`.
+ # Dev/source tree (set by bin/dev-setup): detection is persisted
+ # above; the dev workspace renders the :user variant into its own
+ # untracked dir (.claude/gstack-rendered), and other projects get
+ # blocks via `gstack-config gbrain-refresh`.
log "gbrain detected — GSTACK_SKIP_GBRAIN_REGEN set: leaving tracked SKILL.md canonical (dev/source tree)."
else
- log "gbrain detected — regenerating Claude SKILL.md with brain-aware blocks (~250 token overhead per planning skill)..."
- (
+ log "gbrain detected — rendering brain-aware Claude SKILL.md into $_GSTACK_RENDER_DIR (~250 token overhead per planning skill; source checkout stays clean)..."
+ # Render into a tmp dir and swap it in only on SUCCESS. Installed
+ # skills SYMLINK into the render dir (relink prefers it), so wiping
+ # it before the render meant one transient failure left every
+ # brain-aware SKILL.md link dangling — the whole skill set vanished
+ # from Claude Code until a successful re-render.
+ _GSTACK_RENDER_TMP="$_GSTACK_RENDER_DIR.tmp.$$"
+ rm -rf "$_GSTACK_RENDER_TMP"
+ if (
cd "$SOURCE_GSTACK_DIR"
# No pipe before the || guard: `cmd | tail -3` reports TAIL's exit
# status, so a generator crash read as success (same masking the
# main gen:skill-docs site had). Capture, show the tail, propagate.
- _GEN_USER_OUT=$(bun_cmd run gen:skill-docs:user --host claude 2>&1)
+ _GEN_USER_OUT=$(bun_cmd run gen:skill-docs:user --host claude --out-dir "$_GSTACK_RENDER_TMP" 2>&1)
_GEN_USER_RC=$?
printf '%s\n' "$_GEN_USER_OUT" | tail -3
exit "$_GEN_USER_RC"
- ) || log " warning: gen:skill-docs:user failed — run 'bun run gen:skill-docs:user' manually if you want brain-aware blocks"
+ ); then
+ _swap_in_render "$_GSTACK_RENDER_DIR" "$_GSTACK_RENDER_TMP"
+ # Repoint the installed skills at the fresh render — the installer
+ # prefers rendered files when present (#2569).
+ if [ "${_CLAUDE_SKILLS_LINKED:-0}" -eq 1 ]; then
+ link_claude_skill_dirs "$SOURCE_GSTACK_DIR" "$INSTALL_SKILLS_DIR" >/dev/null
+ fi
+ else
+ rm -rf "$_GSTACK_RENDER_TMP"
+ log " warning: gen:skill-docs:user failed — previous render (if any) left in place, links stay valid. Run 'bun run gen:skill-docs:user --host claude --out-dir $_GSTACK_RENDER_DIR' manually if you want fresh brain-aware blocks"
+ fi
fi
else
log "gbrain not detected — brain-aware blocks suppressed in planning-skill SKILL.md files (zero token overhead)."
log " To enable: install gbrain via /setup-gbrain, then re-run ./setup or 'gstack-config gbrain-refresh'."
+ # A render from a previous gbrain install would shadow canonical files
+ # on the next link/relink — drop it and restore canonical links.
+ if [ -d "$_GSTACK_RENDER_DIR" ] && [ -z "${GSTACK_SKIP_GBRAIN_REGEN:-}" ]; then
+ rm -rf "$_GSTACK_RENDER_DIR"
+ if [ "${_CLAUDE_SKILLS_LINKED:-0}" -eq 1 ]; then
+ link_claude_skill_dirs "$SOURCE_GSTACK_DIR" "$INSTALL_SKILLS_DIR" >/dev/null
+ fi
+ fi
fi
else
rm -f "$DETECTION_TMP"
@@ -1722,24 +2156,74 @@ if [ "$NO_TEAM_MODE" -ne 1 ] \
fi
fi
-# Also tear down plan-tune hooks on --no-team (matches the existing pattern).
+# ─── Timeline Stop hook (#2553) ──────────────────────────────────────────────
+# The preamble writes event:"started" to the project timeline at every skill
+# start; the completion write lives in end-of-workflow prose and is
+# unenforceable — interrupted sessions leaked started > completed forever.
+# Register a Stop-event hook that closes dangling entries. FAIL-OPEN contract
+# (F5): the hook always exits 0 and repairs best-effort — it can never block
+# a session. Idempotent via the (event, source) dedup in gstack-settings-hook;
+# removed by --no-team and gstack-uninstall.
+TIMELINE_STOP_HOOK="$SOURCE_GSTACK_DIR/hosts/claude/hooks/timeline-stop-hook"
+if [ "$NO_TEAM_MODE" -ne 1 ] && [ -x "$SETTINGS_HOOK" ] && [ -x "$TIMELINE_STOP_HOOK" ]; then
+ if ! "$SETTINGS_HOOK" list-sources 2>/dev/null | grep -q "gstack-timeline-stop"; then
+ if "$SETTINGS_HOOK" add-event \
+ --event Stop \
+ --command "$TIMELINE_STOP_HOOK" \
+ --source gstack-timeline-stop \
+ --timeout 5 >/dev/null 2>&1; then
+ log " registered Stop hook: session timeline entries now close even when a skill is interrupted (backup: settings.json.bak.<ts>; remove: $SETTINGS_HOOK remove-source --source gstack-timeline-stop)"
+ fi
+ fi
+fi
+
+# Also tear down plan-tune + timeline hooks on --no-team (matches the existing pattern).
if [ "$NO_TEAM_MODE" -eq 1 ] && [ -x "$SETTINGS_HOOK" ]; then
"$SETTINGS_HOOK" remove-source --source plan-tune-cathedral 2>/dev/null || true
+ "$SETTINGS_HOOK" remove-source --source gstack-timeline-stop 2>/dev/null || true
fi
-# ─── Redact pre-push guard hint (#1946) ──────────────────────────────────────
+# ─── Redact pre-push guard consent (#1946) ───────────────────────────────────
# The credential pre-push hook is per-REPO state — setup runs in the gstack
-# checkout, the wrong repo to install it into. /ship offers the install once
-# at the moment of relevance (first push) and silently installs in any repo
-# where redact_prepush_hook=true. This hint is setup's whole involvement.
-# Hint only when UNSET — an explicit "false" is a recorded decline and must
-# not be re-nagged on every setup run (adversarial review finding 11).
+# checkout, the wrong repo to install it into, so setup NEVER installs the
+# hook itself. /ship installs it silently in any repo where
+# redact_prepush_hook=true. What setup owns is CONSENT: on a real interactive
+# terminal it asks ONCE whether pushes should be scanned, recording the
+# answer to the existing redact_prepush_hook key (default stays false — a
+# timeout or non-interactive run changes nothing and keeps the hint-only
+# posture). An explicit answer is persisted and never re-asked; an explicit
+# "false" is a recorded decline (adversarial review finding 11).
# `gstack-config get` defaults absent keys to "false", which is
# indistinguishable from a decline — test key presence in the config file.
_GSTACK_CFG_FILE="${GSTACK_HOME:-$HOME/.gstack}/config.yaml"
if ! grep -q '^redact_prepush_hook:' "$_GSTACK_CFG_FILE" 2>/dev/null; then
- log ""
- log "Tip: gstack can block pushes containing credentials (per-repo git hook)."
- log " Enable once: gstack-config set redact_prepush_hook true — /ship"
- log " installs the hook automatically in every repo you ship from."
+ if [ "$QUIET" -ne 1 ] && [ -t 0 ] && [ -t 1 ]; then
+ _REDACT_PROMPT_TIMEOUT=10
+ log ""
+ log "Credential push guard: gstack can block pushes containing credentials"
+ log "(a per-repo git pre-push hook; /ship installs it automatically in every"
+ log "repo you ship from — nothing is installed right now)."
+ printf "Enable the pre-push credential guard? [y/N] (default: N, auto-skips in %ss): " "$_REDACT_PROMPT_TIMEOUT"
+ read -t "$_REDACT_PROMPT_TIMEOUT" -r _REDACT_REPLY </dev/tty 2>/dev/null || _REDACT_REPLY=""
+ case "$_REDACT_REPLY" in
+ y|Y)
+ "$GSTACK_CONFIG" set redact_prepush_hook true 2>/dev/null || true
+ log "Enabled. /ship will install the guard in each repo at first push."
+ ;;
+ n|N)
+ "$GSTACK_CONFIG" set redact_prepush_hook false 2>/dev/null || true
+ log "Declined — recorded. Re-enable anytime: gstack-config set redact_prepush_hook true"
+ ;;
+ *)
+ # Timed out / empty: don't persist a decline — hint and ask next time.
+ log ""
+ log "Skipped for now. Enable anytime: gstack-config set redact_prepush_hook true"
+ ;;
+ esac
+ else
+ log ""
+ log "Tip: gstack can block pushes containing credentials (per-repo git hook)."
+ log " Enable once: gstack-config set redact_prepush_hook true — /ship"
+ log " installs the hook automatically in every repo you ship from."
+ fi
fi
diff --git a/setup-browser-cookies/SKILL.md b/setup-browser-cookies/SKILL.md
index df6db6027..57f831718 100644
--- a/setup-browser-cookies/SKILL.md
+++ b/setup-browser-cookies/SKILL.md
@@ -104,9 +104,11 @@ else
fi
~/.claude/skills/gstack/bin/gstack-timeline-log '{"skill":"setup-browser-cookies","event":"started","branch":"'"$_BRANCH"'","session":"'"$_SESSION_ID"'"}' 2>/dev/null &
_HAS_ROUTING="no"
-if [ -f CLAUDE.md ] && grep -q "## Skill routing" CLAUDE.md 2>/dev/null; then
- _HAS_ROUTING="yes"
-fi
+for _RF in CLAUDE.md AGENTS.md; do
+ if [ -f "$_RF" ] && grep -q "## Skill routing" "$_RF" 2>/dev/null; then
+ _HAS_ROUTING="yes"
+ fi
+done
_ROUTING_DECLINED=$(~/.claude/skills/gstack/bin/gstack-config get routing_declined 2>/dev/null || echo "false")
echo "HAS_ROUTING: $_HAS_ROUTING"
echo "ROUTING_DECLINED: $_ROUTING_DECLINED"
@@ -375,10 +377,13 @@ _BRAIN_SYNC_MODE=$("$_BRAIN_CONFIG_BIN" get artifacts_sync_mode 2>/dev/null || e
# Detect remote-MCP mode (Path 4 of /setup-gbrain). Local artifacts sync is
# a no-op in remote mode; the brain server pulls from GitHub/GitLab on its
# own cadence. Read claude.json directly to keep this preamble fast (no
-# subprocess to claude CLI on every skill start).
+# subprocess to claude CLI on every skill start). Both registration scopes
+# are read (#2499): user scope, then the nearest-ancestor project scope.
_GBRAIN_MCP_MODE="none"
+_GBRAIN_MCP_ENTRY=""
if command -v jq >/dev/null 2>&1 && [ -f "$HOME/.claude.json" ]; then
- _GBRAIN_MCP_TYPE=$(jq -r '.mcpServers.gbrain.type // .mcpServers.gbrain.transport // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_ENTRY=$(jq -c --arg cwd "$PWD" '.mcpServers.gbrain // ((.projects // {}) | to_entries | map(select((.key as $k | $cwd == $k or ($cwd | startswith($k + "/"))) and ((try .value.mcpServers.gbrain catch null) != null))) | sort_by(.key | length) | last | .value.mcpServers.gbrain) // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_TYPE=$(printf '%s' "$_GBRAIN_MCP_ENTRY" | jq -r '.type // .transport // empty' 2>/dev/null)
case "$_GBRAIN_MCP_TYPE" in
url|http|sse) _GBRAIN_MCP_MODE="remote-http" ;;
stdio) _GBRAIN_MCP_MODE="local-stdio" ;;
@@ -399,6 +404,7 @@ if [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_DO_PULL=1
if [ -f "$_BRAIN_LAST_PULL_FILE" ]; then
_BRAIN_LAST=$(cat "$_BRAIN_LAST_PULL_FILE" 2>/dev/null || echo 0)
+ case "$_BRAIN_LAST" in ''|*[!0-9]*) _BRAIN_LAST=0 ;; esac
_BRAIN_AGE=$(( _BRAIN_NOW - _BRAIN_LAST ))
[ "$_BRAIN_AGE" -lt 86400 ] && _BRAIN_DO_PULL=0
fi
@@ -412,7 +418,7 @@ fi
if [ "$_GBRAIN_MCP_MODE" = "remote-http" ]; then
# Remote-MCP mode: local artifacts sync is a no-op (brain admin's server
# pulls from GitHub/GitLab). Show the user this is by design, not broken.
- _GBRAIN_HOST=$(jq -r '.mcpServers.gbrain.url // empty' "$HOME/.claude.json" 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|')
+ _GBRAIN_HOST=$(printf '%s' "${_GBRAIN_MCP_ENTRY:-}" | jq -r '.url // empty' 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|' | head -1 | tr -cd 'A-Za-z0-9._-')
echo "ARTIFACTS_SYNC: remote-mode (managed by brain server ${_GBRAIN_HOST:-remote})"
elif [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_QUEUE_DEPTH=0
diff --git a/setup-deploy/SKILL.md b/setup-deploy/SKILL.md
index d4eb17044..5777c69ff 100644
--- a/setup-deploy/SKILL.md
+++ b/setup-deploy/SKILL.md
@@ -111,9 +111,11 @@ else
fi
~/.claude/skills/gstack/bin/gstack-timeline-log '{"skill":"setup-deploy","event":"started","branch":"'"$_BRANCH"'","session":"'"$_SESSION_ID"'"}' 2>/dev/null &
_HAS_ROUTING="no"
-if [ -f CLAUDE.md ] && grep -q "## Skill routing" CLAUDE.md 2>/dev/null; then
- _HAS_ROUTING="yes"
-fi
+for _RF in CLAUDE.md AGENTS.md; do
+ if [ -f "$_RF" ] && grep -q "## Skill routing" "$_RF" 2>/dev/null; then
+ _HAS_ROUTING="yes"
+ fi
+done
_ROUTING_DECLINED=$(~/.claude/skills/gstack/bin/gstack-config get routing_declined 2>/dev/null || echo "false")
echo "HAS_ROUTING: $_HAS_ROUTING"
echo "ROUTING_DECLINED: $_ROUTING_DECLINED"
@@ -507,10 +509,13 @@ _BRAIN_SYNC_MODE=$("$_BRAIN_CONFIG_BIN" get artifacts_sync_mode 2>/dev/null || e
# Detect remote-MCP mode (Path 4 of /setup-gbrain). Local artifacts sync is
# a no-op in remote mode; the brain server pulls from GitHub/GitLab on its
# own cadence. Read claude.json directly to keep this preamble fast (no
-# subprocess to claude CLI on every skill start).
+# subprocess to claude CLI on every skill start). Both registration scopes
+# are read (#2499): user scope, then the nearest-ancestor project scope.
_GBRAIN_MCP_MODE="none"
+_GBRAIN_MCP_ENTRY=""
if command -v jq >/dev/null 2>&1 && [ -f "$HOME/.claude.json" ]; then
- _GBRAIN_MCP_TYPE=$(jq -r '.mcpServers.gbrain.type // .mcpServers.gbrain.transport // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_ENTRY=$(jq -c --arg cwd "$PWD" '.mcpServers.gbrain // ((.projects // {}) | to_entries | map(select((.key as $k | $cwd == $k or ($cwd | startswith($k + "/"))) and ((try .value.mcpServers.gbrain catch null) != null))) | sort_by(.key | length) | last | .value.mcpServers.gbrain) // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_TYPE=$(printf '%s' "$_GBRAIN_MCP_ENTRY" | jq -r '.type // .transport // empty' 2>/dev/null)
case "$_GBRAIN_MCP_TYPE" in
url|http|sse) _GBRAIN_MCP_MODE="remote-http" ;;
stdio) _GBRAIN_MCP_MODE="local-stdio" ;;
@@ -531,6 +536,7 @@ if [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_DO_PULL=1
if [ -f "$_BRAIN_LAST_PULL_FILE" ]; then
_BRAIN_LAST=$(cat "$_BRAIN_LAST_PULL_FILE" 2>/dev/null || echo 0)
+ case "$_BRAIN_LAST" in ''|*[!0-9]*) _BRAIN_LAST=0 ;; esac
_BRAIN_AGE=$(( _BRAIN_NOW - _BRAIN_LAST ))
[ "$_BRAIN_AGE" -lt 86400 ] && _BRAIN_DO_PULL=0
fi
@@ -544,7 +550,7 @@ fi
if [ "$_GBRAIN_MCP_MODE" = "remote-http" ]; then
# Remote-MCP mode: local artifacts sync is a no-op (brain admin's server
# pulls from GitHub/GitLab). Show the user this is by design, not broken.
- _GBRAIN_HOST=$(jq -r '.mcpServers.gbrain.url // empty' "$HOME/.claude.json" 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|')
+ _GBRAIN_HOST=$(printf '%s' "${_GBRAIN_MCP_ENTRY:-}" | jq -r '.url // empty' 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|' | head -1 | tr -cd 'A-Za-z0-9._-')
echo "ARTIFACTS_SYNC: remote-mode (managed by brain server ${_GBRAIN_HOST:-remote})"
elif [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_QUEUE_DEPTH=0
@@ -629,8 +635,8 @@ eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)"
_PROJ="${GSTACK_HOME:-$HOME/.gstack}/projects/${SLUG:-unknown}"
if [ -d "$_PROJ" ]; then
echo "--- RECENT ARTIFACTS ---"
- find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs ls -t 2>/dev/null | head -3
- [ -f "$_PROJ/${_BRANCH}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/${_BRANCH}-reviews.jsonl" | tr -d ' ') entries"
+ find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3
+ [ -f "$_PROJ/${BRANCH:-unknown}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/${BRANCH:-unknown}-reviews.jsonl" | tr -d ' ') entries"
[ -f "$_PROJ/timeline.jsonl" ] && tail -5 "$_PROJ/timeline.jsonl"
if [ -f "$_PROJ/timeline.jsonl" ]; then
_LAST=$(grep "\"branch\":\"${_BRANCH}\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -1)
@@ -638,7 +644,7 @@ if [ -d "$_PROJ" ]; then
_RECENT_SKILLS=$(grep "\"branch\":\"${_BRANCH}\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -3 | grep -o '"skill":"[^"]*"' | sed 's/"skill":"//;s/"//' | tr '\n' ',')
[ -n "$_RECENT_SKILLS" ] && echo "RECENT_PATTERN: $_RECENT_SKILLS"
fi
- _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs ls -t 2>/dev/null | head -1)
+ _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs -r ls -t 2>/dev/null | head -1)
[ -n "$_LATEST_CP" ] && echo "LATEST_CHECKPOINT: $_LATEST_CP"
if [ -f "$_PROJ/decisions.active.json" ]; then
echo "--- ACTIVE DECISIONS (recent, scope-relevant) ---"
@@ -714,7 +720,7 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST
## Question Tuning (skip entirely if `QUESTION_TUNING: false`)
-Before each AskUserQuestion, choose `question_id` from `scripts/question-registry.ts` or `{skill}-{slug}`, then run `printf '%s' "<question summary>" | ~/.claude/skills/gstack/bin/gstack-question-preference --check "<id>" --summary-stdin` (piped summary feeds the one-way keyword net, #2024). `AUTO_DECIDE` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." `ASK_NORMALLY` means ask.
+Before each AskUserQuestion, choose `question_id` from `~/.claude/skills/gstack/scripts/question-registry.ts` or `{skill}-{slug}`, then run `printf '%s' "<question summary>" | ~/.claude/skills/gstack/bin/gstack-question-preference --check "<id>" --summary-stdin` (piped summary feeds the one-way keyword net, #2024). `AUTO_DECIDE` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." `ASK_NORMALLY` means ask.
**Embed the question_id as a marker in the question text** so hooks can identify it deterministically (plan-tune cathedral T14 / D18 progressive markers). Append `<gstack-qid:{question_id}>` somewhere in the rendered question (the leading line or trailing line is fine; the marker doesn't render visibly to the user when wrapped in HTML-style angle brackets, but the hook strips it). Without the marker the PreToolUse enforcement hook treats the AUQ as observed-only and never auto-decides — so always include it when the question matches a registered `question_id`.
diff --git a/setup-gbrain/SKILL.md b/setup-gbrain/SKILL.md
index 0cc751fbc..877648586 100644
--- a/setup-gbrain/SKILL.md
+++ b/setup-gbrain/SKILL.md
@@ -110,9 +110,11 @@ else
fi
~/.claude/skills/gstack/bin/gstack-timeline-log '{"skill":"setup-gbrain","event":"started","branch":"'"$_BRANCH"'","session":"'"$_SESSION_ID"'"}' 2>/dev/null &
_HAS_ROUTING="no"
-if [ -f CLAUDE.md ] && grep -q "## Skill routing" CLAUDE.md 2>/dev/null; then
- _HAS_ROUTING="yes"
-fi
+for _RF in CLAUDE.md AGENTS.md; do
+ if [ -f "$_RF" ] && grep -q "## Skill routing" "$_RF" 2>/dev/null; then
+ _HAS_ROUTING="yes"
+ fi
+done
_ROUTING_DECLINED=$(~/.claude/skills/gstack/bin/gstack-config get routing_declined 2>/dev/null || echo "false")
echo "HAS_ROUTING: $_HAS_ROUTING"
echo "ROUTING_DECLINED: $_ROUTING_DECLINED"
@@ -506,10 +508,13 @@ _BRAIN_SYNC_MODE=$("$_BRAIN_CONFIG_BIN" get artifacts_sync_mode 2>/dev/null || e
# Detect remote-MCP mode (Path 4 of /setup-gbrain). Local artifacts sync is
# a no-op in remote mode; the brain server pulls from GitHub/GitLab on its
# own cadence. Read claude.json directly to keep this preamble fast (no
-# subprocess to claude CLI on every skill start).
+# subprocess to claude CLI on every skill start). Both registration scopes
+# are read (#2499): user scope, then the nearest-ancestor project scope.
_GBRAIN_MCP_MODE="none"
+_GBRAIN_MCP_ENTRY=""
if command -v jq >/dev/null 2>&1 && [ -f "$HOME/.claude.json" ]; then
- _GBRAIN_MCP_TYPE=$(jq -r '.mcpServers.gbrain.type // .mcpServers.gbrain.transport // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_ENTRY=$(jq -c --arg cwd "$PWD" '.mcpServers.gbrain // ((.projects // {}) | to_entries | map(select((.key as $k | $cwd == $k or ($cwd | startswith($k + "/"))) and ((try .value.mcpServers.gbrain catch null) != null))) | sort_by(.key | length) | last | .value.mcpServers.gbrain) // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_TYPE=$(printf '%s' "$_GBRAIN_MCP_ENTRY" | jq -r '.type // .transport // empty' 2>/dev/null)
case "$_GBRAIN_MCP_TYPE" in
url|http|sse) _GBRAIN_MCP_MODE="remote-http" ;;
stdio) _GBRAIN_MCP_MODE="local-stdio" ;;
@@ -530,6 +535,7 @@ if [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_DO_PULL=1
if [ -f "$_BRAIN_LAST_PULL_FILE" ]; then
_BRAIN_LAST=$(cat "$_BRAIN_LAST_PULL_FILE" 2>/dev/null || echo 0)
+ case "$_BRAIN_LAST" in ''|*[!0-9]*) _BRAIN_LAST=0 ;; esac
_BRAIN_AGE=$(( _BRAIN_NOW - _BRAIN_LAST ))
[ "$_BRAIN_AGE" -lt 86400 ] && _BRAIN_DO_PULL=0
fi
@@ -543,7 +549,7 @@ fi
if [ "$_GBRAIN_MCP_MODE" = "remote-http" ]; then
# Remote-MCP mode: local artifacts sync is a no-op (brain admin's server
# pulls from GitHub/GitLab). Show the user this is by design, not broken.
- _GBRAIN_HOST=$(jq -r '.mcpServers.gbrain.url // empty' "$HOME/.claude.json" 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|')
+ _GBRAIN_HOST=$(printf '%s' "${_GBRAIN_MCP_ENTRY:-}" | jq -r '.url // empty' 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|' | head -1 | tr -cd 'A-Za-z0-9._-')
echo "ARTIFACTS_SYNC: remote-mode (managed by brain server ${_GBRAIN_HOST:-remote})"
elif [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_QUEUE_DEPTH=0
@@ -628,8 +634,8 @@ eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)"
_PROJ="${GSTACK_HOME:-$HOME/.gstack}/projects/${SLUG:-unknown}"
if [ -d "$_PROJ" ]; then
echo "--- RECENT ARTIFACTS ---"
- find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs ls -t 2>/dev/null | head -3
- [ -f "$_PROJ/${_BRANCH}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/${_BRANCH}-reviews.jsonl" | tr -d ' ') entries"
+ find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3
+ [ -f "$_PROJ/${BRANCH:-unknown}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/${BRANCH:-unknown}-reviews.jsonl" | tr -d ' ') entries"
[ -f "$_PROJ/timeline.jsonl" ] && tail -5 "$_PROJ/timeline.jsonl"
if [ -f "$_PROJ/timeline.jsonl" ]; then
_LAST=$(grep "\"branch\":\"${_BRANCH}\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -1)
@@ -637,7 +643,7 @@ if [ -d "$_PROJ" ]; then
_RECENT_SKILLS=$(grep "\"branch\":\"${_BRANCH}\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -3 | grep -o '"skill":"[^"]*"' | sed 's/"skill":"//;s/"//' | tr '\n' ',')
[ -n "$_RECENT_SKILLS" ] && echo "RECENT_PATTERN: $_RECENT_SKILLS"
fi
- _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs ls -t 2>/dev/null | head -1)
+ _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs -r ls -t 2>/dev/null | head -1)
[ -n "$_LATEST_CP" ] && echo "LATEST_CHECKPOINT: $_LATEST_CP"
if [ -f "$_PROJ/decisions.active.json" ]; then
echo "--- ACTIVE DECISIONS (recent, scope-relevant) ---"
@@ -713,7 +719,7 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST
## Question Tuning (skip entirely if `QUESTION_TUNING: false`)
-Before each AskUserQuestion, choose `question_id` from `scripts/question-registry.ts` or `{skill}-{slug}`, then run `printf '%s' "<question summary>" | ~/.claude/skills/gstack/bin/gstack-question-preference --check "<id>" --summary-stdin` (piped summary feeds the one-way keyword net, #2024). `AUTO_DECIDE` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." `ASK_NORMALLY` means ask.
+Before each AskUserQuestion, choose `question_id` from `~/.claude/skills/gstack/scripts/question-registry.ts` or `{skill}-{slug}`, then run `printf '%s' "<question summary>" | ~/.claude/skills/gstack/bin/gstack-question-preference --check "<id>" --summary-stdin` (piped summary feeds the one-way keyword net, #2024). `AUTO_DECIDE` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." `ASK_NORMALLY` means ask.
**Embed the question_id as a marker in the question text** so hooks can identify it deterministically (plan-tune cathedral T14 / D18 progressive markers). Append `<gstack-qid:{question_id}>` somewhere in the rendered question (the leading line or trailing line is fine; the marker doesn't render visibly to the user when wrapped in HTML-style angle brackets, but the hook strips it). Without the marker the PreToolUse enforcement hook treats the AUQ as observed-only and never auto-decides — so always include it when the question matches a registered `question_id`.
@@ -1502,7 +1508,7 @@ curated `~/.gstack/` artifacts into gbrain so the retrieval surface
Run the probe to size the operation:
```bash
-~/.claude/skills/gstack/bin/gstack-memory-ingest --probe
+bun run ~/.claude/skills/gstack/bin/gstack-memory-ingest.ts --probe
```
Read the output. If `Total files in window: 0`, skip — there's nothing
@@ -1510,7 +1516,7 @@ to ingest. Set `gstack-config set transcript_ingest_mode incremental`
silently and continue to Step 8.
If `New (never ingested)` is < 200 AND total bytes are < 100MB: silent
-bulk via `gstack-memory-ingest --bulk --quiet`. Set
+bulk via `bun run ~/.claude/skills/gstack/bin/gstack-memory-ingest.ts --bulk --quiet`. Set
`transcript_ingest_mode=incremental` and continue.
Otherwise (the "many transcripts on disk" path): AskUserQuestion with
@@ -1547,14 +1553,14 @@ Options:
After answer:
```bash
~/.claude/skills/gstack/bin/gstack-config set transcript_ingest_mode <choice>
-~/.claude/skills/gstack/bin/gstack-gbrain-sync --full --no-brain-sync
+bun run ~/.claude/skills/gstack/bin/gstack-gbrain-sync.ts --full --no-brain-sync
```
(`--no-brain-sync` because Step 7 already wired that path; this just
runs the code import + memory ingest stages. Brain-sync will run on the
next preamble hook.)
If A/D/E, ingest is incremental from this point on; preamble-boundary
-hook runs `gstack-gbrain-sync --incremental --quiet` on every skill
+hook runs `bun run ~/.claude/skills/gstack/bin/gstack-gbrain-sync.ts --incremental --quiet` on every skill
start (cheap mtime fast-path).
Reference doc for users: `setup-gbrain/memory.md` (linked from CLAUDE.md
diff --git a/setup-gbrain/SKILL.md.tmpl b/setup-gbrain/SKILL.md.tmpl
index 2eff76403..3636a4f9b 100644
--- a/setup-gbrain/SKILL.md.tmpl
+++ b/setup-gbrain/SKILL.md.tmpl
@@ -736,7 +736,7 @@ curated `~/.gstack/` artifacts into gbrain so the retrieval surface
Run the probe to size the operation:
```bash
-~/.claude/skills/gstack/bin/gstack-memory-ingest --probe
+bun run ~/.claude/skills/gstack/bin/gstack-memory-ingest.ts --probe
```
Read the output. If `Total files in window: 0`, skip — there's nothing
@@ -744,7 +744,7 @@ to ingest. Set `gstack-config set transcript_ingest_mode incremental`
silently and continue to Step 8.
If `New (never ingested)` is < 200 AND total bytes are < 100MB: silent
-bulk via `gstack-memory-ingest --bulk --quiet`. Set
+bulk via `bun run ~/.claude/skills/gstack/bin/gstack-memory-ingest.ts --bulk --quiet`. Set
`transcript_ingest_mode=incremental` and continue.
Otherwise (the "many transcripts on disk" path): AskUserQuestion with
@@ -781,14 +781,14 @@ Options:
After answer:
```bash
~/.claude/skills/gstack/bin/gstack-config set transcript_ingest_mode <choice>
-~/.claude/skills/gstack/bin/gstack-gbrain-sync --full --no-brain-sync
+bun run ~/.claude/skills/gstack/bin/gstack-gbrain-sync.ts --full --no-brain-sync
```
(`--no-brain-sync` because Step 7 already wired that path; this just
runs the code import + memory ingest stages. Brain-sync will run on the
next preamble hook.)
If A/D/E, ingest is incremental from this point on; preamble-boundary
-hook runs `gstack-gbrain-sync --incremental --quiet` on every skill
+hook runs `bun run ~/.claude/skills/gstack/bin/gstack-gbrain-sync.ts --incremental --quiet` on every skill
start (cheap mtime fast-path).
Reference doc for users: `setup-gbrain/memory.md` (linked from CLAUDE.md
diff --git a/setup-gbrain/memory.md b/setup-gbrain/memory.md
index 7732af4ce..c57744e37 100644
--- a/setup-gbrain/memory.md
+++ b/setup-gbrain/memory.md
@@ -47,9 +47,9 @@ v1.33.0.0 — off by default. To re-enable it (adds ~4-8 min to cold runs
on a large transcript corpus), use either:
```bash
-gstack-memory-ingest --bulk --scan-secrets
+bun run bin/gstack-memory-ingest.ts --bulk --scan-secrets
# or
-GSTACK_MEMORY_INGEST_SCAN_SECRETS=1 gstack-memory-ingest --bulk
+GSTACK_MEMORY_INGEST_SCAN_SECRETS=1 bun run bin/gstack-memory-ingest.ts --bulk
```
When enabled, gitleaks covers:
@@ -155,7 +155,7 @@ verdict block. If a row is RED, the row tells you what to do.
Common cases:
- **Salience block is empty** — your transcripts may not be ingested
- yet. Run `gstack-gbrain-sync --full` to do a full pass.
+ yet. Run `bun run bin/gstack-gbrain-sync.ts --full` to do a full pass.
- **"gbrain CLI missing" in the preamble output** — gbrain isn't on
your PATH. Run `/setup-gbrain` to install/wire it.
@@ -166,7 +166,7 @@ Common cases:
--pglite && gbrain import <brain-remote-clone-dir>`.
- **A page has stale or wrong content** — `gbrain delete_page <slug>`,
- then re-run `gstack-gbrain-sync --incremental` to re-ingest from
+ then re-run `bun run bin/gstack-gbrain-sync.ts --incremental` to re-ingest from
source if the source file is still on disk and unchanged.
## Privacy + audit
diff --git a/ship/SKILL.md b/ship/SKILL.md
index f0cacac22..c6785f91c 100644
--- a/ship/SKILL.md
+++ b/ship/SKILL.md
@@ -112,9 +112,11 @@ else
fi
~/.claude/skills/gstack/bin/gstack-timeline-log '{"skill":"ship","event":"started","branch":"'"$_BRANCH"'","session":"'"$_SESSION_ID"'"}' 2>/dev/null &
_HAS_ROUTING="no"
-if [ -f CLAUDE.md ] && grep -q "## Skill routing" CLAUDE.md 2>/dev/null; then
- _HAS_ROUTING="yes"
-fi
+for _RF in CLAUDE.md AGENTS.md; do
+ if [ -f "$_RF" ] && grep -q "## Skill routing" "$_RF" 2>/dev/null; then
+ _HAS_ROUTING="yes"
+ fi
+done
_ROUTING_DECLINED=$(~/.claude/skills/gstack/bin/gstack-config get routing_declined 2>/dev/null || echo "false")
echo "HAS_ROUTING: $_HAS_ROUTING"
echo "ROUTING_DECLINED: $_ROUTING_DECLINED"
@@ -508,10 +510,13 @@ _BRAIN_SYNC_MODE=$("$_BRAIN_CONFIG_BIN" get artifacts_sync_mode 2>/dev/null || e
# Detect remote-MCP mode (Path 4 of /setup-gbrain). Local artifacts sync is
# a no-op in remote mode; the brain server pulls from GitHub/GitLab on its
# own cadence. Read claude.json directly to keep this preamble fast (no
-# subprocess to claude CLI on every skill start).
+# subprocess to claude CLI on every skill start). Both registration scopes
+# are read (#2499): user scope, then the nearest-ancestor project scope.
_GBRAIN_MCP_MODE="none"
+_GBRAIN_MCP_ENTRY=""
if command -v jq >/dev/null 2>&1 && [ -f "$HOME/.claude.json" ]; then
- _GBRAIN_MCP_TYPE=$(jq -r '.mcpServers.gbrain.type // .mcpServers.gbrain.transport // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_ENTRY=$(jq -c --arg cwd "$PWD" '.mcpServers.gbrain // ((.projects // {}) | to_entries | map(select((.key as $k | $cwd == $k or ($cwd | startswith($k + "/"))) and ((try .value.mcpServers.gbrain catch null) != null))) | sort_by(.key | length) | last | .value.mcpServers.gbrain) // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_TYPE=$(printf '%s' "$_GBRAIN_MCP_ENTRY" | jq -r '.type // .transport // empty' 2>/dev/null)
case "$_GBRAIN_MCP_TYPE" in
url|http|sse) _GBRAIN_MCP_MODE="remote-http" ;;
stdio) _GBRAIN_MCP_MODE="local-stdio" ;;
@@ -532,6 +537,7 @@ if [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_DO_PULL=1
if [ -f "$_BRAIN_LAST_PULL_FILE" ]; then
_BRAIN_LAST=$(cat "$_BRAIN_LAST_PULL_FILE" 2>/dev/null || echo 0)
+ case "$_BRAIN_LAST" in ''|*[!0-9]*) _BRAIN_LAST=0 ;; esac
_BRAIN_AGE=$(( _BRAIN_NOW - _BRAIN_LAST ))
[ "$_BRAIN_AGE" -lt 86400 ] && _BRAIN_DO_PULL=0
fi
@@ -545,7 +551,7 @@ fi
if [ "$_GBRAIN_MCP_MODE" = "remote-http" ]; then
# Remote-MCP mode: local artifacts sync is a no-op (brain admin's server
# pulls from GitHub/GitLab). Show the user this is by design, not broken.
- _GBRAIN_HOST=$(jq -r '.mcpServers.gbrain.url // empty' "$HOME/.claude.json" 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|')
+ _GBRAIN_HOST=$(printf '%s' "${_GBRAIN_MCP_ENTRY:-}" | jq -r '.url // empty' 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|' | head -1 | tr -cd 'A-Za-z0-9._-')
echo "ARTIFACTS_SYNC: remote-mode (managed by brain server ${_GBRAIN_HOST:-remote})"
elif [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_QUEUE_DEPTH=0
@@ -630,8 +636,8 @@ eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)"
_PROJ="${GSTACK_HOME:-$HOME/.gstack}/projects/${SLUG:-unknown}"
if [ -d "$_PROJ" ]; then
echo "--- RECENT ARTIFACTS ---"
- find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs ls -t 2>/dev/null | head -3
- [ -f "$_PROJ/${_BRANCH}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/${_BRANCH}-reviews.jsonl" | tr -d ' ') entries"
+ find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3
+ [ -f "$_PROJ/${BRANCH:-unknown}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/${BRANCH:-unknown}-reviews.jsonl" | tr -d ' ') entries"
[ -f "$_PROJ/timeline.jsonl" ] && tail -5 "$_PROJ/timeline.jsonl"
if [ -f "$_PROJ/timeline.jsonl" ]; then
_LAST=$(grep "\"branch\":\"${_BRANCH}\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -1)
@@ -639,7 +645,7 @@ if [ -d "$_PROJ" ]; then
_RECENT_SKILLS=$(grep "\"branch\":\"${_BRANCH}\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -3 | grep -o '"skill":"[^"]*"' | sed 's/"skill":"//;s/"//' | tr '\n' ',')
[ -n "$_RECENT_SKILLS" ] && echo "RECENT_PATTERN: $_RECENT_SKILLS"
fi
- _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs ls -t 2>/dev/null | head -1)
+ _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs -r ls -t 2>/dev/null | head -1)
[ -n "$_LATEST_CP" ] && echo "LATEST_CHECKPOINT: $_LATEST_CP"
if [ -f "$_PROJ/decisions.active.json" ]; then
echo "--- ACTIVE DECISIONS (recent, scope-relevant) ---"
@@ -715,7 +721,7 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST
## Question Tuning (skip entirely if `QUESTION_TUNING: false`)
-Before each AskUserQuestion, choose `question_id` from `scripts/question-registry.ts` or `{skill}-{slug}`, then run `printf '%s' "<question summary>" | ~/.claude/skills/gstack/bin/gstack-question-preference --check "<id>" --summary-stdin` (piped summary feeds the one-way keyword net, #2024). `AUTO_DECIDE` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." `ASK_NORMALLY` means ask.
+Before each AskUserQuestion, choose `question_id` from `~/.claude/skills/gstack/scripts/question-registry.ts` or `{skill}-{slug}`, then run `printf '%s' "<question summary>" | ~/.claude/skills/gstack/bin/gstack-question-preference --check "<id>" --summary-stdin` (piped summary feeds the one-way keyword net, #2024). `AUTO_DECIDE` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." `ASK_NORMALLY` means ask.
**Embed the question_id as a marker in the question text** so hooks can identify it deterministically (plan-tune cathedral T14 / D18 progressive markers). Append `<gstack-qid:{question_id}>` somewhere in the rendered question (the leading line or trailing line is fine; the marker doesn't render visibly to the user when wrapped in HTML-style angle brackets, but the hook strips it). Without the marker the PreToolUse enforcement hook treats the AUQ as observed-only and never auto-decides — so always include it when the question matches a registered `question_id`.
@@ -1105,7 +1111,7 @@ stay agent judgment; the slot pick stays `gstack-next-version`.
```bash
bun run ~/.claude/skills/gstack/bin/gstack-version-bump write --version "$NEW_VERSION"
```
- The CLI validates the 4-digit `MAJOR.MINOR.PATCH.MICRO` pattern and writes **both** VERSION and package.json. On a half-write (VERSION written, package.json failed) it exits 3 — re-run, and classify will report DRIFT_STALE_PKG for `repair` to fix.
+ The CLI validates the version pattern (4-digit `MAJOR.MINOR.PATCH.MICRO`; 3-digit for repos whose pinned version source uses plain semver) and writes VERSION, the manifest, and the manifest's npm lockfiles (`package-lock.json` / `npm-shrinkwrap.json`) when they already exist — never created. The manifest is resolved as `--package-json-path` → `.gstack/package-json-path` → `./package.json`, so a repo whose only Node package lives in a subdirectory (`web/`, `app/`) is covered by a one-line pin instead of silently getting a VERSION-only bump. npm rejects 4-component versions, so the manifest and lockfiles carry the npm-valid 3-digit translation (`1.67.0.0` → `1.67.0`); VERSION stays the 4-digit source of truth and classify judges drift against the translated form. On a half-write it exits 3 — re-run, and classify will report DRIFT_STALE_PKG for `repair` to fix.
5. **Record the release decision** (durable cross-session memory). The bump level is a real decision the next session should not re-derive blind:
```bash
diff --git a/ship/SKILL.md.tmpl b/ship/SKILL.md.tmpl
index ecbeaefcc..19c2a0876 100644
--- a/ship/SKILL.md.tmpl
+++ b/ship/SKILL.md.tmpl
@@ -201,7 +201,7 @@ stay agent judgment; the slot pick stays `gstack-next-version`.
```bash
bun run ~/.claude/skills/gstack/bin/gstack-version-bump write --version "$NEW_VERSION"
```
- The CLI validates the 4-digit `MAJOR.MINOR.PATCH.MICRO` pattern and writes **both** VERSION and package.json. On a half-write (VERSION written, package.json failed) it exits 3 — re-run, and classify will report DRIFT_STALE_PKG for `repair` to fix.
+ The CLI validates the version pattern (4-digit `MAJOR.MINOR.PATCH.MICRO`; 3-digit for repos whose pinned version source uses plain semver) and writes VERSION, the manifest, and the manifest's npm lockfiles (`package-lock.json` / `npm-shrinkwrap.json`) when they already exist — never created. The manifest is resolved as `--package-json-path` → `.gstack/package-json-path` → `./package.json`, so a repo whose only Node package lives in a subdirectory (`web/`, `app/`) is covered by a one-line pin instead of silently getting a VERSION-only bump. npm rejects 4-component versions, so the manifest and lockfiles carry the npm-valid 3-digit translation (`1.67.0.0` → `1.67.0`); VERSION stays the 4-digit source of truth and classify judges drift against the translated form. On a half-write it exits 3 — re-run, and classify will report DRIFT_STALE_PKG for `repair` to fix.
5. **Record the release decision** (durable cross-session memory). The bump level is a real decision the next session should not re-derive blind:
```bash
diff --git a/ship/sections/adversarial.md b/ship/sections/adversarial.md
index 59a0ff141..1161fc536 100644
--- a/ship/sections/adversarial.md
+++ b/ship/sections/adversarial.md
@@ -23,10 +23,20 @@ _CODEX_CFG=$(~/.claude/skills/gstack/bin/gstack-config get codex_reviews 2>/dev/
source ~/.claude/skills/gstack/bin/gstack-codex-probe 2>/dev/null || true
if [ "$_CODEX_CFG" = "disabled" ]; then
_CODEX_MODE="disabled"
+# Running-under-Codex presence probe (#2519): a live Codex session exports
+# CODEX_THREAD_ID / CODEX_SANDBOX into every shell it spawns (verified
+# against a live `codex exec 'env | grep -i codex'` capture, codex 0.147.0).
+# Nested codex spawns from inside a Codex host multiply token burn
+# (observed: one /review = 15M tokens). GSTACK_FORCE_CODEX_REVIEW=1 forces
+# the nested passes anyway.
+elif [ "${GSTACK_FORCE_CODEX_REVIEW:-0}" != "1" ] && { [ -n "${CODEX_THREAD_ID:-}" ] || [ -n "${CODEX_SANDBOX:-}" ]; }; then
+ _CODEX_MODE="under_codex"
elif ! command -v codex >/dev/null 2>&1; then
_CODEX_MODE="not_installed"; _gstack_codex_log_event "codex_cli_missing" 2>/dev/null || true
elif ! _gstack_codex_auth_probe >/dev/null 2>&1; then
_CODEX_MODE="not_authed"; _gstack_codex_log_event "codex_auth_failed" 2>/dev/null || true
+elif ! _gstack_codex_model_probe; then
+ _CODEX_MODE="model_unusable"
else
_CODEX_MODE="ready"; _gstack_codex_version_check 2>/dev/null || true
fi
@@ -36,7 +46,9 @@ echo "CODEX_MODE: $_CODEX_MODE"
Branch on the echoed `CODEX_MODE`:
- **`disabled`** — the user turned Codex reviews off (`codex_reviews=disabled`). Skip the Codex passes only; the Claude adversarial subagent below STILL runs (it is free and fast). Print: "Codex passes skipped (codex_reviews disabled) — running Claude adversarial only."
- **`not_installed`** — Codex CLI absent. Print: "Codex not installed — using Claude subagent. Install for cross-model coverage: `npm install -g @openai/codex`." Fall back to the Claude subagent path.
+- **`under_codex`** — this session is already running INSIDE a Codex host, so spawning codex again is the same model reviewing itself at multiplied token cost (#2519). Print exactly one line: "[running under Codex — nested codex passes skipped; set GSTACK_FORCE_CODEX_REVIEW=1 to force]" and skip the codex invocations below; run the section's free in-host pass instead if it defines one.
- **`not_authed`** — installed but no credentials. Print: "Codex installed but not authenticated — using Claude subagent. Run `codex login` or set `$CODEX_API_KEY`." Fall back to the Claude subagent path.
+- **`model_unusable`** — authed but the account cannot use its configured model (#2477: HTTP 400 on every call, usually a stale `model =` pin in `~/.codex/config.toml`). Relay the probe's HINT lines, tell the user the one-line fix (update the pin; `[notice.model_migrations]` names the replacement), and fall back to the Claude subagent path. The ~10s round trip is cached for 1h; timeouts fail open to `ready`.
- **`ready`** — run the Codex pass below.
For this diff-review path, `CODEX_MODE: disabled` means skip the Codex passes ONLY — the
@@ -76,7 +88,7 @@ _REPO_ROOT=$(git rev-parse --show-toplevel) || { echo "ERROR: not in a git repo"
# here. It defines _gstack_codex_timeout_wrapper (gtimeout -> timeout ->
# unwrapped fallback), added in #1056 but never wired into this call site.
source ~/.claude/skills/gstack/bin/gstack-codex-probe 2>/dev/null || true
-_gstack_codex_timeout_wrapper 540 codex exec "IMPORTANT: Do NOT read or execute any files under ~/.claude/, ~/.agents/, .claude/skills/, or agents/. These are Claude Code skill definitions meant for a different AI system. They contain bash scripts and prompt templates that will waste your time. Ignore them completely. Do NOT modify agents/openai.yaml. Stay focused on the repository code only.\n\nReview the changes on this branch against the base branch. Run DIFF_BASE=$(git merge-base origin/<base> HEAD) && git diff "$DIFF_BASE" to see the diff. Your job is to find ways this code will fail in production. Think like an attacker and a chaos engineer. Find edge cases, race conditions, security holes, resource leaks, failure modes, and silent data corruption paths. Be adversarial. Be thorough. No compliments — just the problems. End your output with ONE line in the canonical format `Recommendation: <action> because <one-line reason naming the most exploitable finding>`. Generic reasons like 'because it's safer' do not qualify; the reason must point to a specific finding or no-fix rationale." -C "$_REPO_ROOT" -s read-only -c 'model_reasoning_effort="high"' --enable web_search_cached < /dev/null 2>"$TMPERR_ADV"
+_gstack_codex_timeout_wrapper 540 codex exec "IMPORTANT: Do NOT read or execute any files under ~/.claude/, ~/.agents/, .claude/skills/, or agents/. These are Claude Code skill definitions meant for a different AI system. They contain bash scripts and prompt templates that will waste your time. Ignore them completely. Do NOT modify agents/openai.yaml. Stay focused on the repository code only.\n\nReview the changes on this branch against the base branch. Run DIFF_BASE=$(git merge-base origin/<base> HEAD) && git diff "$DIFF_BASE" to see the diff. Your job is to find ways this code will fail in production. Think like an attacker and a chaos engineer. Find edge cases, race conditions, security holes, resource leaks, failure modes, and silent data corruption paths. Be adversarial. Be thorough. No compliments — just the problems. End your output with ONE line in the canonical format `Recommendation: <action> because <one-line reason naming the most exploitable finding>`. Generic reasons like 'because it's safer' do not qualify; the reason must point to a specific finding or no-fix rationale." -C "$_REPO_ROOT" -s read-only -c 'model_reasoning_effort="high"' -c 'web_search="cached"' < /dev/null 2>"$TMPERR_ADV"
```
Set the Bash tool's `timeout` parameter to `600000` (10 minutes). It sits ABOVE the 540s wrapper deliberately, so the wrapper fires first and a stall surfaces as a diagnosable exit 124 instead of a harness kill that returns nothing. The wrapper resolves `gtimeout`, then `timeout`, then runs unwrapped, so it is safe on a macOS without coreutils. After the command completes, read stderr:
@@ -109,7 +121,7 @@ cd "$_REPO_ROOT"
# here. It defines _gstack_codex_timeout_wrapper (gtimeout -> timeout ->
# unwrapped fallback), added in #1056 but never wired into this call site.
source ~/.claude/skills/gstack/bin/gstack-codex-probe 2>/dev/null || true
-_gstack_codex_timeout_wrapper 540 codex review --base <base> -c 'model_reasoning_effort="high"' --enable web_search_cached < /dev/null 2>"$TMPERR"
+_gstack_codex_timeout_wrapper 540 codex review --base <base> -c 'model_reasoning_effort="high"' -c 'web_search="cached"' < /dev/null 2>"$TMPERR"
```
**No prompt argument.** `--base` is what scopes the review, and the positional `[PROMPT]` is mutually exclusive with it — passing both fails at argv parsing. Do NOT "fix" that error by dropping `--base` and keeping the prompt: a prompt-only `codex review` silently falls back to the **uncommitted working-tree** scope (`git status --short; git diff`), so it reviews the wrong changes and reports "no changes" on a clean tree. Prompt text describing the diff range does not change what the CLI feeds the reviewer. Unlike the adversarial pass above, which uses `codex exec` and really does run the git command it's told to, this path gets a pre-computed diff from the CLI — which is also why it needs no filesystem boundary.
diff --git a/ship/sections/plan-completion.md b/ship/sections/plan-completion.md
index 25df24cd8..f75b74acc 100644
--- a/ship/sections/plan-completion.md
+++ b/ship/sections/plan-completion.md
@@ -16,7 +16,7 @@
```bash
setopt +o nomatch 2>/dev/null || true # zsh compat
-BRANCH=$(git branch --show-current 2>/dev/null | tr '/' '-')
+BRANCH=$(git branch --show-current 2>/dev/null | tr '/' '-' | tr -cd 'a-zA-Z0-9._-')
REPO=$(basename "$(git rev-parse --show-toplevel 2>/dev/null)")
# Compute project slug for ~/.gstack/projects/ lookup
_PLAN_SLUG=$(git remote get-url origin 2>/dev/null | sed 's|.*[:/]\([^/]*/[^/]*\)\.git$|\1|;s|.*[:/]\([^/]*/[^/]*\)$|\1|' | tr '/' '-' | tr -cd 'a-zA-Z0-9._-') || true
@@ -26,7 +26,7 @@ for PLAN_DIR in "$HOME/.gstack/projects/$_PLAN_SLUG" "$HOME/.claude/plans" "$HOM
[ -d "$PLAN_DIR" ] || continue
PLAN=$(ls -t "$PLAN_DIR"/*.md 2>/dev/null | xargs grep -l "$BRANCH" 2>/dev/null | head -1)
[ -z "$PLAN" ] && PLAN=$(ls -t "$PLAN_DIR"/*.md 2>/dev/null | xargs grep -l "$REPO" 2>/dev/null | head -1)
- [ -z "$PLAN" ] && PLAN=$(find "$PLAN_DIR" -name '*.md' -mmin -1440 -maxdepth 1 2>/dev/null | xargs ls -t 2>/dev/null | head -1)
+ [ -z "$PLAN" ] && PLAN=$(find "$PLAN_DIR" -name '*.md' -mmin -1440 -maxdepth 1 2>/dev/null | xargs -r ls -t 2>/dev/null | head -1)
[ -n "$PLAN" ] && break
done
[ -n "$PLAN" ] && echo "PLAN_FILE: $PLAN" || echo "NO_PLAN_FILE"
diff --git a/ship/sections/review-army.md b/ship/sections/review-army.md
index c1c934c39..245433056 100644
--- a/ship/sections/review-army.md
+++ b/ship/sections/review-army.md
@@ -118,7 +118,7 @@ If Codex is available, run a lightweight design check on the diff:
```bash
TMPERR_DRL=$(mktemp /tmp/codex-drl-XXXXXXXX)
_REPO_ROOT=$(git rev-parse --show-toplevel) || { echo "ERROR: not in a git repo" >&2; exit 1; }
-codex exec "Review the git diff on this branch. Run 7 litmus checks (YES/NO each): 1. Brand/product unmistakable in first screen? 2. One strong visual anchor present? 3. Page understandable by scanning headlines only? 4. Each section has one job? 5. Are cards actually necessary? 6. Does motion improve hierarchy or atmosphere? 7. Would design feel premium with all decorative shadows removed? Flag any hard rejections: 1. Generic SaaS card grid as first impression 2. Beautiful image with weak brand 3. Strong headline with no clear action 4. Busy imagery behind text 5. Sections repeating same mood statement 6. Carousel with no narrative purpose 7. App UI made of stacked cards instead of layout 5 most important design findings only. Reference file:line." -C "$_REPO_ROOT" -s read-only -c 'model_reasoning_effort="high"' --enable web_search_cached < /dev/null 2>"$TMPERR_DRL"
+codex exec "Review the git diff on this branch. Run 7 litmus checks (YES/NO each): 1. Brand/product unmistakable in first screen? 2. One strong visual anchor present? 3. Page understandable by scanning headlines only? 4. Each section has one job? 5. Are cards actually necessary? 6. Does motion improve hierarchy or atmosphere? 7. Would design feel premium with all decorative shadows removed? Flag any hard rejections: 1. Generic SaaS card grid as first impression 2. Beautiful image with weak brand 3. Strong headline with no clear action 4. Busy imagery behind text 5. Sections repeating same mood statement 6. Carousel with no narrative purpose 7. App UI made of stacked cards instead of layout 5 most important design findings only. Reference file:line." -C "$_REPO_ROOT" -s read-only -c 'model_reasoning_effort="high"' -c 'web_search="cached"' < /dev/null 2>"$TMPERR_DRL"
```
Use a 5-minute timeout (`timeout: 300000`). After the command completes, read stderr:
@@ -383,7 +383,8 @@ Output a summary header: `Pre-Landing Review: N issues (X critical, Y informatio
- If 3 or fewer ASK items, you may use individual AskUserQuestion calls instead
7. **After all fixes (auto + user-approved):**
- - If ANY fixes were applied: commit fixed files by name (`git add <fixed-files> && git commit -m "fix: pre-landing review fixes"`), then **STOP** and tell the user to run `/ship` again to re-test.
+ - If ANY fixes were applied: commit fixed files by name (`git add <fixed-files> && git commit -m "fix: pre-landing review fixes"`), then **stay in this invocation and loop**: re-run the test suite (Step 5) on the fixed code, then re-run this review (Step 9 items 2-6) against the updated diff. Repeat until one full pass applies ZERO fixes — tests green and review clean — then continue to Step 12. NEVER stop to tell the user to run `/ship` again; a fix-and-rerun cycle has no user decision in it, and stopping there breaks the fully-automated contract (#2391).
+ - **Bound: 3 fix cycles.** If the 3rd cycle still applies fixes, STOP and report which findings keep reappearing — a review that won't converge is a genuine blocker worth human eyes, not a re-run request.
- If no fixes applied (all ASK items skipped, or no issues found): continue to Step 12.
8. Output summary: `Pre-Landing Review: N issues — M auto-fixed, K asked (J fixed, L skipped)`
diff --git a/ship/sections/review-army.md.tmpl b/ship/sections/review-army.md.tmpl
index e55db627e..541531355 100644
--- a/ship/sections/review-army.md.tmpl
+++ b/ship/sections/review-army.md.tmpl
@@ -33,7 +33,8 @@ Review the diff for structural issues that tests don't catch.
- If 3 or fewer ASK items, you may use individual AskUserQuestion calls instead
7. **After all fixes (auto + user-approved):**
- - If ANY fixes were applied: commit fixed files by name (`git add <fixed-files> && git commit -m "fix: pre-landing review fixes"`), then **STOP** and tell the user to run `/ship` again to re-test.
+ - If ANY fixes were applied: commit fixed files by name (`git add <fixed-files> && git commit -m "fix: pre-landing review fixes"`), then **stay in this invocation and loop**: re-run the test suite (Step 5) on the fixed code, then re-run this review (Step 9 items 2-6) against the updated diff. Repeat until one full pass applies ZERO fixes — tests green and review clean — then continue to Step 12. NEVER stop to tell the user to run `/ship` again; a fix-and-rerun cycle has no user decision in it, and stopping there breaks the fully-automated contract (#2391).
+ - **Bound: 3 fix cycles.** If the 3rd cycle still applies fixes, STOP and report which findings keep reappearing — a review that won't converge is a genuine blocker worth human eyes, not a re-run request.
- If no fixes applied (all ASK items skipped, or no issues found): continue to Step 12.
8. Output summary: `Pre-Landing Review: N issues — M auto-fixed, K asked (J fixed, L skipped)`
diff --git a/skillify/SKILL.md b/skillify/SKILL.md
index 0bbacd857..d70bde916 100644
--- a/skillify/SKILL.md
+++ b/skillify/SKILL.md
@@ -109,9 +109,11 @@ else
fi
~/.claude/skills/gstack/bin/gstack-timeline-log '{"skill":"skillify","event":"started","branch":"'"$_BRANCH"'","session":"'"$_SESSION_ID"'"}' 2>/dev/null &
_HAS_ROUTING="no"
-if [ -f CLAUDE.md ] && grep -q "## Skill routing" CLAUDE.md 2>/dev/null; then
- _HAS_ROUTING="yes"
-fi
+for _RF in CLAUDE.md AGENTS.md; do
+ if [ -f "$_RF" ] && grep -q "## Skill routing" "$_RF" 2>/dev/null; then
+ _HAS_ROUTING="yes"
+ fi
+done
_ROUTING_DECLINED=$(~/.claude/skills/gstack/bin/gstack-config get routing_declined 2>/dev/null || echo "false")
echo "HAS_ROUTING: $_HAS_ROUTING"
echo "ROUTING_DECLINED: $_ROUTING_DECLINED"
@@ -505,10 +507,13 @@ _BRAIN_SYNC_MODE=$("$_BRAIN_CONFIG_BIN" get artifacts_sync_mode 2>/dev/null || e
# Detect remote-MCP mode (Path 4 of /setup-gbrain). Local artifacts sync is
# a no-op in remote mode; the brain server pulls from GitHub/GitLab on its
# own cadence. Read claude.json directly to keep this preamble fast (no
-# subprocess to claude CLI on every skill start).
+# subprocess to claude CLI on every skill start). Both registration scopes
+# are read (#2499): user scope, then the nearest-ancestor project scope.
_GBRAIN_MCP_MODE="none"
+_GBRAIN_MCP_ENTRY=""
if command -v jq >/dev/null 2>&1 && [ -f "$HOME/.claude.json" ]; then
- _GBRAIN_MCP_TYPE=$(jq -r '.mcpServers.gbrain.type // .mcpServers.gbrain.transport // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_ENTRY=$(jq -c --arg cwd "$PWD" '.mcpServers.gbrain // ((.projects // {}) | to_entries | map(select((.key as $k | $cwd == $k or ($cwd | startswith($k + "/"))) and ((try .value.mcpServers.gbrain catch null) != null))) | sort_by(.key | length) | last | .value.mcpServers.gbrain) // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_TYPE=$(printf '%s' "$_GBRAIN_MCP_ENTRY" | jq -r '.type // .transport // empty' 2>/dev/null)
case "$_GBRAIN_MCP_TYPE" in
url|http|sse) _GBRAIN_MCP_MODE="remote-http" ;;
stdio) _GBRAIN_MCP_MODE="local-stdio" ;;
@@ -529,6 +534,7 @@ if [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_DO_PULL=1
if [ -f "$_BRAIN_LAST_PULL_FILE" ]; then
_BRAIN_LAST=$(cat "$_BRAIN_LAST_PULL_FILE" 2>/dev/null || echo 0)
+ case "$_BRAIN_LAST" in ''|*[!0-9]*) _BRAIN_LAST=0 ;; esac
_BRAIN_AGE=$(( _BRAIN_NOW - _BRAIN_LAST ))
[ "$_BRAIN_AGE" -lt 86400 ] && _BRAIN_DO_PULL=0
fi
@@ -542,7 +548,7 @@ fi
if [ "$_GBRAIN_MCP_MODE" = "remote-http" ]; then
# Remote-MCP mode: local artifacts sync is a no-op (brain admin's server
# pulls from GitHub/GitLab). Show the user this is by design, not broken.
- _GBRAIN_HOST=$(jq -r '.mcpServers.gbrain.url // empty' "$HOME/.claude.json" 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|')
+ _GBRAIN_HOST=$(printf '%s' "${_GBRAIN_MCP_ENTRY:-}" | jq -r '.url // empty' 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|' | head -1 | tr -cd 'A-Za-z0-9._-')
echo "ARTIFACTS_SYNC: remote-mode (managed by brain server ${_GBRAIN_HOST:-remote})"
elif [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_QUEUE_DEPTH=0
@@ -627,8 +633,8 @@ eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)"
_PROJ="${GSTACK_HOME:-$HOME/.gstack}/projects/${SLUG:-unknown}"
if [ -d "$_PROJ" ]; then
echo "--- RECENT ARTIFACTS ---"
- find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs ls -t 2>/dev/null | head -3
- [ -f "$_PROJ/${_BRANCH}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/${_BRANCH}-reviews.jsonl" | tr -d ' ') entries"
+ find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3
+ [ -f "$_PROJ/${BRANCH:-unknown}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/${BRANCH:-unknown}-reviews.jsonl" | tr -d ' ') entries"
[ -f "$_PROJ/timeline.jsonl" ] && tail -5 "$_PROJ/timeline.jsonl"
if [ -f "$_PROJ/timeline.jsonl" ]; then
_LAST=$(grep "\"branch\":\"${_BRANCH}\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -1)
@@ -636,7 +642,7 @@ if [ -d "$_PROJ" ]; then
_RECENT_SKILLS=$(grep "\"branch\":\"${_BRANCH}\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -3 | grep -o '"skill":"[^"]*"' | sed 's/"skill":"//;s/"//' | tr '\n' ',')
[ -n "$_RECENT_SKILLS" ] && echo "RECENT_PATTERN: $_RECENT_SKILLS"
fi
- _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs ls -t 2>/dev/null | head -1)
+ _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs -r ls -t 2>/dev/null | head -1)
[ -n "$_LATEST_CP" ] && echo "LATEST_CHECKPOINT: $_LATEST_CP"
if [ -f "$_PROJ/decisions.active.json" ]; then
echo "--- ACTIVE DECISIONS (recent, scope-relevant) ---"
@@ -712,7 +718,7 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST
## Question Tuning (skip entirely if `QUESTION_TUNING: false`)
-Before each AskUserQuestion, choose `question_id` from `scripts/question-registry.ts` or `{skill}-{slug}`, then run `printf '%s' "<question summary>" | ~/.claude/skills/gstack/bin/gstack-question-preference --check "<id>" --summary-stdin` (piped summary feeds the one-way keyword net, #2024). `AUTO_DECIDE` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." `ASK_NORMALLY` means ask.
+Before each AskUserQuestion, choose `question_id` from `~/.claude/skills/gstack/scripts/question-registry.ts` or `{skill}-{slug}`, then run `printf '%s' "<question summary>" | ~/.claude/skills/gstack/bin/gstack-question-preference --check "<id>" --summary-stdin` (piped summary feeds the one-way keyword net, #2024). `AUTO_DECIDE` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." `ASK_NORMALLY` means ask.
**Embed the question_id as a marker in the question text** so hooks can identify it deterministically (plan-tune cathedral T14 / D18 progressive markers). Append `<gstack-qid:{question_id}>` somewhere in the rendered question (the leading line or trailing line is fine; the marker doesn't render visibly to the user when wrapped in HTML-style angle brackets, but the hook strips it). Without the marker the PreToolUse enforcement hook treats the AUQ as observed-only and never auto-decides — so always include it when the question matches a registered `question_id`.
diff --git a/spec/SKILL.md b/spec/SKILL.md
index 7c881b68d..283d8960d 100644
--- a/spec/SKILL.md
+++ b/spec/SKILL.md
@@ -110,9 +110,11 @@ else
fi
~/.claude/skills/gstack/bin/gstack-timeline-log '{"skill":"spec","event":"started","branch":"'"$_BRANCH"'","session":"'"$_SESSION_ID"'"}' 2>/dev/null &
_HAS_ROUTING="no"
-if [ -f CLAUDE.md ] && grep -q "## Skill routing" CLAUDE.md 2>/dev/null; then
- _HAS_ROUTING="yes"
-fi
+for _RF in CLAUDE.md AGENTS.md; do
+ if [ -f "$_RF" ] && grep -q "## Skill routing" "$_RF" 2>/dev/null; then
+ _HAS_ROUTING="yes"
+ fi
+done
_ROUTING_DECLINED=$(~/.claude/skills/gstack/bin/gstack-config get routing_declined 2>/dev/null || echo "false")
echo "HAS_ROUTING: $_HAS_ROUTING"
echo "ROUTING_DECLINED: $_ROUTING_DECLINED"
@@ -506,10 +508,13 @@ _BRAIN_SYNC_MODE=$("$_BRAIN_CONFIG_BIN" get artifacts_sync_mode 2>/dev/null || e
# Detect remote-MCP mode (Path 4 of /setup-gbrain). Local artifacts sync is
# a no-op in remote mode; the brain server pulls from GitHub/GitLab on its
# own cadence. Read claude.json directly to keep this preamble fast (no
-# subprocess to claude CLI on every skill start).
+# subprocess to claude CLI on every skill start). Both registration scopes
+# are read (#2499): user scope, then the nearest-ancestor project scope.
_GBRAIN_MCP_MODE="none"
+_GBRAIN_MCP_ENTRY=""
if command -v jq >/dev/null 2>&1 && [ -f "$HOME/.claude.json" ]; then
- _GBRAIN_MCP_TYPE=$(jq -r '.mcpServers.gbrain.type // .mcpServers.gbrain.transport // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_ENTRY=$(jq -c --arg cwd "$PWD" '.mcpServers.gbrain // ((.projects // {}) | to_entries | map(select((.key as $k | $cwd == $k or ($cwd | startswith($k + "/"))) and ((try .value.mcpServers.gbrain catch null) != null))) | sort_by(.key | length) | last | .value.mcpServers.gbrain) // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_TYPE=$(printf '%s' "$_GBRAIN_MCP_ENTRY" | jq -r '.type // .transport // empty' 2>/dev/null)
case "$_GBRAIN_MCP_TYPE" in
url|http|sse) _GBRAIN_MCP_MODE="remote-http" ;;
stdio) _GBRAIN_MCP_MODE="local-stdio" ;;
@@ -530,6 +535,7 @@ if [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_DO_PULL=1
if [ -f "$_BRAIN_LAST_PULL_FILE" ]; then
_BRAIN_LAST=$(cat "$_BRAIN_LAST_PULL_FILE" 2>/dev/null || echo 0)
+ case "$_BRAIN_LAST" in ''|*[!0-9]*) _BRAIN_LAST=0 ;; esac
_BRAIN_AGE=$(( _BRAIN_NOW - _BRAIN_LAST ))
[ "$_BRAIN_AGE" -lt 86400 ] && _BRAIN_DO_PULL=0
fi
@@ -543,7 +549,7 @@ fi
if [ "$_GBRAIN_MCP_MODE" = "remote-http" ]; then
# Remote-MCP mode: local artifacts sync is a no-op (brain admin's server
# pulls from GitHub/GitLab). Show the user this is by design, not broken.
- _GBRAIN_HOST=$(jq -r '.mcpServers.gbrain.url // empty' "$HOME/.claude.json" 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|')
+ _GBRAIN_HOST=$(printf '%s' "${_GBRAIN_MCP_ENTRY:-}" | jq -r '.url // empty' 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|' | head -1 | tr -cd 'A-Za-z0-9._-')
echo "ARTIFACTS_SYNC: remote-mode (managed by brain server ${_GBRAIN_HOST:-remote})"
elif [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_QUEUE_DEPTH=0
@@ -628,8 +634,8 @@ eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)"
_PROJ="${GSTACK_HOME:-$HOME/.gstack}/projects/${SLUG:-unknown}"
if [ -d "$_PROJ" ]; then
echo "--- RECENT ARTIFACTS ---"
- find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs ls -t 2>/dev/null | head -3
- [ -f "$_PROJ/${_BRANCH}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/${_BRANCH}-reviews.jsonl" | tr -d ' ') entries"
+ find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3
+ [ -f "$_PROJ/${BRANCH:-unknown}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/${BRANCH:-unknown}-reviews.jsonl" | tr -d ' ') entries"
[ -f "$_PROJ/timeline.jsonl" ] && tail -5 "$_PROJ/timeline.jsonl"
if [ -f "$_PROJ/timeline.jsonl" ]; then
_LAST=$(grep "\"branch\":\"${_BRANCH}\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -1)
@@ -637,7 +643,7 @@ if [ -d "$_PROJ" ]; then
_RECENT_SKILLS=$(grep "\"branch\":\"${_BRANCH}\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -3 | grep -o '"skill":"[^"]*"' | sed 's/"skill":"//;s/"//' | tr '\n' ',')
[ -n "$_RECENT_SKILLS" ] && echo "RECENT_PATTERN: $_RECENT_SKILLS"
fi
- _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs ls -t 2>/dev/null | head -1)
+ _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs -r ls -t 2>/dev/null | head -1)
[ -n "$_LATEST_CP" ] && echo "LATEST_CHECKPOINT: $_LATEST_CP"
if [ -f "$_PROJ/decisions.active.json" ]; then
echo "--- ACTIVE DECISIONS (recent, scope-relevant) ---"
@@ -713,7 +719,7 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST
## Question Tuning (skip entirely if `QUESTION_TUNING: false`)
-Before each AskUserQuestion, choose `question_id` from `scripts/question-registry.ts` or `{skill}-{slug}`, then run `printf '%s' "<question summary>" | ~/.claude/skills/gstack/bin/gstack-question-preference --check "<id>" --summary-stdin` (piped summary feeds the one-way keyword net, #2024). `AUTO_DECIDE` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." `ASK_NORMALLY` means ask.
+Before each AskUserQuestion, choose `question_id` from `~/.claude/skills/gstack/scripts/question-registry.ts` or `{skill}-{slug}`, then run `printf '%s' "<question summary>" | ~/.claude/skills/gstack/bin/gstack-question-preference --check "<id>" --summary-stdin` (piped summary feeds the one-way keyword net, #2024). `AUTO_DECIDE` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." `ASK_NORMALLY` means ask.
**Embed the question_id as a marker in the question text** so hooks can identify it deterministically (plan-tune cathedral T14 / D18 progressive markers). Append `<gstack-qid:{question_id}>` somewhere in the rendered question (the leading line or trailing line is fine; the marker doesn't render visibly to the user when wrapped in HTML-style angle brackets, but the hook strips it). Without the marker the PreToolUse enforcement hook treats the AUQ as observed-only and never auto-decides — so always include it when the question matches a registered `question_id`.
diff --git a/sync-gbrain/SKILL.md b/sync-gbrain/SKILL.md
index 4637351c7..6a5b71377 100644
--- a/sync-gbrain/SKILL.md
+++ b/sync-gbrain/SKILL.md
@@ -111,9 +111,11 @@ else
fi
~/.claude/skills/gstack/bin/gstack-timeline-log '{"skill":"sync-gbrain","event":"started","branch":"'"$_BRANCH"'","session":"'"$_SESSION_ID"'"}' 2>/dev/null &
_HAS_ROUTING="no"
-if [ -f CLAUDE.md ] && grep -q "## Skill routing" CLAUDE.md 2>/dev/null; then
- _HAS_ROUTING="yes"
-fi
+for _RF in CLAUDE.md AGENTS.md; do
+ if [ -f "$_RF" ] && grep -q "## Skill routing" "$_RF" 2>/dev/null; then
+ _HAS_ROUTING="yes"
+ fi
+done
_ROUTING_DECLINED=$(~/.claude/skills/gstack/bin/gstack-config get routing_declined 2>/dev/null || echo "false")
echo "HAS_ROUTING: $_HAS_ROUTING"
echo "ROUTING_DECLINED: $_ROUTING_DECLINED"
@@ -507,10 +509,13 @@ _BRAIN_SYNC_MODE=$("$_BRAIN_CONFIG_BIN" get artifacts_sync_mode 2>/dev/null || e
# Detect remote-MCP mode (Path 4 of /setup-gbrain). Local artifacts sync is
# a no-op in remote mode; the brain server pulls from GitHub/GitLab on its
# own cadence. Read claude.json directly to keep this preamble fast (no
-# subprocess to claude CLI on every skill start).
+# subprocess to claude CLI on every skill start). Both registration scopes
+# are read (#2499): user scope, then the nearest-ancestor project scope.
_GBRAIN_MCP_MODE="none"
+_GBRAIN_MCP_ENTRY=""
if command -v jq >/dev/null 2>&1 && [ -f "$HOME/.claude.json" ]; then
- _GBRAIN_MCP_TYPE=$(jq -r '.mcpServers.gbrain.type // .mcpServers.gbrain.transport // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_ENTRY=$(jq -c --arg cwd "$PWD" '.mcpServers.gbrain // ((.projects // {}) | to_entries | map(select((.key as $k | $cwd == $k or ($cwd | startswith($k + "/"))) and ((try .value.mcpServers.gbrain catch null) != null))) | sort_by(.key | length) | last | .value.mcpServers.gbrain) // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_TYPE=$(printf '%s' "$_GBRAIN_MCP_ENTRY" | jq -r '.type // .transport // empty' 2>/dev/null)
case "$_GBRAIN_MCP_TYPE" in
url|http|sse) _GBRAIN_MCP_MODE="remote-http" ;;
stdio) _GBRAIN_MCP_MODE="local-stdio" ;;
@@ -531,6 +536,7 @@ if [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_DO_PULL=1
if [ -f "$_BRAIN_LAST_PULL_FILE" ]; then
_BRAIN_LAST=$(cat "$_BRAIN_LAST_PULL_FILE" 2>/dev/null || echo 0)
+ case "$_BRAIN_LAST" in ''|*[!0-9]*) _BRAIN_LAST=0 ;; esac
_BRAIN_AGE=$(( _BRAIN_NOW - _BRAIN_LAST ))
[ "$_BRAIN_AGE" -lt 86400 ] && _BRAIN_DO_PULL=0
fi
@@ -544,7 +550,7 @@ fi
if [ "$_GBRAIN_MCP_MODE" = "remote-http" ]; then
# Remote-MCP mode: local artifacts sync is a no-op (brain admin's server
# pulls from GitHub/GitLab). Show the user this is by design, not broken.
- _GBRAIN_HOST=$(jq -r '.mcpServers.gbrain.url // empty' "$HOME/.claude.json" 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|')
+ _GBRAIN_HOST=$(printf '%s' "${_GBRAIN_MCP_ENTRY:-}" | jq -r '.url // empty' 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|' | head -1 | tr -cd 'A-Za-z0-9._-')
echo "ARTIFACTS_SYNC: remote-mode (managed by brain server ${_GBRAIN_HOST:-remote})"
elif [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_QUEUE_DEPTH=0
@@ -629,8 +635,8 @@ eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)"
_PROJ="${GSTACK_HOME:-$HOME/.gstack}/projects/${SLUG:-unknown}"
if [ -d "$_PROJ" ]; then
echo "--- RECENT ARTIFACTS ---"
- find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs ls -t 2>/dev/null | head -3
- [ -f "$_PROJ/${_BRANCH}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/${_BRANCH}-reviews.jsonl" | tr -d ' ') entries"
+ find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3
+ [ -f "$_PROJ/${BRANCH:-unknown}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/${BRANCH:-unknown}-reviews.jsonl" | tr -d ' ') entries"
[ -f "$_PROJ/timeline.jsonl" ] && tail -5 "$_PROJ/timeline.jsonl"
if [ -f "$_PROJ/timeline.jsonl" ]; then
_LAST=$(grep "\"branch\":\"${_BRANCH}\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -1)
@@ -638,7 +644,7 @@ if [ -d "$_PROJ" ]; then
_RECENT_SKILLS=$(grep "\"branch\":\"${_BRANCH}\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -3 | grep -o '"skill":"[^"]*"' | sed 's/"skill":"//;s/"//' | tr '\n' ',')
[ -n "$_RECENT_SKILLS" ] && echo "RECENT_PATTERN: $_RECENT_SKILLS"
fi
- _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs ls -t 2>/dev/null | head -1)
+ _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs -r ls -t 2>/dev/null | head -1)
[ -n "$_LATEST_CP" ] && echo "LATEST_CHECKPOINT: $_LATEST_CP"
if [ -f "$_PROJ/decisions.active.json" ]; then
echo "--- ACTIVE DECISIONS (recent, scope-relevant) ---"
@@ -714,7 +720,7 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST
## Question Tuning (skip entirely if `QUESTION_TUNING: false`)
-Before each AskUserQuestion, choose `question_id` from `scripts/question-registry.ts` or `{skill}-{slug}`, then run `printf '%s' "<question summary>" | ~/.claude/skills/gstack/bin/gstack-question-preference --check "<id>" --summary-stdin` (piped summary feeds the one-way keyword net, #2024). `AUTO_DECIDE` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." `ASK_NORMALLY` means ask.
+Before each AskUserQuestion, choose `question_id` from `~/.claude/skills/gstack/scripts/question-registry.ts` or `{skill}-{slug}`, then run `printf '%s' "<question summary>" | ~/.claude/skills/gstack/bin/gstack-question-preference --check "<id>" --summary-stdin` (piped summary feeds the one-way keyword net, #2024). `AUTO_DECIDE` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." `ASK_NORMALLY` means ask.
**Embed the question_id as a marker in the question text** so hooks can identify it deterministically (plan-tune cathedral T14 / D18 progressive markers). Append `<gstack-qid:{question_id}>` somewhere in the rendered question (the leading line or trailing line is fine; the marker doesn't render visibly to the user when wrapped in HTML-style angle brackets, but the hook strips it). Without the marker the PreToolUse enforcement hook treats the AUQ as observed-only and never auto-decides — so always include it when the question matches a registered `question_id`.
@@ -1103,6 +1109,10 @@ if [ -f ~/.gbrain/config.json ] && \
fi
fi
gbrain delete "$SLUG" 2>/dev/null || true
+# #2503: on worktree-pinned brains `gbrain put` can materialize the page as
+# <slug>.md in the CURRENT directory (the user's repo), and `gbrain delete`
+# removes the page, not the file. Remove the litter explicitly.
+rm -f "./${SLUG}.md" 2>/dev/null || true
```
Then update CLAUDE.md based on capability state:
diff --git a/sync-gbrain/SKILL.md.tmpl b/sync-gbrain/SKILL.md.tmpl
index fa8becfd5..11471deb1 100644
--- a/sync-gbrain/SKILL.md.tmpl
+++ b/sync-gbrain/SKILL.md.tmpl
@@ -336,6 +336,10 @@ if [ -f ~/.gbrain/config.json ] && \
fi
fi
gbrain delete "$SLUG" 2>/dev/null || true
+# #2503: on worktree-pinned brains `gbrain put` can materialize the page as
+# <slug>.md in the CURRENT directory (the user's repo), and `gbrain delete`
+# removes the page, not the file. Remove the litter explicitly.
+rm -f "./${SLUG}.md" 2>/dev/null || true
```
Then update CLAUDE.md based on capability state:
diff --git a/test/artifacts-allowlist-decisions.test.ts b/test/artifacts-allowlist-decisions.test.ts
new file mode 100644
index 000000000..7908cd28d
--- /dev/null
+++ b/test/artifacts-allowlist-decisions.test.ts
@@ -0,0 +1,66 @@
+import { describe, test, expect } from "bun:test";
+import * as fs from "fs";
+import * as path from "path";
+
+const ROOT = path.resolve(import.meta.dir, "..");
+const INIT = fs.readFileSync(path.join(ROOT, "bin", "gstack-artifacts-init"), "utf-8");
+
+/** Pull a quoted heredoc body out of gstack-artifacts-init by target filename. */
+function heredoc(target: string): string {
+ const re = new RegExp(`cat > "\\$GSTACK_HOME/${target}" <<'EOF'\\n([\\s\\S]*?)\\nEOF\\n`);
+ const m = INIT.match(re);
+ if (!m) throw new Error(`heredoc for ${target} not found in gstack-artifacts-init`);
+ return m[1];
+}
+
+/** fnmatch.fnmatchcase semantics, as compute_paths_to_stage applies them:
+ * `*` does not cross a path separator. */
+function globToRe(g: string): RegExp {
+ return new RegExp("^" + g.split("*").map((s) => s.replace(/[.]/g, "[.]")).join("[^/]*") + "$");
+}
+
+const DECISION_PATHS = [
+ "projects/acme-widget/decisions.jsonl",
+ "projects/acme-widget/decisions.active.json",
+ "projects/acme-widget/decisions.archive.jsonl",
+];
+
+/**
+ * gstack-decision-log:40 enqueues projects/<slug>/decisions.jsonl after EVERY write,
+ * but no managed glob matched it, so compute_paths_to_stage rejected all of them at
+ * its "must match at least one allowlist glob" check. The writer and the syncer
+ * disagreed silently: turning artifacts sync on backed up learnings, plans, designs
+ * and timelines -- everything EXCEPT the durable decision ledger -- and nothing
+ * anywhere reported a miss, because a dropped path prints exactly what a synced one
+ * does when the queue is otherwise empty.
+ *
+ * Source-level rather than end-to-end: gstack-artifacts-init.test.ts drives the real
+ * script through #!/bin/bash shims and a colon-separated PATH, so it cannot run on
+ * Windows -- which is the platform where this bug bit.
+ */
+describe("the artifacts allowlist covers the decision store", () => {
+ const globs = heredoc("\\.brain-allowlist")
+ .split("\n")
+ .map((l) => l.trim())
+ .filter((l) => l && !l.startsWith("#"));
+
+ test("every decisions.* path matches at least one allowlist glob", () => {
+ for (const p of DECISION_PATHS) {
+ expect({ p, matched: globs.some((g) => globToRe(g).test(p)) }).toEqual({ p, matched: true });
+ }
+ });
+
+ test("decisions.* are class artifact, so they sync in artifacts-only mode too", () => {
+ const map = JSON.parse(heredoc("\\.brain-privacy-map\\.json"));
+ for (const p of DECISION_PATHS) {
+ const hit = map.find((e: { pattern: string; class: string }) => globToRe(e.pattern).test(p));
+ expect({ p, cls: hit?.class }).toEqual({ p, cls: "artifact" });
+ }
+ });
+
+ test("the allowlist still ends with the user-additions marker", () => {
+ // Additions below it survive re-init; a glob added above would be silently
+ // overwritten the next time gstack-artifacts-init runs.
+ expect(heredoc("\\.brain-allowlist").trimEnd()).toMatch(/# ---- USER ADDITIONS BELOW ----/);
+ });
+});
diff --git a/test/basic-ftp-security-pin.test.ts b/test/basic-ftp-security-pin.test.ts
deleted file mode 100644
index a2e9f9f8e..000000000
--- a/test/basic-ftp-security-pin.test.ts
+++ /dev/null
@@ -1,58 +0,0 @@
-import { describe, test, expect } from 'bun:test';
-import { readFileSync } from 'fs';
-import { join } from 'path';
-
-const ROOT = join(import.meta.dir, '..');
-
-// Security regression guard for the basic-ftp transitive dependency.
-//
-// basic-ftp reaches the tree only transitively:
-// puppeteer-core > @puppeteer/browsers > proxy-agent > pac-proxy-agent > get-uri > basic-ftp
-//
-// Versions <= 5.3.0 carry four HIGH advisories, all fixed in 5.3.1:
-// - GHSA-chqc-8p9q-pq6q CVE-2026-39983 FTP command injection via CRLF (fixed 5.2.1)
-// - GHSA-6v7q-wjvx-w8wg incomplete CRLF protection, USER/PASS + MKD bypass (fixed 5.2.2)
-// - GHSA-rpmf-866q-6p89 DoS via unbounded multiline control-response buffering
-// - GHSA-rp42-5vxx-qpwr DoS via unbounded memory in Client.list()
-//
-// The fix is a bun `overrides` pin (not a phantom direct dependency): overriding
-// forces EVERY basic-ftp in the tree to the safe version, including get-uri's
-// nested copy. A direct-dependency bump leaves that nested copy behind — which is
-// exactly the failure mode this test is here to catch. See the CVE-2026-39983
-// upgrade fix for the full rationale.
-const MIN_SAFE = '5.3.1';
-
-function cmpSemver(a: string, b: string): number {
- const pa = a.split('.').map(Number);
- const pb = b.split('.').map(Number);
- for (let i = 0; i < 3; i++) {
- if ((pa[i] ?? 0) !== (pb[i] ?? 0)) return (pa[i] ?? 0) - (pb[i] ?? 0);
- }
- return 0;
-}
-
-describe('basic-ftp security pin (CVE-2026-39983 and siblings)', () => {
- test('package.json overrides basic-ftp to a safe version', () => {
- const pkg = JSON.parse(readFileSync(join(ROOT, 'package.json'), 'utf-8'));
- const pin = pkg.overrides?.['basic-ftp'];
- expect(pin, 'package.json overrides.basic-ftp must exist').toBeDefined();
- const pinned = String(pin).replace(/^[\^~]/, '');
- expect(
- cmpSemver(pinned, MIN_SAFE) >= 0,
- `overrides.basic-ftp is "${pin}" but must be >= ${MIN_SAFE}`,
- ).toBe(true);
- });
-
- test('no basic-ftp entry in bun.lock resolves below the safe version', () => {
- const lock = readFileSync(join(ROOT, 'bun.lock'), 'utf-8');
- // Match every resolved basic-ftp specifier, including nested paths like
- // "get-uri/basic-ftp" that a direct-dependency bump would leave vulnerable.
- const versions = [...lock.matchAll(/basic-ftp@(\d+\.\d+\.\d+)/g)].map(m => m[1]);
- expect(versions.length, 'expected at least one basic-ftp entry in bun.lock').toBeGreaterThan(0);
- const vulnerable = versions.filter(v => cmpSemver(v, MIN_SAFE) < 0);
- expect(
- vulnerable,
- `bun.lock still resolves vulnerable basic-ftp version(s): ${vulnerable.join(', ')}`,
- ).toEqual([]);
- });
-});
diff --git a/test/bin-context-windows-slug.test.ts b/test/bin-context-windows-slug.test.ts
new file mode 100644
index 000000000..47f05b8da
--- /dev/null
+++ b/test/bin-context-windows-slug.test.ts
@@ -0,0 +1,113 @@
+import { describe, test, expect, beforeEach, afterEach } from "bun:test";
+import { spawnSync } from "child_process";
+import * as fs from "fs";
+import * as os from "os";
+import * as path from "path";
+import {
+ toMsysPath,
+ slugFromEnvironment,
+ resolveSlug,
+ NEEDS_NATIVE_SLUG_ON_WINDOWS,
+} from "../lib/bin-context";
+
+const ROOT = path.resolve(import.meta.dir, "..");
+const read = (rel: string) => fs.readFileSync(path.join(ROOT, rel), "utf-8");
+
+let tmp: string;
+beforeEach(() => { tmp = fs.mkdtempSync(path.join(os.tmpdir(), "gstack-slug-")); });
+afterEach(() => { try { fs.rmSync(tmp, { recursive: true, force: true }); } catch {} });
+
+/**
+ * Windows cannot exec bin/gstack-slug -- a `#!/usr/bin/env bash` script with no file
+ * extension -- so spawnSync fails ENOENT and resolveSlug used to return the literal
+ * string "unknown". Every decision on the machine landed in one shared
+ * ~/.gstack/projects/unknown/ bucket, while the bash-side Context Recovery preamble
+ * resolved the real slug and silently found nothing there.
+ *
+ * These exercise the native fallback on EVERY platform (it is only the *gating* that
+ * is win32-specific), so macOS/Linux CI catches a regression that would otherwise
+ * only ever surface on a Windows user's disk.
+ */
+describe("native slug fallback mirrors bin/gstack-slug", () => {
+ test("toMsysPath reproduces the git-bash cache key", () => {
+ // gstack-slug does: CACHE_KEY=$(printf '%s' "$(pwd)" | tr '/' '_')
+ // and git-bash `pwd` reports C:\Users\j\foo as /c/Users/j/foo.
+ expect(toMsysPath("C:\\Users\\j\\foo")).toBe("/c/Users/j/foo");
+ expect(toMsysPath("D:/Work/Repo")).toBe("/d/Work/Repo");
+ expect(toMsysPath("/already/posix")).toBe("/already/posix");
+ // The cache FILENAME is the real contract:
+ expect(toMsysPath("C:\\Users\\j\\foo").replace(/\//g, "_")).toBe("_c_Users_j_foo");
+ });
+
+ test("step 1: a cached slug wins over everything else", () => {
+ const cwd = path.join(tmp, "proj");
+ fs.mkdirSync(cwd);
+ const cacheDir = path.join(tmp, "home", "slug-cache");
+ fs.mkdirSync(cacheDir, { recursive: true });
+ fs.writeFileSync(path.join(cacheDir, toMsysPath(cwd).replace(/\//g, "_")), "cached-wins");
+ expect(slugFromEnvironment(path.join(tmp, "home"), cwd)).toBe("cached-wins");
+ });
+
+ test("step 2: derives owner-repo from the git remote, https and ssh alike", () => {
+ for (const [url, want] of [
+ ["https://github.com/acme/Widget.git", "acme-Widget"],
+ ["[email protected]:acme/Widget.git", "acme-Widget"],
+ ["https://gitlab.com/acme/Widget", "acme-Widget"],
+ ] as const) {
+ const cwd = fs.mkdtempSync(path.join(tmp, "repo-"));
+ spawnSync("git", ["init", "-q"], { cwd });
+ spawnSync("git", ["remote", "add", "origin", url], { cwd });
+ expect(slugFromEnvironment(path.join(tmp, "home2"), cwd)).toBe(want);
+ }
+ });
+
+ test("step 3: falls back to the sanitized directory name", () => {
+ // `tr -cd 'a-zA-Z0-9._-'` DELETES disallowed characters rather than replacing them.
+ const cwd = path.join(tmp, "My Proj+v2");
+ fs.mkdirSync(cwd);
+ expect(slugFromEnvironment(path.join(tmp, "home3"), cwd)).toBe("MyProjv2");
+ });
+
+ test("the resolved slug is cached back, as the shell script does", () => {
+ const cwd = path.join(tmp, "cacheme");
+ fs.mkdirSync(cwd);
+ const home = path.join(tmp, "home4");
+ const slug = slugFromEnvironment(home, cwd);
+ const key = path.join(home, "slug-cache", toMsysPath(cwd).replace(/\//g, "_"));
+ expect(fs.existsSync(key)).toBe(true);
+ // no trailing newline: gstack-slug writes with printf '%s'
+ expect(fs.readFileSync(key, "utf-8")).toBe(slug);
+ });
+
+ test("never returns the empty string", () => {
+ expect(slugFromEnvironment(path.join(tmp, "h"), tmp).length).toBeGreaterThan(0);
+ });
+});
+
+describe("the fallback stays win32-gated", () => {
+ // Static tripwire in the style of gbrain-spawn-windows-shell.test.ts: POSIX CI
+ // cannot observe the Windows branch at runtime, so pin the gate itself. Removing
+ // it would silently change macOS/Linux behaviour, which today is byte-identical.
+ test("NEEDS_NATIVE_SLUG_ON_WINDOWS is platform-gated", () => {
+ expect(read("lib/bin-context.ts")).toMatch(
+ /export const NEEDS_NATIVE_SLUG_ON_WINDOWS\s*=\s*process\.platform === "win32"/,
+ );
+ expect(NEEDS_NATIVE_SLUG_ON_WINDOWS).toBe(process.platform === "win32");
+ });
+
+ test("resolveSlug no longer returns a bare literal on a failed spawn", () => {
+ const src = read("lib/bin-context.ts");
+ expect(src).not.toMatch(/return m \? m\[1\]\.trim\(\) : "unknown";/);
+ expect(src).toMatch(/if \(NEEDS_NATIVE_SLUG_ON_WINDOWS\) return slugFromEnvironment\(\);/);
+ });
+
+ test("a spawn that cannot run resolves to a real slug, not 'unknown'", () => {
+ // The exact production failure: the helper path does not exist / cannot exec.
+ const got = resolveSlug(path.join(tmp, "definitely-not-a-real-bin"));
+ if (NEEDS_NATIVE_SLUG_ON_WINDOWS) {
+ expect(got).not.toBe("unknown");
+ } else {
+ expect(got).toBe("unknown"); // POSIX behaviour deliberately unchanged
+ }
+ });
+});
diff --git a/test/brain-cache-roundtrip.test.ts b/test/brain-cache-roundtrip.test.ts
index 060ae26f9..0466bd287 100644
--- a/test/brain-cache-roundtrip.test.ts
+++ b/test/brain-cache-roundtrip.test.ts
@@ -131,6 +131,59 @@ describe('brain-cache endpoint detection', () => {
expect(typeof hash).toBe('string');
expect(hash.length).toBeGreaterThan(0);
});
+
+ // #2499: project-scoped registrations (.projects["/path"].mcpServers.gbrain)
+ // were never read — two different project-scoped brains both hashed to
+ // 'local', so switching between them never invalidated the cache.
+ test('detectEndpointHash resolves a project-scoped gbrain URL for a cwd inside the project (#2499)', async () => {
+ const mod = await importCache();
+ const cj = join(TMP_HOME, 'claude.json');
+ writeFileSync(cj, JSON.stringify({
+ projects: {
+ '/w/repo': { mcpServers: { gbrain: { type: 'http', url: 'https://a.example/mcp' } } },
+ },
+ }));
+ const inside = mod.detectEndpointHash(cj, '/w/repo/src/deep');
+ expect(inside).not.toBe('local');
+ expect(inside).toHaveLength(8);
+ // Path-boundary check: /w/repo2 is NOT inside /w/repo.
+ expect(mod.detectEndpointHash(cj, '/w/repo2')).toBe('local');
+ });
+
+ test('detectEndpointHash prefers the nearest-ancestor project entry (#2499)', async () => {
+ const mod = await importCache();
+ const cj = join(TMP_HOME, 'claude.json');
+ writeFileSync(cj, JSON.stringify({
+ projects: {
+ '/w/repo': { mcpServers: { gbrain: { url: 'https://outer.example/mcp' } } },
+ '/w/repo/nested': { mcpServers: { gbrain: { url: 'https://inner.example/mcp' } } },
+ },
+ }));
+ const inner = mod.detectEndpointHash(cj, '/w/repo/nested/sub');
+ const outer = mod.detectEndpointHash(cj, '/w/repo/other');
+ expect(inner).not.toBe(outer); // two brains → two hashes (the docstring scenario)
+ expect(inner).not.toBe('local');
+ expect(outer).not.toBe('local');
+ });
+
+ test('detectEndpointHash still prefers user scope over project scope (#2499)', async () => {
+ const mod = await importCache();
+ const cj = join(TMP_HOME, 'claude.json');
+ writeFileSync(cj, JSON.stringify({
+ mcpServers: { gbrain: { url: 'https://user.example/mcp' } },
+ projects: {
+ '/w/repo': { mcpServers: { gbrain: { url: 'https://proj.example/mcp' } } },
+ },
+ }));
+ const userScoped = mod.detectEndpointHash(cj, '/w/repo');
+ // Same file minus the user-scope entry → different hash proves user scope won.
+ writeFileSync(cj, JSON.stringify({
+ projects: {
+ '/w/repo': { mcpServers: { gbrain: { url: 'https://proj.example/mcp' } } },
+ },
+ }));
+ expect(mod.detectEndpointHash(cj, '/w/repo')).not.toBe(userScoped);
+ });
});
describe('brain-cache schema mismatch behavior', () => {
@@ -153,7 +206,12 @@ describe('brain-cache schema mismatch behavior', () => {
// the file gets deleted by the rebuild step. State should be 'missing' or
// 'stale-fallback' depending on whether the rebuild left a file behind.
expect(['missing', 'cold-refreshed', 'stale-fallback']).toContain(result.state);
- });
+ }, 30000);
+ // ^ 30s: the schema-mismatch rebuild refreshes EVERY per-project entity,
+ // each spawning the real gbrain CLI (no mock here). With an unreachable
+ // brain each spawn runs to its own timeout, and under machine load the
+ // stack exceeds bun's 5s default — observed at 5.2-5.4s on a loaded box,
+ // identically on pre-fix binaries (load flake, not a code regression).
});
describe('brain-cache state machine', () => {
diff --git a/test/brain-sync.test.ts b/test/brain-sync.test.ts
index a4587f806..4f22f933d 100644
--- a/test/brain-sync.test.ts
+++ b/test/brain-sync.test.ts
@@ -448,3 +448,235 @@ describe('gstack-brain-sync --discover-new', () => {
expect(queue.trim()).toBe('');
});
});
+
+// ---------------------------------------------------------------
+// #2549 queue integrity: classified drops, privacy retention,
+// surgical rewrite, unpushed-commit detector
+// ---------------------------------------------------------------
+describe('#2549 queue integrity', () => {
+ function initWithMode(mode: string) {
+ run(['gstack-artifacts-init', '--remote', bareRemote]);
+ run(['gstack-config', 'set', 'artifacts_sync_mode', mode]);
+ }
+ const queueText = () => fs.readFileSync(path.join(tmpHome, '.brain-queue.jsonl'), 'utf-8');
+ const statusJson = () => JSON.parse(fs.readFileSync(path.join(tmpHome, '.brain-sync-status.json'), 'utf-8'));
+
+ test('privacy-held entries are RETAINED and classified, not wiped as "no allowlisted changes"', () => {
+ // timeline.jsonl is class=behavioral; artifacts-only mode holds it.
+ initWithMode('artifacts-only');
+ fs.mkdirSync(path.join(tmpHome, 'projects', 'p'), { recursive: true });
+ fs.writeFileSync(path.join(tmpHome, 'projects/p/timeline.jsonl'), '{"skill":"x","event":"started"}\n');
+ run(['gstack-brain-enqueue', 'projects/p/timeline.jsonl']);
+ const r = run(['gstack-brain-sync', '--once']);
+ expect(r.status).toBe(0);
+ // The exact #2549 repro: the old code truncated the queue here and said
+ // "no allowlisted changes in queue". The entry must survive, and the
+ // status must attribute the hold honestly.
+ expect(queueText()).toContain('projects/p/timeline.jsonl');
+ const s = statusJson();
+ expect(s.status).toBe('idle');
+ expect(s.message).toContain('privacy-held retained');
+ expect(s.message).not.toContain('no allowlisted changes');
+ });
+
+ test('unmatched and missing entries drop WITH counts and a 0600 drops sidecar', () => {
+ initWithMode('full');
+ fs.mkdirSync(path.join(tmpHome, 'projects', 'p'), { recursive: true });
+ // Unmatched: no allowlist glob covers .txt scratch files.
+ fs.writeFileSync(path.join(tmpHome, 'projects/p/scratch.txt'), 'x\n');
+ fs.appendFileSync(path.join(tmpHome, '.brain-queue.jsonl'), '{"file":"projects/p/scratch.txt"}\n');
+ // Missing: allowlisted name that does not exist on disk.
+ fs.appendFileSync(path.join(tmpHome, '.brain-queue.jsonl'), '{"file":"projects/p/learnings.jsonl"}\n');
+ const r = run(['gstack-brain-sync', '--once']);
+ expect(r.status).toBe(0);
+ expect(queueText()).not.toContain('scratch.txt');
+ expect(queueText()).not.toContain('learnings.jsonl');
+ const s = statusJson();
+ expect(s.message).toContain('1 unmatched dropped');
+ expect(s.message).toContain('1 missing dropped');
+ const drops = path.join(tmpHome, '.brain-sync-drops.json');
+ expect(fs.existsSync(drops)).toBe(true);
+ if (process.platform !== 'win32') {
+ expect(fs.statSync(drops).mode & 0o777).toBe(0o600);
+ }
+ const detail = JSON.parse(fs.readFileSync(drops, 'utf-8'));
+ expect(detail.dropped.unmatched).toContain('projects/p/scratch.txt');
+ expect(detail.dropped.missing).toContain('projects/p/learnings.jsonl');
+ });
+
+ test('an unparseable queue line is preserved, never destroyed', () => {
+ initWithMode('full');
+ fs.appendFileSync(path.join(tmpHome, '.brain-queue.jsonl'), 'not json at all\n');
+ const r = run(['gstack-brain-sync', '--once']);
+ expect(r.status).toBe(0);
+ expect(queueText()).toContain('not json at all');
+ });
+
+ test('surgical rewrite: a synced entry leaves the queue while a held sibling survives the same drain', () => {
+ // Proves the rewrite is a live filtered rewrite, not a truncation: two
+ // entries drain in one --once, one stages+pushes, one is mode-held.
+ initWithMode('artifacts-only');
+ fs.mkdirSync(path.join(tmpHome, 'projects', 'p'), { recursive: true });
+ fs.writeFileSync(path.join(tmpHome, 'projects/p/learnings.jsonl'), '{"skill":"x","insight":"y","ts":"2026-01-01T00:00:00Z"}\n');
+ fs.writeFileSync(path.join(tmpHome, 'projects/p/timeline.jsonl'), '{"skill":"x","event":"started"}\n');
+ run(['gstack-brain-enqueue', 'projects/p/learnings.jsonl']);
+ run(['gstack-brain-enqueue', 'projects/p/timeline.jsonl']);
+ const r = run(['gstack-brain-sync', '--once']);
+ expect(r.status).toBe(0);
+ expect(queueText()).not.toContain('learnings.jsonl'); // synced, removed
+ expect(queueText()).toContain('timeline.jsonl'); // held, retained
+ const log = spawnSync('git', ['--git-dir=' + bareRemote, 'log', '--oneline'], { encoding: 'utf-8' });
+ expect(log.stdout).toMatch(/sync: 1 file/);
+ });
+
+ test('push failure retains the commit locally and the run-start detector re-pushes it', () => {
+ initWithMode('full');
+ // Establish origin/main so the detector has a remote ref to compare.
+ fs.mkdirSync(path.join(tmpHome, 'projects', 'p'), { recursive: true });
+ fs.writeFileSync(path.join(tmpHome, 'projects/p/learnings.jsonl'), '{"skill":"a","ts":"2026-01-01T00:00:00Z"}\n');
+ run(['gstack-brain-enqueue', 'projects/p/learnings.jsonl']);
+ expect(run(['gstack-brain-sync', '--once']).status).toBe(0);
+
+ // Reject the next push at the remote (pre-receive hook exits 1 with an
+ // auth-shaped message so the auth branch is exercised too).
+ const hook = path.join(bareRemote, 'hooks', 'pre-receive');
+ fs.writeFileSync(hook, '#!/bin/sh\necho "403 forbidden" >&2\nexit 1\n');
+ fs.chmodSync(hook, 0o755);
+
+ fs.appendFileSync(path.join(tmpHome, 'projects/p/learnings.jsonl'), '{"skill":"b","ts":"2026-01-02T00:00:00Z"}\n');
+ run(['gstack-brain-enqueue', 'projects/p/learnings.jsonl']);
+ const fail = run(['gstack-brain-sync', '--once']);
+ expect(fail.status).toBe(0);
+ const s = statusJson();
+ expect(s.status).toBe('push_failed');
+ expect(s.message).toContain('commit retained locally');
+ // Drained path left the queue — it lives in the local commit now.
+ expect(queueText()).not.toContain('learnings.jsonl');
+ // The commit exists locally, ahead of origin.
+ const ahead = git(['rev-list', '--count', 'origin/main..HEAD']).stdout.trim();
+ expect(Number(ahead)).toBeGreaterThan(0);
+
+ // Remote healthy again: an EMPTY-queue run must still deliver the
+ // stranded commit (the detector, not the drain, pushes it).
+ fs.rmSync(hook);
+ const retry = run(['gstack-brain-sync', '--once']);
+ expect(retry.status).toBe(0);
+ const log = spawnSync('git', ['--git-dir=' + bareRemote, 'log', '--oneline'], { encoding: 'utf-8' });
+ expect(log.stdout).toMatch(/sync: 1 file/);
+ expect(git(['rev-list', '--count', 'origin/main..HEAD']).stdout.trim()).toBe('0');
+ });
+
+ test('receipt refusal at the detector skips the retry without wedging the drain', () => {
+ if (process.platform === 'win32' || process.getuid?.() === 0) return; // chmod advisory there
+ initWithMode('full');
+ fs.mkdirSync(path.join(tmpHome, 'projects', 'p'), { recursive: true });
+ fs.writeFileSync(path.join(tmpHome, 'projects/p/learnings.jsonl'), '{"skill":"a","ts":"2026-01-01T00:00:00Z"}\n');
+ run(['gstack-brain-enqueue', 'projects/p/learnings.jsonl']);
+ expect(run(['gstack-brain-sync', '--once']).status).toBe(0);
+
+ // Strand a commit: reject pushes, drain once.
+ const hook = path.join(bareRemote, 'hooks', 'pre-receive');
+ fs.writeFileSync(hook, '#!/bin/sh\nexit 1\n');
+ fs.chmodSync(hook, 0o755);
+ fs.appendFileSync(path.join(tmpHome, 'projects/p/learnings.jsonl'), '{"skill":"b","ts":"2026-01-02T00:00:00Z"}\n');
+ run(['gstack-brain-enqueue', 'projects/p/learnings.jsonl']);
+ expect(run(['gstack-brain-sync', '--once']).status).toBe(0);
+ fs.rmSync(hook);
+
+ // Break receipts. The detector's retry must be SKIPPED (no wedge), and
+ // the run must still exit 0 with nothing else to do.
+ fs.mkdirSync(path.join(tmpHome, 'security'), { recursive: true });
+ fs.chmodSync(path.join(tmpHome, 'security'), 0o500);
+ try {
+ const r = run(['gstack-brain-sync', '--once']);
+ expect(r.status).toBe(0);
+ // Commit still stranded (retry skipped, not attempted unreceipted).
+ expect(Number(git(['rev-list', '--count', 'origin/main..HEAD']).stdout.trim())).toBeGreaterThan(0);
+ } finally {
+ fs.chmodSync(path.join(tmpHome, 'security'), 0o700);
+ }
+
+ // Receipts healthy: detector delivers. The refused attempt above stamped
+ // the 10-minute throttle (deliberately — refusals must not busy-loop the
+ // network at every skill boundary), so model the interval passing.
+ fs.writeFileSync(path.join(tmpHome, '.brain-last-push-attempt'), '0');
+ expect(run(['gstack-brain-sync', '--once']).status).toBe(0);
+ expect(git(['rev-list', '--count', 'origin/main..HEAD']).stdout.trim()).toBe('0');
+ });
+
+ test('detector attempts are throttled to one per interval', () => {
+ initWithMode('full');
+ fs.mkdirSync(path.join(tmpHome, 'projects', 'p'), { recursive: true });
+ fs.writeFileSync(path.join(tmpHome, 'projects/p/learnings.jsonl'), '{"skill":"a","ts":"2026-01-01T00:00:00Z"}\n');
+ run(['gstack-brain-enqueue', 'projects/p/learnings.jsonl']);
+ expect(run(['gstack-brain-sync', '--once']).status).toBe(0);
+
+ // Strand a commit behind a rejecting remote.
+ const hook = path.join(bareRemote, 'hooks', 'pre-receive');
+ fs.writeFileSync(hook, '#!/bin/sh\nexit 1\n');
+ fs.chmodSync(hook, 0o755);
+ fs.appendFileSync(path.join(tmpHome, 'projects/p/learnings.jsonl'), '{"skill":"b","ts":"2026-01-02T00:00:00Z"}\n');
+ run(['gstack-brain-enqueue', 'projects/p/learnings.jsonl']);
+ expect(run(['gstack-brain-sync', '--once']).status).toBe(0);
+ fs.rmSync(hook);
+
+ // First empty-queue run: detector attempts (stamps the throttle), pushes.
+ expect(run(['gstack-brain-sync', '--once']).status).toBe(0);
+ const stamp1 = fs.readFileSync(path.join(tmpHome, '.brain-last-push-attempt'), 'utf-8');
+ expect(Number(stamp1)).toBeGreaterThan(0);
+ expect(git(['rev-list', '--count', 'origin/main..HEAD']).stdout.trim()).toBe('0');
+
+ // Strand another; an immediate second run must NOT attempt (stamp fresh).
+ fs.writeFileSync(hook, '#!/bin/sh\nexit 1\n');
+ fs.chmodSync(hook, 0o755);
+ fs.appendFileSync(path.join(tmpHome, 'projects/p/learnings.jsonl'), '{"skill":"c","ts":"2026-01-03T00:00:00Z"}\n');
+ run(['gstack-brain-enqueue', 'projects/p/learnings.jsonl']);
+ expect(run(['gstack-brain-sync', '--once']).status).toBe(0);
+ fs.rmSync(hook);
+ const stampBefore = fs.readFileSync(path.join(tmpHome, '.brain-last-push-attempt'), 'utf-8');
+ expect(run(['gstack-brain-sync', '--once']).status).toBe(0);
+ // Throttled: stamp unchanged, commit still stranded.
+ expect(fs.readFileSync(path.join(tmpHome, '.brain-last-push-attempt'), 'utf-8')).toBe(stampBefore);
+ expect(Number(git(['rev-list', '--count', 'origin/main..HEAD']).stdout.trim())).toBeGreaterThan(0);
+
+ // Interval passed: delivers.
+ fs.writeFileSync(path.join(tmpHome, '.brain-last-push-attempt'), '0');
+ expect(run(['gstack-brain-sync', '--once']).status).toBe(0);
+ expect(git(['rev-list', '--count', 'origin/main..HEAD']).stdout.trim()).toBe('0');
+ });
+
+ test('an interleaved user commit disables the detector push (exclusive author gate)', () => {
+ initWithMode('full');
+ fs.mkdirSync(path.join(tmpHome, 'projects', 'p'), { recursive: true });
+ fs.writeFileSync(path.join(tmpHome, 'projects/p/learnings.jsonl'), '{"skill":"a","ts":"2026-01-01T00:00:00Z"}\n');
+ run(['gstack-brain-enqueue', 'projects/p/learnings.jsonl']);
+ expect(run(['gstack-brain-sync', '--once']).status).toBe(0);
+
+ // Strand a bot commit behind a rejecting remote.
+ const hook = path.join(bareRemote, 'hooks', 'pre-receive');
+ fs.writeFileSync(hook, '#!/bin/sh\nexit 1\n');
+ fs.chmodSync(hook, 0o755);
+ fs.appendFileSync(path.join(tmpHome, 'projects/p/learnings.jsonl'), '{"skill":"b","ts":"2026-01-02T00:00:00Z"}\n');
+ run(['gstack-brain-enqueue', 'projects/p/learnings.jsonl']);
+ expect(run(['gstack-brain-sync', '--once']).status).toBe(0);
+ fs.rmSync(hook);
+
+ // A user manually commits in ~/.gstack on top of the stranded bot commit.
+ expect(git(['-c', 'user.name=Garry', '-c', '[email protected]',
+ '-c', 'commit.gpgsign=false',
+ 'commit', '--allow-empty', '-m', 'manual note']).status).toBe(0);
+
+ // Interval passed, remote healthy, queue empty: the detector must STILL
+ // refuse — `push origin HEAD` would publish the user's commit uninvited.
+ fs.writeFileSync(path.join(tmpHome, '.brain-last-push-attempt'), '0');
+ expect(run(['gstack-brain-sync', '--once']).status).toBe(0);
+ expect(Number(git(['rev-list', '--count', 'origin/main..HEAD']).stdout.trim())).toBe(2);
+
+ // A REAL drain still rides the user commit along, as before — the gate
+ // scopes only the detector's autonomous retry, not user-initiated syncs.
+ fs.appendFileSync(path.join(tmpHome, 'projects/p/learnings.jsonl'), '{"skill":"c","ts":"2026-01-03T00:00:00Z"}\n');
+ run(['gstack-brain-enqueue', 'projects/p/learnings.jsonl']);
+ expect(run(['gstack-brain-sync', '--once']).status).toBe(0);
+ expect(git(['rev-list', '--count', 'origin/main..HEAD']).stdout.trim()).toBe('0');
+ });
+});
diff --git a/test/branch-slug-hygiene.test.ts b/test/branch-slug-hygiene.test.ts
new file mode 100644
index 000000000..58c7cccaf
--- /dev/null
+++ b/test/branch-slug-hygiene.test.ts
@@ -0,0 +1,134 @@
+/**
+ * Branch-name slug hygiene in file-path positions (#2550, #1851/#1127).
+ *
+ * gstack-review-log WRITES `<canonical-branch>-reviews.jsonl` where the
+ * canonical form comes from bin/gstack-slug (tr '/' '-' then
+ * tr -cd 'a-zA-Z0-9._-'). Context Recovery used to PROBE the same file with
+ * raw $_BRANCH (`git branch --show-current`) — so for any branch containing
+ * a `/` (most feature branches) the REVIEWS line never fired. Same class:
+ * review.ts's plan content-search sanitized with tr '/' '-' only, missing
+ * the tr -cd half of the canonical pipeline.
+ *
+ * Discipline pinned here:
+ * - FILE-PATH positions interpolate the slug-canonical $BRANCH (set by the
+ * gstack-slug eval that opens Context Recovery).
+ * - Raw $_BRANCH stays for display (BRANCH: echo) and for timeline.jsonl
+ * content greps — the timeline writer stores the RAW branch, so slugging
+ * the reader would break that pairing.
+ *
+ * Reader-side fix folded from community PR #1851 by @harjothkhara.
+ */
+import { describe, test, expect } from 'bun:test';
+import { execSync } from 'child_process';
+import * as fs from 'fs';
+import * as os from 'os';
+import * as path from 'path';
+import { HOST_PATHS } from '../scripts/resolvers/types';
+import type { TemplateContext } from '../scripts/resolvers/types';
+import { generateContextRecovery } from '../scripts/resolvers/preamble/generate-context-recovery';
+
+const ROOT = path.join(import.meta.dir, '..');
+
+// Raw $_BRANCH (either spelling) immediately before/after a path separator.
+const PATH_ADJACENT = /\/\$\{?_BRANCH|\$\{_BRANCH\}\/|\$_BRANCH\//;
+// Raw $_BRANCH as a filename prefix (…-reviews.jsonl and friends).
+const FILENAME_PREFIX = /\$\{?_BRANCH\}?[A-Za-z0-9._-]*\.(?:jsonl|json|md|txt|log)/;
+
+function renderedSkillFiles(): string[] {
+ const out = execSync(
+ `find "${ROOT}" -name 'SKILL.md' -not -path '*/node_modules/*' -not -path '*/.claude/*' ; find "${ROOT}" -path '*/sections/*.md' -not -path '*/node_modules/*' -not -path '*/.claude/*'`,
+ { encoding: 'utf-8' },
+ );
+ return out.split('\n').filter(Boolean);
+}
+
+describe('branch slug hygiene (#2550, #1851)', () => {
+ test('no generated SKILL.md or section interpolates raw $_BRANCH in a path position', () => {
+ const offenders: string[] = [];
+ for (const file of renderedSkillFiles()) {
+ const content = fs.readFileSync(file, 'utf-8');
+ if (PATH_ADJACENT.test(content) || FILENAME_PREFIX.test(content)) {
+ offenders.push(path.relative(ROOT, file));
+ }
+ }
+ expect(offenders).toEqual([]);
+ });
+
+ test('Context Recovery probes reviews.jsonl with the slug-canonical $BRANCH', () => {
+ const ctx: TemplateContext = {
+ skillName: 'test-skill',
+ tmplPath: 'test.tmpl',
+ host: 'claude',
+ paths: HOST_PATHS.claude,
+ preambleTier: 2,
+ };
+ const out = generateContextRecovery(ctx);
+ expect(out).toContain('${BRANCH:-unknown}-reviews.jsonl');
+ expect(out).not.toContain('${_BRANCH}-reviews.jsonl');
+ // The gstack-slug eval that defines $BRANCH must render BEFORE the probe.
+ const evalIdx = out.indexOf('gstack-slug');
+ const probeIdx = out.indexOf('${BRANCH:-unknown}-reviews.jsonl');
+ expect(evalIdx).toBeGreaterThan(-1);
+ expect(evalIdx).toBeLessThan(probeIdx);
+ // Raw $_BRANCH stays for the timeline.jsonl content greps (writer stores raw).
+ expect(out).toContain('"branch\\":\\"${_BRANCH}');
+ });
+
+ test('plan content-search BRANCH uses the full gstack-slug canonical pipeline', () => {
+ const rendered = fs.readFileSync(
+ path.join(ROOT, 'ship', 'sections', 'plan-completion.md'),
+ 'utf-8',
+ );
+ expect(rendered).toContain(
+ `BRANCH=$(git branch --show-current 2>/dev/null | tr '/' '-' | tr -cd 'a-zA-Z0-9._-')`,
+ );
+ });
+
+ test('live round-trip: gstack-review-log writes, Context Recovery probe finds it (slash branch)', () => {
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-home-'));
+ const repo = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-repo-'));
+ try {
+ const env = { ...process.env, GSTACK_HOME: home };
+ execSync(
+ 'git init -q && git -c user.email=t@t -c user.name=t commit -q --allow-empty -m init && git checkout -q -b feat/slug-hygiene',
+ { cwd: repo, encoding: 'utf-8' },
+ );
+
+ // Writer: the real gstack-review-log (canonicalizes via gstack-slug).
+ execSync(
+ `"${path.join(ROOT, 'bin', 'gstack-review-log')}" '{"skill":"ship","status":"ok"}'`,
+ { cwd: repo, env, encoding: 'utf-8' },
+ );
+
+ // The slug-canonical filename must exist; the raw form must not.
+ const slugVars = execSync(`"${path.join(ROOT, 'bin', 'gstack-slug')}"`, {
+ cwd: repo, env, encoding: 'utf-8',
+ });
+ const slug = slugVars.match(/^SLUG=(.*)$/m)![1];
+ const branch = slugVars.match(/^BRANCH=(.*)$/m)![1];
+ expect(branch).toBe('feat-slug-hygiene');
+ const proj = path.join(home, 'projects', slug);
+ expect(fs.existsSync(path.join(proj, 'feat-slug-hygiene-reviews.jsonl'))).toBe(true);
+
+ // Reader: execute the rendered probe line with $BRANCH from gstack-slug.
+ const ctx: TemplateContext = {
+ skillName: 'test-skill', tmplPath: 'test.tmpl', host: 'claude',
+ paths: HOST_PATHS.claude, preambleTier: 2,
+ };
+ const probeLine = generateContextRecovery(ctx)
+ .split('\n')
+ .find((l) => l.includes('-reviews.jsonl'))!;
+ const script = `_PROJ="${proj}"\nBRANCH="${branch}"\n${probeLine.trim()}`;
+ const out = execSync(`bash -c '${script.replace(/'/g, `'\\''`)}'`, {
+ cwd: repo, encoding: 'utf-8',
+ });
+ expect(out).toContain('REVIEWS: 1 entries');
+
+ // Negative control: the raw-branch probe (the pre-fix shape) misses.
+ expect(fs.existsSync(path.join(proj, 'feat/slug-hygiene-reviews.jsonl'))).toBe(false);
+ } finally {
+ fs.rmSync(home, { recursive: true, force: true });
+ fs.rmSync(repo, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/test/build-gbrain-env.test.ts b/test/build-gbrain-env.test.ts
index 46403ba41..d97e3a8d2 100644
--- a/test/build-gbrain-env.test.ts
+++ b/test/build-gbrain-env.test.ts
@@ -77,17 +77,34 @@ describe("buildGbrainEnv", () => {
expect(result.DATABASE_URL).toBe("postgresql://app/db");
});
- it("honors GBRAIN_HOME when set (config aligned with detectEngineTier)", () => {
- // Move the config to an alternate dir; set GBRAIN_HOME to point at it.
+ it("honors GBRAIN_HOME when set, with gbrain's parent-dir semantics (#2521)", () => {
+ // Move the config to an alternate dir; set GBRAIN_HOME to point at its
+ // PARENT — gbrain's configDir() appends `.gbrain` itself, so
+ // GBRAIN_HOME=/x reads /x/.gbrain/config.json.
const altGbrainHome = join(home, "alt-gbrain");
- mkdirSync(altGbrainHome, { recursive: true });
- writeFileSync(join(altGbrainHome, "config.json"), JSON.stringify({ database_url: "postgresql://alt/db" }));
+ mkdirSync(join(altGbrainHome, ".gbrain"), { recursive: true });
+ writeFileSync(
+ join(altGbrainHome, ".gbrain", "config.json"),
+ JSON.stringify({ database_url: "postgresql://alt/db" }),
+ );
// No file at the default ~/.gbrain location.
const baseEnv = { HOME: home, GBRAIN_HOME: altGbrainHome };
const result = buildGbrainEnv({ baseEnv });
expect(result.DATABASE_URL).toBe("postgresql://alt/db");
});
+ it("ignores a config at $GBRAIN_HOME/config.json — gbrain never reads that file (#2521)", () => {
+ const altGbrainHome = join(home, "alt-gbrain-flat");
+ mkdirSync(altGbrainHome, { recursive: true });
+ writeFileSync(
+ join(altGbrainHome, "config.json"),
+ JSON.stringify({ database_url: "postgresql://alt/db" }),
+ );
+ const baseEnv = { HOME: home, GBRAIN_HOME: altGbrainHome };
+ const result = buildGbrainEnv({ baseEnv });
+ expect(result.DATABASE_URL).toBeUndefined();
+ });
+
it("returns a fresh env object — never the caller's env by identity", () => {
// Codex review #11: object-identity equality lets later mutation of the
// returned env leak back into the caller's view. The helper MUST clone.
diff --git a/test/catalog-trim.test.ts b/test/catalog-trim.test.ts
index 6ff8cb4dd..79380c341 100644
--- a/test/catalog-trim.test.ts
+++ b/test/catalog-trim.test.ts
@@ -23,8 +23,37 @@ import {
buildTrimmedDescription,
buildWhenToInvokeSection,
applyCatalogTrim,
+ toYamlInlineScalar,
} from '../scripts/gen-skill-docs';
+describe('toYamlInlineScalar', () => {
+ const parses = (out: string) => Bun.YAML.parse(`d: ${out}`);
+
+ test("scalar containing '...' (YAML document-end marker) is quoted and round-trips", () => {
+ const out = toYamlInlineScalar('Truncated lead ends with... more (gstack)');
+ expect(out.startsWith('"')).toBe(true);
+ expect((parses(out) as { d: string }).d).toContain('...');
+ });
+
+ test("interior ': ' is quoted (nested-mapping ambiguity, #1778)", () => {
+ const out = toYamlInlineScalar('Ship workflow: detect and merge');
+ expect(out.startsWith('"')).toBe(true);
+ expect((parses(out) as { d: string }).d).toBe('Ship workflow: detect and merge');
+ });
+
+ test('plain safe scalar passes through unquoted', () => {
+ expect(toYamlInlineScalar('Simple description here')).toBe('Simple description here');
+ });
+
+ test('leading YAML indicator char is quoted', () => {
+ expect(toYamlInlineScalar('- leading dash').startsWith('"')).toBe(true);
+ });
+
+ test('trailing whitespace is quoted', () => {
+ expect(toYamlInlineScalar('has trailing space ').startsWith('"')).toBe(true);
+ });
+});
+
describe('splitCatalogDescription', () => {
test('extracts lead sentence + routing prose from simple multi-line description', () => {
const desc =
diff --git a/test/code-intelligence.test.ts b/test/code-intelligence.test.ts
index aac388f71..8d9705f32 100644
--- a/test/code-intelligence.test.ts
+++ b/test/code-intelligence.test.ts
@@ -953,7 +953,9 @@ exit 1
...process.env,
GSTACK_HOME: home,
HOME: home,
- GBRAIN_HOME: gbrainHome,
+ // #2521: GBRAIN_HOME is the PARENT of .gbrain per gbrain's configDir()
+ // contract — pointing it at `home` resolves to home/.gbrain/config.json.
+ GBRAIN_HOME: home,
PATH: `${shimDir}:${process.env.PATH}`,
// Dead loopback port → the Sourcebot probe fails fast + deterministically
// (connection refused) instead of poking whatever operator dev server
diff --git a/test/codex-hardening.test.ts b/test/codex-hardening.test.ts
index ade705a55..3c7600a58 100644
--- a/test/codex-hardening.test.ts
+++ b/test/codex-hardening.test.ts
@@ -287,6 +287,29 @@ describe('gstack-codex-probe: timeout wrapper + namespace hygiene', () => {
}
});
+ test('bash-native watchdog kills a hung command at the deadline (exit 124, no timeout binary)', () => {
+ // Stock macOS ships neither gtimeout nor timeout(1) — the old fallback ran
+ // the command unwrapped, so a hung `codex exec` blocked the calling
+ // workflow forever. Force the fallback everywhere (Linux /bin has timeout
+ // via usrmerge) with a PATH holding ONLY bash and sleep, then prove a
+ // 30s sleep dies at the 1s deadline with timeout(1)'s exit code. The
+ // runProbe 5s spawnSync cap doubles as the "actually killed fast" bound.
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-watchdog-'));
+ try {
+ const which = (tool: string) =>
+ spawnSync('bash', ['-c', `command -v ${tool}`]).stdout.toString().trim() || `/bin/${tool}`;
+ fs.symlinkSync(which('bash'), path.join(dir, 'bash'));
+ fs.symlinkSync(which('sleep'), path.join(dir, 'sleep'));
+ const r = runProbe({
+ snippet: `_gstack_codex_timeout_wrapper 1 sleep 30; echo "rc=$?"`,
+ env: { PATH: dir },
+ });
+ expect(r.stdout).toContain('rc=124');
+ } finally {
+ fs.rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
test('sourcing probe does NOT set errexit/trap/IFS in caller shell (namespace hygiene)', () => {
// Capture `set -o` output before and after sourcing. Any drift means the
// probe polluted the caller.
diff --git a/test/codex-model-probe.test.ts b/test/codex-model-probe.test.ts
new file mode 100644
index 000000000..5d4b89981
--- /dev/null
+++ b/test/codex-model-probe.test.ts
@@ -0,0 +1,219 @@
+/**
+ * _gstack_codex_model_probe — round-trip model readiness (#2477).
+ *
+ * The auth probe accepts "auth exists" as readiness, but a ChatGPT account
+ * with a stale `model = "..."` pin in ~/.codex/config.toml passes auth and
+ * then dies with an HTTP 400 on every invocation. The model probe does one
+ * short `codex exec "reply OK"` round trip with the configured model.
+ *
+ * Contract pinned here (all runs use a STUBBED codex binary):
+ * - exit 0 -> MODEL_OK, result cached (1h TTL + config/auth
+ * mtime signature), second call does NOT re-invoke
+ * - model 400 output -> MODEL_UNUSABLE (exit 1) + config.toml HINT lines,
+ * negative-cached 15 min (same exit-1 + hints from
+ * cache; re-probing every preflight charged the
+ * affected user 30s + real tokens per section)
+ * - transient failure -> MODEL_PROBE_INCONCLUSIVE, FAIL-OPEN (exit 0),
+ * never cached
+ * - config.toml mtime change invalidates a cached MODEL_OK and a cached
+ * MODEL_UNUSABLE (editing the pin IS the fix)
+ */
+import { describe, test, expect } from 'bun:test';
+import { spawnSync } from 'child_process';
+import * as fs from 'fs';
+import * as os from 'os';
+import * as path from 'path';
+
+const ROOT = path.resolve(import.meta.dir, '..');
+const PROBE = path.join(ROOT, 'bin', 'gstack-codex-probe');
+
+const STUB = `#!/usr/bin/env bash
+echo "invoked" >> "$STUB_LOG"
+case "\${STUB_MODE:-ok}" in
+ ok) echo "OK"; exit 0 ;;
+ model400)
+ echo 'warning: Model metadata for \`gpt-5.4\` not found.' >&2
+ echo 'ERROR: {"type":"error","status":400,"error":{"type":"invalid_request_error","message":"The '"'"'gpt-5.4'"'"' model is not supported when using Codex with a ChatGPT account."}}' >&2
+ exit 1 ;;
+ transient) echo "stream error: network unreachable" >&2; exit 7 ;;
+esac
+`;
+
+interface Fixture {
+ home: string;
+ stubDir: string;
+ codexHome: string;
+ gstackHome: string;
+ stubLog: string;
+}
+
+function makeFixture(): Fixture {
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-model-probe-'));
+ const stubDir = path.join(home, 'stub-bin');
+ const codexHome = path.join(home, '.codex');
+ const gstackHome = path.join(home, '.gstack');
+ fs.mkdirSync(stubDir, { recursive: true });
+ fs.mkdirSync(codexHome, { recursive: true });
+ fs.mkdirSync(gstackHome, { recursive: true });
+ fs.writeFileSync(path.join(stubDir, 'codex'), STUB, { mode: 0o755 });
+ fs.writeFileSync(path.join(codexHome, 'config.toml'), 'model = "gpt-5.4"\n');
+ fs.writeFileSync(path.join(codexHome, 'auth.json'), '{}');
+ const stubLog = path.join(home, 'stub.log');
+ return { home, stubDir, codexHome, gstackHome, stubLog };
+}
+
+function runProbe(f: Fixture, stubMode: string): { stdout: string; status: number } {
+ const result = spawnSync(
+ 'bash',
+ ['-c', `set +e\nsource "${PROBE}"\n_gstack_codex_model_probe`],
+ {
+ env: {
+ PATH: `${f.stubDir}:${process.env.PATH ?? ''}`,
+ HOME: f.home,
+ CODEX_HOME: f.codexHome,
+ GSTACK_HOME: f.gstackHome,
+ STUB_MODE: stubMode,
+ STUB_LOG: f.stubLog,
+ _TEL: 'off',
+ },
+ timeout: 10000,
+ },
+ );
+ return { stdout: (result.stdout ?? '').toString(), status: result.status ?? -1 };
+}
+
+function invocations(f: Fixture): number {
+ try {
+ return fs.readFileSync(f.stubLog, 'utf-8').split('\n').filter(Boolean).length;
+ } catch {
+ return 0;
+ }
+}
+
+describe('codex model probe (#2477)', () => {
+ test('successful round trip -> MODEL_OK, cached, no re-invocation', () => {
+ const f = makeFixture();
+ try {
+ const first = runProbe(f, 'ok');
+ expect(first.stdout.trim()).toBe('MODEL_OK');
+ expect(first.status).toBe(0);
+ expect(invocations(f)).toBe(1);
+ expect(fs.existsSync(path.join(f.gstackHome, '.codex-model-probe'))).toBe(true);
+
+ const second = runProbe(f, 'ok');
+ expect(second.stdout.trim()).toBe('MODEL_OK (cached)');
+ expect(second.status).toBe(0);
+ expect(invocations(f)).toBe(1); // cache hit: stub not re-invoked
+ } finally {
+ fs.rmSync(f.home, { recursive: true, force: true });
+ }
+ });
+
+ test('model 400 -> MODEL_UNUSABLE with config.toml hints, exit 1, negative-cached', () => {
+ const f = makeFixture();
+ try {
+ const r = runProbe(f, 'model400');
+ expect(r.stdout).toContain('MODEL_UNUSABLE');
+ expect(r.stdout).toContain('config.toml');
+ expect(r.stdout).toContain('model_migrations');
+ // Surfaces the actual rejection so the user sees WHICH model.
+ expect(r.stdout).toContain('gpt-5.4');
+ expect(r.status).toBe(1);
+ // The deterministic 400 is config-driven: re-probing every preflight
+ // charged the user a 30s round trip + real tokens per review section.
+ // A second run within the 15-min TTL must NOT re-invoke codex, and must
+ // keep the exit-1 + hints contract so callers can't tell the difference.
+ expect(invocations(f)).toBe(1);
+ const second = runProbe(f, 'model400');
+ expect(second.stdout).toContain('MODEL_UNUSABLE (cached)');
+ expect(second.stdout).toContain('config.toml');
+ expect(second.status).toBe(1);
+ expect(invocations(f)).toBe(1);
+ } finally {
+ fs.rmSync(f.home, { recursive: true, force: true });
+ }
+ });
+
+ test('config.toml change re-probes past a cached MODEL_UNUSABLE (the recovery path)', () => {
+ const f = makeFixture();
+ try {
+ runProbe(f, 'model400');
+ expect(invocations(f)).toBe(1);
+ // Fixing the model pin changes the mtime signature — the negative cache
+ // must not outlive the config it condemned.
+ fs.writeFileSync(path.join(f.codexHome, 'config.toml'), 'model = "gpt-5.5"\n');
+ const future = Date.now() / 1000 + 10;
+ fs.utimesSync(path.join(f.codexHome, 'config.toml'), future, future);
+ const r = runProbe(f, 'ok');
+ expect(r.stdout.trim()).toBe('MODEL_OK');
+ expect(r.status).toBe(0);
+ expect(invocations(f)).toBe(2);
+ } finally {
+ fs.rmSync(f.home, { recursive: true, force: true });
+ }
+ });
+
+ test('transient failure -> inconclusive, FAIL-OPEN exit 0', () => {
+ const f = makeFixture();
+ try {
+ const r = runProbe(f, 'transient');
+ expect(r.stdout).toContain('MODEL_PROBE_INCONCLUSIVE');
+ expect(r.status).toBe(0);
+ } finally {
+ fs.rmSync(f.home, { recursive: true, force: true });
+ }
+ });
+
+ test('TTL expiry: a cached MODEL_OK older than 3600s re-probes (T5)', () => {
+ const f = makeFixture();
+ try {
+ runProbe(f, 'ok');
+ expect(invocations(f)).toBe(1);
+ // Backdate the cache line's timestamp past the 1h TTL, keeping the
+ // signature valid — TTL alone must force the re-probe.
+ const cachePath = path.join(f.gstackHome, '.codex-model-probe');
+ const [status, ts, sig] = fs.readFileSync(cachePath, 'utf-8').trim().split(' ');
+ expect(status).toBe('MODEL_OK');
+ fs.writeFileSync(cachePath, `MODEL_OK ${Number(ts) - 3700} ${sig}\n`);
+ const r = runProbe(f, 'ok');
+ expect(r.stdout.trim()).toBe('MODEL_OK'); // not "(cached)"
+ expect(invocations(f)).toBe(2); // re-probed
+ } finally {
+ fs.rmSync(f.home, { recursive: true, force: true });
+ }
+ });
+
+ test('auth.json mtime change invalidates the cached MODEL_OK (T5: re-login re-probes)', () => {
+ const f = makeFixture();
+ try {
+ runProbe(f, 'ok');
+ expect(invocations(f)).toBe(1);
+ // A re-login rewrites auth.json; the mtime signature must invalidate
+ // the cache even though config.toml is untouched.
+ const future = Date.now() / 1000 + 10;
+ fs.utimesSync(path.join(f.codexHome, 'auth.json'), future, future);
+ const r = runProbe(f, 'ok');
+ expect(r.stdout.trim()).toBe('MODEL_OK');
+ expect(invocations(f)).toBe(2); // re-probed
+ } finally {
+ fs.rmSync(f.home, { recursive: true, force: true });
+ }
+ });
+
+ test('config.toml change invalidates the cached MODEL_OK', () => {
+ const f = makeFixture();
+ try {
+ runProbe(f, 'ok');
+ expect(invocations(f)).toBe(1);
+ // Change the model pin; mtime signature must invalidate the cache.
+ fs.writeFileSync(path.join(f.codexHome, 'config.toml'), 'model = "gpt-5.5"\n');
+ const future = Date.now() / 1000 + 10;
+ fs.utimesSync(path.join(f.codexHome, 'config.toml'), future, future);
+ const r = runProbe(f, 'ok');
+ expect(r.stdout.trim()).toBe('MODEL_OK');
+ expect(invocations(f)).toBe(2); // re-probed
+ } finally {
+ fs.rmSync(f.home, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/test/codex-under-codex-detection.test.ts b/test/codex-under-codex-detection.test.ts
new file mode 100644
index 000000000..b2428244e
--- /dev/null
+++ b/test/codex-under-codex-detection.test.ts
@@ -0,0 +1,104 @@
+/**
+ * Running-under-Codex detection (#2519, maintainer decision 7).
+ *
+ * /review executed inside a Codex host used to spawn nested codex
+ * specialists — the same model reviewing itself at multiplied token cost
+ * (observed: 15M tokens for one /review). A live Codex session exports
+ * CODEX_THREAD_ID / CODEX_SANDBOX into every shell it spawns (verified
+ * against a live `codex exec 'env | grep -i codex'` capture on codex
+ * 0.147.0: CODEX_THREAD_ID, CODEX_SANDBOX=seatbelt,
+ * CODEX_SANDBOX_NETWORK_DISABLED=1, CODEX_CI=1). The shared codexPreflight
+ * presence-probes those vars and yields CODEX_MODE=under_codex, skipping
+ * nested spawns with a one-line notice; GSTACK_FORCE_CODEX_REVIEW=1
+ * overrides.
+ */
+import { describe, test, expect } from 'bun:test';
+import { spawnSync } from 'child_process';
+import * as fs from 'fs';
+import * as path from 'path';
+import { codexPreflight } from '../scripts/resolvers/constants';
+
+const ROOT = path.resolve(import.meta.dir, '..');
+
+/** Extract the runnable bash from the rendered preflight (strip fences/prose). */
+function preflightBash(): string {
+ const rendered = codexPreflight({ disabledBehavior: 'codex-only' });
+ const start = rendered.indexOf('```bash') + '```bash'.length;
+ const end = rendered.indexOf('```', start);
+ return rendered.slice(start, end);
+}
+
+function runPreflight(env: Record<string, string>): string {
+ const result = spawnSync('bash', ['-c', `set +e\n${preflightBash()}`], {
+ env: {
+ // Minimal PATH without codex so the not_installed branch is reachable
+ // and no real gstack-config/codex runs. The block's fallbacks
+ // (`|| echo enabled`) keep it self-contained.
+ PATH: '/usr/bin:/bin',
+ HOME: '/nonexistent-home',
+ ...env,
+ },
+ timeout: 10000,
+ });
+ return (result.stdout ?? '').toString();
+}
+
+describe('under-codex detection bash (#2519)', () => {
+ test('CODEX_THREAD_ID present -> under_codex', () => {
+ const out = runPreflight({ CODEX_THREAD_ID: '01a00ba9-ff91-7143-b424-c2d9b0cc89ff' });
+ expect(out).toContain('CODEX_MODE: under_codex');
+ });
+
+ test('CODEX_SANDBOX present (no thread id) -> under_codex', () => {
+ const out = runPreflight({ CODEX_SANDBOX: 'seatbelt' });
+ expect(out).toContain('CODEX_MODE: under_codex');
+ });
+
+ test('GSTACK_FORCE_CODEX_REVIEW=1 overrides the presence probe', () => {
+ const out = runPreflight({
+ CODEX_THREAD_ID: '01a00ba9-ff91-7143-b424-c2d9b0cc89ff',
+ CODEX_SANDBOX: 'seatbelt',
+ GSTACK_FORCE_CODEX_REVIEW: '1',
+ });
+ expect(out).not.toContain('CODEX_MODE: under_codex');
+ // With codex absent from the restricted PATH, the forced probe falls
+ // through to the ordinary availability chain.
+ expect(out).toContain('CODEX_MODE: not_installed');
+ });
+
+ test('no CODEX_* env -> ordinary availability chain', () => {
+ const out = runPreflight({});
+ expect(out).not.toContain('CODEX_MODE: under_codex');
+ expect(out).toContain('CODEX_MODE: not_installed');
+ });
+});
+
+describe('under-codex wiring renders (#2519)', () => {
+ test('rendered adversarial section carries the probe + override + notice', () => {
+ const rendered = fs.readFileSync(
+ path.join(ROOT, 'ship', 'sections', 'adversarial.md'),
+ 'utf-8',
+ );
+ expect(rendered).toContain('CODEX_THREAD_ID');
+ expect(rendered).toContain('GSTACK_FORCE_CODEX_REVIEW');
+ expect(rendered).toContain('under_codex');
+ expect(rendered).toContain('nested codex passes skipped');
+ });
+
+ test('rendered codex skill stops with the one-line notice when under codex', () => {
+ const rendered = fs.readFileSync(path.join(ROOT, 'codex', 'SKILL.md'), 'utf-8');
+ expect(rendered).toContain('UNDER_CODEX');
+ expect(rendered).toContain('GSTACK_FORCE_CODEX_REVIEW=1');
+ });
+
+ test('all three codexPreflight consumers render the probe', () => {
+ for (const file of [
+ path.join(ROOT, 'ship', 'sections', 'adversarial.md'),
+ path.join(ROOT, 'plan-ceo-review', 'sections', 'review-sections.md'),
+ path.join(ROOT, 'document-release', 'sections', 'release-body.md'),
+ ]) {
+ const rendered = fs.readFileSync(file, 'utf-8');
+ expect(rendered).toContain('under_codex');
+ }
+ });
+});
diff --git a/test/codex-web-search-flag.test.ts b/test/codex-web-search-flag.test.ts
new file mode 100644
index 000000000..7e13ea607
--- /dev/null
+++ b/test/codex-web-search-flag.test.ts
@@ -0,0 +1,65 @@
+/**
+ * Deprecated codex web-search flag tripwire (#2525).
+ *
+ * codex >=0.144 deprecates `--enable web_search_cached` (its `--enable
+ * <FEATURE>` surface now means `-c features.<name>=true`); the replacement
+ * is `-c 'web_search="cached"'`, owned by ONE constant:
+ * CODEX_WEB_SEARCH_FLAG in scripts/resolvers/constants.ts. Resolvers
+ * interpolate it; templates reference {{CODEX_WEB_SEARCH_FLAG}}.
+ *
+ * These tests fail CI if the deprecated spelling re-enters any source
+ * (resolver, template, helper) or any rendered SKILL.md / section / golden.
+ */
+import { describe, test, expect } from 'bun:test';
+import { execSync } from 'child_process';
+import * as fs from 'fs';
+import * as path from 'path';
+import { CODEX_WEB_SEARCH_FLAG } from '../scripts/resolvers/constants';
+
+const ROOT = path.join(import.meta.dir, '..');
+const DEPRECATED = '--enable web_search_cached';
+
+function grepRepo(pattern: string, includes: string[]): string[] {
+ const includeArgs = includes.map((i) => `--include='${i}'`).join(' ');
+ const out = execSync(
+ `grep -rln ${includeArgs} -e '${pattern}' "${ROOT}" || true`,
+ { encoding: 'utf-8' },
+ );
+ return out
+ .split('\n')
+ .filter(Boolean)
+ .filter((f) => !f.includes('node_modules'))
+ // The workspace-local .claude/ install is not generated output and can
+ // carry dangling symlinks from unrelated sessions.
+ .filter((f) => !f.includes('/.claude/'))
+ .filter((f) => !f.endsWith('test/codex-web-search-flag.test.ts'));
+}
+
+describe('deprecated codex web-search flag is gone (#2525)', () => {
+ test('the replacement flag has exactly the documented shape', () => {
+ expect(CODEX_WEB_SEARCH_FLAG).toBe(`-c 'web_search="cached"'`);
+ });
+
+ test('no rendered SKILL.md or section carries the deprecated flag', () => {
+ const hits = grepRepo(DEPRECATED, ['SKILL.md', '*.md']);
+ expect(hits).toEqual([]);
+ });
+
+ test('no source file (resolver, template, helper) carries the deprecated flag', () => {
+ const hits = grepRepo(DEPRECATED, ['*.ts', '*.tmpl']);
+ expect(hits).toEqual([]);
+ });
+
+ test('rendered codex skill actually resolves the token to the live flag', () => {
+ const rendered = fs.readFileSync(path.join(ROOT, 'codex', 'SKILL.md'), 'utf-8');
+ expect(rendered).toContain(CODEX_WEB_SEARCH_FLAG);
+ expect(rendered).not.toContain('{{CODEX_WEB_SEARCH_FLAG}}');
+ });
+
+ test('rendered autoplan skill resolves the token at every inline site', () => {
+ const rendered = fs.readFileSync(path.join(ROOT, 'autoplan', 'SKILL.md'), 'utf-8');
+ const count = rendered.split(CODEX_WEB_SEARCH_FLAG).length - 1;
+ expect(count).toBeGreaterThanOrEqual(4);
+ expect(rendered).not.toContain('{{CODEX_WEB_SEARCH_FLAG}}');
+ });
+});
diff --git a/test/diff-scope.test.ts b/test/diff-scope.test.ts
index 3e80fe451..6b4104451 100644
--- a/test/diff-scope.test.ts
+++ b/test/diff-scope.test.ts
@@ -178,3 +178,160 @@ describe('gstack-diff-scope', () => {
expect(scope).toHaveProperty('SCOPE_AUTH');
});
});
+
+// ---------------------------------------------------------------------------
+// #2526 / #2455 / #2299 — glob classes, exit-code contract, dirty-tree union,
+// independent categories.
+// ---------------------------------------------------------------------------
+
+function runScopeFull(dir: string): { vars: Record<string, string>; status: number; stdout: string } {
+ const result = spawnSync('bash', [SCRIPT, 'main'], {
+ cwd: dir, stdio: 'pipe', timeout: 5000,
+ });
+ const stdout = result.stdout.toString();
+ const vars: Record<string, string> = {};
+ for (const line of stdout.trim().split('\n')) {
+ if (line.startsWith('#')) continue;
+ const [key, val] = line.split('=');
+ if (key && val) vars[key] = val;
+ }
+ return { vars, status: result.status ?? -1, stdout };
+}
+
+describe('glob classes (table-driven, #2526 + #2455)', () => {
+ // One row per glob class the case arms cover. `expects` lists every scope
+ // that MUST be true; categories are independent (#2299), so extra true
+ // flags beyond `expects` are asserted per-row via `alsoFalse`.
+ const TABLE: { name: string; file: string; expects: string[]; alsoFalse?: string[] }[] = [
+ // API — the #2526 headline: root-level api/ (Vercel/serverless layout).
+ { name: 'root-level api/ (#2526)', file: 'api/ipospays/process-payment.ts', expects: ['SCOPE_API', 'SCOPE_BACKEND'] },
+ { name: 'nested */api/*', file: 'src/api/foo.ts', expects: ['SCOPE_API', 'SCOPE_BACKEND'] },
+ { name: 'controller name', file: 'app/controllers/users_controller.rb', expects: ['SCOPE_API', 'SCOPE_BACKEND'] },
+ { name: 'openapi schema', file: 'openapi.yaml', expects: ['SCOPE_API', 'SCOPE_CONFIG'] },
+ // Migrations — root-level migrations/ + the data_migrate gem's db/data (#2455).
+ { name: 'root-level migrations/ (#2526)', file: 'migrations/0001_initial.sql', expects: ['SCOPE_MIGRATIONS'] },
+ { name: 'nested */migrations/*', file: 'app/migrations/0001_initial.py', expects: ['SCOPE_MIGRATIONS', 'SCOPE_BACKEND'] },
+ {
+ name: 'db/data data migration (#2455) — MIGRATIONS and BACKEND both',
+ file: 'db/data/20260804123456_backfill_x.rb',
+ expects: ['SCOPE_MIGRATIONS', 'SCOPE_BACKEND'],
+ },
+ { name: 'data_migrations/ dir', file: 'data_migrations/backfill.rb', expects: ['SCOPE_MIGRATIONS', 'SCOPE_BACKEND'] },
+ { name: 'db/migrate schema migration', file: 'db/migrate/20260330_create_users.rb', expects: ['SCOPE_MIGRATIONS', 'SCOPE_BACKEND'] },
+ // Independent categories (#2299): test-suffixed frontend files carry BOTH.
+ {
+ name: 'Button.test.jsx is FRONTEND and TESTS (#2299)',
+ file: 'src/Button.test.jsx',
+ expects: ['SCOPE_FRONTEND', 'SCOPE_TESTS'],
+ alsoFalse: ['SCOPE_BACKEND'], // frontend files never claim backend
+ },
+ { name: 'util.test.ts is BACKEND and TESTS (#2299)', file: 'src/util.test.ts', expects: ['SCOPE_BACKEND', 'SCOPE_TESTS'] },
+ { name: 'auth code carries AUTH and BACKEND', file: 'src/lib/auth.ts', expects: ['SCOPE_AUTH', 'SCOPE_BACKEND'] },
+ // Plain classes unchanged.
+ { name: 'plain component', file: 'src/A.jsx', expects: ['SCOPE_FRONTEND'], alsoFalse: ['SCOPE_TESTS', 'SCOPE_BACKEND'] },
+ { name: 'plain backend', file: 'server.go', expects: ['SCOPE_BACKEND'], alsoFalse: ['SCOPE_FRONTEND'] },
+ { name: 'docs', file: 'docs/guide.md', expects: ['SCOPE_DOCS'] },
+ { name: 'prompts', file: 'app/services/prompt_builder.rb', expects: ['SCOPE_PROMPTS', 'SCOPE_BACKEND'] },
+ ];
+
+ for (const row of TABLE) {
+ test(row.name, () => {
+ const { vars, status } = runScopeFull(createRepo([row.file]));
+ expect(status).toBe(0);
+ for (const key of row.expects) {
+ expect(`${key}=${vars[key]}`).toBe(`${key}=true`);
+ }
+ for (const key of row.alsoFalse ?? []) {
+ expect(`${key}=${vars[key]}`).toBe(`${key}=false`);
+ }
+ expect(vars.SCOPE_ERROR).toBeUndefined();
+ });
+ }
+});
+
+describe('exit-code contract (#2526)', () => {
+ test('clean tree, no changes → all false, exit 0, no SCOPE_ERROR', () => {
+ const dir = createRepo([]);
+ const { vars, status } = runScopeFull(dir);
+ expect(status).toBe(0);
+ expect(vars.SCOPE_ERROR).toBeUndefined();
+ expect(Object.values(vars).every((v) => v === 'false')).toBe(true);
+ });
+
+ test('changed files but ZERO matches → SCOPE_ERROR=unmatched + exit 2 + paths listed', () => {
+ const dir = createRepo(['Makefile.custom', 'weird/layout.xyz']);
+ const { vars, status, stdout } = runScopeFull(dir);
+ expect(status).toBe(2);
+ expect(vars.SCOPE_ERROR).toBe('unmatched');
+ expect(stdout).toContain('# unmatched: weird/layout.xyz');
+ // Still prints all nine flags so `source <(...)` consumers get vars.
+ expect(vars.SCOPE_FRONTEND).toBe('false');
+ expect(vars.SCOPE_API).toBe('false');
+ });
+
+ test('unresolvable base → SCOPE_ERROR=no_base + exit 2 (a green would mean "could not look")', () => {
+ const dir = createRepo(['app.ts']);
+ const result = spawnSync('bash', [SCRIPT, 'no-such-branch'], { cwd: dir, stdio: 'pipe', timeout: 5000 });
+ expect(result.status).toBe(2);
+ const out = result.stdout.toString();
+ expect(out).toContain('SCOPE_ERROR=no_base');
+ expect(out).toContain('SCOPE_FRONTEND=false');
+ });
+
+ test('output stays shell-safe for sourcing consumers in every state', () => {
+ // eval'd rather than `source <(...)`: macOS system bash 3.2 sources a
+ // process substitution as 0 bytes (st_size-based buffer on a FIFO), which
+ // would test the shell, not the script. The property under test is that
+ // every output line is a valid assignment or comment.
+ const dir = createRepo(['weird/layout.xyz']);
+ const result = spawnSync('bash', ['-c', `out="$(bash "${SCRIPT}" main)"; eval "$out"; echo "ERR=$SCOPE_ERROR FRONT=$SCOPE_FRONTEND"`], {
+ cwd: dir, stdio: 'pipe', timeout: 5000,
+ });
+ expect(result.stdout.toString()).toContain('ERR=unmatched FRONT=false');
+ });
+});
+
+describe('uncommitted work is visible (#2299)', () => {
+ test('uncommitted change on a branch with no commits sets the scope', () => {
+ const dir = mkdtempSync(join(tmpdir(), 'diff-scope-dirty-'));
+ dirs.push(dir);
+ const run = (cmd: string, args: string[]) => spawnSync(cmd, args, { cwd: dir, stdio: 'pipe', timeout: 5000 });
+ run('git', ['init', '-b', 'main']);
+ run('git', ['config', 'user.email', '[email protected]']);
+ run('git', ['config', 'user.name', 'T']);
+ mkdirSync(join(dir, 'src'), { recursive: true });
+ writeFileSync(join(dir, 'src', 'Button.jsx'), '// x\n');
+ run('git', ['add', '.']);
+ run('git', ['commit', '-m', 'initial']);
+ run('git', ['checkout', '-b', 'feat/x']); // no commits on the branch
+ writeFileSync(join(dir, 'src', 'Button.jsx'), '// modified, uncommitted\n');
+ const { vars, status } = runScopeFull(dir);
+ expect(status).toBe(0);
+ expect(vars.SCOPE_FRONTEND).toBe('true'); // was false pre-fix (all-false early exit)
+ });
+
+ test('an UNTRACKED new migration sets SCOPE_MIGRATIONS (reviewers must see it)', () => {
+ const dir = mkdtempSync(join(tmpdir(), 'diff-scope-untracked-'));
+ dirs.push(dir);
+ const run = (cmd: string, args: string[]) => spawnSync(cmd, args, { cwd: dir, stdio: 'pipe', timeout: 5000 });
+ run('git', ['init', '-b', 'main']);
+ run('git', ['config', 'user.email', '[email protected]']);
+ run('git', ['config', 'user.name', 'T']);
+ writeFileSync(join(dir, 'README.md'), '# t\n');
+ run('git', ['add', '.']);
+ run('git', ['commit', '-m', 'initial']);
+ mkdirSync(join(dir, 'db', 'data'), { recursive: true });
+ writeFileSync(join(dir, 'db', 'data', '20260816_backfill.rb'), '# data migration\n');
+ const { vars, status } = runScopeFull(dir);
+ expect(status).toBe(0);
+ expect(vars.SCOPE_MIGRATIONS).toBe('true');
+ expect(vars.SCOPE_BACKEND).toBe('true');
+ });
+
+ test('non-ASCII path still matches extension globs (NUL-safe file listing, #2526)', () => {
+ const dir = createRepo(['docs/M2 — Notes.md']);
+ const { vars, status } = runScopeFull(dir);
+ expect(status).toBe(0);
+ expect(vars.SCOPE_DOCS).toBe('true'); // pre-fix: git's octal quoting defeated *.md
+ });
+});
diff --git a/test/egress-lib.test.ts b/test/egress-lib.test.ts
index 2cfb51c45..faa0f63b7 100644
--- a/test/egress-lib.test.ts
+++ b/test/egress-lib.test.ts
@@ -17,7 +17,7 @@ import * as os from 'os';
import * as path from 'path';
import { listReceipts, sha256Hex } from '../lib/egress-receipt';
-const ROOT = path.resolve(new URL(import.meta.url).pathname, '..', '..');
+const ROOT = path.resolve(import.meta.path, '..', '..');
const LIB = path.join(ROOT, 'bin', 'gstack-egress-lib.sh');
const received: string[] = [];
diff --git a/test/egress-receipt-wiring.test.ts b/test/egress-receipt-wiring.test.ts
index 484a1e1ff..0ac0ae67e 100644
--- a/test/egress-receipt-wiring.test.ts
+++ b/test/egress-receipt-wiring.test.ts
@@ -28,7 +28,7 @@ import { describe, test, expect } from 'bun:test';
import * as fs from 'fs';
import * as path from 'path';
-const ROOT = path.resolve(new URL(import.meta.url).pathname, '..', '..');
+const ROOT = path.resolve(import.meta.path, '..', '..');
function read(rel: string): string {
return fs.readFileSync(path.join(ROOT, rel), 'utf-8');
diff --git a/test/egress-receipt.test.ts b/test/egress-receipt.test.ts
index 64e6f3928..233d7695d 100644
--- a/test/egress-receipt.test.ts
+++ b/test/egress-receipt.test.ts
@@ -31,7 +31,7 @@ import {
writeReceipt,
} from '../lib/egress-receipt';
-const ROOT = path.resolve(new URL(import.meta.url).pathname, '..', '..');
+const ROOT = path.resolve(import.meta.path, '..', '..');
let home: string;
diff --git a/test/empty-find-fallthrough.test.ts b/test/empty-find-fallthrough.test.ts
new file mode 100644
index 000000000..10782ae9d
--- /dev/null
+++ b/test/empty-find-fallthrough.test.ts
@@ -0,0 +1,95 @@
+/**
+ * Empty `find | xargs ls -t` must not fall through to cwd (#2483).
+ *
+ * GNU xargs runs `ls -t` once even on EMPTY input, and `ls -t` with no
+ * operands lists the CURRENT DIRECTORY — so on a fresh install (no
+ * ceo-plans / checkpoints / plans yet) a random cwd .md becomes "the plan"
+ * or "the latest checkpoint". `xargs -r` pins the BSD skip-on-empty
+ * behavior on both GNU and BSD (same shape as the landed
+ * bin/gstack-codex-session-import fix, #2482).
+ *
+ * Re-derived from community PR #2483 by @tranthanhnhatkhoa.
+ */
+import { describe, test, expect } from 'bun:test';
+import { execSync } from 'child_process';
+import * as fs from 'fs';
+import * as os from 'os';
+import * as path from 'path';
+import { HOST_PATHS } from '../scripts/resolvers/types';
+import type { TemplateContext } from '../scripts/resolvers/types';
+import { generateContextRecovery } from '../scripts/resolvers/preamble/generate-context-recovery';
+
+const ROOT = path.join(import.meta.dir, '..');
+
+function makeCtx(): TemplateContext {
+ return {
+ skillName: 'test-skill',
+ tmplPath: 'test.tmpl',
+ host: 'claude',
+ paths: HOST_PATHS.claude,
+ preambleTier: 2,
+ };
+}
+
+describe('empty find must not fall through to cwd (#2483)', () => {
+ test('no resolver emits a bare `xargs ls -t` (must be `xargs -r ls -t`)', () => {
+ const out = execSync(
+ `grep -rn "xargs ls -t" "${path.join(ROOT, 'scripts')}" "${path.join(ROOT, 'bin')}" || true`,
+ { encoding: 'utf-8' },
+ );
+ expect(out.trim()).toBe('');
+ });
+
+ test('rendered Context Recovery uses the guarded form at both find sites', () => {
+ const rendered = generateContextRecovery(makeCtx());
+ const bareSites = rendered.split('xargs ls -t').length - 1;
+ expect(bareSites).toBe(0);
+ const guardedSites = rendered.split('xargs -r ls -t').length - 1;
+ expect(guardedSites).toBe(2);
+ });
+
+ test('live block: empty checkpoints dir yields NO checkpoint, not a cwd file', () => {
+ const rendered = generateContextRecovery(makeCtx());
+ const m = rendered.match(/_LATEST_CP=\$\(.*\)/);
+ expect(m).not.toBeNull();
+ const line = m![0];
+
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-home-'));
+ const cwd = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-cwd-'));
+ try {
+ // Fresh install shape: the checkpoints dir exists but is EMPTY,
+ // and the cwd holds a decoy markdown file.
+ const proj = path.join(home, 'projects', 'unknown');
+ fs.mkdirSync(path.join(proj, 'checkpoints'), { recursive: true });
+ fs.writeFileSync(path.join(cwd, 'DECOY.md'), '# not a checkpoint\n');
+
+ const script = `_PROJ="${proj}"\n${line.replace(/\$\{_PROJ\}|"\$_PROJ"/g, '"$_PROJ"')}\necho "LATEST_CP=[$_LATEST_CP]"`;
+ const out = execSync(`bash -c '${script.replace(/'/g, `'\\''`)}'`, {
+ cwd,
+ encoding: 'utf-8',
+ });
+ expect(out).toContain('LATEST_CP=[]');
+ expect(out).not.toContain('DECOY.md');
+ } finally {
+ fs.rmSync(home, { recursive: true, force: true });
+ fs.rmSync(cwd, { recursive: true, force: true });
+ }
+ });
+
+ test('no generated SKILL.md carries the unguarded form', () => {
+ const out = execSync(
+ `grep -rln "xargs ls -t" --include=SKILL.md "${ROOT}" || true`,
+ { encoding: 'utf-8' },
+ );
+ // node_modules and vendored trees are not generated output; nothing in
+ // the repo's generated skills may carry the unguarded form.
+ const hits = out
+ .split('\n')
+ .filter(Boolean)
+ .filter((f) => !f.includes('node_modules'))
+ // The workspace-local .claude/ install is not generated output and can
+ // carry dangling symlinks from unrelated sessions.
+ .filter((f) => !f.includes('/.claude/'));
+ expect(hits).toEqual([]);
+ });
+});
diff --git a/test/fixtures/golden/claude-ship-SKILL.md b/test/fixtures/golden/claude-ship-SKILL.md
index f0cacac22..c6785f91c 100644
--- a/test/fixtures/golden/claude-ship-SKILL.md
+++ b/test/fixtures/golden/claude-ship-SKILL.md
@@ -112,9 +112,11 @@ else
fi
~/.claude/skills/gstack/bin/gstack-timeline-log '{"skill":"ship","event":"started","branch":"'"$_BRANCH"'","session":"'"$_SESSION_ID"'"}' 2>/dev/null &
_HAS_ROUTING="no"
-if [ -f CLAUDE.md ] && grep -q "## Skill routing" CLAUDE.md 2>/dev/null; then
- _HAS_ROUTING="yes"
-fi
+for _RF in CLAUDE.md AGENTS.md; do
+ if [ -f "$_RF" ] && grep -q "## Skill routing" "$_RF" 2>/dev/null; then
+ _HAS_ROUTING="yes"
+ fi
+done
_ROUTING_DECLINED=$(~/.claude/skills/gstack/bin/gstack-config get routing_declined 2>/dev/null || echo "false")
echo "HAS_ROUTING: $_HAS_ROUTING"
echo "ROUTING_DECLINED: $_ROUTING_DECLINED"
@@ -508,10 +510,13 @@ _BRAIN_SYNC_MODE=$("$_BRAIN_CONFIG_BIN" get artifacts_sync_mode 2>/dev/null || e
# Detect remote-MCP mode (Path 4 of /setup-gbrain). Local artifacts sync is
# a no-op in remote mode; the brain server pulls from GitHub/GitLab on its
# own cadence. Read claude.json directly to keep this preamble fast (no
-# subprocess to claude CLI on every skill start).
+# subprocess to claude CLI on every skill start). Both registration scopes
+# are read (#2499): user scope, then the nearest-ancestor project scope.
_GBRAIN_MCP_MODE="none"
+_GBRAIN_MCP_ENTRY=""
if command -v jq >/dev/null 2>&1 && [ -f "$HOME/.claude.json" ]; then
- _GBRAIN_MCP_TYPE=$(jq -r '.mcpServers.gbrain.type // .mcpServers.gbrain.transport // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_ENTRY=$(jq -c --arg cwd "$PWD" '.mcpServers.gbrain // ((.projects // {}) | to_entries | map(select((.key as $k | $cwd == $k or ($cwd | startswith($k + "/"))) and ((try .value.mcpServers.gbrain catch null) != null))) | sort_by(.key | length) | last | .value.mcpServers.gbrain) // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_TYPE=$(printf '%s' "$_GBRAIN_MCP_ENTRY" | jq -r '.type // .transport // empty' 2>/dev/null)
case "$_GBRAIN_MCP_TYPE" in
url|http|sse) _GBRAIN_MCP_MODE="remote-http" ;;
stdio) _GBRAIN_MCP_MODE="local-stdio" ;;
@@ -532,6 +537,7 @@ if [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_DO_PULL=1
if [ -f "$_BRAIN_LAST_PULL_FILE" ]; then
_BRAIN_LAST=$(cat "$_BRAIN_LAST_PULL_FILE" 2>/dev/null || echo 0)
+ case "$_BRAIN_LAST" in ''|*[!0-9]*) _BRAIN_LAST=0 ;; esac
_BRAIN_AGE=$(( _BRAIN_NOW - _BRAIN_LAST ))
[ "$_BRAIN_AGE" -lt 86400 ] && _BRAIN_DO_PULL=0
fi
@@ -545,7 +551,7 @@ fi
if [ "$_GBRAIN_MCP_MODE" = "remote-http" ]; then
# Remote-MCP mode: local artifacts sync is a no-op (brain admin's server
# pulls from GitHub/GitLab). Show the user this is by design, not broken.
- _GBRAIN_HOST=$(jq -r '.mcpServers.gbrain.url // empty' "$HOME/.claude.json" 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|')
+ _GBRAIN_HOST=$(printf '%s' "${_GBRAIN_MCP_ENTRY:-}" | jq -r '.url // empty' 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|' | head -1 | tr -cd 'A-Za-z0-9._-')
echo "ARTIFACTS_SYNC: remote-mode (managed by brain server ${_GBRAIN_HOST:-remote})"
elif [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_QUEUE_DEPTH=0
@@ -630,8 +636,8 @@ eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)"
_PROJ="${GSTACK_HOME:-$HOME/.gstack}/projects/${SLUG:-unknown}"
if [ -d "$_PROJ" ]; then
echo "--- RECENT ARTIFACTS ---"
- find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs ls -t 2>/dev/null | head -3
- [ -f "$_PROJ/${_BRANCH}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/${_BRANCH}-reviews.jsonl" | tr -d ' ') entries"
+ find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3
+ [ -f "$_PROJ/${BRANCH:-unknown}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/${BRANCH:-unknown}-reviews.jsonl" | tr -d ' ') entries"
[ -f "$_PROJ/timeline.jsonl" ] && tail -5 "$_PROJ/timeline.jsonl"
if [ -f "$_PROJ/timeline.jsonl" ]; then
_LAST=$(grep "\"branch\":\"${_BRANCH}\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -1)
@@ -639,7 +645,7 @@ if [ -d "$_PROJ" ]; then
_RECENT_SKILLS=$(grep "\"branch\":\"${_BRANCH}\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -3 | grep -o '"skill":"[^"]*"' | sed 's/"skill":"//;s/"//' | tr '\n' ',')
[ -n "$_RECENT_SKILLS" ] && echo "RECENT_PATTERN: $_RECENT_SKILLS"
fi
- _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs ls -t 2>/dev/null | head -1)
+ _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs -r ls -t 2>/dev/null | head -1)
[ -n "$_LATEST_CP" ] && echo "LATEST_CHECKPOINT: $_LATEST_CP"
if [ -f "$_PROJ/decisions.active.json" ]; then
echo "--- ACTIVE DECISIONS (recent, scope-relevant) ---"
@@ -715,7 +721,7 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST
## Question Tuning (skip entirely if `QUESTION_TUNING: false`)
-Before each AskUserQuestion, choose `question_id` from `scripts/question-registry.ts` or `{skill}-{slug}`, then run `printf '%s' "<question summary>" | ~/.claude/skills/gstack/bin/gstack-question-preference --check "<id>" --summary-stdin` (piped summary feeds the one-way keyword net, #2024). `AUTO_DECIDE` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." `ASK_NORMALLY` means ask.
+Before each AskUserQuestion, choose `question_id` from `~/.claude/skills/gstack/scripts/question-registry.ts` or `{skill}-{slug}`, then run `printf '%s' "<question summary>" | ~/.claude/skills/gstack/bin/gstack-question-preference --check "<id>" --summary-stdin` (piped summary feeds the one-way keyword net, #2024). `AUTO_DECIDE` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." `ASK_NORMALLY` means ask.
**Embed the question_id as a marker in the question text** so hooks can identify it deterministically (plan-tune cathedral T14 / D18 progressive markers). Append `<gstack-qid:{question_id}>` somewhere in the rendered question (the leading line or trailing line is fine; the marker doesn't render visibly to the user when wrapped in HTML-style angle brackets, but the hook strips it). Without the marker the PreToolUse enforcement hook treats the AUQ as observed-only and never auto-decides — so always include it when the question matches a registered `question_id`.
@@ -1105,7 +1111,7 @@ stay agent judgment; the slot pick stays `gstack-next-version`.
```bash
bun run ~/.claude/skills/gstack/bin/gstack-version-bump write --version "$NEW_VERSION"
```
- The CLI validates the 4-digit `MAJOR.MINOR.PATCH.MICRO` pattern and writes **both** VERSION and package.json. On a half-write (VERSION written, package.json failed) it exits 3 — re-run, and classify will report DRIFT_STALE_PKG for `repair` to fix.
+ The CLI validates the version pattern (4-digit `MAJOR.MINOR.PATCH.MICRO`; 3-digit for repos whose pinned version source uses plain semver) and writes VERSION, the manifest, and the manifest's npm lockfiles (`package-lock.json` / `npm-shrinkwrap.json`) when they already exist — never created. The manifest is resolved as `--package-json-path` → `.gstack/package-json-path` → `./package.json`, so a repo whose only Node package lives in a subdirectory (`web/`, `app/`) is covered by a one-line pin instead of silently getting a VERSION-only bump. npm rejects 4-component versions, so the manifest and lockfiles carry the npm-valid 3-digit translation (`1.67.0.0` → `1.67.0`); VERSION stays the 4-digit source of truth and classify judges drift against the translated form. On a half-write it exits 3 — re-run, and classify will report DRIFT_STALE_PKG for `repair` to fix.
5. **Record the release decision** (durable cross-session memory). The bump level is a real decision the next session should not re-derive blind:
```bash
diff --git a/test/fixtures/golden/codex-ship-SKILL.md b/test/fixtures/golden/codex-ship-SKILL.md
index 2127b6221..c1a60ee3f 100644
--- a/test/fixtures/golden/codex-ship-SKILL.md
+++ b/test/fixtures/golden/codex-ship-SKILL.md
@@ -98,9 +98,11 @@ else
fi
$GSTACK_BIN/gstack-timeline-log '{"skill":"ship","event":"started","branch":"'"$_BRANCH"'","session":"'"$_SESSION_ID"'"}' 2>/dev/null &
_HAS_ROUTING="no"
-if [ -f AGENTS.md ] && grep -q "## Skill routing" AGENTS.md 2>/dev/null; then
- _HAS_ROUTING="yes"
-fi
+for _RF in AGENTS.md AGENTS.md; do
+ if [ -f "$_RF" ] && grep -q "## Skill routing" "$_RF" 2>/dev/null; then
+ _HAS_ROUTING="yes"
+ fi
+done
_ROUTING_DECLINED=$($GSTACK_BIN/gstack-config get routing_declined 2>/dev/null || echo "false")
echo "HAS_ROUTING: $_HAS_ROUTING"
echo "ROUTING_DECLINED: $_ROUTING_DECLINED"
@@ -494,10 +496,13 @@ _BRAIN_SYNC_MODE=$("$_BRAIN_CONFIG_BIN" get artifacts_sync_mode 2>/dev/null || e
# Detect remote-MCP mode (Path 4 of /setup-gbrain). Local artifacts sync is
# a no-op in remote mode; the brain server pulls from GitHub/GitLab on its
# own cadence. Read claude.json directly to keep this preamble fast (no
-# subprocess to claude CLI on every skill start).
+# subprocess to claude CLI on every skill start). Both registration scopes
+# are read (#2499): user scope, then the nearest-ancestor project scope.
_GBRAIN_MCP_MODE="none"
+_GBRAIN_MCP_ENTRY=""
if command -v jq >/dev/null 2>&1 && [ -f "$HOME/.claude.json" ]; then
- _GBRAIN_MCP_TYPE=$(jq -r '.mcpServers.gbrain.type // .mcpServers.gbrain.transport // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_ENTRY=$(jq -c --arg cwd "$PWD" '.mcpServers.gbrain // ((.projects // {}) | to_entries | map(select((.key as $k | $cwd == $k or ($cwd | startswith($k + "/"))) and ((try .value.mcpServers.gbrain catch null) != null))) | sort_by(.key | length) | last | .value.mcpServers.gbrain) // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_TYPE=$(printf '%s' "$_GBRAIN_MCP_ENTRY" | jq -r '.type // .transport // empty' 2>/dev/null)
case "$_GBRAIN_MCP_TYPE" in
url|http|sse) _GBRAIN_MCP_MODE="remote-http" ;;
stdio) _GBRAIN_MCP_MODE="local-stdio" ;;
@@ -518,6 +523,7 @@ if [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_DO_PULL=1
if [ -f "$_BRAIN_LAST_PULL_FILE" ]; then
_BRAIN_LAST=$(cat "$_BRAIN_LAST_PULL_FILE" 2>/dev/null || echo 0)
+ case "$_BRAIN_LAST" in ''|*[!0-9]*) _BRAIN_LAST=0 ;; esac
_BRAIN_AGE=$(( _BRAIN_NOW - _BRAIN_LAST ))
[ "$_BRAIN_AGE" -lt 86400 ] && _BRAIN_DO_PULL=0
fi
@@ -531,7 +537,7 @@ fi
if [ "$_GBRAIN_MCP_MODE" = "remote-http" ]; then
# Remote-MCP mode: local artifacts sync is a no-op (brain admin's server
# pulls from GitHub/GitLab). Show the user this is by design, not broken.
- _GBRAIN_HOST=$(jq -r '.mcpServers.gbrain.url // empty' "$HOME/.claude.json" 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|')
+ _GBRAIN_HOST=$(printf '%s' "${_GBRAIN_MCP_ENTRY:-}" | jq -r '.url // empty' 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|' | head -1 | tr -cd 'A-Za-z0-9._-')
echo "ARTIFACTS_SYNC: remote-mode (managed by brain server ${_GBRAIN_HOST:-remote})"
elif [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_QUEUE_DEPTH=0
@@ -616,8 +622,8 @@ eval "$($GSTACK_BIN/gstack-slug 2>/dev/null)"
_PROJ="${GSTACK_HOME:-$HOME/.gstack}/projects/${SLUG:-unknown}"
if [ -d "$_PROJ" ]; then
echo "--- RECENT ARTIFACTS ---"
- find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs ls -t 2>/dev/null | head -3
- [ -f "$_PROJ/${_BRANCH}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/${_BRANCH}-reviews.jsonl" | tr -d ' ') entries"
+ find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3
+ [ -f "$_PROJ/${BRANCH:-unknown}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/${BRANCH:-unknown}-reviews.jsonl" | tr -d ' ') entries"
[ -f "$_PROJ/timeline.jsonl" ] && tail -5 "$_PROJ/timeline.jsonl"
if [ -f "$_PROJ/timeline.jsonl" ]; then
_LAST=$(grep "\"branch\":\"${_BRANCH}\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -1)
@@ -625,7 +631,7 @@ if [ -d "$_PROJ" ]; then
_RECENT_SKILLS=$(grep "\"branch\":\"${_BRANCH}\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -3 | grep -o '"skill":"[^"]*"' | sed 's/"skill":"//;s/"//' | tr '\n' ',')
[ -n "$_RECENT_SKILLS" ] && echo "RECENT_PATTERN: $_RECENT_SKILLS"
fi
- _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs ls -t 2>/dev/null | head -1)
+ _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs -r ls -t 2>/dev/null | head -1)
[ -n "$_LATEST_CP" ] && echo "LATEST_CHECKPOINT: $_LATEST_CP"
if [ -f "$_PROJ/decisions.active.json" ]; then
echo "--- ACTIVE DECISIONS (recent, scope-relevant) ---"
@@ -701,7 +707,7 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST
## Question Tuning (skip entirely if `QUESTION_TUNING: false`)
-Before each AskUserQuestion, choose `question_id` from `scripts/question-registry.ts` or `{skill}-{slug}`, then run `printf '%s' "<question summary>" | $GSTACK_BIN/gstack-question-preference --check "<id>" --summary-stdin` (piped summary feeds the one-way keyword net, #2024). `AUTO_DECIDE` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." `ASK_NORMALLY` means ask.
+Before each AskUserQuestion, choose `question_id` from `$GSTACK_ROOT/scripts/question-registry.ts` or `{skill}-{slug}`, then run `printf '%s' "<question summary>" | $GSTACK_BIN/gstack-question-preference --check "<id>" --summary-stdin` (piped summary feeds the one-way keyword net, #2024). `AUTO_DECIDE` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." `ASK_NORMALLY` means ask.
**Embed the question_id as a marker in the question text** so hooks can identify it deterministically (plan-tune cathedral T14 / D18 progressive markers). Append `<gstack-qid:{question_id}>` somewhere in the rendered question (the leading line or trailing line is fine; the marker doesn't render visibly to the user when wrapped in HTML-style angle brackets, but the hook strips it). Without the marker the PreToolUse enforcement hook treats the AUQ as observed-only and never auto-decides — so always include it when the question matches a registered `question_id`.
@@ -1707,7 +1713,7 @@ Repo: {owner/repo}
```bash
setopt +o nomatch 2>/dev/null || true # zsh compat
-BRANCH=$(git branch --show-current 2>/dev/null | tr '/' '-')
+BRANCH=$(git branch --show-current 2>/dev/null | tr '/' '-' | tr -cd 'a-zA-Z0-9._-')
REPO=$(basename "$(git rev-parse --show-toplevel 2>/dev/null)")
# Compute project slug for ~/.gstack/projects/ lookup
_PLAN_SLUG=$(git remote get-url origin 2>/dev/null | sed 's|.*[:/]\([^/]*/[^/]*\)\.git$|\1|;s|.*[:/]\([^/]*/[^/]*\)$|\1|' | tr '/' '-' | tr -cd 'a-zA-Z0-9._-') || true
@@ -1717,7 +1723,7 @@ for PLAN_DIR in "$HOME/.gstack/projects/$_PLAN_SLUG" "$HOME/.claude/plans" "$HOM
[ -d "$PLAN_DIR" ] || continue
PLAN=$(ls -t "$PLAN_DIR"/*.md 2>/dev/null | xargs grep -l "$BRANCH" 2>/dev/null | head -1)
[ -z "$PLAN" ] && PLAN=$(ls -t "$PLAN_DIR"/*.md 2>/dev/null | xargs grep -l "$REPO" 2>/dev/null | head -1)
- [ -z "$PLAN" ] && PLAN=$(find "$PLAN_DIR" -name '*.md' -mmin -1440 -maxdepth 1 2>/dev/null | xargs ls -t 2>/dev/null | head -1)
+ [ -z "$PLAN" ] && PLAN=$(find "$PLAN_DIR" -name '*.md' -mmin -1440 -maxdepth 1 2>/dev/null | xargs -r ls -t 2>/dev/null | head -1)
[ -n "$PLAN" ] && break
done
[ -n "$PLAN" ] && echo "PLAN_FILE: $PLAN" || echo "NO_PLAN_FILE"
@@ -2150,7 +2156,8 @@ Output a summary header: `Pre-Landing Review: N issues (X critical, Y informatio
- If 3 or fewer ASK items, you may use individual AskUserQuestion calls instead
7. **After all fixes (auto + user-approved):**
- - If ANY fixes were applied: commit fixed files by name (`git add <fixed-files> && git commit -m "fix: pre-landing review fixes"`), then **STOP** and tell the user to run `/ship` again to re-test.
+ - If ANY fixes were applied: commit fixed files by name (`git add <fixed-files> && git commit -m "fix: pre-landing review fixes"`), then **stay in this invocation and loop**: re-run the test suite (Step 5) on the fixed code, then re-run this review (Step 9 items 2-6) against the updated diff. Repeat until one full pass applies ZERO fixes — tests green and review clean — then continue to Step 12. NEVER stop to tell the user to run `/ship` again; a fix-and-rerun cycle has no user decision in it, and stopping there breaks the fully-automated contract (#2391).
+ - **Bound: 3 fix cycles.** If the 3rd cycle still applies fixes, STOP and report which findings keep reappearing — a review that won't converge is a genuine blocker worth human eyes, not a re-run request.
- If no fixes applied (all ASK items skipped, or no issues found): continue to Step 12.
8. Output summary: `Pre-Landing Review: N issues — M auto-fixed, K asked (J fixed, L skipped)`
@@ -2296,7 +2303,7 @@ stay agent judgment; the slot pick stays `gstack-next-version`.
```bash
bun run $GSTACK_ROOT/bin/gstack-version-bump write --version "$NEW_VERSION"
```
- The CLI validates the 4-digit `MAJOR.MINOR.PATCH.MICRO` pattern and writes **both** VERSION and package.json. On a half-write (VERSION written, package.json failed) it exits 3 — re-run, and classify will report DRIFT_STALE_PKG for `repair` to fix.
+ The CLI validates the version pattern (4-digit `MAJOR.MINOR.PATCH.MICRO`; 3-digit for repos whose pinned version source uses plain semver) and writes VERSION, the manifest, and the manifest's npm lockfiles (`package-lock.json` / `npm-shrinkwrap.json`) when they already exist — never created. The manifest is resolved as `--package-json-path` → `.gstack/package-json-path` → `./package.json`, so a repo whose only Node package lives in a subdirectory (`web/`, `app/`) is covered by a one-line pin instead of silently getting a VERSION-only bump. npm rejects 4-component versions, so the manifest and lockfiles carry the npm-valid 3-digit translation (`1.67.0.0` → `1.67.0`); VERSION stays the 4-digit source of truth and classify judges drift against the translated form. On a half-write it exits 3 — re-run, and classify will report DRIFT_STALE_PKG for `repair` to fix.
5. **Record the release decision** (durable cross-session memory). The bump level is a real decision the next session should not re-derive blind:
```bash
diff --git a/test/fixtures/golden/factory-ship-SKILL.md b/test/fixtures/golden/factory-ship-SKILL.md
index d013de225..e75d8dc91 100644
--- a/test/fixtures/golden/factory-ship-SKILL.md
+++ b/test/fixtures/golden/factory-ship-SKILL.md
@@ -100,9 +100,11 @@ else
fi
$GSTACK_BIN/gstack-timeline-log '{"skill":"ship","event":"started","branch":"'"$_BRANCH"'","session":"'"$_SESSION_ID"'"}' 2>/dev/null &
_HAS_ROUTING="no"
-if [ -f CLAUDE.md ] && grep -q "## Skill routing" CLAUDE.md 2>/dev/null; then
- _HAS_ROUTING="yes"
-fi
+for _RF in CLAUDE.md AGENTS.md; do
+ if [ -f "$_RF" ] && grep -q "## Skill routing" "$_RF" 2>/dev/null; then
+ _HAS_ROUTING="yes"
+ fi
+done
_ROUTING_DECLINED=$($GSTACK_BIN/gstack-config get routing_declined 2>/dev/null || echo "false")
echo "HAS_ROUTING: $_HAS_ROUTING"
echo "ROUTING_DECLINED: $_ROUTING_DECLINED"
@@ -496,10 +498,13 @@ _BRAIN_SYNC_MODE=$("$_BRAIN_CONFIG_BIN" get artifacts_sync_mode 2>/dev/null || e
# Detect remote-MCP mode (Path 4 of /setup-gbrain). Local artifacts sync is
# a no-op in remote mode; the brain server pulls from GitHub/GitLab on its
# own cadence. Read claude.json directly to keep this preamble fast (no
-# subprocess to claude CLI on every skill start).
+# subprocess to claude CLI on every skill start). Both registration scopes
+# are read (#2499): user scope, then the nearest-ancestor project scope.
_GBRAIN_MCP_MODE="none"
+_GBRAIN_MCP_ENTRY=""
if command -v jq >/dev/null 2>&1 && [ -f "$HOME/.claude.json" ]; then
- _GBRAIN_MCP_TYPE=$(jq -r '.mcpServers.gbrain.type // .mcpServers.gbrain.transport // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_ENTRY=$(jq -c --arg cwd "$PWD" '.mcpServers.gbrain // ((.projects // {}) | to_entries | map(select((.key as $k | $cwd == $k or ($cwd | startswith($k + "/"))) and ((try .value.mcpServers.gbrain catch null) != null))) | sort_by(.key | length) | last | .value.mcpServers.gbrain) // empty' "$HOME/.claude.json" 2>/dev/null)
+ _GBRAIN_MCP_TYPE=$(printf '%s' "$_GBRAIN_MCP_ENTRY" | jq -r '.type // .transport // empty' 2>/dev/null)
case "$_GBRAIN_MCP_TYPE" in
url|http|sse) _GBRAIN_MCP_MODE="remote-http" ;;
stdio) _GBRAIN_MCP_MODE="local-stdio" ;;
@@ -520,6 +525,7 @@ if [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_DO_PULL=1
if [ -f "$_BRAIN_LAST_PULL_FILE" ]; then
_BRAIN_LAST=$(cat "$_BRAIN_LAST_PULL_FILE" 2>/dev/null || echo 0)
+ case "$_BRAIN_LAST" in ''|*[!0-9]*) _BRAIN_LAST=0 ;; esac
_BRAIN_AGE=$(( _BRAIN_NOW - _BRAIN_LAST ))
[ "$_BRAIN_AGE" -lt 86400 ] && _BRAIN_DO_PULL=0
fi
@@ -533,7 +539,7 @@ fi
if [ "$_GBRAIN_MCP_MODE" = "remote-http" ]; then
# Remote-MCP mode: local artifacts sync is a no-op (brain admin's server
# pulls from GitHub/GitLab). Show the user this is by design, not broken.
- _GBRAIN_HOST=$(jq -r '.mcpServers.gbrain.url // empty' "$HOME/.claude.json" 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|')
+ _GBRAIN_HOST=$(printf '%s' "${_GBRAIN_MCP_ENTRY:-}" | jq -r '.url // empty' 2>/dev/null | sed -E 's|^https?://([^/:]+).*|\1|' | head -1 | tr -cd 'A-Za-z0-9._-')
echo "ARTIFACTS_SYNC: remote-mode (managed by brain server ${_GBRAIN_HOST:-remote})"
elif [ -d "$_GSTACK_HOME/.git" ] && [ "$_BRAIN_SYNC_MODE" != "off" ]; then
_BRAIN_QUEUE_DEPTH=0
@@ -618,8 +624,8 @@ eval "$($GSTACK_BIN/gstack-slug 2>/dev/null)"
_PROJ="${GSTACK_HOME:-$HOME/.gstack}/projects/${SLUG:-unknown}"
if [ -d "$_PROJ" ]; then
echo "--- RECENT ARTIFACTS ---"
- find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs ls -t 2>/dev/null | head -3
- [ -f "$_PROJ/${_BRANCH}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/${_BRANCH}-reviews.jsonl" | tr -d ' ') entries"
+ find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3
+ [ -f "$_PROJ/${BRANCH:-unknown}-reviews.jsonl" ] && echo "REVIEWS: $(wc -l < "$_PROJ/${BRANCH:-unknown}-reviews.jsonl" | tr -d ' ') entries"
[ -f "$_PROJ/timeline.jsonl" ] && tail -5 "$_PROJ/timeline.jsonl"
if [ -f "$_PROJ/timeline.jsonl" ]; then
_LAST=$(grep "\"branch\":\"${_BRANCH}\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -1)
@@ -627,7 +633,7 @@ if [ -d "$_PROJ" ]; then
_RECENT_SKILLS=$(grep "\"branch\":\"${_BRANCH}\"" "$_PROJ/timeline.jsonl" 2>/dev/null | grep '"event":"completed"' | tail -3 | grep -o '"skill":"[^"]*"' | sed 's/"skill":"//;s/"//' | tr '\n' ',')
[ -n "$_RECENT_SKILLS" ] && echo "RECENT_PATTERN: $_RECENT_SKILLS"
fi
- _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs ls -t 2>/dev/null | head -1)
+ _LATEST_CP=$(find "$_PROJ/checkpoints" -name "*.md" -type f 2>/dev/null | xargs -r ls -t 2>/dev/null | head -1)
[ -n "$_LATEST_CP" ] && echo "LATEST_CHECKPOINT: $_LATEST_CP"
if [ -f "$_PROJ/decisions.active.json" ]; then
echo "--- ACTIVE DECISIONS (recent, scope-relevant) ---"
@@ -703,7 +709,7 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST
## Question Tuning (skip entirely if `QUESTION_TUNING: false`)
-Before each AskUserQuestion, choose `question_id` from `scripts/question-registry.ts` or `{skill}-{slug}`, then run `printf '%s' "<question summary>" | $GSTACK_BIN/gstack-question-preference --check "<id>" --summary-stdin` (piped summary feeds the one-way keyword net, #2024). `AUTO_DECIDE` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." `ASK_NORMALLY` means ask.
+Before each AskUserQuestion, choose `question_id` from `$GSTACK_ROOT/scripts/question-registry.ts` or `{skill}-{slug}`, then run `printf '%s' "<question summary>" | $GSTACK_BIN/gstack-question-preference --check "<id>" --summary-stdin` (piped summary feeds the one-way keyword net, #2024). `AUTO_DECIDE` means choose the recommended option and say "Auto-decided [summary] → [option] (your preference). Change with /plan-tune." `ASK_NORMALLY` means ask.
**Embed the question_id as a marker in the question text** so hooks can identify it deterministically (plan-tune cathedral T14 / D18 progressive markers). Append `<gstack-qid:{question_id}>` somewhere in the rendered question (the leading line or trailing line is fine; the marker doesn't render visibly to the user when wrapped in HTML-style angle brackets, but the hook strips it). Without the marker the PreToolUse enforcement hook treats the AUQ as observed-only and never auto-decides — so always include it when the question matches a registered `question_id`.
@@ -1709,7 +1715,7 @@ Repo: {owner/repo}
```bash
setopt +o nomatch 2>/dev/null || true # zsh compat
-BRANCH=$(git branch --show-current 2>/dev/null | tr '/' '-')
+BRANCH=$(git branch --show-current 2>/dev/null | tr '/' '-' | tr -cd 'a-zA-Z0-9._-')
REPO=$(basename "$(git rev-parse --show-toplevel 2>/dev/null)")
# Compute project slug for ~/.gstack/projects/ lookup
_PLAN_SLUG=$(git remote get-url origin 2>/dev/null | sed 's|.*[:/]\([^/]*/[^/]*\)\.git$|\1|;s|.*[:/]\([^/]*/[^/]*\)$|\1|' | tr '/' '-' | tr -cd 'a-zA-Z0-9._-') || true
@@ -1719,7 +1725,7 @@ for PLAN_DIR in "$HOME/.gstack/projects/$_PLAN_SLUG" "$HOME/.claude/plans" "$HOM
[ -d "$PLAN_DIR" ] || continue
PLAN=$(ls -t "$PLAN_DIR"/*.md 2>/dev/null | xargs grep -l "$BRANCH" 2>/dev/null | head -1)
[ -z "$PLAN" ] && PLAN=$(ls -t "$PLAN_DIR"/*.md 2>/dev/null | xargs grep -l "$REPO" 2>/dev/null | head -1)
- [ -z "$PLAN" ] && PLAN=$(find "$PLAN_DIR" -name '*.md' -mmin -1440 -maxdepth 1 2>/dev/null | xargs ls -t 2>/dev/null | head -1)
+ [ -z "$PLAN" ] && PLAN=$(find "$PLAN_DIR" -name '*.md' -mmin -1440 -maxdepth 1 2>/dev/null | xargs -r ls -t 2>/dev/null | head -1)
[ -n "$PLAN" ] && break
done
[ -n "$PLAN" ] && echo "PLAN_FILE: $PLAN" || echo "NO_PLAN_FILE"
@@ -2139,7 +2145,7 @@ If Codex is available, run a lightweight design check on the diff:
```bash
TMPERR_DRL=$(mktemp /tmp/codex-drl-XXXXXXXX)
_REPO_ROOT=$(git rev-parse --show-toplevel) || { echo "ERROR: not in a git repo" >&2; exit 1; }
-codex exec "Review the git diff on this branch. Run 7 litmus checks (YES/NO each): 1. Brand/product unmistakable in first screen? 2. One strong visual anchor present? 3. Page understandable by scanning headlines only? 4. Each section has one job? 5. Are cards actually necessary? 6. Does motion improve hierarchy or atmosphere? 7. Would design feel premium with all decorative shadows removed? Flag any hard rejections: 1. Generic SaaS card grid as first impression 2. Beautiful image with weak brand 3. Strong headline with no clear action 4. Busy imagery behind text 5. Sections repeating same mood statement 6. Carousel with no narrative purpose 7. App UI made of stacked cards instead of layout 5 most important design findings only. Reference file:line." -C "$_REPO_ROOT" -s read-only -c 'model_reasoning_effort="high"' --enable web_search_cached < /dev/null 2>"$TMPERR_DRL"
+codex exec "Review the git diff on this branch. Run 7 litmus checks (YES/NO each): 1. Brand/product unmistakable in first screen? 2. One strong visual anchor present? 3. Page understandable by scanning headlines only? 4. Each section has one job? 5. Are cards actually necessary? 6. Does motion improve hierarchy or atmosphere? 7. Would design feel premium with all decorative shadows removed? Flag any hard rejections: 1. Generic SaaS card grid as first impression 2. Beautiful image with weak brand 3. Strong headline with no clear action 4. Busy imagery behind text 5. Sections repeating same mood statement 6. Carousel with no narrative purpose 7. App UI made of stacked cards instead of layout 5 most important design findings only. Reference file:line." -C "$_REPO_ROOT" -s read-only -c 'model_reasoning_effort="high"' -c 'web_search="cached"' < /dev/null 2>"$TMPERR_DRL"
```
Use a 5-minute timeout (`timeout: 300000`). After the command completes, read stderr:
@@ -2404,7 +2410,8 @@ Output a summary header: `Pre-Landing Review: N issues (X critical, Y informatio
- If 3 or fewer ASK items, you may use individual AskUserQuestion calls instead
7. **After all fixes (auto + user-approved):**
- - If ANY fixes were applied: commit fixed files by name (`git add <fixed-files> && git commit -m "fix: pre-landing review fixes"`), then **STOP** and tell the user to run `/ship` again to re-test.
+ - If ANY fixes were applied: commit fixed files by name (`git add <fixed-files> && git commit -m "fix: pre-landing review fixes"`), then **stay in this invocation and loop**: re-run the test suite (Step 5) on the fixed code, then re-run this review (Step 9 items 2-6) against the updated diff. Repeat until one full pass applies ZERO fixes — tests green and review clean — then continue to Step 12. NEVER stop to tell the user to run `/ship` again; a fix-and-rerun cycle has no user decision in it, and stopping there breaks the fully-automated contract (#2391).
+ - **Bound: 3 fix cycles.** If the 3rd cycle still applies fixes, STOP and report which findings keep reappearing — a review that won't converge is a genuine blocker worth human eyes, not a re-run request.
- If no fixes applied (all ASK items skipped, or no issues found): continue to Step 12.
8. Output summary: `Pre-Landing Review: N issues — M auto-fixed, K asked (J fixed, L skipped)`
@@ -2498,10 +2505,20 @@ _CODEX_CFG=$($GSTACK_ROOT/bin/gstack-config get codex_reviews 2>/dev/null || ech
source $GSTACK_ROOT/bin/gstack-codex-probe 2>/dev/null || true
if [ "$_CODEX_CFG" = "disabled" ]; then
_CODEX_MODE="disabled"
+# Running-under-Codex presence probe (#2519): a live Codex session exports
+# CODEX_THREAD_ID / CODEX_SANDBOX into every shell it spawns (verified
+# against a live `codex exec 'env | grep -i codex'` capture, codex 0.147.0).
+# Nested codex spawns from inside a Codex host multiply token burn
+# (observed: one /review = 15M tokens). GSTACK_FORCE_CODEX_REVIEW=1 forces
+# the nested passes anyway.
+elif [ "${GSTACK_FORCE_CODEX_REVIEW:-0}" != "1" ] && { [ -n "${CODEX_THREAD_ID:-}" ] || [ -n "${CODEX_SANDBOX:-}" ]; }; then
+ _CODEX_MODE="under_codex"
elif ! command -v codex >/dev/null 2>&1; then
_CODEX_MODE="not_installed"; _gstack_codex_log_event "codex_cli_missing" 2>/dev/null || true
elif ! _gstack_codex_auth_probe >/dev/null 2>&1; then
_CODEX_MODE="not_authed"; _gstack_codex_log_event "codex_auth_failed" 2>/dev/null || true
+elif ! _gstack_codex_model_probe; then
+ _CODEX_MODE="model_unusable"
else
_CODEX_MODE="ready"; _gstack_codex_version_check 2>/dev/null || true
fi
@@ -2511,7 +2528,9 @@ echo "CODEX_MODE: $_CODEX_MODE"
Branch on the echoed `CODEX_MODE`:
- **`disabled`** — the user turned Codex reviews off (`codex_reviews=disabled`). Skip the Codex passes only; the Claude adversarial subagent below STILL runs (it is free and fast). Print: "Codex passes skipped (codex_reviews disabled) — running Claude adversarial only."
- **`not_installed`** — Codex CLI absent. Print: "Codex not installed — using Claude subagent. Install for cross-model coverage: `npm install -g @openai/codex`." Fall back to the Claude subagent path.
+- **`under_codex`** — this session is already running INSIDE a Codex host, so spawning codex again is the same model reviewing itself at multiplied token cost (#2519). Print exactly one line: "[running under Codex — nested codex passes skipped; set GSTACK_FORCE_CODEX_REVIEW=1 to force]" and skip the codex invocations below; run the section's free in-host pass instead if it defines one.
- **`not_authed`** — installed but no credentials. Print: "Codex installed but not authenticated — using Claude subagent. Run `codex login` or set `$CODEX_API_KEY`." Fall back to the Claude subagent path.
+- **`model_unusable`** — authed but the account cannot use its configured model (#2477: HTTP 400 on every call, usually a stale `model =` pin in `~/.codex/config.toml`). Relay the probe's HINT lines, tell the user the one-line fix (update the pin; `[notice.model_migrations]` names the replacement), and fall back to the Claude subagent path. The ~10s round trip is cached for 1h; timeouts fail open to `ready`.
- **`ready`** — run the Codex pass below.
For this diff-review path, `CODEX_MODE: disabled` means skip the Codex passes ONLY — the
@@ -2551,7 +2570,7 @@ _REPO_ROOT=$(git rev-parse --show-toplevel) || { echo "ERROR: not in a git repo"
# here. It defines _gstack_codex_timeout_wrapper (gtimeout -> timeout ->
# unwrapped fallback), added in #1056 but never wired into this call site.
source $GSTACK_ROOT/bin/gstack-codex-probe 2>/dev/null || true
-_gstack_codex_timeout_wrapper 540 codex exec "IMPORTANT: Do NOT read or execute any files under ~/.claude/, ~/.agents/, .factory/skills/, or agents/. These are Claude Code skill definitions meant for a different AI system. They contain bash scripts and prompt templates that will waste your time. Ignore them completely. Do NOT modify agents/openai.yaml. Stay focused on the repository code only.\n\nReview the changes on this branch against the base branch. Run DIFF_BASE=$(git merge-base origin/<base> HEAD) && git diff "$DIFF_BASE" to see the diff. Your job is to find ways this code will fail in production. Think like an attacker and a chaos engineer. Find edge cases, race conditions, security holes, resource leaks, failure modes, and silent data corruption paths. Be adversarial. Be thorough. No compliments — just the problems. End your output with ONE line in the canonical format `Recommendation: <action> because <one-line reason naming the most exploitable finding>`. Generic reasons like 'because it's safer' do not qualify; the reason must point to a specific finding or no-fix rationale." -C "$_REPO_ROOT" -s read-only -c 'model_reasoning_effort="high"' --enable web_search_cached < /dev/null 2>"$TMPERR_ADV"
+_gstack_codex_timeout_wrapper 540 codex exec "IMPORTANT: Do NOT read or execute any files under ~/.claude/, ~/.agents/, .factory/skills/, or agents/. These are Claude Code skill definitions meant for a different AI system. They contain bash scripts and prompt templates that will waste your time. Ignore them completely. Do NOT modify agents/openai.yaml. Stay focused on the repository code only.\n\nReview the changes on this branch against the base branch. Run DIFF_BASE=$(git merge-base origin/<base> HEAD) && git diff "$DIFF_BASE" to see the diff. Your job is to find ways this code will fail in production. Think like an attacker and a chaos engineer. Find edge cases, race conditions, security holes, resource leaks, failure modes, and silent data corruption paths. Be adversarial. Be thorough. No compliments — just the problems. End your output with ONE line in the canonical format `Recommendation: <action> because <one-line reason naming the most exploitable finding>`. Generic reasons like 'because it's safer' do not qualify; the reason must point to a specific finding or no-fix rationale." -C "$_REPO_ROOT" -s read-only -c 'model_reasoning_effort="high"' -c 'web_search="cached"' < /dev/null 2>"$TMPERR_ADV"
```
Set the Bash tool's `timeout` parameter to `600000` (10 minutes). It sits ABOVE the 540s wrapper deliberately, so the wrapper fires first and a stall surfaces as a diagnosable exit 124 instead of a harness kill that returns nothing. The wrapper resolves `gtimeout`, then `timeout`, then runs unwrapped, so it is safe on a macOS without coreutils. After the command completes, read stderr:
@@ -2584,7 +2603,7 @@ cd "$_REPO_ROOT"
# here. It defines _gstack_codex_timeout_wrapper (gtimeout -> timeout ->
# unwrapped fallback), added in #1056 but never wired into this call site.
source $GSTACK_ROOT/bin/gstack-codex-probe 2>/dev/null || true
-_gstack_codex_timeout_wrapper 540 codex review --base <base> -c 'model_reasoning_effort="high"' --enable web_search_cached < /dev/null 2>"$TMPERR"
+_gstack_codex_timeout_wrapper 540 codex review --base <base> -c 'model_reasoning_effort="high"' -c 'web_search="cached"' < /dev/null 2>"$TMPERR"
```
**No prompt argument.** `--base` is what scopes the review, and the positional `[PROMPT]` is mutually exclusive with it — passing both fails at argv parsing. Do NOT "fix" that error by dropping `--base` and keeping the prompt: a prompt-only `codex review` silently falls back to the **uncommitted working-tree** scope (`git status --short; git diff`), so it reviews the wrong changes and reports "no changes" on a clean tree. Prompt text describing the diff range does not change what the CLI feeds the reviewer. Unlike the adversarial pass above, which uses `codex exec` and really does run the git command it's told to, this path gets a pre-computed diff from the CLI — which is also why it needs no filesystem boundary.
@@ -2712,7 +2731,7 @@ stay agent judgment; the slot pick stays `gstack-next-version`.
```bash
bun run $GSTACK_ROOT/bin/gstack-version-bump write --version "$NEW_VERSION"
```
- The CLI validates the 4-digit `MAJOR.MINOR.PATCH.MICRO` pattern and writes **both** VERSION and package.json. On a half-write (VERSION written, package.json failed) it exits 3 — re-run, and classify will report DRIFT_STALE_PKG for `repair` to fix.
+ The CLI validates the version pattern (4-digit `MAJOR.MINOR.PATCH.MICRO`; 3-digit for repos whose pinned version source uses plain semver) and writes VERSION, the manifest, and the manifest's npm lockfiles (`package-lock.json` / `npm-shrinkwrap.json`) when they already exist — never created. The manifest is resolved as `--package-json-path` → `.gstack/package-json-path` → `./package.json`, so a repo whose only Node package lives in a subdirectory (`web/`, `app/`) is covered by a one-line pin instead of silently getting a VERSION-only bump. npm rejects 4-component versions, so the manifest and lockfiles carry the npm-valid 3-digit translation (`1.67.0.0` → `1.67.0`); VERSION stays the 4-digit source of truth and classify judges drift against the translated form. On a half-write it exits 3 — re-run, and classify will report DRIFT_STALE_PKG for `repair` to fix.
5. **Record the release decision** (durable cross-session memory). The bump level is a real decision the next session should not re-derive blind:
```bash
diff --git a/test/fixtures/ios-qa/FixtureApp/Package.swift b/test/fixtures/ios-qa/FixtureApp/Package.swift
index 40477f0fe..c5b9a7318 100644
--- a/test/fixtures/ios-qa/FixtureApp/Package.swift
+++ b/test/fixtures/ios-qa/FixtureApp/Package.swift
@@ -32,7 +32,17 @@ let package = Package(
dependencies: [],
path: "Sources/DebugBridgeTouch",
publicHeadersPath: "include",
+ cSettings: [
+ // Explicit, because the source guard depends on it. SwiftPM's
+ // implicit DEBUG for C-family targets is not something to bet a
+ // private-API exposure on — the two Swift targets already declare
+ // it, and this target is the one that actually links private API.
+ .define("DEBUG", .when(configuration: .debug)),
+ ],
linkerSettings: [
+ // IOKit is loaded dynamically via dlopen at runtime (it's a
+ // private framework on iOS and can't be linked statically).
+ // UIKit links normally.
.linkedFramework("UIKit", .when(platforms: [.iOS])),
]
),
diff --git a/test/fixtures/ios-qa/FixtureApp/Sources/DebugBridgeTouch/DebugBridgeTouch.m b/test/fixtures/ios-qa/FixtureApp/Sources/DebugBridgeTouch/DebugBridgeTouch.m
index aa6954c6d..e82199467 100644
--- a/test/fixtures/ios-qa/FixtureApp/Sources/DebugBridgeTouch/DebugBridgeTouch.m
+++ b/test/fixtures/ios-qa/FixtureApp/Sources/DebugBridgeTouch/DebugBridgeTouch.m
@@ -20,7 +20,29 @@
#import "DebugBridgeTouch.h"
#import <TargetConditionals.h>
-#if TARGET_OS_IOS
+#if !defined(DEBUG)
+
+// RELEASE BUILD: this file deliberately emits NOTHING — no class, no symbols, no
+// private-API references. The header still declares the interface, which is inert
+// on its own; every consumer of DebugBridgeTouch is itself `#if DEBUG` guarded, so
+// nothing references it here and nothing fails to link.
+//
+// This guard was added because the comments at the top of this file and in the
+// header both PROMISED "DEBUG-only; never shipped to App Store" and "never link in
+// Release" — and nothing enforced it. Only `#if TARGET_OS_IOS` was tested, so a
+// Release build for iOS compiled the whole implementation in. Measured on a real
+// app (Seize Day, 2026-08-15), `nm -j` on a Release binary returned 15 DebugBridge
+// symbols including +[DebugBridgeTouch sendTapAtPoint:inWindow:], plus
+// IOHIDEventCreateDigitizer, AXSSetAutomationEnabled and IOKit.framework strings.
+// That is a Guideline 2.5.1 private-API exposure in a shippable binary.
+//
+// Package.swift's stated guard — `.when(configuration: .debug)` on the consuming
+// target's dependency — only exists for SwiftPM consumers. An app integrating this
+// as a local package inside an .xcodeproj cannot express it: Xcode's Filters column
+// in Frameworks/Libraries offers platform conditions only, never configuration. So
+// the guard has to live here, in the source, where it holds for every consumer.
+
+#elif TARGET_OS_IOS
#import <UIKit/UIKit.h>
#import <objc/runtime.h>
@@ -340,4 +362,4 @@ static id DBT_HitTestView(UIWindow *window, CGPoint point) {
}
@end
-#endif // TARGET_OS_IOS
+#endif // !DEBUG / TARGET_OS_IOS
diff --git a/test/fixtures/ios-qa/FixtureApp/Sources/DebugBridgeUI/Bridges.swift b/test/fixtures/ios-qa/FixtureApp/Sources/DebugBridgeUI/Bridges.swift
index 4a91142de..74e227928 100644
--- a/test/fixtures/ios-qa/FixtureApp/Sources/DebugBridgeUI/Bridges.swift
+++ b/test/fixtures/ios-qa/FixtureApp/Sources/DebugBridgeUI/Bridges.swift
@@ -60,12 +60,13 @@ private func debugBridgeAccessibilityChildren(of element: NSObject) -> [NSObject
@MainActor
enum ScreenshotBridgeImpl {
- /// Capture a PNG of the active window. Uses UIGraphicsImageRenderer
+ /// Capture a PNG of the visible UI. Uses UIGraphicsImageRenderer
/// (modern API, replaces UIGraphicsBeginImageContext). Returns nil if
- /// no key window is available (e.g., app backgrounded).
+ /// no window is available (e.g., app backgrounded).
static func capturePNG() -> Data? {
- guard let scene = activeScene(), let window = activeKeyWindow(in: scene) else { return nil }
- let bounds = window.bounds
+ guard let scene = activeScene() else { return nil }
+ let windows = orderedWindows(in: scene)
+ guard let bounds = windows.first?.bounds else { return nil }
let format = UIGraphicsImageRendererFormat.default()
// /tap consumes UIKit window points. Render at 1x so screenshot pixels
// use that same coordinate space on 2x/3x devices.
@@ -75,24 +76,73 @@ enum ScreenshotBridgeImpl {
// drawHierarchy is the documented way to snapshot real UIKit
// layers including layer-backed views. afterScreenUpdates: false
// because we want the CURRENT visible state, not a forced layout.
- window.drawHierarchy(in: bounds, afterScreenUpdates: false)
+ //
+ // Back-to-front across every window: a UIMenu, alert or action
+ // sheet lives in its OWN window, so drawing only the key window
+ // silently drops it from the screenshot.
+ for window in windows.reversed() {
+ window.drawHierarchy(in: window.bounds, afterScreenUpdates: false)
+ }
}
return image.pngData()
}
- private static func activeScene() -> UIWindowScene? {
+ static func activeScene() -> UIWindowScene? {
UIApplication.shared.connectedScenes
.compactMap { $0 as? UIWindowScene }
.first { $0.activationState == .foregroundActive }
?? (UIApplication.shared.connectedScenes.first as? UIWindowScene)
}
- private static func activeKeyWindow(in scene: UIWindowScene) -> UIWindow? {
+ static func activeKeyWindow(in scene: UIWindowScene) -> UIWindow? {
let windows = scene.windows.filter { window in
!window.isHidden && !String(describing: type(of: window)).contains("PassThroughWindow")
}
return windows.first(where: { $0.isKeyWindow }) ?? windows.max(by: { $0.windowLevel < $1.windowLevel })
}
+
+ /// Visible windows, front-most first: higher `windowLevel` wins, and within
+ /// a level the later window sits on top. Menus, alerts and action sheets
+ /// get their own window, so `isKeyWindow` alone does not find them.
+ /// PassThroughWindow overlays stay filtered (same rule as activeKeyWindow).
+ static func orderedWindows(in scene: UIWindowScene) -> [UIWindow] {
+ scene.windows
+ .filter {
+ !$0.isHidden && $0.alpha > 0.01 && !$0.bounds.isEmpty
+ && !String(describing: type(of: $0)).contains("PassThroughWindow")
+ }
+ .enumerated()
+ .sorted {
+ ($0.element.windowLevel.rawValue, Double($0.offset))
+ > ($1.element.windowLevel.rawValue, Double($1.offset))
+ }
+ .map(\.element)
+ }
+
+ /// The window the user is actually touching — front-most, not merely key.
+ static func frontmostWindow() -> UIWindow? {
+ guard let scene = activeScene() else { return nil }
+ return orderedWindows(in: scene).first ?? activeKeyWindow(in: scene)
+ }
+
+ /// Roots to search, front-most first: for each window, the top-most
+ /// presented view controller's view before the window itself.
+ ///
+ /// Tree order is NOT front-most order. A presented sheet sits *after* the
+ /// screen it covers in `window.subviews`, so a walk rooted at the window
+ /// emits the covered screen first and a client taking the first match for a
+ /// label gets a control the user cannot reach.
+ static func searchRoots() -> [UIView] {
+ guard let scene = activeScene() else { return [] }
+ var roots: [UIView] = []
+ for window in orderedWindows(in: scene) {
+ var controller = window.rootViewController
+ while let presented = controller?.presentedViewController { controller = presented }
+ if let view = controller?.view, view !== window { roots.append(view) }
+ roots.append(window)
+ }
+ return roots
+ }
}
// MARK: - ElementsBridge implementation
@@ -103,19 +153,26 @@ enum ElementsBridgeImpl {
/// Each entry has frame (in window coords), accessibility label,
/// identifier, traits as a bitmask, and a parent path. Skips
/// non-accessible / hidden views.
+ /// Front-most content first, so a client taking the first match for a
+ /// label gets the element the user can actually reach — a presented view
+ /// is also reachable through its window, so the roots overlap by design
+ /// and the shared visited set emits each view once, at its front-most
+ /// position.
static func snapshot() -> [JSONDict] {
- guard let scene = activeScene(), let window = activeKeyWindow(in: scene) else { return [] }
var elements: [JSONDict] = []
var visited = Set<ObjectIdentifier>()
var remaining = 2_048
- collect(
- view: window,
- parentPath: "",
- window: window,
- visited: &visited,
- remaining: &remaining,
- into: &elements
- )
+ for root in ScreenshotBridgeImpl.searchRoots() {
+ guard let window = (root as? UIWindow) ?? root.window else { continue }
+ collect(
+ view: root,
+ parentPath: "",
+ window: window,
+ visited: &visited,
+ remaining: &remaining,
+ into: &elements
+ )
+ }
return elements
}
@@ -263,20 +320,6 @@ enum ElementsBridgeImpl {
}
}
}
-
- private static func activeScene() -> UIWindowScene? {
- UIApplication.shared.connectedScenes
- .compactMap { $0 as? UIWindowScene }
- .first { $0.activationState == .foregroundActive }
- ?? (UIApplication.shared.connectedScenes.first as? UIWindowScene)
- }
-
- private static func activeKeyWindow(in scene: UIWindowScene) -> UIWindow? {
- let windows = scene.windows.filter { window in
- !window.isHidden && !String(describing: type(of: window)).contains("PassThroughWindow")
- }
- return windows.first(where: { $0.isKeyWindow }) ?? windows.max(by: { $0.windowLevel < $1.windowLevel })
- }
}
// MARK: - MutationBridge implementation
@@ -301,7 +344,9 @@ enum MutationBridgeImpl {
guard let x = payload["x"] as? NSNumber,
let y = payload["y"] as? NSNumber else { return false }
let point = CGPoint(x: x.doubleValue, y: y.doubleValue)
- guard let scene = activeScene(), let window = activeKeyWindow(in: scene) else { return false }
+ // Front-most, not merely key: a menu/alert/sheet lives in its own
+ // window, and a tap aimed there must not land on the covered screen.
+ guard let window = ScreenshotBridgeImpl.frontmostWindow() else { return false }
if let element = findActivatableAXElement(at: point, in: window),
element.accessibilityActivate() {
return true
@@ -353,8 +398,10 @@ enum MutationBridgeImpl {
/// Set text on the first responder if it's a UITextField or UITextView.
private static func handleType(_ payload: JSONDict) -> Bool {
guard let text = payload["text"] as? String else { return false }
- guard let scene = activeScene(), let window = activeKeyWindow(in: scene) else { return false }
- guard let responder = findFirstResponder(in: window) else { return false }
+ // Search front-most roots first: the focused field in a presented
+ // sheet wins over a same-named field on the covered screen.
+ guard let responder = ScreenshotBridgeImpl.searchRoots()
+ .lazy.compactMap({ findFirstResponder(in: $0) }).first else { return false }
if let field = responder as? UITextField {
field.text = text
field.sendActions(for: .editingChanged)
@@ -379,8 +426,10 @@ enum MutationBridgeImpl {
let from = CGPoint(x: fx.doubleValue, y: fy.doubleValue)
let to = CGPoint(x: tx.doubleValue, y: ty.doubleValue)
- guard let scene = activeScene(), let window = activeKeyWindow(in: scene) else { return false }
- guard let hit = window.hitTest(from, with: nil) else { return false }
+ // Hit-test front-most roots first (sheet before covered screen).
+ guard let hit = ScreenshotBridgeImpl.searchRoots()
+ .lazy.compactMap({ $0.hitTest($0.convert(from, from: nil), with: nil) })
+ .first else { return false }
// Find the nearest enclosing UIScrollView.
var node: UIView? = hit
@@ -420,20 +469,6 @@ enum MutationBridgeImpl {
}
return nil
}
-
- private static func activeScene() -> UIWindowScene? {
- UIApplication.shared.connectedScenes
- .compactMap { $0 as? UIWindowScene }
- .first { $0.activationState == .foregroundActive }
- ?? (UIApplication.shared.connectedScenes.first as? UIWindowScene)
- }
-
- private static func activeKeyWindow(in scene: UIWindowScene) -> UIWindow? {
- let windows = scene.windows.filter { window in
- !window.isHidden && !String(describing: type(of: window)).contains("PassThroughWindow")
- }
- return windows.first(where: { $0.isKeyWindow }) ?? windows.max(by: { $0.windowLevel < $1.windowLevel })
- }
}
#endif // DEBUG && canImport(UIKit)
diff --git a/test/gbrain-detection-override.test.ts b/test/gbrain-detection-override.test.ts
index c4905d897..7ecae820b 100644
--- a/test/gbrain-detection-override.test.ts
+++ b/test/gbrain-detection-override.test.ts
@@ -157,6 +157,33 @@ describe('gbrain detection override → gen-skill-docs', () => {
}
});
+ test('with status "engine-locked" (PGLite single-writer, #2456), brain blocks render like "ok"', () => {
+ const { tmpHome, cleanup } = makeFixture(
+ JSON.stringify({
+ gbrain_local_status: 'engine-locked',
+ gbrain_on_path: true,
+ gbrain_version: 'test-0.42.26',
+ }),
+ );
+ try {
+ const snap = regenAndSnapshot({
+ respectDetection: true,
+ tmpHome,
+ files: PROBE_FILES,
+ });
+ const content = probeUnion(snap);
+
+ // PGLite is single-writer: a live `gbrain serve` (the recommended
+ // /setup-gbrain default spawns one at session start) legitimately owns
+ // the embedded DB. gbrain is installed and healthy — a transient lock
+ // must not silently strip brain blocks (same reasoning as "timeout").
+ expect(content).toContain('## Save Results to Brain');
+ expect(content).toContain('gbrain put "office-hours/');
+ } finally {
+ cleanup();
+ }
+ });
+
test('with detected:false (status != "ok"), brain blocks stay suppressed', () => {
const { tmpHome, cleanup } = makeFixture(
JSON.stringify({ gbrain_local_status: 'no-cli', gbrain_on_path: false, gbrain_version: null }),
diff --git a/test/gbrain-dream-stage.test.ts b/test/gbrain-dream-stage.test.ts
index d53a6568c..c5f3b6814 100644
--- a/test/gbrain-dream-stage.test.ts
+++ b/test/gbrain-dream-stage.test.ts
@@ -160,15 +160,31 @@ describe("CLI gate wiring (dry-run subprocess — never spawns a real dream)", (
// Canned `gbrain dream` cycle logs (verbatim shapes observed against a real
// 0.41.x brain). These let us test the post-flight guard WITHOUT a real cycle.
const LOG = {
- // Pack lacks the code-symbol phase: extract_atoms is undeclared AND the edge
- // resolver matches nothing. Both signals present — pack message must win.
- notCodeAware:
+ // #2341: the DEFAULT base packs legitimately skip the CONTENT phases
+ // (extract_atoms, synthesize_concepts) while resolve_symbol_edges still runs
+ // — gbrain's only emitters of "does not declare this phase" are those
+ // content phases, so the bare-phrase match fired on EVERY base-pack brain
+ // and told users to churn schema packs for nothing. This shape (content
+ // phase undeclared, resolver ran, resolved 0) must classify as the 0-edge
+ // outcome, not the pack-capability one.
+ basePackZeroEdges:
"[cycle.extract] done\n" +
" - extract_atoms extract_atoms: active pack does not declare this phase\n" +
"[cycle.resolve_symbol_edges] start\n" +
"[cycle.resolve_symbol_edges] done\n" +
" ✓ resolve_symbol_edges 3864 chunk(s) walked; resolved 0, ambiguous 0, unmatched 0\n" +
" totals: extracted=0 embedded=1\n",
+ // #2341 headline shape: base pack skips content phases AND the graph built
+ // fine — a healthy run that used to WARN.
+ basePackBuiltEdges:
+ " - extract_atoms extract_atoms: active pack does not declare this phase\n" +
+ " ✓ resolve_symbol_edges 6001 chunk(s) walked; resolved 42, ambiguous 0, unmatched 0\n" +
+ " - synthesize_concepts synthesize_concepts: active pack does not declare this phase\n",
+ // The GRAPH phase itself is undeclared: the one shape where the
+ // pack-capability WARN is the right diagnosis.
+ graphPhaseUndeclared:
+ " - resolve_symbol_edges resolve_symbol_edges: active pack does not declare this phase\n" +
+ " totals: extracted=0 embedded=1\n",
// Embed phase failed for a missing key (isolated: no pack-capability line).
embedFailed:
"[cycle.embed] start\n" +
@@ -202,8 +218,19 @@ describe("parseResolvedEdges", () => {
});
describe("classifyDreamOutcome — post-flight truth guard", () => {
- it("flags a non-code-aware schema pack (wins over the 0-edge signal)", () => {
- const w = classifyDreamOutcome(LOG.notCodeAware);
+ it("base-pack content-phase skips classify as 0-edge, NOT pack-capability (#2341)", () => {
+ const w = classifyDreamOutcome(LOG.basePackZeroEdges);
+ expect(w).not.toBeNull();
+ expect(w).toContain("resolved 0");
+ expect(w).not.toContain("code-aware");
+ });
+
+ it("a healthy base-pack run with a built graph is clean (#2341 headline)", () => {
+ expect(classifyDreamOutcome(LOG.basePackBuiltEdges)).toBeNull();
+ });
+
+ it("flags pack capability only when the GRAPH phase itself is undeclared", () => {
+ const w = classifyDreamOutcome(LOG.graphPhaseUndeclared);
expect(w).not.toBeNull();
expect(w).toContain("schema pack");
expect(w).toContain("code-aware");
diff --git a/test/gbrain-local-status.test.ts b/test/gbrain-local-status.test.ts
index 495d28371..299f32f44 100644
--- a/test/gbrain-local-status.test.ts
+++ b/test/gbrain-local-status.test.ts
@@ -66,6 +66,8 @@ function makeEnv(opts: {
withConfig?: boolean;
/** #2051: config carries gbrain's remote_mcp thin-client marker. */
thinClientConfig?: boolean;
+ /** #2520: content for ~/.claude.json (host MCP registrations). */
+ claudeJson?: object;
}): FakeEnv {
const tmp = mkdtempSync(join(tmpdir(), "gbrain-local-status-test-"));
const bindir = join(tmp, "bin");
@@ -99,6 +101,10 @@ function makeEnv(opts: {
chmodSync(gbrainPath, 0o755);
}
+ if (opts.claudeJson) {
+ writeFileSync(join(home, ".claude.json"), JSON.stringify(opts.claudeJson));
+ }
+
return {
tmp,
bindir,
@@ -263,20 +269,46 @@ describe("lib/gbrain-local-status — status classification", () => {
expect(localEngineStatus({ noCache: true })).toBe("timeout");
});
- it("honors GBRAIN_HOME for config detection (codex D11)", () => {
- // Config lives ONLY at the alternate GBRAIN_HOME; ~/.gbrain has none.
+ it("honors GBRAIN_HOME for config detection (codex D11) with gbrain's parent-dir semantics (#2521)", () => {
+ // Config lives ONLY under the alternate GBRAIN_HOME; ~/.gbrain has none.
+ // gbrain's configDir() treats GBRAIN_HOME as a PARENT dir and appends
+ // `.gbrain` itself: GBRAIN_HOME=/x → /x/.gbrain/config.json.
env = makeEnv({ withGbrain: true, gbrainBehavior: "ok", withConfig: false });
restoreEnv = applyEnv(env);
const altHome = join(env.tmp, "alt-gbrain");
- mkdirSync(altHome, { recursive: true });
+ mkdirSync(join(altHome, ".gbrain"), { recursive: true });
writeFileSync(
- join(altHome, "config.json"),
+ join(altHome, ".gbrain", "config.json"),
JSON.stringify({ engine: "pglite", database_url: "pglite:///fake" }),
);
// Without GBRAIN_HOME: misclassified as missing-config.
expect(localEngineStatus({ noCache: true })).toBe("missing-config");
- // With GBRAIN_HOME: the relocated config is found.
+ // With GBRAIN_HOME: the relocated config is found at $GBRAIN_HOME/.gbrain.
+ process.env.GBRAIN_HOME = altHome;
+ expect(localEngineStatus({ noCache: true })).toBe("ok");
+ });
+
+ it("does NOT read $GBRAIN_HOME/config.json directly — gbrain never reads that file (#2521)", () => {
+ // A config placed at gstack's OLD (wrong) resolution must be invisible:
+ // gbrain itself would report "No brain configured" for this layout, so
+ // gstack classifying "ok" from it is the #2521 split-brain.
+ env = makeEnv({ withGbrain: true, gbrainBehavior: "ok", withConfig: false });
+ restoreEnv = applyEnv(env);
+ const altHome = join(env.tmp, "alt-gbrain-flat");
+ mkdirSync(altHome, { recursive: true });
+ writeFileSync(
+ join(altHome, "config.json"),
+ JSON.stringify({ engine: "pglite", database_url: "pglite:///fake" }),
+ );
process.env.GBRAIN_HOME = altHome;
+ expect(localEngineStatus({ noCache: true })).toBe("missing-config");
+ });
+
+ it("with GBRAIN_HOME unset, config resolution stays at ~/.gbrain (#2521 unset half)", () => {
+ env = makeEnv({ withGbrain: true, gbrainBehavior: "ok", withConfig: true });
+ restoreEnv = applyEnv(env);
+ // applyEnv deletes GBRAIN_HOME; config was written at $HOME/.gbrain.
+ expect(process.env.GBRAIN_HOME).toBeUndefined();
expect(localEngineStatus({ noCache: true })).toBe("ok");
});
});
@@ -526,3 +558,125 @@ describe("lib/gbrain-local-status — thin-client (#2051)", () => {
expect(r.status).toBe(1);
});
});
+
+// ---------------------------------------------------------------------------
+// #2520: bearer-token thin clients (`gbrain connect --token`) — no remote_mcp
+// marker in config.json; the evidence is the host's remote-HTTP MCP
+// registration in ~/.claude.json.
+// ---------------------------------------------------------------------------
+
+describe("lib/gbrain-local-status — bearer-token thin-client (#2520)", () => {
+ let env: FakeEnv | null = null;
+ let restoreEnv: (() => void) | null = null;
+
+ afterEach(() => {
+ if (restoreEnv) restoreEnv();
+ if (env) env.cleanup();
+ env = null;
+ restoreEnv = null;
+ });
+
+ const REMOTE_GBRAIN = {
+ type: "http",
+ url: "https://brain.example.com/mcp",
+ headers: { Authorization: "Bearer test-token" },
+ };
+ const LOCAL_GBRAIN = { type: "stdio", command: "gbrain", args: ["serve"] };
+
+ it("returns 'thin-client' when config.json is absent but a remote-HTTP gbrain MCP is registered (user scope)", () => {
+ env = makeEnv({
+ withGbrain: true,
+ gbrainBehavior: "ok",
+ withConfig: false,
+ claudeJson: { mcpServers: { gbrain: REMOTE_GBRAIN } },
+ });
+ restoreEnv = applyEnv(env);
+ expect(localEngineStatus({ noCache: true })).toBe("thin-client");
+ });
+
+ it("returns 'thin-client' when config.json is absent and the registration is PROJECT-scoped (#2499)", () => {
+ env = makeEnv({
+ withGbrain: true,
+ gbrainBehavior: "ok",
+ withConfig: false,
+ claudeJson: {
+ projects: { "/some/repo": { mcpServers: { "gbrain-remote": REMOTE_GBRAIN } } },
+ },
+ });
+ restoreEnv = applyEnv(env);
+ expect(localEngineStatus({ noCache: true })).toBe("thin-client");
+ });
+
+ it("reclassifies a failed local probe (engine-locked) as 'thin-client' when the only gbrain MCP is remote", () => {
+ // The reporter's exact shape: leftover local pglite config, dead/absent
+ // local engine (probe exits 124 "connect timed out"), brain fully working
+ // over remote-HTTP MCP with a bearer token.
+ env = makeEnv({
+ withGbrain: true,
+ gbrainBehavior: "engine-locked",
+ withConfig: true,
+ claudeJson: { mcpServers: { gbrain: REMOTE_GBRAIN } },
+ });
+ restoreEnv = applyEnv(env);
+ expect(localEngineStatus({ noCache: true })).toBe("thin-client");
+ });
+
+ it("reclassifies broken-db as 'thin-client' when the only gbrain MCP is remote", () => {
+ env = makeEnv({
+ withGbrain: true,
+ gbrainBehavior: "broken-db",
+ withConfig: true,
+ claudeJson: { mcpServers: { gbrain: REMOTE_GBRAIN } },
+ });
+ restoreEnv = applyEnv(env);
+ expect(localEngineStatus({ noCache: true })).toBe("thin-client");
+ });
+
+ it("preserves 'engine-locked' when a local-stdio gbrain MCP is ALSO registered (federation guard)", () => {
+ // A local-stdio registration means the user runs a local engine —
+ // local-engine statuses must keep their precise meaning, even if a
+ // second (e.g. team) brain is registered remote-HTTP.
+ env = makeEnv({
+ withGbrain: true,
+ gbrainBehavior: "engine-locked",
+ withConfig: true,
+ claudeJson: {
+ mcpServers: { gbrain: LOCAL_GBRAIN, "gbrain-work": REMOTE_GBRAIN },
+ },
+ });
+ restoreEnv = applyEnv(env);
+ expect(localEngineStatus({ noCache: true })).toBe("engine-locked");
+ });
+
+ it("still returns 'missing-config' when no gbrain MCP registration exists (discriminator)", () => {
+ env = makeEnv({
+ withGbrain: true,
+ gbrainBehavior: "ok",
+ withConfig: false,
+ claudeJson: { mcpServers: { "other-server": { type: "http", url: "https://x.example/mcp" } } },
+ });
+ restoreEnv = applyEnv(env);
+ expect(localEngineStatus({ noCache: true })).toBe("missing-config");
+ });
+
+ it("--is-ok exits 0 on a bearer thin-client fixture (end-to-end gate)", () => {
+ env = makeEnv({
+ withGbrain: true,
+ gbrainBehavior: "engine-locked",
+ withConfig: true,
+ claudeJson: { mcpServers: { gbrain: REMOTE_GBRAIN } },
+ });
+ const detectBin = join(import.meta.dir, "..", "bin", "gstack-gbrain-detect");
+ const bunDir = dirname(process.execPath);
+ const r = spawnSync(detectBin, ["--is-ok"], {
+ encoding: "utf-8",
+ env: {
+ HOME: env.home,
+ PATH: `${env.bindir}:${bunDir}:/usr/bin:/bin`,
+ GSTACK_HOME: env.gstackHome,
+ GSTACK_DETECT_NO_CACHE: "1",
+ },
+ });
+ expect(r.status).toBe(0);
+ });
+});
diff --git a/test/gbrain-refresh-install-render.test.ts b/test/gbrain-refresh-install-render.test.ts
index 0b803ed2a..b630402c6 100644
--- a/test/gbrain-refresh-install-render.test.ts
+++ b/test/gbrain-refresh-install-render.test.ts
@@ -44,13 +44,18 @@ describe('gstack-config gbrain-refresh: machine-wide render guards', () => {
expect(branch).toContain('command -v bun');
});
- test('renders the :user variant in place into the install', () => {
+ test('renders the :user variant for the claude host', () => {
expect(branch).toContain('gen:skill-docs:user --host claude');
});
- test('is self-documenting about the reset --hard / re-run cycle', () => {
- expect(branch).toContain('reset --hard');
- expect(branch).toContain('gbrain-refresh');
+ // #2569: the render goes to an UNTRACKED out-dir, never in place — the old
+ // in-place render dirtied the install checkout on every refresh, and this
+ // branch used to self-document a reset --hard / re-run cycle as the
+ // workaround. The out-dir render makes that cycle unnecessary.
+ test('renders to an untracked out-dir, never in place (#2569)', () => {
+ expect(branch).toContain('--out-dir');
+ expect(branch).toContain('render/claude');
+ expect(branch).not.toContain('reset --hard');
});
});
diff --git a/test/gbrain-spawn-windows-shell.test.ts b/test/gbrain-spawn-windows-shell.test.ts
index d968d2f68..76a8b68ab 100644
--- a/test/gbrain-spawn-windows-shell.test.ts
+++ b/test/gbrain-spawn-windows-shell.test.ts
@@ -2,6 +2,8 @@ import { describe, test, expect } from "bun:test";
import * as fs from "fs";
import * as path from "path";
+import { bashScriptInvocation, gbrainInvocation, windowsShellQuote } from "../lib/gbrain-exec";
+
const ROOT = path.resolve(import.meta.dir, "..");
const read = (rel: string) => fs.readFileSync(path.join(ROOT, rel), "utf-8");
@@ -16,30 +18,149 @@ describe("#1731 gbrain spawns carry the Windows shell flag", () => {
expect(src).toMatch(/export const NEEDS_SHELL_ON_WINDOWS\s*=\s*process\.platform === "win32"/);
});
- // Every direct `gbrain` child spawn in these files must be matched by a
- // shell:NEEDS_SHELL_ON_WINDOWS flag. Count openers vs flags as a cheap,
- // refactor-resistant invariant.
- const gbrainSpawnFiles = [
- "lib/gbrain-exec.ts",
- "lib/gbrain-sources.ts",
- "lib/gbrain-local-status.ts",
- ];
- for (const rel of gbrainSpawnFiles) {
- test(`${rel}: every gbrain spawn has shell:NEEDS_SHELL_ON_WINDOWS`, () => {
+ // #2471 upgraded the #1731 invariant for the seamed files: gbrain spawns
+ // there must build their (cmd, argv, shell) triple via gbrainInvocation()
+ // (which owns BOTH the shell flag and cmd.exe quoting), so a direct
+ // `spawn*("gbrain"` opener is itself the violation.
+ const seamedFiles = ["lib/gbrain-exec.ts", "lib/gbrain-sources.ts"];
+ for (const rel of seamedFiles) {
+ test(`${rel}: gbrain spawns route through gbrainInvocation (no direct openers)`, () => {
const src = read(rel);
- const spawnOpeners = src.match(/(spawnSync|spawn|execFileSync)\("gbrain"/g)?.length ?? 0;
- const shellFlags = src.match(/shell:\s*NEEDS_SHELL_ON_WINDOWS/g)?.length ?? 0;
- expect(spawnOpeners).toBeGreaterThan(0);
- expect(shellFlags).toBeGreaterThanOrEqual(spawnOpeners);
+ const directOpeners = src.match(/(spawnSync|spawn|execFileSync)\(\s*["']gbrain["']/g)?.length ?? 0;
+ expect(directOpeners).toBe(0);
+ expect(src).toContain("gbrainInvocation(");
});
}
- test("orchestrator brain-sync spawns carry the Windows shell flag", () => {
+ // Not-yet-seamed file: every direct gbrain spawn must still carry the
+ // #1731 shell flag. (Migrate to gbrainInvocation when next touched.)
+ test("lib/gbrain-local-status.ts: every gbrain spawn has shell:NEEDS_SHELL_ON_WINDOWS", () => {
+ const src = read("lib/gbrain-local-status.ts");
+ const spawnOpeners = src.match(/(spawnSync|spawn|execFileSync)\("gbrain"/g)?.length ?? 0;
+ const shellFlags = src.match(/shell:\s*NEEDS_SHELL_ON_WINDOWS/g)?.length ?? 0;
+ expect(spawnOpeners).toBeGreaterThan(0);
+ expect(shellFlags).toBeGreaterThanOrEqual(spawnOpeners);
+ });
+
+ // NOT the brain-sync script. `shell: true` is right for the gbrain.cmd shim
+ // and wrong for a bash shebang script: cmd.exe resolves .cmd/.bat via PATHEXT
+ // and has no concept of a shebang, so gstack-brain-sync came back as "is not
+ // recognized as an internal or external command" on EVERY Windows run. It
+ // needs an interpreter, not a shell — see bashScriptInvocation.
+ test("orchestrator invokes brain-sync through bash, never a raw spawn", () => {
const src = read("bin/gstack-gbrain-sync.ts");
- const brainSyncSpawns = src.match(/spawnSync\(brainSyncPath,/g)?.length ?? 0;
- expect(brainSyncSpawns).toBe(2);
- // Both spawnSync(brainSyncPath, ...) blocks must include the shell flag.
- const withShell = src.match(/spawnSync\(brainSyncPath,[\s\S]*?shell:\s*NEEDS_SHELL_ON_WINDOWS/g)?.length ?? 0;
- expect(withShell).toBe(2);
+ expect(src).toMatch(/bashScriptInvocation\(brainSyncPath, \["--discover-new"\]\)/);
+ expect(src).toMatch(/bashScriptInvocation\(brainSyncPath, \["--once"\]\)/);
+ // The old shape must not come back: it fails silently-ish on Windows.
+ expect(src).not.toMatch(/spawnSync\(brainSyncPath,/);
+ expect(src).not.toMatch(/spawnSync\(brainSyncPath,[\s\S]*?shell:\s*NEEDS_SHELL_ON_WINDOWS/);
+ });
+});
+
+describe("bashScriptInvocation", () => {
+ const WIN_BASH = "C:\\Program Files\\Git\\bin\\bash.exe";
+
+ test("POSIX execs the script directly, no interpreter needed", () => {
+ const inv = bashScriptInvocation("/home/u/.claude/skills/gstack/bin/gstack-brain-sync", ["--once"], {
+ platform: "linux",
+ });
+ expect(inv).toEqual({
+ cmd: "/home/u/.claude/skills/gstack/bin/gstack-brain-sync",
+ argv: ["--once"],
+ shell: false,
+ });
+ });
+
+ test("Windows routes through Git bash with the script as argv[0]", () => {
+ const inv = bashScriptInvocation("C:\\Users\\u\\.claude\\skills\\gstack\\bin\\gstack-brain-sync", ["--once"], {
+ platform: "win32",
+ exists: (p) => p === WIN_BASH,
+ env: {},
+ });
+ expect(inv?.cmd).toBe(WIN_BASH);
+ expect(inv?.argv[1]).toBe("--once");
+ });
+
+ test("Windows forward-slashes the script path", () => {
+ // bash treats backslashes as escapes, so a verbatim Windows path loses its
+ // separators and the script is never found.
+ const inv = bashScriptInvocation("C:\\Users\\u\\bin\\gstack-brain-sync", [], {
+ platform: "win32",
+ exists: (p) => p === WIN_BASH,
+ env: {},
+ });
+ expect(inv?.argv[0]).toBe("C:/Users/u/bin/gstack-brain-sync");
+ expect(inv?.argv[0]).not.toContain("\\");
+ });
+
+ test("never asks for a shell — cmd.exe is what broke this", () => {
+ const inv = bashScriptInvocation("C:\\x\\gstack-brain-sync", [], {
+ platform: "win32",
+ exists: (p) => p === WIN_BASH,
+ env: {},
+ });
+ expect(inv?.shell).toBe(false);
+ });
+
+ test("GSTACK_BASH overrides the search for unusual installs", () => {
+ const custom = "D:\\tools\\git\\bin\\bash.exe";
+ const inv = bashScriptInvocation("C:\\x\\gstack-brain-sync", [], {
+ platform: "win32",
+ exists: (p) => p === custom || p === WIN_BASH,
+ env: { GSTACK_BASH: custom },
+ });
+ expect(inv?.cmd).toBe(custom);
+ });
+
+ test("returns null when Windows has no bash, so the caller can say why", () => {
+ const inv = bashScriptInvocation("C:\\x\\gstack-brain-sync", [], {
+ platform: "win32",
+ exists: () => false,
+ env: {},
+ });
+ expect(inv).toBeNull();
+ });
+});
+
+// #2471: with `shell: true` on Windows, node/bun JOIN argv into one cmd.exe
+// string without quoting — a path with a space (`C:\Users\First Last\repo`)
+// splits into two arguments and `gbrain sources add --path` targets the wrong
+// directory. The invocation seam quotes every risky argument exactly once.
+describe("#2471 gbrain invocation seam quotes for cmd.exe", () => {
+ test("safe charset passes through untouched", () => {
+ expect(windowsShellQuote("sources")).toBe("sources");
+ expect(windowsShellQuote("--json")).toBe("--json");
+ expect(windowsShellQuote("C:\\Users\\j\\repo")).toBe("C:\\Users\\j\\repo");
+ });
+
+ test("a path with a space is double-quoted", () => {
+ expect(windowsShellQuote("C:\\Users\\First Last\\repo")).toBe('"C:\\Users\\First Last\\repo"');
+ });
+
+ test("embedded quotes are doubled (cmd.exe escape)", () => {
+ expect(windowsShellQuote('we"ird')).toBe('"we""ird"');
+ });
+
+ test("empty argument stays a quoted empty string, not vanishing", () => {
+ expect(windowsShellQuote("")).toBe('""');
+ });
+
+ test("shell metacharacters are wrapped so cmd.exe cannot interpret them", () => {
+ for (const bad of ["a b", "a&b", "a|b", "a>b", "a<b", "a^b", "a(b)", "a;b"]) {
+ expect(windowsShellQuote(bad).startsWith('"')).toBe(true);
+ }
+ });
+
+ test("gbrainInvocation on POSIX is a passthrough with shell:false", () => {
+ if (process.platform === "win32") return; // the win32 half is the map+quote path above
+ const inv = gbrainInvocation(["sources", "add", "id", "--path", "/a dir/with space"]);
+ expect(inv).toEqual({ cmd: "gbrain", argv: ["sources", "add", "id", "--path", "/a dir/with space"], shell: false });
+ });
+
+ test("no direct un-seamed gbrain spawn remains in gbrain-sources.ts", () => {
+ const src = read("lib/gbrain-sources.ts");
+ expect(src).not.toMatch(/spawnSync\(\s*["']gbrain["']/);
+ expect(src).not.toMatch(/execFileSync\(\s*["']gbrain["']/);
+ expect(src).toContain("gbrainInvocation(");
});
});
diff --git a/test/gen-skill-docs-out-dir.test.ts b/test/gen-skill-docs-out-dir.test.ts
index 7b187c56e..acf80075f 100644
--- a/test/gen-skill-docs-out-dir.test.ts
+++ b/test/gen-skill-docs-out-dir.test.ts
@@ -20,11 +20,17 @@ describe('gen-skill-docs --out-dir (B2 render isolation)', () => {
return createHash('sha256').update(fs.readFileSync(p)).digest('hex');
}
+ function porcelain(): string {
+ const r = spawnSync('git', ['status', '--porcelain'], { cwd: ROOT, encoding: 'utf-8' });
+ return r.status === 0 ? r.stdout : '';
+ }
+
test('renders :user to out-dir, rewrites section paths, leaves worktree canonical', () => {
const tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-home-'));
const outDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-out-'));
const worktreeSkill = path.join(ROOT, 'ship', 'SKILL.md');
const beforeHash = hashFile(worktreeSkill);
+ const beforePorcelain = porcelain();
try {
// Force gbrain detection ON for --respect-detection.
fs.writeFileSync(
@@ -47,6 +53,11 @@ describe('gen-skill-docs --out-dir (B2 render isolation)', () => {
// (a) worktree byte-unchanged
expect(hashFile(worktreeSkill)).toBe(beforeHash);
+ // (a2, #2569) the render adds ZERO new dirt to the source checkout —
+ // compared before/after rather than asserting empty, so a dev's own
+ // unrelated dirty files can't false-fail the suite.
+ expect(porcelain()).toBe(beforePorcelain);
+
// (b) inline block present in the rendered SKILL.md
expect(skillContent).toContain('Brain Context Load');
diff --git a/test/gen-skill-docs.test.ts b/test/gen-skill-docs.test.ts
index e9d440e02..04f50c7e9 100644
--- a/test/gen-skill-docs.test.ts
+++ b/test/gen-skill-docs.test.ts
@@ -1,4 +1,5 @@
import { describe, test, expect, beforeAll } from 'bun:test';
+import { assertSinglePreamble } from '../scripts/gen-skill-docs';
import { COMMAND_DESCRIPTIONS } from '../browse/src/commands';
import { SNAPSHOT_FLAGS } from '../browse/src/snapshot';
import * as fs from 'fs';
@@ -257,10 +258,16 @@ describe('gen-skill-docs', () => {
expect(violations).toEqual([]);
});
- test('package.json version matches VERSION file', () => {
+ test('package.json version matches VERSION file (npm-valid translation)', () => {
+ // Decision 11 (v1.67 wave): VERSION stays the 4-digit source of truth;
+ // package.json carries the npm-valid 3-digit translation (npm rejects a
+ // fourth component). The pre-v1.67 1:1 four-digit mirror is also accepted
+ // (grandfathered until the next write), matching gstack-version-bump's
+ // own drift contract.
const pkg = JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf-8'));
const version = fs.readFileSync(path.join(ROOT, 'VERSION'), 'utf-8').trim();
- expect(pkg.version).toBe(version);
+ const npmTranslation = version.split('.').slice(0, 3).join('.');
+ expect([npmTranslation, version]).toContain(pkg.version);
});
test('generated files are fresh (match --dry-run)', () => {
@@ -1507,6 +1514,25 @@ describe('CHANGELOG_WORKFLOW resolver', () => {
});
});
+// --- Duplicate {{PREAMBLE}} guard (#2508/#2362) ---
+
+describe('assertSinglePreamble', () => {
+ test('one {{PREAMBLE}} passes', () => {
+ expect(() => assertSinglePreamble('a\n{{PREAMBLE}}\nb', 'x/SKILL.md.tmpl')).not.toThrow();
+ });
+
+ test('zero {{PREAMBLE}} passes (sections have none)', () => {
+ expect(() => assertSinglePreamble('no macro here', 'x/sections/y.md.tmpl')).not.toThrow();
+ });
+
+ test('a second occurrence throws with the template path — even in prose', () => {
+ // The original #2508 bug WAS a prose mention: "emitted by {{PREAMBLE}}'s
+ // preamble bash". Resolution is context-blind, so the guard must be too.
+ const tmpl = '{{PREAMBLE}}\n\n...later: emitted by {{PREAMBLE}}\'s preamble bash';
+ expect(() => assertSinglePreamble(tmpl, 'spec/SKILL.md.tmpl')).toThrow(/spec\/SKILL\.md\.tmpl.*2 times/);
+ });
+});
+
// --- Parameterized resolver infrastructure tests ---
describe('parameterized resolver support', () => {
@@ -1537,8 +1563,11 @@ describe('parameterized resolver support', () => {
describe('preamble routing injection', () => {
const shipContent = readShipUnion();
- test('preamble bash checks for routing section in CLAUDE.md', () => {
- expect(shipContent).toContain('grep -q "## Skill routing" CLAUDE.md');
+ test('preamble bash checks for routing section in CLAUDE.md and AGENTS.md', () => {
+ // #2500: the probe iterates CLAUDE.md AND AGENTS.md — non-Claude hosts
+ // route skills via AGENTS.md, the cross-harness convention file.
+ expect(shipContent).toContain('for _RF in CLAUDE.md AGENTS.md');
+ expect(shipContent).toContain('grep -q "## Skill routing" "$_RF"');
expect(shipContent).toContain('HAS_ROUTING');
});
@@ -2003,8 +2032,15 @@ describe('Codex generation (--host codex)', () => {
// timeout-wrapper guidance documents the Codex CLI's own rollout-log
// location (a user-facing CLI path, same class as ~/.codex/logs/ in the
// codex skill), not the gstack Codex host install path.
+ // `~/.codex/config.toml` is the same user-facing class: the shared
+ // codexPreflight's model_unusable branch (#2477) points at the CLI's own
+ // config file, where the rejected `model =` pin lives.
expect(content).not.toContain('.agents/skills');
- expect(content.replaceAll('~/.codex/sessions/', '')).not.toContain('~/.codex/');
+ expect(
+ content
+ .replaceAll('~/.codex/sessions/', '')
+ .replaceAll('~/.codex/config.toml', ''),
+ ).not.toContain('~/.codex/');
});
test('Claude output unchanged: ship skill still uses .claude/skills/ paths', () => {
@@ -2012,8 +2048,14 @@ describe('Codex generation (--host codex)', () => {
expect(content).toContain('~/.claude/skills/gstack');
expect(content).not.toContain('.agents/skills');
// ~/.codex/sessions/ is the Codex CLI's rollout-log path (user-facing),
- // documented by the adversarial-pass timeout guidance — see review test above.
- expect(content.replaceAll('~/.codex/sessions/', '')).not.toContain('~/.codex/');
+ // documented by the adversarial-pass timeout guidance; ~/.codex/config.toml
+ // is the CLI's own config file (model_unusable guidance, #2477) — see the
+ // review test above.
+ expect(
+ content
+ .replaceAll('~/.codex/sessions/', '')
+ .replaceAll('~/.codex/config.toml', ''),
+ ).not.toContain('~/.codex/');
});
test('Claude output unchanged: all Claude skills have zero Codex paths', () => {
@@ -2023,10 +2065,16 @@ describe('Codex generation (--host codex)', () => {
// codex + autoplan document the Codex CLI auth file (~/.codex/auth.json)
// and log path (~/.codex/logs/) — those are user-facing Codex CLI paths,
// not the gstack Codex host install path. ~/.codex/sessions/ (rollout
- // logs, referenced by the review/ship timeout guidance) is the same
- // user-facing class, so it is scrubbed before the ban.
+ // logs, referenced by the review/ship timeout guidance) and
+ // ~/.codex/config.toml (the model_unusable guidance in the shared
+ // codexPreflight, #2477) are the same user-facing class, so they are
+ // scrubbed before the ban.
if (skill.dir !== 'pair-agent' && skill.dir !== 'codex' && skill.dir !== 'autoplan') {
- expect(content.replaceAll('~/.codex/sessions/', '')).not.toContain('~/.codex/');
+ expect(
+ content
+ .replaceAll('~/.codex/sessions/', '')
+ .replaceAll('~/.codex/config.toml', ''),
+ ).not.toContain('~/.codex/');
}
// gstack-upgrade legitimately references .agents/skills for cross-platform detection
if (skill.dir !== 'gstack-upgrade') {
@@ -2330,10 +2378,13 @@ describe('setup script validation', () => {
test('Codex install uses link_codex_skill_dirs', () => {
// The Codex install section (section 5) should use the Codex function
+ // End marker: the next numbered section header (a marker that doesn't
+ // exist slices to EOF and the assertion reads unrelated sections).
const codexSection = setupContent.slice(
setupContent.indexOf('# 5. Install for Codex'),
- setupContent.indexOf('# 6. Create')
+ setupContent.indexOf('# 6. Install for Kiro')
);
+ expect(setupContent.indexOf('# 6. Install for Kiro')).toBeGreaterThan(-1);
expect(codexSection).toContain('create_codex_runtime_root');
expect(codexSection).toContain('link_codex_skill_dirs');
expect(codexSection).not.toContain('link_claude_skill_dirs');
@@ -2378,7 +2429,10 @@ describe('setup script validation', () => {
const fnBody = setupContent.slice(fnStart, fnEnd);
expect(fnBody).toContain('mkdir -p "$target"');
// v1.36.0.0: routes through _link_or_copy helper for Windows fallback (cp on MSYS2/Git Bash).
- expect(fnBody).toContain('_link_or_copy "$gstack_dir/$dir_name/SKILL.md" "$target/SKILL.md"');
+ // v1.67 (#2569): the source is render-aware — canonical SKILL.md, or the
+ // rendered :user variant from ${GSTACK_HOME}/render/claude when present.
+ expect(fnBody).toContain('_skill_md_src="$gstack_dir/$dir_name/SKILL.md"');
+ expect(fnBody).toContain('_link_or_copy "$_skill_md_src" "$target/SKILL.md"');
});
// REGRESSION: cleanup functions must handle both old symlinks AND new real-directory pattern
@@ -2415,7 +2469,10 @@ describe('setup script validation', () => {
const fnEnd = setupContent.indexOf('# ─── Helper: remove old unprefixed Claude skill entries', fnStart);
const fnBody = setupContent.slice(fnStart, fnEnd);
expect(fnBody).toContain('_gstack-command');
- expect(fnBody).toContain('_link_or_copy "$gstack_dir/SKILL.md" "$target/SKILL.md"');
+ // #2511: the alias must be a rewritten COPY (unique frontmatter name),
+ // never a verbatim symlink of the canonical SKILL.md.
+ expect(fnBody).toContain('_install_alias_skill_md "$gstack_dir/SKILL.md" "$target" "_gstack-command"');
+ expect(fnBody).not.toContain('_link_or_copy "$gstack_dir/SKILL.md"');
const claudeSection = setupContent.slice(
setupContent.indexOf('# 4. Install for Claude'),
@@ -2467,6 +2524,86 @@ describe('setup script validation', () => {
expect(setupContent).toContain('OPENCODE_GSTACK="$OPENCODE_SKILLS/gstack"');
});
+ // --host cursor full install slice (#1358, PR #2547 by @szsunyuan re-derived)
+ test('auto mode detects Cursor via binary or ~/.cursor directory', () => {
+ expect(setupContent).toContain('command -v cursor');
+ expect(setupContent).toContain('[ -d "$HOME/.cursor" ] && INSTALL_CURSOR=1');
+ });
+
+ test('setup supports --host cursor with install section and Cursor skill path vars', () => {
+ expect(setupContent).toContain('INSTALL_CURSOR=');
+ expect(setupContent).toContain('CURSOR_SKILLS="$HOME/.cursor/skills"');
+ expect(setupContent).toContain('CURSOR_GSTACK="$CURSOR_SKILLS/gstack"');
+ expect(setupContent).toContain('create_cursor_runtime_root');
+ expect(setupContent).toContain('create_cursor_sidecar');
+ expect(setupContent).toContain('link_cursor_skill_dirs');
+ expect(setupContent).toContain('gstack ready (cursor).');
+ });
+
+ test('create_cursor_runtime_root exposes only Cursor runtime assets', () => {
+ const fnStart = setupContent.indexOf('create_cursor_runtime_root()');
+ const fnEnd = setupContent.indexOf('create_cursor_sidecar()', fnStart);
+ const fnBody = setupContent.slice(fnStart, fnEnd);
+ expect(fnBody).toContain('gstack/SKILL.md');
+ expect(fnBody).toContain('browse/dist');
+ expect(fnBody).toContain('browse/bin');
+ expect(fnBody).toContain('gstack-upgrade/SKILL.md');
+ expect(fnBody).toContain('checklist.md');
+ expect(fnBody).toContain('TODOS-format.md');
+ // bin scripts import ../lib — the two must travel together.
+ expect(fnBody).toContain('$cursor_gstack/lib');
+ expect(fnBody).not.toContain('design-checklist.md');
+ expect(fnBody).not.toContain('greptile-triage.md');
+ expect(fnBody).not.toContain('review/specialists');
+ expect(fnBody).not.toContain('qa/templates');
+ expect(fnBody).not.toContain('_link_or_copy "$gstack_dir" "$cursor_gstack"');
+ });
+
+ test('create_cursor_sidecar plants runtime assets without wiping generated SKILL.md', () => {
+ const fnStart = setupContent.indexOf('create_cursor_sidecar()');
+ const fnEnd = setupContent.indexOf('link_cursor_skill_dirs()', fnStart);
+ const fnBody = setupContent.slice(fnStart, fnEnd);
+ expect(fnBody).toContain('.cursor/skills/gstack');
+ expect(fnBody).toContain('bin');
+ expect(fnBody).toContain('browse/dist');
+ expect(fnBody).toContain('browse/bin');
+ expect(fnBody).toContain('ETHOS.md');
+ expect(fnBody).not.toContain('rm -rf');
+ });
+
+ test('link_cursor_skill_dirs skips the gstack runtime root directory', () => {
+ const fnStart = setupContent.indexOf('link_cursor_skill_dirs()');
+ const fnEnd = setupContent.indexOf('}', setupContent.indexOf('linked[@]', fnStart));
+ const fnBody = setupContent.slice(fnStart, fnEnd);
+ expect(fnBody).toContain('[ "$skill_name" = "gstack" ] && continue');
+ // #2444-aware guard: Windows bypass, else only replace symlink-or-missing.
+ expect(fnBody).toContain('[ "$IS_WINDOWS" -eq 1 ] || [ -L "$target" ] || [ ! -e "$target" ]');
+ });
+
+ // #2142 deleted existing ~/.cursor/skills/<name> dirs with `rm -rf "$target"`
+ // before relinking. That can wipe unowned Cursor skills. Only replace a
+ // symlink or a missing path; never the whole skills directory.
+ test('link_cursor_skill_dirs does not delete unowned Cursor skill directories', () => {
+ const fnStart = setupContent.indexOf('link_cursor_skill_dirs()');
+ const fnEnd = setupContent.indexOf('}', setupContent.indexOf('linked[@]', fnStart));
+ const fnBody = setupContent.slice(fnStart, fnEnd);
+ expect(fnBody).not.toContain('rm -rf "$target"');
+ expect(fnBody).not.toContain('rm -rf "$skills_dir"');
+ expect(setupContent).not.toContain('rm -rf "$CURSOR_SKILLS"');
+ });
+
+ test('Cursor install links generated skills before planting the sidecar', () => {
+ const cursorInstall = setupContent.slice(
+ setupContent.indexOf('# 6d. Install for Cursor'),
+ setupContent.indexOf('# 7. Create .agents/ sidecar'),
+ );
+ const linkCall = cursorInstall.indexOf('link_cursor_skill_dirs "$SOURCE_GSTACK_DIR"');
+ const sidecarCall = cursorInstall.indexOf('create_cursor_sidecar "$SOURCE_GSTACK_DIR"');
+ expect(linkCall).toBeGreaterThan(-1);
+ expect(sidecarCall).toBeGreaterThan(-1);
+ expect(linkCall).toBeLessThan(sidecarCall);
+ });
+
test('setup installs OpenCode skills into a nested gstack runtime root', () => {
expect(setupContent).toContain('create_opencode_runtime_root');
expect(setupContent).toContain('.opencode/skills');
@@ -3495,3 +3632,83 @@ describe('PREAMBLE resolution requires declared preamble-tier', () => {
expect(offenders).toEqual([]);
});
});
+
+// ---------------------------------------------------------------------------
+// #2499: gbrain MCP detection must read BOTH ~/.claude.json scopes.
+// Claude Code registers MCP servers at user scope (.mcpServers) and project
+// scope (.projects["/abs/path"].mcpServers — what `claude mcp add` without
+// --scope user writes). The rendered brain-sync block previously read only
+// user scope, so a correctly configured project-scoped brain was invisible.
+// ---------------------------------------------------------------------------
+describe('brain-sync block reads project-scoped MCP registrations (#2499)', () => {
+ const rendered = fs.readFileSync(path.join(ROOT, 'SKILL.md'), 'utf-8');
+
+ test('rendered _GBRAIN_MCP_ENTRY jq resolves project scope with nearest-ancestor cwd match', () => {
+ const line = rendered.split('\n').find((l) => l.includes('_GBRAIN_MCP_ENTRY=$('));
+ expect(line).toBeDefined();
+ // Project-scope read present, driven by $PWD.
+ expect(line!).toContain('--arg cwd "$PWD"');
+ expect(line!).toContain('.projects');
+ // User scope still resolved first.
+ expect(line!).toContain('.mcpServers.gbrain');
+ // The old user-scope-only filter is gone from the rendered output.
+ expect(rendered).not.toContain('.mcpServers.gbrain.type // .mcpServers.gbrain.transport');
+ expect(rendered).not.toContain(".mcpServers.gbrain.url // empty");
+ });
+
+ test('rendered _GBRAIN_MCP_TYPE and _GBRAIN_HOST extract from the resolved entry', () => {
+ const typeLine = rendered.split('\n').find((l) => l.includes('_GBRAIN_MCP_TYPE=$('));
+ const hostLine = rendered.split('\n').find((l) => l.includes('_GBRAIN_HOST=$('));
+ expect(typeLine).toBeDefined();
+ expect(hostLine).toBeDefined();
+ expect(typeLine!).toContain('_GBRAIN_MCP_ENTRY');
+ expect(hostLine!).toContain('_GBRAIN_MCP_ENTRY');
+ });
+
+ test('rendered jq lines FUNCTION: project-scoped registration resolves for a cwd inside the project', () => {
+ // Execute the exact rendered bytes, not a re-derivation: extract the
+ // _GBRAIN_MCP_ENTRY + _GBRAIN_MCP_TYPE lines from the generated SKILL.md
+ // and run them in bash against a fixture ~/.claude.json that carries ONLY
+ // a project-scoped gbrain registration.
+ const lines = rendered.split('\n');
+ const entryLine = lines.find((l) => l.includes('_GBRAIN_MCP_ENTRY=$('));
+ const typeLine = lines.find((l) => l.includes('_GBRAIN_MCP_TYPE=$('));
+ expect(entryLine).toBeDefined();
+ expect(typeLine).toBeDefined();
+
+ const tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-2499-home-'));
+ const projectDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-2499-proj-'));
+ const nestedCwd = path.join(projectDir, 'src', 'deep');
+ fs.mkdirSync(nestedCwd, { recursive: true });
+ try {
+ fs.writeFileSync(
+ path.join(tmpHome, '.claude.json'),
+ JSON.stringify({
+ projects: {
+ [projectDir]: {
+ mcpServers: { gbrain: { type: 'http', url: 'https://brain.example.com/mcp' } },
+ },
+ },
+ }),
+ );
+ const script = `cd "$1" || exit 1\n${entryLine!.trim()}\n${typeLine!.trim()}\necho "RESOLVED:$_GBRAIN_MCP_TYPE"`;
+ const r = spawnSync('bash', ['-c', script, 'bash', nestedCwd], {
+ encoding: 'utf-8',
+ env: { ...process.env, HOME: tmpHome },
+ timeout: 10_000,
+ });
+ expect(r.stdout).toContain('RESOLVED:http');
+
+ // Discriminator: a cwd OUTSIDE the project must NOT resolve it.
+ const outside = spawnSync('bash', ['-c', script, 'bash', os.tmpdir()], {
+ encoding: 'utf-8',
+ env: { ...process.env, HOME: tmpHome },
+ timeout: 10_000,
+ });
+ expect(outside.stdout).toContain('RESOLVED:\n');
+ } finally {
+ fs.rmSync(tmpHome, { recursive: true, force: true });
+ fs.rmSync(projectDir, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/test/gstack-egress-cli.test.ts b/test/gstack-egress-cli.test.ts
index 4881de80f..6d9f19f8d 100644
--- a/test/gstack-egress-cli.test.ts
+++ b/test/gstack-egress-cli.test.ts
@@ -19,7 +19,7 @@ import {
writeReceipt,
} from '../lib/egress-receipt';
-const ROOT = path.resolve(new URL(import.meta.url).pathname, '..', '..');
+const ROOT = path.resolve(import.meta.path, '..', '..');
const BIN = path.join(ROOT, 'bin', 'gstack-egress');
let home: string;
diff --git a/test/gstack-gbrain-sync.test.ts b/test/gstack-gbrain-sync.test.ts
index 19a9bac4e..9948da51c 100644
--- a/test/gstack-gbrain-sync.test.ts
+++ b/test/gstack-gbrain-sync.test.ts
@@ -8,7 +8,7 @@
*/
import { describe, it, expect, beforeEach, afterEach } from "bun:test";
-import { mkdtempSync, writeFileSync, readFileSync, existsSync, rmSync, mkdirSync, chmodSync } from "fs";
+import { mkdtempSync, writeFileSync, readFileSync, existsSync, rmSync, mkdirSync, chmodSync, symlinkSync } from "fs";
import { tmpdir } from "os";
import { join } from "path";
import { spawnSync } from "child_process";
@@ -62,6 +62,14 @@ describe("gstack-gbrain-sync CLI", () => {
expect(source).toContain("localEngineStatus");
});
+ it("uses GBrain's config environment when resolving dream sources", () => {
+ const source = readFileSync(SCRIPT, "utf-8");
+
+ expect(source).not.toContain("resolveCodeSourceId(root, process.env)");
+ expect(source).toContain("resolveCodeSourceId(root, gbrainEnv)");
+ expect(source).toContain("cycleCompleted(resolveCodeSourceId(root, gbrainEnv), gbrainEnv)");
+ });
+
it("--dry-run with --code-only reports the code import preview only", () => {
const home = makeTestHome();
const gstackHome = join(home, ".gstack");
@@ -122,6 +130,139 @@ describe("gstack-gbrain-sync CLI", () => {
rmSync(home, { recursive: true, force: true });
});
+ it("uses a local .gbrain-source in dry-run without spawning gbrain", () => {
+ const home = makeTestHome();
+ const gstackHome = join(home, ".gstack");
+ const bindir = mkdtempSync(join(tmpdir(), "gstack-pinned-source-bin-"));
+ const repo = mkdtempSync(join(tmpdir(), "gstack-pinned-source-repo-"));
+ const commandLog = join(home, "gbrain-commands.log");
+ mkdirSync(gstackHome, { recursive: true });
+ spawnSync("git", ["init", "--quiet", "-b", "main"], { cwd: repo });
+ writeFileSync(join(repo, ".gbrain-source"), "client-acme-app\n");
+ writeFileSync(join(bindir, "gbrain"), `#!/bin/sh
+printf '%s\\n' "$*" >> "$GSTACK_TEST_GBRAIN_LOG"
+exit 99
+`);
+ chmodSync(join(bindir, "gbrain"), 0o755);
+
+ const r = spawnSync("bun", [SCRIPT, "--dry-run", "--code-only", "--quiet"], {
+ encoding: "utf-8",
+ timeout: 60000,
+ cwd: repo,
+ env: {
+ ...process.env,
+ HOME: home,
+ GSTACK_HOME: gstackHome,
+ GSTACK_TEST_GBRAIN_LOG: commandLog,
+ PATH: `${bindir}:${process.env.PATH || ""}`,
+ },
+ });
+
+ expect(r.status).toBe(0);
+ expect(r.stdout).toContain("gbrain sync --strategy code --source client-acme-app");
+ expect(r.stdout).not.toContain("gbrain sources add");
+ expect(r.stdout).not.toContain("--federated");
+ expect(existsSync(commandLog)).toBe(false);
+ rmSync(repo, { recursive: true, force: true });
+ rmSync(bindir, { recursive: true, force: true });
+ rmSync(home, { recursive: true, force: true });
+ });
+
+ it("keeps a symlink-equivalent pinned source registered as-is", () => {
+ const home = makeTestHome();
+ const gstackHome = join(home, ".gstack");
+ const repo = mkdtempSync(join(tmpdir(), "gstack-pinned-source-repo-"));
+ const linkDir = mkdtempSync(join(tmpdir(), "gstack-pinned-source-link-"));
+ const link = join(linkDir, "repo");
+ const bindir = mkdtempSync(join(tmpdir(), "gstack-pinned-source-bin-"));
+ const commandLog = join(home, "gbrain-commands.log");
+ mkdirSync(gstackHome, { recursive: true });
+ mkdirSync(join(home, ".gbrain"), { recursive: true });
+ writeFileSync(join(home, ".gbrain", "config.json"), JSON.stringify({ engine: "pglite", database_url: "pglite:///test" }));
+ spawnSync("git", ["init", "--quiet", "-b", "main"], { cwd: repo });
+ writeFileSync(join(repo, ".gbrain-source"), "client-acme-app\n");
+ symlinkSync(repo, link, "dir");
+ writeFileSync(join(bindir, "gbrain"), `#!/bin/sh
+printf '%s\\n' "$*" >> "$GSTACK_TEST_GBRAIN_LOG"
+case "$*" in
+ --version) echo 'gbrain 0.42.0.0' ;;
+ "sources list --json") echo '{"sources":[{"id":"client-acme-app","local_path":"${link}","page_count":1}]}' ;;
+ "sync --strategy code --source client-acme-app"|"sources attach client-acme-app") ;;
+ *) echo "unexpected gbrain command: $*" >&2; exit 1 ;;
+esac
+`);
+ chmodSync(join(bindir, "gbrain"), 0o755);
+
+ const r = spawnSync("bun", [SCRIPT, "--code-only", "--quiet"], {
+ encoding: "utf-8",
+ timeout: 60000,
+ cwd: link,
+ env: {
+ ...process.env,
+ HOME: home,
+ GSTACK_HOME: gstackHome,
+ GSTACK_TEST_GBRAIN_LOG: commandLog,
+ PATH: `${bindir}:${process.env.PATH || ""}`,
+ },
+ });
+
+ const commands = readFileSync(commandLog, "utf-8");
+ expect(r.status).toBe(0);
+ expect(commands).toContain("sync --strategy code --source client-acme-app");
+ expect(commands).toContain("sources attach client-acme-app");
+ expect(commands).not.toMatch(/^sources (add|remove) /m);
+ rmSync(repo, { recursive: true, force: true });
+ rmSync(linkDir, { recursive: true, force: true });
+ rmSync(bindir, { recursive: true, force: true });
+ rmSync(home, { recursive: true, force: true });
+ });
+
+ it("uses a local pin for a dry-run dream without spawning gbrain", () => {
+ const home = makeTestHome();
+ const gstackHome = join(home, ".gstack");
+ const bindir = mkdtempSync(join(tmpdir(), "gstack-pinned-dream-bin-"));
+ const repo = mkdtempSync(join(tmpdir(), "gstack-pinned-dream-repo-"));
+ mkdirSync(gstackHome, { recursive: true });
+ spawnSync("git", ["init", "--quiet", "-b", "main"], { cwd: repo });
+ writeFileSync(join(repo, ".gbrain-source"), "client-acme-app\n");
+ writeFileSync(join(bindir, "gbrain"), "#!/bin/sh\nexit 99\n");
+ chmodSync(join(bindir, "gbrain"), 0o755);
+
+ const r = spawnSync("bun", [SCRIPT, "--dry-run", "--dream", "--no-code", "--no-memory", "--no-brain-sync", "--quiet"], {
+ encoding: "utf-8",
+ timeout: 60000,
+ cwd: repo,
+ env: { ...process.env, HOME: home, GSTACK_HOME: gstackHome, PATH: `${bindir}:${process.env.PATH || ""}` },
+ });
+
+ expect(r.status).toBe(0);
+ expect(r.stdout).toContain("gbrain dream --source client-acme-app");
+ rmSync(repo, { recursive: true, force: true });
+ rmSync(bindir, { recursive: true, force: true });
+ rmSync(home, { recursive: true, force: true });
+ });
+
+ it("falls back to a derived source when .gbrain-source cannot be read", () => {
+ const home = makeTestHome();
+ const gstackHome = join(home, ".gstack");
+ const repo = mkdtempSync(join(tmpdir(), "gstack-unreadable-pin-repo-"));
+ mkdirSync(gstackHome, { recursive: true });
+ spawnSync("git", ["init", "--quiet", "-b", "main"], { cwd: repo });
+ mkdirSync(join(repo, ".gbrain-source"));
+
+ const r = spawnSync("bun", [SCRIPT, "--dry-run", "--code-only", "--quiet"], {
+ encoding: "utf-8",
+ timeout: 60000,
+ cwd: repo,
+ env: { ...process.env, HOME: home, GSTACK_HOME: gstackHome },
+ });
+
+ expect(r.status).toBe(0);
+ expect(r.stdout).toMatch(/gbrain sources add gstack-code-/);
+ rmSync(repo, { recursive: true, force: true });
+ rmSync(home, { recursive: true, force: true });
+ });
+
it("derived source ids are gbrain-valid (≤32 chars, alnum + interior hyphens, no dots) for any remote", () => {
// gbrain enforces source ids to be 1-32 lowercase alnum chars with optional interior
// hyphens. Pre-fix, the slug came from canonicalizeRemote() with only `/` and
diff --git a/test/gstack-memory-helpers.test.ts b/test/gstack-memory-helpers.test.ts
index 2bc89c83f..48a3dbd81 100644
--- a/test/gstack-memory-helpers.test.ts
+++ b/test/gstack-memory-helpers.test.ts
@@ -462,10 +462,13 @@ describe("detectEngineTier", () => {
// Regression test for #1415: gbrain >=0.25 doctor output dropped the
// top-level `engine` field. The detect path must fall back to config.json.
// We force the doctor call to fail (PATH stripped of gbrain) and write a
- // synthetic config to GBRAIN_HOME so the fallback path is deterministic.
+ // synthetic config under GBRAIN_HOME so the fallback path is
+ // deterministic. Per gbrain's configDir() contract (#2521), GBRAIN_HOME
+ // is a parent dir — the config lives at $GBRAIN_HOME/.gbrain/config.json.
process.env.PATH = "/nonexistent-no-gbrain-here";
+ mkdirSync(join(testGbrainHome, ".gbrain"), { recursive: true });
writeFileSync(
- join(testGbrainHome, "config.json"),
+ join(testGbrainHome, ".gbrain", "config.json"),
JSON.stringify({ engine: "postgres", database_url: "postgresql://test/example" }),
"utf-8"
);
@@ -500,8 +503,9 @@ exit 0
{ mode: 0o755 }
);
process.env.PATH = `${binDir}:${process.env.PATH || ""}`;
+ mkdirSync(join(testGbrainHome, ".gbrain"), { recursive: true });
writeFileSync(
- join(testGbrainHome, "config.json"),
+ join(testGbrainHome, ".gbrain", "config.json"),
JSON.stringify({ engine: "pglite" }),
"utf-8"
);
diff --git a/test/gstack-memory-ingest.test.ts b/test/gstack-memory-ingest.test.ts
index 039beefad..b2d0a7b42 100644
--- a/test/gstack-memory-ingest.test.ts
+++ b/test/gstack-memory-ingest.test.ts
@@ -818,3 +818,46 @@ exit 0
rmSync(home, { recursive: true, force: true });
});
});
+
+// #2105: current Codex rollout records are
+// { type: 'response_item', payload: { type: 'message', role, content: [...] } }
+// — the legacy payload.message branch never fired on them, so every Codex
+// session imported as an empty shell (message_count: 0, 243/243 on the
+// reporting machine).
+describe("#2105 codex response_item rollout shape", () => {
+ it("extracts messages from response_item records", async () => {
+ const { parseTranscriptJsonl } = await import("../bin/gstack-memory-ingest");
+ const dir = mkdtempSync(join(tmpdir(), "ingest-2105-"));
+ const file = join(dir, "rollout-2026-06-01.jsonl");
+ writeFileSync(file, [
+ JSON.stringify({ type: "session_meta", payload: { id: "s1", cwd: "/tmp/x" }, timestamp: "2026-06-01T00:00:00Z" }),
+ JSON.stringify({ type: "response_item", payload: { type: "message", role: "user", content: [{ type: "input_text", text: "hello codex" }] } }),
+ JSON.stringify({ type: "response_item", payload: { type: "message", role: "assistant", content: [{ type: "output_text", text: "hello human" }] } }),
+ // Non-message response_items must not count as messages.
+ JSON.stringify({ type: "response_item", payload: { type: "reasoning", summary: [] } }),
+ ].join("\n") + "\n");
+
+ const parsed = parseTranscriptJsonl(file)!;
+ expect(parsed).not.toBeNull();
+ expect(parsed.agent).toBe("codex");
+ expect(parsed.message_count).toBe(2);
+ expect(parsed.body).toContain("## User\n\nhello codex");
+ expect(parsed.body).toContain("## Assistant\n\nhello human");
+ rmSync(dir, { recursive: true, force: true });
+ });
+
+ it("legacy payload.message shape still parses", async () => {
+ const { parseTranscriptJsonl } = await import("../bin/gstack-memory-ingest");
+ const dir = mkdtempSync(join(tmpdir(), "ingest-2105-legacy-"));
+ const file = join(dir, "rollout-legacy.jsonl");
+ writeFileSync(file, [
+ JSON.stringify({ type: "session_meta", payload: { id: "s2", cwd: "/tmp/y" }, timestamp: "2026-06-01T00:00:00Z" }),
+ JSON.stringify({ payload: { message: { role: "user", content: "old shape" } } }),
+ ].join("\n") + "\n");
+
+ const parsed = parseTranscriptJsonl(file)!;
+ expect(parsed.message_count).toBe(1);
+ expect(parsed.body).toContain("## User\n\nold shape");
+ rmSync(dir, { recursive: true, force: true });
+ });
+});
diff --git a/test/gstack-next-version.test.ts b/test/gstack-next-version.test.ts
index f72ec0149..ec3c34b2b 100644
--- a/test/gstack-next-version.test.ts
+++ b/test/gstack-next-version.test.ts
@@ -13,9 +13,12 @@ import {
fmtVersion,
bumpVersion,
cmpVersion,
+ versionWidth,
+ extractVersion,
pickNextSlot,
markActiveSiblings,
resolveVersionPath,
+ fetchGitClaimed,
} from "../bin/gstack-next-version";
describe("parseVersion", () => {
@@ -29,8 +32,20 @@ describe("parseVersion", () => {
expect(parseVersion(" 1.2.3.4 \n")).toEqual([1, 2, 3, 4]);
});
+ test("accepts 3-digit semver, padding the micro slot (#2501)", () => {
+ // 3-digit repos (a package.json holding plain semver) used to fail parsing
+ // outright, which exited this CLI 2 on EVERY run — and since this CLI is
+ // the queue-collision check, /ship then fell back to naive local
+ // arithmetic and duplicate version slots shipped silently. The pad keeps
+ // comparison uniform; versionWidth narrows output back.
+ expect(parseVersion("0.99.2")).toEqual([0, 99, 2, 0]);
+ expect(parseVersion("1.2.3")).toEqual([1, 2, 3, 0]);
+ expect(versionWidth("0.99.2")).toBe(3);
+ expect(versionWidth("1.6.3.0")).toBe(4);
+ });
+
test("rejects malformed", () => {
- expect(parseVersion("1.2.3")).toBeNull();
+ expect(parseVersion("1.2")).toBeNull();
expect(parseVersion("1.2.3.4.5")).toBeNull();
expect(parseVersion("v1.2.3.4")).toBeNull();
expect(parseVersion("")).toBeNull();
@@ -39,6 +54,49 @@ describe("parseVersion", () => {
});
});
+describe("3-digit repos keep their width (#2501)", () => {
+ test("formatting narrows to the repo's own width", () => {
+ expect(fmtVersion([0, 99, 3, 0], 3)).toBe("0.99.3");
+ expect(fmtVersion([0, 99, 3, 0], 4)).toBe("0.99.3.0");
+ expect(fmtVersion([0, 99, 3, 0])).toBe("0.99.3.0"); // default stays 4-digit
+ });
+
+ test("micro is carried out as patch when there is no micro component", () => {
+ // /ship auto-picks MICRO by default. Erroring would make it unusable in
+ // every 3-digit repo; a no-op would be worse — it would write back the
+ // version it started with and claim a slot already taken.
+ expect(bumpVersion([0, 99, 2, 0], "micro", 3)).toEqual([0, 99, 3, 0]);
+ expect(bumpVersion([0, 99, 2, 0], "patch", 3)).toEqual([0, 99, 3, 0]);
+ expect(bumpVersion([0, 99, 2, 3], "micro", 4)).toEqual([0, 99, 2, 4]); // 4-digit unchanged
+ });
+
+ test("slot picking stays inside the repo's width", () => {
+ const { version } = pickNextSlot([0, 99, 2, 0], [[0, 99, 5, 0]], "patch", 3);
+ expect(fmtVersion(version, 3)).toBe("0.99.6");
+ });
+});
+
+describe("extractVersion (#2501)", () => {
+ test("reads .version when the version-path is a package.json", () => {
+ const pkg = JSON.stringify({ name: "frontend", version: "0.99.2", private: true });
+ expect(extractVersion(pkg, "frontend/package.json")).toBe("0.99.2");
+ expect(extractVersion(pkg, "deep/nested/package.json")).toBe("0.99.2");
+ });
+
+ test("reads raw text for a plain VERSION file", () => {
+ expect(extractVersion("1.6.3.0\n", "VERSION")).toBe("1.6.3.0");
+ expect(extractVersion(" 1.6.3.0 ", "version/CURRENT")).toBe("1.6.3.0");
+ });
+
+ test("a JSON path that isn't valid JSON yields empty, not garbage", () => {
+ // The old readers ran a package.json through a whitespace strip and handed
+ // the caller '{"name":"frontend",...' as if it were a version. Empty lets
+ // callers fall back loudly.
+ expect(extractVersion("{ not json", "package.json")).toBe("");
+ expect(extractVersion(JSON.stringify({ name: "x" }), "package.json")).toBe("");
+ });
+});
+
describe("bumpVersion", () => {
test("major zeros everything right", () => {
expect(bumpVersion([1, 6, 3, 0], "major")).toEqual([2, 0, 0, 0]);
@@ -322,6 +380,168 @@ describe("default-base detection (no --base)", () => {
// Integration smoke — only runs if gh is available and authenticated. Confirms
// the CLI executes end-to-end against real APIs without crashing.
+describe("offline output contract (what /ship branches on, #2545)", () => {
+ // /ship's Step 12 reads `.fallback` to decide whether the pick is
+ // trustworthy when the PR queue is unreachable. That field is therefore
+ // load-bearing prose-to-code coupling: if it silently stopped being emitted,
+ // /ship would read undefined, treat the run as fully online, and lose the
+ // "verify no sibling holds it" prompt. Asserted end-to-end with a stub `gh`
+ // that always fails, which is what an expired token or an offline laptop
+ // looks like from here.
+ test("emits fallback:'git' and still returns a version when gh fails", async () => {
+ const stubDir = mkdtempSync(join(tmpdir(), "nextver-stubgh-"));
+ writeFileSync(join(stubDir, "gh"), "#!/bin/sh\nexit 1\n", { mode: 0o755 });
+ const proc = Bun.spawnSync(
+ ["bun", "run", "./bin/gstack-next-version", "--base", "main",
+ "--bump", "patch", "--current-version", "1.0.0.0", "--workspace-root", "null"],
+ { env: { ...process.env, PATH: `${stubDir}:${process.env.PATH}` } },
+ );
+ rmSync(stubDir, { recursive: true, force: true });
+ const out = JSON.parse(new TextDecoder().decode(proc.stdout));
+ expect(out.offline).toBe(true);
+ expect(out.fallback).toBe("git");
+ // The whole point: degraded queue view, NOT a degraded allocation.
+ expect(out.version).toMatch(/^\d+\.\d+\.\d+\.\d+$/);
+ expect(out.warnings.join(" ")).toContain("allocated from git");
+ }, 30000);
+
+ test("online runs leave fallback null", async () => {
+ const proc = Bun.spawnSync(
+ ["bun", "run", "./bin/gstack-next-version", "--base", "main",
+ "--bump", "patch", "--current-version", "1.0.0.0", "--workspace-root", "null"],
+ );
+ const out = JSON.parse(new TextDecoder().decode(proc.stdout));
+ if (out.offline) return; // no network / no gh auth on this machine: nothing to assert
+ expect(out.fallback).toBe(null);
+ }, 30000);
+});
+
+describe("fetchGitClaimed (offline allocation — the anti-duplicate fallback, #2545)", () => {
+ // Why this exists: when `gh pr list` failed, the util returned
+ // `offline:true` with an EMPTY claim set and /ship's instruction was
+ // "fall back to local BUMP_LEVEL arithmetic". Local arithmetic cannot see a
+ // sibling's claim, so it re-allocated a version an open PR already held.
+ // That produced two commits reading v0.1.57.0 on a downstream repo's main
+ // (plus three earlier pairs found in the same audit). Git knows what the API
+ // was asked for, so offline now degrades the QUEUE VIEW, not the ALLOCATION.
+ function git(cwd: string, ...args: string[]) {
+ return Bun.spawnSync(["git", "-c", "user.email=t@t", "-c", "user.name=t", ...args], { cwd });
+ }
+
+ function fixture(): string {
+ const dir = mkdtempSync(join(tmpdir(), "nextver-git-"));
+ git(dir, "init", "-q", "-b", "main");
+ writeFileSync(join(dir, "VERSION"), "0.1.66.0\n");
+ git(dir, "add", "-A");
+ git(dir, "commit", "-qm", "v0.1.66.0 chore: base");
+ // A sibling PR branch that already claimed 0.1.67.0, present as a fetched
+ // remote-tracking ref — which is the shape a real `git fetch` leaves.
+ git(dir, "checkout", "-q", "-b", "sibling");
+ writeFileSync(join(dir, "VERSION"), "0.1.67.0\n");
+ git(dir, "add", "-A");
+ git(dir, "commit", "-qm", "v0.1.67.0 feat: sibling claimed this");
+ const sha = new TextDecoder().decode(git(dir, "rev-parse", "HEAD").stdout).trim();
+ git(dir, "checkout", "-q", "main");
+ git(dir, "update-ref", "refs/remotes/origin/sibling", sha);
+ git(dir, "update-ref", "refs/remotes/origin/main", "main");
+ return dir;
+ }
+
+ test("finds a sibling branch's claim from remote-tracking refs", () => {
+ const dir = fixture();
+ const cwd = process.cwd();
+ try {
+ process.chdir(dir);
+ const warnings: string[] = [];
+ const claims = fetchGitClaimed("main", "VERSION", warnings);
+ const versions = claims.map((c) => c.version);
+ expect(versions).toContain("0.1.67.0");
+ } finally {
+ process.chdir(cwd);
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ test("the sibling's claim is enough to push the pick past it", () => {
+ // The end-to-end consequence: with the claim visible, pickNextSlot lands
+ // on 0.1.68.0 instead of re-issuing the sibling's 0.1.67.0.
+ const dir = fixture();
+ const cwd = process.cwd();
+ try {
+ process.chdir(dir);
+ const claims = fetchGitClaimed("main", "VERSION", []);
+ const base = parseVersion("0.1.66.0")!;
+ const claimed = claims
+ .map((c) => parseVersion(c.version))
+ .filter((v): v is [number, number, number, number] => v !== null)
+ .filter((v) => cmpVersion(v, base) > 0);
+ const { version } = pickNextSlot(base, claimed, "patch");
+ expect(fmtVersion(version)).toBe("0.1.68.0");
+ } finally {
+ process.chdir(cwd);
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ test("also reports versions already shipped on the base", () => {
+ // Catches a number that merged and was then re-picked — the VERSION file
+ // alone cannot see that, because it only holds the newest value.
+ const dir = fixture();
+ const cwd = process.cwd();
+ try {
+ process.chdir(dir);
+ const claims = fetchGitClaimed("main", "VERSION", []);
+ const shipped = claims.filter((c) => c.branch.startsWith("(shipped on"));
+ expect(shipped.map((c) => c.version)).toContain("0.1.66.0");
+ } finally {
+ process.chdir(cwd);
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ test("reads a JSON version-path on remote refs and keeps the branch's own width", () => {
+ // A sibling repo pinned to frontend/package.json (#2501): its claim is the
+ // JSON .version, not the whitespace-stripped file bytes.
+ const dir = mkdtempSync(join(tmpdir(), "nextver-gitjson-"));
+ const cwd = process.cwd();
+ try {
+ git(dir, "init", "-q", "-b", "main");
+ mkdirSync(join(dir, "frontend"), { recursive: true });
+ writeFileSync(join(dir, "frontend", "package.json"), JSON.stringify({ name: "f", version: "0.99.2" }, null, 2) + "\n");
+ git(dir, "add", "-A");
+ git(dir, "commit", "-qm", "base");
+ git(dir, "checkout", "-q", "-b", "sibling");
+ writeFileSync(join(dir, "frontend", "package.json"), JSON.stringify({ name: "f", version: "0.99.3" }, null, 2) + "\n");
+ git(dir, "add", "-A");
+ git(dir, "commit", "-qm", "sibling claim");
+ const sha = new TextDecoder().decode(git(dir, "rev-parse", "HEAD").stdout).trim();
+ git(dir, "checkout", "-q", "main");
+ git(dir, "update-ref", "refs/remotes/origin/sibling", sha);
+ process.chdir(dir);
+ const claims = fetchGitClaimed("main", "frontend/package.json", []);
+ expect(claims.map((c) => c.version)).toContain("0.99.3");
+ } finally {
+ process.chdir(cwd);
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ test("degrades to a warning, never a throw, outside a git repo", () => {
+ const dir = mkdtempSync(join(tmpdir(), "nextver-nogit-"));
+ const cwd = process.cwd();
+ try {
+ process.chdir(dir);
+ const warnings: string[] = [];
+ const claims = fetchGitClaimed("main", "VERSION", warnings);
+ expect(claims).toEqual([]);
+ expect(warnings.length).toBeGreaterThan(0);
+ } finally {
+ process.chdir(cwd);
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+});
+
describe("integration (smoke)", () => {
// Bumps timeout to 30s — the test spawns a real `bun run` subprocess that
// does a `gh pr list` against the live GitHub API to inspect claimed slots.
diff --git a/test/gstack-settings-hook-schema-aware.test.ts b/test/gstack-settings-hook-schema-aware.test.ts
index ada8ec40c..5a5f302ec 100644
--- a/test/gstack-settings-hook-schema-aware.test.ts
+++ b/test/gstack-settings-hook-schema-aware.test.ts
@@ -111,6 +111,55 @@ describe('add-event', () => {
expect(s.hooks.PreToolUse[0].hooks[0].command).toBe('/v2');
});
+ test('dedup includes command: same (event, matcher, command) with different source updates in place', () => {
+ run([
+ 'add-event',
+ '--event', 'PostToolUse',
+ '--matcher', '(AskUserQuestion|mcp__.*__AskUserQuestion)',
+ '--command', '/abs/path/to/question-log-hook',
+ '--source', 'source-A',
+ '--timeout', '5',
+ ]);
+ run([
+ 'add-event',
+ '--event', 'PostToolUse',
+ '--matcher', '(AskUserQuestion|mcp__.*__AskUserQuestion)',
+ '--command', '/abs/path/to/question-log-hook',
+ '--source', 'source-B',
+ '--timeout', '5',
+ ]);
+ const s = settings();
+ expect(s.hooks.PostToolUse).toHaveLength(1);
+ expect(s.hooks.PostToolUse[0]._gstack_source).toBe('source-B');
+ });
+
+ test('dedup includes command: untagged entry with same command is updated not duplicated', () => {
+ fs.writeFileSync(
+ settingsFile,
+ JSON.stringify({
+ hooks: {
+ PostToolUse: [
+ {
+ matcher: '(AskUserQuestion|mcp__.*__AskUserQuestion)',
+ hooks: [{ type: 'command', command: '/abs/path/to/question-log-hook', timeout: 5 }],
+ },
+ ],
+ },
+ }, null, 2),
+ );
+ run([
+ 'add-event',
+ '--event', 'PostToolUse',
+ '--matcher', '(AskUserQuestion|mcp__.*__AskUserQuestion)',
+ '--command', '/abs/path/to/question-log-hook',
+ '--source', 'plan-tune-cathedral',
+ '--timeout', '5',
+ ]);
+ const s = settings();
+ expect(s.hooks.PostToolUse).toHaveLength(1);
+ expect(s.hooks.PostToolUse[0]._gstack_source).toBe('plan-tune-cathedral');
+ });
+
test('preserves unrelated existing hooks', () => {
fs.writeFileSync(
settingsFile,
diff --git a/test/gstack-slug-cwd-walk-up.test.ts b/test/gstack-slug-cwd-walk-up.test.ts
index 96db5e303..b129b8e79 100644
--- a/test/gstack-slug-cwd-walk-up.test.ts
+++ b/test/gstack-slug-cwd-walk-up.test.ts
@@ -39,9 +39,14 @@ function runSlug(
tmpHome: string,
extraEnv: Record<string, string> = {},
): SpawnSyncReturns<string> {
+ // GSTACK_HOME must be pinned to the temp home too: the cache dir is
+ // GSTACK_HOME-aware (matching lib/bin-context.ts's native port), and a
+ // sibling test file leaking process.env.GSTACK_HOME in a shared-process
+ // shard would otherwise point the bin at a different cache than the one
+ // these tests seed and assert on.
// Scrub PATH so we always use system bash + system git; pass HOME so the
// script's cache writes land in tmpHome, never AJ's real ~/.gstack.
- const env = { ...process.env, HOME: tmpHome, ...extraEnv };
+ const env = { ...process.env, HOME: tmpHome, GSTACK_HOME: path.join(tmpHome, '.gstack'), ...extraEnv };
return spawnSync('bash', [SCRIPT], {
cwd,
env,
diff --git a/test/gstack-slug-sanitize.test.ts b/test/gstack-slug-sanitize.test.ts
index 7c5dc8f7d..ab0eb0b7f 100644
--- a/test/gstack-slug-sanitize.test.ts
+++ b/test/gstack-slug-sanitize.test.ts
@@ -63,3 +63,44 @@ describe('gstack-slug cache-read sanitization', () => {
}
});
});
+
+// The GSTACK_PROJECT_SLUG escape hatch is per-invocation, never durable: a
+// test exporting it from the repo root once rebound the ENTIRE repo's session
+// state (evals, decisions, timelines) to the test's slug via the cwd cache.
+// The cache is also GSTACK_HOME-aware now, matching lib/bin-context.ts's
+// native port — temp-home runs must not litter the real ~/.gstack (observed:
+// 2,528 stale temp-cwd entries).
+describe('slug cache hygiene', () => {
+ test('an env-override run never writes the cwd cache', () => {
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'slug-env-'));
+ try {
+ const r = spawnSync(['bash', SLUG_BIN], {
+ cwd: os.tmpdir(),
+ env: { ...process.env, GSTACK_HOME: home, GSTACK_PROJECT_SLUG: 'override-slug' },
+ });
+ expect(r.stdout.toString()).toContain('SLUG=override-slug');
+ expect(fs.existsSync(path.join(home, 'slug-cache'))).toBe(false);
+ } finally {
+ fs.rmSync(home, { recursive: true, force: true });
+ }
+ });
+
+ test('an env-less run caches under GSTACK_HOME, not $HOME', () => {
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'slug-home-'));
+ try {
+ // Strip any ambient override: a sibling test leaking
+ // GSTACK_PROJECT_SLUG in a shared-process shard would flip this run
+ // into override mode, which (correctly) skips the cache write.
+ const { GSTACK_PROJECT_SLUG: _drop, ...ambient } = process.env;
+ const r = spawnSync(['bash', SLUG_BIN], {
+ cwd: os.tmpdir(),
+ env: { ...ambient, GSTACK_HOME: home },
+ });
+ expect(r.exitCode).toBe(0);
+ const entries = fs.readdirSync(path.join(home, 'slug-cache'));
+ expect(entries.length).toBe(1);
+ } finally {
+ fs.rmSync(home, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/test/gstack-version-bump.test.ts b/test/gstack-version-bump.test.ts
index ffcecd1a7..f7ea38828 100644
--- a/test/gstack-version-bump.test.ts
+++ b/test/gstack-version-bump.test.ts
@@ -39,10 +39,18 @@ describe('VERSION_RE', () => {
test('accepts 4-digit semver', () => {
expect(VERSION_RE.test('1.2.3.4')).toBe(true);
});
- test('rejects 3-digit and garbage', () => {
- expect(VERSION_RE.test('1.2.3')).toBe(false);
+ test('accepts 3-digit semver too (#2501)', () => {
+ // A repo whose pinned version source is a package.json holds plain
+ // 3-digit semver. Rejecting it meant /ship could not write a version in
+ // such a repo at all.
+ expect(VERSION_RE.test('1.2.3')).toBe(true);
+ expect(VERSION_RE.test('0.99.2')).toBe(true);
+ });
+ test('rejects garbage', () => {
+ expect(VERSION_RE.test('1.2')).toBe(false);
expect(VERSION_RE.test('v1.2.3.4')).toBe(false);
expect(VERSION_RE.test('1.2.3.4-rc')).toBe(false);
+ expect(VERSION_RE.test('1.2.3.4.5')).toBe(false);
});
});
@@ -54,16 +62,21 @@ describe('write (FRESH bump)', () => {
fs.writeFileSync(path.join(dir, 'VERSION'), '1.0.0.0\n');
fs.writeFileSync(path.join(dir, 'package.json'), JSON.stringify({ name: 'x', version: '1.0.0.0', scripts: { t: 'y' } }, null, 2) + '\n');
const out = execFileSync('bun', [BIN, 'write', '--version', '1.1.0.0'], { cwd: dir }).toString();
- expect(JSON.parse(out)).toEqual({ wrote: '1.1.0.0', packageJson: true });
+ expect(JSON.parse(out)).toEqual({
+ wrote: '1.1.0.0', packageJson: true, packageJsonPath: 'package.json',
+ packageJsonVersion: '1.1.0', packageLock: false,
+ });
expect(fs.readFileSync(path.join(dir, 'VERSION'), 'utf-8').trim()).toBe('1.1.0.0');
const pkg = JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf-8'));
- expect(pkg.version).toBe('1.1.0.0');
+ // Decision 11: the manifest carries the npm-valid 3-digit translation;
+ // VERSION keeps the 4-digit form and stays the source of truth.
+ expect(pkg.version).toBe('1.1.0');
expect(pkg.scripts).toEqual({ t: 'y' }); // untouched
});
test('rejects a malformed version with exit 2', () => {
let code = 0;
- try { execFileSync('bun', [BIN, 'write', '--version', '1.2.3'], { cwd: dir, stdio: 'pipe' }); }
+ try { execFileSync('bun', [BIN, 'write', '--version', '1.2.3.4.5'], { cwd: dir, stdio: 'pipe' }); }
catch (e: any) { code = e.status; }
expect(code).toBe(2);
});
@@ -72,7 +85,10 @@ describe('write (FRESH bump)', () => {
const d2 = fs.mkdtempSync(path.join(os.tmpdir(), 'vbump-noPkg-'));
fs.writeFileSync(path.join(d2, 'VERSION'), '0.1.0.0\n');
const out = execFileSync('bun', [BIN, 'write', '--version', '0.2.0.0'], { cwd: d2 }).toString();
- expect(JSON.parse(out)).toEqual({ wrote: '0.2.0.0', packageJson: false });
+ expect(JSON.parse(out)).toEqual({
+ wrote: '0.2.0.0', packageJson: false, packageJsonPath: null,
+ packageJsonVersion: null, packageLock: false,
+ });
expect(fs.readFileSync(path.join(d2, 'VERSION'), 'utf-8').trim()).toBe('0.2.0.0');
fs.rmSync(d2, { recursive: true, force: true });
});
@@ -86,8 +102,10 @@ describe('repair (DRIFT_STALE_PKG)', () => {
fs.writeFileSync(path.join(dir, 'VERSION'), '2.0.0.0\n');
fs.writeFileSync(path.join(dir, 'package.json'), JSON.stringify({ name: 'x', version: '1.9.0.0' }, null, 2) + '\n');
const out = execFileSync('bun', [BIN, 'repair'], { cwd: dir }).toString();
- expect(JSON.parse(out)).toEqual({ repaired: '2.0.0.0' });
- expect(JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf-8')).version).toBe('2.0.0.0');
+ expect(JSON.parse(out)).toEqual({
+ repaired: '2.0.0.0', packageJsonPath: 'package.json', packageJsonVersion: '2.0.0',
+ });
+ expect(JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf-8')).version).toBe('2.0.0');
expect(fs.readFileSync(path.join(dir, 'VERSION'), 'utf-8').trim()).toBe('2.0.0.0'); // unchanged
});
@@ -100,6 +118,81 @@ describe('repair (DRIFT_STALE_PKG)', () => {
});
});
+describe('write/repair sync npm lockfiles (both version fields, #2567)', () => {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'vbump-lock-'));
+ afterAll(() => { try { fs.rmSync(dir, { recursive: true, force: true }); } catch { /* noop */ } });
+
+ const lock = (v: string) => JSON.stringify({
+ name: 'x', version: v, lockfileVersion: 3,
+ packages: { '': { name: 'x', version: v }, 'node_modules/a': { version: '9.9.9' } },
+ }, null, 2) + '\n';
+
+ test('write updates top-level version and packages[""].version, leaves deps alone', () => {
+ fs.writeFileSync(path.join(dir, 'VERSION'), '1.0.0.0\n');
+ fs.writeFileSync(path.join(dir, 'package.json'), JSON.stringify({ name: 'x', version: '1.0.0' }, null, 2) + '\n');
+ fs.writeFileSync(path.join(dir, 'package-lock.json'), lock('1.0.0'));
+ const out = execFileSync('bun', [BIN, 'write', '--version', '1.1.0.0'], { cwd: dir }).toString();
+ expect(JSON.parse(out)).toEqual({
+ wrote: '1.1.0.0', packageJson: true, packageJsonPath: 'package.json',
+ packageJsonVersion: '1.1.0', packageLock: true,
+ });
+ const l = JSON.parse(fs.readFileSync(path.join(dir, 'package-lock.json'), 'utf-8'));
+ expect(l.version).toBe('1.1.0');
+ expect(l.packages[''].version).toBe('1.1.0');
+ expect(l.packages['node_modules/a'].version).toBe('9.9.9'); // untouched
+ });
+
+ test('repair heals a stale lockfile alongside package.json', () => {
+ fs.writeFileSync(path.join(dir, 'VERSION'), '2.0.0.0\n');
+ fs.writeFileSync(path.join(dir, 'package.json'), JSON.stringify({ name: 'x', version: '1.9.0' }, null, 2) + '\n');
+ fs.writeFileSync(path.join(dir, 'package-lock.json'), lock('1.9.0'));
+ execFileSync('bun', [BIN, 'repair'], { cwd: dir });
+ const l = JSON.parse(fs.readFileSync(path.join(dir, 'package-lock.json'), 'utf-8'));
+ expect(l.version).toBe('2.0.0');
+ expect(l.packages[''].version).toBe('2.0.0');
+ });
+
+ test('lockfileVersion 1 (no packages map) syncs top-level only, no crash', () => {
+ fs.writeFileSync(path.join(dir, 'VERSION'), '3.0.0.0\n');
+ fs.writeFileSync(path.join(dir, 'package.json'), JSON.stringify({ name: 'x', version: '2.9.0' }, null, 2) + '\n');
+ fs.writeFileSync(path.join(dir, 'package-lock.json'), JSON.stringify({ name: 'x', version: '2.9.0', lockfileVersion: 1 }, null, 2) + '\n');
+ execFileSync('bun', [BIN, 'repair'], { cwd: dir });
+ const l = JSON.parse(fs.readFileSync(path.join(dir, 'package-lock.json'), 'utf-8'));
+ expect(l.version).toBe('3.0.0');
+ expect(l.packages).toBeUndefined();
+ });
+
+ test('npm-shrinkwrap.json is synced too when present (never created)', () => {
+ const d2 = fs.mkdtempSync(path.join(os.tmpdir(), 'vbump-shrink-'));
+ fs.writeFileSync(path.join(d2, 'VERSION'), '1.0.0.0\n');
+ fs.writeFileSync(path.join(d2, 'package.json'), JSON.stringify({ name: 'x', version: '1.0.0' }, null, 2) + '\n');
+ fs.writeFileSync(path.join(d2, 'npm-shrinkwrap.json'), lock('1.0.0').replace('package-lock', 'npm-shrinkwrap'));
+ const out = execFileSync('bun', [BIN, 'write', '--version', '1.1.0.0'], { cwd: d2 }).toString();
+ expect(JSON.parse(out).packageLock).toBe(true);
+ const l = JSON.parse(fs.readFileSync(path.join(d2, 'npm-shrinkwrap.json'), 'utf-8'));
+ expect(l.version).toBe('1.1.0');
+ expect(l.packages[''].version).toBe('1.1.0');
+ // No package-lock.json invented alongside it.
+ expect(fs.existsSync(path.join(d2, 'package-lock.json'))).toBe(false);
+ fs.rmSync(d2, { recursive: true, force: true });
+ });
+
+ test('malformed lockfile fails the write with exit 3 (half-write is loud, not silent)', () => {
+ const d3 = fs.mkdtempSync(path.join(os.tmpdir(), 'vbump-badlock-'));
+ fs.writeFileSync(path.join(d3, 'VERSION'), '1.0.0.0\n');
+ fs.writeFileSync(path.join(d3, 'package.json'), JSON.stringify({ name: 'x', version: '1.0.0.0' }, null, 2) + '\n');
+ fs.writeFileSync(path.join(d3, 'package-lock.json'), '{ not json');
+ let code = 0;
+ try { execFileSync('bun', [BIN, 'write', '--version', '1.1.0.0'], { cwd: d3, stdio: 'pipe' }); }
+ catch (e: any) { code = e.status; }
+ expect(code).toBe(3);
+ // VERSION was written before the failure — exactly the half-write the
+ // exit-3 contract exists to surface.
+ expect(fs.readFileSync(path.join(d3, 'VERSION'), 'utf-8').trim()).toBe('1.1.0.0');
+ fs.rmSync(d3, { recursive: true, force: true });
+ });
+});
+
describe('classify (idempotency over a real git base)', () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'vbump-classify-'));
afterAll(() => { try { fs.rmSync(dir, { recursive: true, force: true }); } catch { /* noop */ } });
@@ -131,3 +224,356 @@ describe('classify (idempotency over a real git base)', () => {
expect(parsed.currentVersion).toBe('1.1.0.0');
});
});
+
+/**
+ * A repo whose single source of truth is a package.json at a non-root path,
+ * holding plain 3-digit semver — the shape gstack's native VERSION-file
+ * assumption failed closed on (#2501). Before this, classify reported
+ * {state: FRESH, baseVersion: "0.0.0.0", pkgExists: false} no matter what the
+ * repo's real version was: it looked for a root VERSION file and a root
+ * package.json, found neither, and reported a pristine repo at version zero.
+ *
+ * These cases pass --version-path explicitly; the .gstack/version-path pin
+ * flows through the same reader once classify/write/repair resolve the pin's
+ * repo-relative form (#2462, covered in its own suite below the pin fix).
+ */
+describe('package.json as the version source (monorepo, 3-digit, #2501)', () => {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'vbump-pkgsrc-'));
+ afterAll(() => { try { fs.rmSync(dir, { recursive: true, force: true }); } catch { /* noop */ } });
+
+ const pkgRel = 'frontend/package.json';
+ const pkgAbs = path.join(dir, pkgRel);
+ fs.mkdirSync(path.join(dir, 'frontend'), { recursive: true });
+ fs.writeFileSync(pkgAbs, JSON.stringify({ name: 'frontend', version: '0.99.2', private: true, scripts: { dev: 'next dev' } }, null, 2) + '\n');
+
+ execFileSync('git', ['init', '-q', '-b', 'main'], { cwd: dir });
+ execFileSync('git', ['config', 'user.email', '[email protected]'], { cwd: dir });
+ execFileSync('git', ['config', 'user.name', 't'], { cwd: dir });
+ execFileSync('git', ['add', '-A'], { cwd: dir });
+ execFileSync('git', ['commit', '-qm', 'v0.99.2 base'], { cwd: dir });
+ const head = execFileSync('git', ['rev-parse', 'HEAD'], { cwd: dir }).toString().trim();
+ fs.mkdirSync(path.join(dir, '.git', 'refs', 'remotes', 'origin'), { recursive: true });
+ fs.writeFileSync(path.join(dir, '.git', 'refs', 'remotes', 'origin', 'main'), head + '\n');
+
+ test('classify reads the real version from the package.json version-path', () => {
+ const out = execFileSync('bun', [BIN, 'classify', '--base', 'main', '--version-path', pkgRel], { cwd: dir }).toString();
+ const parsed = JSON.parse(out);
+ expect(parsed.state).toBe('FRESH');
+ expect(parsed.baseVersion).toBe('0.99.2'); // was "0.0.0.0"
+ expect(parsed.currentVersion).toBe('0.99.2'); // was "0.0.0.0"
+ expect(parsed.pkgExists).toBe(true); // was false
+ });
+
+ test('write updates the package.json in place and creates no VERSION file', () => {
+ const out = execFileSync('bun', [BIN, 'write', '--version', '0.99.3', '--version-path', pkgRel], { cwd: dir }).toString();
+ expect(JSON.parse(out)).toEqual({ wrote: '0.99.3', versionPath: pkgRel, packageJson: true, packageLock: false });
+ const pkg = JSON.parse(fs.readFileSync(pkgAbs, 'utf-8'));
+ expect(pkg.version).toBe('0.99.3');
+ expect(pkg.scripts).toEqual({ dev: 'next dev' }); // rest of the file untouched
+ expect(pkg.name).toBe('frontend');
+ expect(fs.existsSync(path.join(dir, 'VERSION'))).toBe(false);
+ });
+
+ test('classify reports ALREADY_BUMPED after that write, not a drift state', () => {
+ const out = execFileSync('bun', [BIN, 'classify', '--base', 'main', '--version-path', pkgRel], { cwd: dir }).toString();
+ const parsed = JSON.parse(out);
+ expect(parsed.state).toBe('ALREADY_BUMPED');
+ expect(parsed.baseVersion).toBe('0.99.2');
+ expect(parsed.currentVersion).toBe('0.99.3');
+ });
+
+ test('repair is a no-op: there is no second file to drift from', () => {
+ const out = execFileSync('bun', [BIN, 'repair', '--version-path', pkgRel], { cwd: dir }).toString();
+ expect(JSON.parse(out).repaired).toBeNull();
+ });
+
+ test('write refuses a version-path that does not exist', () => {
+ let code = 0;
+ try {
+ execFileSync('bun', [BIN, 'write', '--version', '1.0.0', '--version-path', 'nope/package.json'], { cwd: dir, stdio: 'pipe' });
+ } catch (e: any) { code = e.status; }
+ expect(code).toBe(2);
+ });
+});
+
+/**
+ * #2462: cmdClassify's current-version read resolved the .gstack/version-path
+ * pin, but versionRel — the repo-relative path fed to `git show
+ * origin/<base>:<path>` — came from the CLI flag alone. In a pinned repo with
+ * no --version-path flag, base and current therefore read DIFFERENT files:
+ * current from the pin, base from the root VERSION (which may not exist, so
+ * base always read 0.0.0.0 and every branch looked FRESH). The pin's
+ * repo-relative form now drives all three subcommands.
+ */
+describe('.gstack/version-path pin, no --version-path flag (#2462)', () => {
+ const mkPinned = (pinRel: string): string => {
+ const d = fs.mkdtempSync(path.join(os.tmpdir(), 'vbump-pin-'));
+ fs.mkdirSync(path.dirname(path.join(d, pinRel)), { recursive: true });
+ fs.mkdirSync(path.join(d, '.gstack'), { recursive: true });
+ fs.writeFileSync(path.join(d, '.gstack', 'version-path'), pinRel + '\n');
+ return d;
+ };
+
+ const commitBase = (d: string): void => {
+ execFileSync('git', ['init', '-q', '-b', 'main'], { cwd: d });
+ execFileSync('git', ['config', 'user.email', '[email protected]'], { cwd: d });
+ execFileSync('git', ['config', 'user.name', 't'], { cwd: d });
+ execFileSync('git', ['add', '-A'], { cwd: d });
+ execFileSync('git', ['commit', '-qm', 'base'], { cwd: d });
+ const head = execFileSync('git', ['rev-parse', 'HEAD'], { cwd: d }).toString().trim();
+ fs.mkdirSync(path.join(d, '.git', 'refs', 'remotes', 'origin'), { recursive: true });
+ fs.writeFileSync(path.join(d, '.git', 'refs', 'remotes', 'origin', 'main'), head + '\n');
+ };
+
+ test('classify reads base AND current from the SAME pinned plain-text file', () => {
+ const pinRel = 'sub/VERSION';
+ const d = mkPinned(pinRel);
+ fs.writeFileSync(path.join(d, pinRel), '1.4.0.0\n');
+ commitBase(d);
+ // Move the pinned file past base — NO root VERSION file exists at all.
+ fs.writeFileSync(path.join(d, pinRel), '1.5.0.0\n');
+ const out = JSON.parse(execFileSync('bun', [BIN, 'classify', '--base', 'main'], { cwd: d }).toString());
+ // Before the fix: baseVersion read root VERSION → "0.0.0.0" and the
+ // branch misclassified as... current 1.5.0.0 vs base 0.0.0.0. The REAL
+ // base is the pinned file's committed value.
+ expect(out.baseVersion).toBe('1.4.0.0');
+ expect(out.currentVersion).toBe('1.5.0.0');
+ expect(out.state).toBe('ALREADY_BUMPED');
+ fs.rmSync(d, { recursive: true, force: true });
+ });
+
+ test('classify engages the pinned package.json JSON handling without a flag', () => {
+ const pinRel = 'frontend/package.json';
+ const d = mkPinned(pinRel);
+ fs.writeFileSync(path.join(d, pinRel), JSON.stringify({ name: 'f', version: '0.99.2' }, null, 2) + '\n');
+ commitBase(d);
+ const out = JSON.parse(execFileSync('bun', [BIN, 'classify', '--base', 'main'], { cwd: d }).toString());
+ // Before the fix: versionRel="VERSION" → the pinned JSON was read as raw
+ // text → currentVersion "0.0.0.0", pkgExists false, base from a
+ // nonexistent root VERSION.
+ expect(out.state).toBe('FRESH');
+ expect(out.baseVersion).toBe('0.99.2');
+ expect(out.currentVersion).toBe('0.99.2');
+ expect(out.pkgExists).toBe(true);
+ fs.rmSync(d, { recursive: true, force: true });
+ });
+
+ test('write honors the pin: updates the pinned package.json in place, no root VERSION invented', () => {
+ const pinRel = 'frontend/package.json';
+ const d = mkPinned(pinRel);
+ fs.writeFileSync(path.join(d, pinRel), JSON.stringify({ name: 'f', version: '0.99.2' }, null, 2) + '\n');
+ const out = JSON.parse(execFileSync('bun', [BIN, 'write', '--version', '0.99.3'], { cwd: d }).toString());
+ expect(out).toEqual({ wrote: '0.99.3', versionPath: pinRel, packageJson: true, packageLock: false });
+ expect(JSON.parse(fs.readFileSync(path.join(d, pinRel), 'utf-8')).version).toBe('0.99.3');
+ // Before the fix, write treated versionRel as "VERSION" and overwrote the
+ // pinned JSON file with a bare "0.99.3\n", destroying the manifest.
+ expect(fs.existsSync(path.join(d, 'VERSION'))).toBe(false);
+ fs.rmSync(d, { recursive: true, force: true });
+ });
+
+ test('repair honors the pin: pinned package.json is a no-op single source', () => {
+ const pinRel = 'frontend/package.json';
+ const d = mkPinned(pinRel);
+ fs.writeFileSync(path.join(d, pinRel), JSON.stringify({ name: 'f', version: '0.99.2' }, null, 2) + '\n');
+ const out = JSON.parse(execFileSync('bun', [BIN, 'repair'], { cwd: d }).toString());
+ expect(out.repaired).toBeNull();
+ fs.rmSync(d, { recursive: true, force: true });
+ });
+
+ test('--version-path flag still overrides the pin', () => {
+ const d = mkPinned('sub/VERSION');
+ fs.writeFileSync(path.join(d, 'sub', 'VERSION'), '1.0.0.0\n');
+ fs.writeFileSync(path.join(d, 'OTHER_VERSION'), '2.0.0.0\n');
+ commitBase(d);
+ const out = JSON.parse(
+ execFileSync('bun', [BIN, 'classify', '--base', 'main', '--version-path', 'OTHER_VERSION'], { cwd: d }).toString(),
+ );
+ expect(out.currentVersion).toBe('2.0.0.0');
+ expect(out.baseVersion).toBe('2.0.0.0');
+ fs.rmSync(d, { recursive: true, force: true });
+ });
+});
+
+describe('subdirectory manifest (no root package.json, #2531)', () => {
+ /**
+ * The layout this tool used to silently no-op on: the only Node package
+ * lives in web/, so join(cwd, "package.json") missed it, classify said
+ * pkgExists:false, and write touched VERSION alone — leaving the manifest
+ * to be bumped by hand every release.
+ */
+ const mk = (): string => {
+ const d = fs.mkdtempSync(path.join(os.tmpdir(), 'vbump-subdir-'));
+ fs.mkdirSync(path.join(d, 'web'));
+ fs.mkdirSync(path.join(d, '.gstack'));
+ fs.writeFileSync(path.join(d, '.gstack', 'package-json-path'), 'web/package.json\n');
+ fs.writeFileSync(path.join(d, 'VERSION'), '0.1.0.0\n');
+ return d;
+ };
+
+ test('write finds a pinned manifest and bumps it (npm-valid form)', () => {
+ const d = mk();
+ fs.writeFileSync(path.join(d, 'web', 'package.json'),
+ JSON.stringify({ name: 'w', version: '0.1.0' }, null, 2) + '\n');
+ const out = JSON.parse(execFileSync('bun', [BIN, 'write', '--version', '0.2.0.0'], { cwd: d }).toString());
+ expect(out.packageJson).toBe(true);
+ expect(out.packageJsonPath).toBe('web/package.json');
+ expect(out.packageJsonVersion).toBe('0.2.0');
+ expect(JSON.parse(fs.readFileSync(path.join(d, 'web', 'package.json'), 'utf-8')).version).toBe('0.2.0');
+ fs.rmSync(d, { recursive: true, force: true });
+ });
+
+ test('--package-json-path overrides the pin', () => {
+ const d = mk();
+ fs.mkdirSync(path.join(d, 'app'));
+ fs.writeFileSync(path.join(d, 'web', 'package.json'), JSON.stringify({ version: '0.1.0' }, null, 2) + '\n');
+ fs.writeFileSync(path.join(d, 'app', 'package.json'), JSON.stringify({ version: '0.1.0' }, null, 2) + '\n');
+ const out = JSON.parse(execFileSync('bun',
+ [BIN, 'write', '--version', '0.3.0.0', '--package-json-path', 'app/package.json'], { cwd: d }).toString());
+ expect(out.packageJsonPath).toBe('app/package.json');
+ expect(JSON.parse(fs.readFileSync(path.join(d, 'app', 'package.json'), 'utf-8')).version).toBe('0.3.0');
+ // the pinned one is untouched
+ expect(JSON.parse(fs.readFileSync(path.join(d, 'web', 'package.json'), 'utf-8')).version).toBe('0.1.0');
+ fs.rmSync(d, { recursive: true, force: true });
+ });
+
+ test('classify reads the pinned manifest and judges drift on the translated form', () => {
+ const d = mk();
+ fs.writeFileSync(path.join(d, 'web', 'package.json'),
+ JSON.stringify({ name: 'w', version: '0.1.0' }, null, 2) + '\n');
+ execFileSync('git', ['init', '-q', '-b', 'main'], { cwd: d });
+ execFileSync('git', ['config', 'user.email', '[email protected]'], { cwd: d });
+ execFileSync('git', ['config', 'user.name', 't'], { cwd: d });
+ execFileSync('git', ['add', '-A'], { cwd: d });
+ execFileSync('git', ['commit', '-qm', 'base'], { cwd: d });
+ const head = execFileSync('git', ['rev-parse', 'HEAD'], { cwd: d }).toString().trim();
+ fs.mkdirSync(path.join(d, '.git', 'refs', 'remotes', 'origin'), { recursive: true });
+ fs.writeFileSync(path.join(d, '.git', 'refs', 'remotes', 'origin', 'main'), head + '\n');
+
+ const out = JSON.parse(execFileSync('bun', [BIN, 'classify', '--base', 'main'], { cwd: d }).toString());
+ // 0.1.0 IS the npm-valid translation of 0.1.0.0 — in sync, no drift.
+ expect(out.state).toBe('FRESH');
+ expect(out.pkgExists).toBe(true);
+ expect(out.pkgPath).toBe('web/package.json');
+ expect(out.expectedPkgVersion).toBe('0.1.0');
+ fs.rmSync(d, { recursive: true, force: true });
+ });
+
+ test('repair syncs the pinned manifest to the npm-valid form', () => {
+ const d = mk();
+ fs.writeFileSync(path.join(d, 'web', 'package.json'),
+ JSON.stringify({ name: 'w', version: '0.0.9' }, null, 2) + '\n');
+ const out = JSON.parse(execFileSync('bun', [BIN, 'repair'], { cwd: d }).toString());
+ expect(out).toEqual({ repaired: '0.1.0.0', packageJsonPath: 'web/package.json', packageJsonVersion: '0.1.0' });
+ expect(JSON.parse(fs.readFileSync(path.join(d, 'web', 'package.json'), 'utf-8')).version).toBe('0.1.0');
+ fs.rmSync(d, { recursive: true, force: true });
+ });
+});
+
+describe('npm-valid drift contract (decision 11)', () => {
+ test('a correctly-synced 3-component manifest is NOT read as drift', () => {
+ // Without the translation-aware comparison, 0.1.25 vs 0.1.25.0 reads as
+ // DRIFT forever and every classify returns a false positive.
+ expect(classifyState('0.1.25.0', '0.1.24.0', true, '0.1.25', '0.1.25')).toBe('ALREADY_BUMPED');
+ expect(classifyState('0.1.25.0', '0.1.25.0', true, '0.1.25', '0.1.25')).toBe('FRESH');
+ });
+
+ test('the pre-v1.67 1:1 four-digit mirror is grandfathered as in-sync', () => {
+ // Existing installs still carry package.json 1.66.0.0 next to VERSION
+ // 1.66.0.0. Flagging that as DRIFT_UNEXPECTED would hard-stop /ship on
+ // every repo on upgrade day; the next write migrates the manifest to the
+ // translated form instead.
+ expect(classifyState('1.66.0.0', '1.65.0.0', true, '1.66.0.0', '1.66.0')).toBe('ALREADY_BUMPED');
+ expect(classifyState('1.66.0.0', '1.66.0.0', true, '1.66.0.0', '1.66.0')).toBe('FRESH');
+ });
+
+ test('a genuinely diverged manifest still reads as drift', () => {
+ expect(classifyState('1.67.0.0', '1.66.0.0', true, '1.66.0', '1.67.0')).toBe('DRIFT_STALE_PKG');
+ expect(classifyState('1.66.0.0', '1.66.0.0', true, '9.9.9', '1.66.0')).toBe('DRIFT_UNEXPECTED');
+ });
+});
+
+describe('path containment: pins and flags cannot escape the repo', () => {
+ // .gstack/version-path and .gstack/package-json-path are repo-controlled
+ // content. A cloned repo pinning '../../victim.json' — or an in-repo
+ // symlink pointing outside — must never turn a bump into an arbitrary
+ // file overwrite outside the repository.
+ const outer = fs.mkdtempSync(path.join(os.tmpdir(), 'vbump-contain-'));
+ const dir = path.join(outer, 'repo');
+ const victim = path.join(outer, 'victim.json');
+ afterAll(() => { try { fs.rmSync(outer, { recursive: true, force: true }); } catch { /* noop */ } });
+
+ function runFail(args: string[]): { code: number; stderr: string } {
+ try {
+ execFileSync('bun', [BIN, ...args], { cwd: dir, stdio: 'pipe' });
+ return { code: 0, stderr: '' };
+ } catch (e: any) {
+ return { code: e.status, stderr: (e.stderr || '').toString() };
+ }
+ }
+
+ function resetRepo() {
+ fs.rmSync(dir, { recursive: true, force: true });
+ fs.mkdirSync(path.join(dir, '.gstack'), { recursive: true });
+ fs.writeFileSync(path.join(dir, 'VERSION'), '1.0.0.0\n');
+ fs.writeFileSync(victim, JSON.stringify({ version: '9.9.9' }, null, 2) + '\n');
+ }
+
+ test('a ../ escape in .gstack/version-path fails exit 2 and writes nothing', () => {
+ resetRepo();
+ fs.writeFileSync(path.join(dir, '.gstack', 'version-path'), '../victim.json\n');
+ const r = runFail(['write', '--version', '1.1.0.0']);
+ expect(r.code).toBe(2);
+ expect(r.stderr).toContain('outside the repository');
+ expect(JSON.parse(fs.readFileSync(victim, 'utf-8')).version).toBe('9.9.9');
+ });
+
+ test('an absolute path in .gstack/package-json-path fails exit 2', () => {
+ resetRepo();
+ fs.writeFileSync(path.join(dir, '.gstack', 'package-json-path'), victim + '\n');
+ const r = runFail(['write', '--version', '1.1.0.0']);
+ expect(r.code).toBe(2);
+ expect(r.stderr).toContain('outside the repository');
+ expect(JSON.parse(fs.readFileSync(victim, 'utf-8')).version).toBe('9.9.9');
+ });
+
+ test('an in-repo symlink pointing outside fails exit 2 and never follows', () => {
+ if (process.platform === 'win32') return; // symlink creation needs privileges there
+ resetRepo();
+ fs.symlinkSync(victim, path.join(dir, 'link.json'));
+ fs.writeFileSync(path.join(dir, '.gstack', 'version-path'), 'link.json\n');
+ const r = runFail(['write', '--version', '1.1.0.0']);
+ expect(r.code).toBe(2);
+ expect(r.stderr).toContain('outside the repository');
+ expect(JSON.parse(fs.readFileSync(victim, 'utf-8')).version).toBe('9.9.9');
+ });
+
+ test('classify refuses the same escapes (no read outside the repo)', () => {
+ resetRepo();
+ fs.writeFileSync(path.join(dir, '.gstack', 'version-path'), '../victim.json\n');
+ const r = runFail(['classify', '--base', 'main']);
+ expect(r.code).toBe(2);
+ expect(r.stderr).toContain('outside the repository');
+ });
+
+ test('a lockfile symlinked outside the repo is skipped with a warning, not written', () => {
+ if (process.platform === 'win32') return;
+ resetRepo();
+ const outerLock = path.join(outer, 'outer-lock.json');
+ fs.writeFileSync(outerLock, JSON.stringify({ version: '1.0.0', packages: { '': { version: '1.0.0' } } }, null, 2) + '\n');
+ fs.writeFileSync(path.join(dir, 'package.json'), JSON.stringify({ name: 'x', version: '1.0.0' }, null, 2) + '\n');
+ fs.symlinkSync(outerLock, path.join(dir, 'package-lock.json'));
+ const res = execFileSync('bun', [BIN, 'write', '--version', '1.1.0.0'], { cwd: dir, stdio: 'pipe' });
+ expect(JSON.parse(res.toString()).packageLock).toBe(false);
+ expect(JSON.parse(fs.readFileSync(outerLock, 'utf-8')).version).toBe('1.0.0');
+ });
+
+ test('legitimate subdirectory pins still work (containment is not over-broad)', () => {
+ resetRepo();
+ fs.mkdirSync(path.join(dir, 'frontend'), { recursive: true });
+ fs.writeFileSync(path.join(dir, 'frontend', 'package.json'), JSON.stringify({ name: 'x', version: '1.0.0' }, null, 2) + '\n');
+ fs.writeFileSync(path.join(dir, '.gstack', 'version-path'), 'frontend/package.json\n');
+ const out = execFileSync('bun', [BIN, 'write', '--version', '1.1.0'], { cwd: dir }).toString();
+ expect(JSON.parse(out).wrote).toBe('1.1.0');
+ expect(JSON.parse(fs.readFileSync(path.join(dir, 'frontend', 'package.json'), 'utf-8')).version).toBe('1.1.0');
+ });
+});
diff --git a/test/helpers/carve-guards.ts b/test/helpers/carve-guards.ts
index 40664b651..5aef53296 100644
--- a/test/helpers/carve-guards.ts
+++ b/test/helpers/carve-guards.ts
@@ -126,7 +126,7 @@ export const CARVE_GUARDS: Record<string, CarveGuard> = {
},
behavioral: 'external',
externalTest: 'test/skill-e2e-ship-section-loading.test.ts',
- maxSkeletonBytes: 90_000,
+ maxSkeletonBytes: 90_800, // v1.67 wave + v1.66.1's evidence-ledger prose (merged): measured 90,333
minUnionBytes: 120_000,
mustContain: ['VERSION', 'CHANGELOG', 'review', 'merge', 'PR'],
// v1.58.5.0: pre-push-guard install (#2077) stacks on the shared first-run-guidance preamble.
@@ -157,7 +157,7 @@ export const CARVE_GUARDS: Record<string, CarveGuard> = {
// v1.65 merge: provisional larger-of-both-waves budget; re-measured below.
// Fork port wave 2 (#703): the repo-doc-preference block in the design
// check grew every plan-review skeleton ~0.7KB. Measured values noted.
- maxSkeletonBytes: 92_500, // v1.64+v1.65 merge: both waves' preamble growth; measured 92,004
+ maxSkeletonBytes: 93_000, // v1.67 fix wave: #2499 jq entry-resolution in the brain-sync preamble (~340B/skill) + wave doc additions; measured 92,531
minUnionBytes: 80_000,
mustContain: ['SCOPE EXPANSION', 'SELECTIVE EXPANSION', 'HOLD SCOPE', 'SCOPE REDUCTION'],
// Default-on Codex outside-voice (codexPreflight block + CODEX_MODE branch
@@ -181,7 +181,9 @@ export const CARVE_GUARDS: Record<string, CarveGuard> = {
// v1.65 merge: provisional larger-of-both-waves budget; re-measured below.
// Fork port wave 2 (#703): the repo-doc-preference block in the design
// check grew every plan-review skeleton ~0.7KB. Measured values noted.
- maxSkeletonBytes: 70_000, // measured 68,780
+ // #2499 project-scope MCP jq in the brain-sync block grew every tier-2+
+ // skeleton ~1.5KB (entry resolution emitted once per SKILL.md).
+ maxSkeletonBytes: 70_500, // measured 70,318
minUnionBytes: 70_000,
mustContain: ['Architecture', 'Code Quality', 'Test', 'Performance'],
// Cross-cutting preamble growth (v1.57.2.0 AUQ-failure prose fallback + the
@@ -236,7 +238,9 @@ export const CARVE_GUARDS: Record<string, CarveGuard> = {
// v1.2.0 activation lift: first-run-guidance section in the shared preamble.
// Fork port wave 2 (#703): the repo-doc-preference block in the design
// check grew every plan-review skeleton ~0.7KB. Measured values noted.
- maxSkeletonBytes: 82_000, // measured 80,493
+ // #2499 project-scope MCP jq in the brain-sync block grew every tier-2+
+ // skeleton ~1.5KB (entry resolution emitted once per SKILL.md).
+ maxSkeletonBytes: 82_500, // measured 82,031
minUnionBytes: 70_000,
mustContain: ['developer experience', 'Getting Started'],
// Default-on Codex outside-voice (codexPreflight block + CODEX_MODE branch
@@ -264,7 +268,9 @@ export const CARVE_GUARDS: Record<string, CarveGuard> = {
// (judgment must be visible before the workflow directs the user to a
// vendor site), plus the #703 dual-write + repo-doc-preference block and
// the #538 opt-out + D1 evidence directive — ratio 1.104 measured.
- maxSkeletonBytes: 101_000,
+ // #2499 project-scope MCP jq in the brain-sync block grew every tier-2+
+ // skeleton ~1.5KB (entry resolution emitted once per SKILL.md).
+ maxSkeletonBytes: 101_500, // measured 101,314
minUnionBytes: 70_000,
mustContain: ['design doc', 'problem statement'],
maxSizeRatio: 1.12,
@@ -285,7 +291,7 @@ export const CARVE_GUARDS: Record<string, CarveGuard> = {
// +Conductor AUQ-default-prose rule + one-way/continuation safety in the
// always-loaded AskUserQuestion Format section.
// v1.2.0 activation lift: first-run-guidance section in the shared preamble.
- maxSkeletonBytes: 56_500, // v1.64+v1.65 merge; measured 56,044
+ maxSkeletonBytes: 57_000, // v1.67 fix wave: #2499 preamble growth; measured 56,571
minUnionBytes: 55_000,
mustContain: ['CHANGELOG', 'Diataxis', 'coverage'],
// Two intentional additions stack on this small skill: the AUQ-failure prose
@@ -316,7 +322,7 @@ export const CARVE_GUARDS: Record<string, CarveGuard> = {
// v1.65 merge: provisional larger-of-both-waves budget; re-measured below.
// v1.64.1.0: shared-preamble prose from the two parallel v1.64 waves lands
// the skeleton at 69,022 B; +~1 KB headroom.
- maxSkeletonBytes: 70_000,
+ maxSkeletonBytes: 70_500, // v1.67 fix wave: #2499 preamble growth; measured 70,003
minUnionBytes: 72_000,
mustContain: ['Typography', 'Color', 'Aesthetic Direction'],
// Cross-cutting preamble growth (v1.57.2.0 AUQ-failure prose fallback ~2KB +
@@ -356,7 +362,7 @@ export const CARVE_GUARDS: Record<string, CarveGuard> = {
// +Conductor AUQ-default-prose rule + one-way/continuation safety in the
// always-loaded AskUserQuestion Format section.
// v1.2.0 activation lift: first-run-guidance section in the shared preamble.
- maxSkeletonBytes: 75_800, // v1.64+v1.65 merge; measured 75,364
+ maxSkeletonBytes: 76_400, // v1.67 fix wave: #2499 preamble growth; measured 75,891
minUnionBytes: 72_000,
mustContain: ['OWASP', 'STRIDE', 'daily', 'comprehensive', 'verif'],
// cso keeps its mode-dispatch + FP-filtering phases always-loaded, so the
diff --git a/test/helpers/tool-map.ts b/test/helpers/tool-map.ts
index 9fcf8e7f9..3202dbfd9 100644
--- a/test/helpers/tool-map.ts
+++ b/test/helpers/tool-map.ts
@@ -50,7 +50,7 @@ export const TOOL_COMPATIBILITY: Record<'claude' | 'gpt' | 'gemini', Record<Tool
Glob: false,
Grep: false,
AskUserQuestion: false,
- WebSearch: true, // --enable web_search_cached
+ WebSearch: true, // -c 'web_search="cached"' (CODEX_WEB_SEARCH_FLAG, #2525)
WebFetch: false,
},
gemini: {
diff --git a/test/hermetic-wiring.test.ts b/test/hermetic-wiring.test.ts
index 658344cfe..87fe13523 100644
--- a/test/hermetic-wiring.test.ts
+++ b/test/hermetic-wiring.test.ts
@@ -125,10 +125,21 @@ describe('hermetic wiring tripwire', () => {
expect(configDir.startsWith(runRoot + path.sep)).toBe(true);
expect(configDir.startsWith(operatorClaude)).toBe(false);
const skillsDir = path.join(configDir, 'skills');
+ const repoRootReal = fs.realpathSync(ROOT) + path.sep;
for (const entry of fs.readdirSync(skillsDir)) {
const target = fs.readlinkSync(path.join(skillsDir, entry, 'SKILL.md'));
- expect(target.startsWith(operatorClaude), `${entry}: symlink escapes to ${target}`).toBe(false);
- expect(fs.realpathSync(target).startsWith(fs.realpathSync(ROOT) + path.sep), `${entry}: symlink outside repo: ${target}`).toBe(true);
+ const resolved = fs.realpathSync(target);
+ // Targets inside the live repo checkout are the blessed edge — exempt
+ // them BEFORE the operator-~/.claude ban. On the default global-git
+ // install the repo itself lives at ~/.claude/skills/gstack, so every
+ // CORRECT symlink carries the operatorClaude prefix and an unexempted
+ // ban can never pass (regression 2026-08-15: pristine v1.64.1.0 fails
+ // this test in any worktree under ~/.claude/skills/ and passes
+ // elsewhere — realpath both sides so a symlinked HOME can't dodge it).
+ if (!resolved.startsWith(repoRootReal)) {
+ expect(resolved.startsWith(operatorClaude), `${entry}: symlink escapes to ${target}`).toBe(false);
+ }
+ expect(resolved.startsWith(repoRootReal), `${entry}: symlink outside repo: ${target}`).toBe(true);
}
});
});
diff --git a/test/host-config.test.ts b/test/host-config.test.ts
index ffdf5353a..b685bb89d 100644
--- a/test/host-config.test.ts
+++ b/test/host-config.test.ts
@@ -3,7 +3,7 @@
* host-config-export.ts, and golden-file regression checks.
*/
-import { describe, test, expect } from 'bun:test';
+import { describe, test, expect, beforeAll } from 'bun:test';
import * as fs from 'fs';
import * as path from 'path';
import { validateHostConfig, validateAllConfigs, type HostConfig } from '../scripts/host-config';
@@ -421,6 +421,33 @@ describe('host-config-export.ts CLI', () => {
describe('golden-file regression', () => {
const GOLDEN_DIR = path.join(ROOT, 'test', 'fixtures', 'golden');
+ // #2532: the codex/factory goldens read gitignored .agents/ and .factory/
+ // artifacts that only gen-skill-docs.test.ts (a serial tree-mutating file)
+ // produces. On a clean clone — or when this file runs in isolation — those
+ // dirs don't exist and the goldens fail with ENOENT, an order dependency,
+ // not a regression. Self-provision: generate a host's artifacts iff its
+ // ship SKILL.md is missing. Existing artifacts are never overwritten here,
+ // so a genuinely stale artifact still fails the golden (that is the test's
+ // job; freshness enforcement lives in gen-skill-docs.test.ts).
+ beforeAll(() => {
+ const hostArtifacts: Array<[string, string]> = [
+ ['codex', path.join(ROOT, '.agents', 'skills', 'gstack-ship', 'SKILL.md')],
+ ['factory', path.join(ROOT, '.factory', 'skills', 'gstack-ship', 'SKILL.md')],
+ ];
+ for (const [host, artifact] of hostArtifacts) {
+ if (fs.existsSync(artifact)) continue;
+ const result = Bun.spawnSync(['bun', 'run', 'scripts/gen-skill-docs.ts', '--host', host], {
+ cwd: ROOT,
+ });
+ if (result.exitCode !== 0) {
+ throw new Error(
+ `golden-file beforeAll: gen-skill-docs --host ${host} failed (exit ${result.exitCode}):\n`
+ + result.stderr.toString(),
+ );
+ }
+ }
+ });
+
test('Claude ship skill matches golden baseline', () => {
const golden = fs.readFileSync(path.join(GOLDEN_DIR, 'claude-ship-SKILL.md'), 'utf-8');
const current = fs.readFileSync(path.join(ROOT, 'ship', 'SKILL.md'), 'utf-8');
diff --git a/test/pty-skill-seeding-wiring.test.ts b/test/pty-skill-seeding-wiring.test.ts
index 01f5999ce..bd715a9b4 100644
--- a/test/pty-skill-seeding-wiring.test.ts
+++ b/test/pty-skill-seeding-wiring.test.ts
@@ -17,7 +17,7 @@ import { describe, test, expect } from 'bun:test';
import * as fs from 'fs';
import * as path from 'path';
-const ROOT = path.resolve(new URL(import.meta.url).pathname, '..', '..');
+const ROOT = path.resolve(import.meta.path, '..', '..');
/** A PTY send whose payload starts with a slash command (`/name`, optionally
* followed by `\r`, whitespace, or the closing quote). A second slash right
diff --git a/test/question-tuning-registry-path.test.ts b/test/question-tuning-registry-path.test.ts
new file mode 100644
index 000000000..ec1b2b0d6
--- /dev/null
+++ b/test/question-tuning-registry-path.test.ts
@@ -0,0 +1,62 @@
+/**
+ * Question Tuning registry path must be absolute (#2489).
+ *
+ * The preamble told agents to choose question_id from a RELATIVE
+ * `scripts/question-registry.ts` — which never resolves from a user's
+ * project cwd (the file lives only under the gstack install root). The
+ * lookup silently failed and agents fabricated ids via the {skill}-{slug}
+ * fallback (one observed /plan-eng-review session: 21/21 unregistered).
+ *
+ * The resolver now interpolates the installed path the same way ${bin}
+ * paths are interpolated: ctx.paths.skillRoot (a `~`-rooted path on Claude,
+ * $GSTACK_ROOT on env-var hosts).
+ */
+import { describe, test, expect } from 'bun:test';
+import * as fs from 'fs';
+import * as path from 'path';
+import { HOST_PATHS } from '../scripts/resolvers/types';
+import type { TemplateContext } from '../scripts/resolvers/types';
+import { generateQuestionTuning } from '../scripts/resolvers/question-tuning';
+
+const ROOT = path.join(import.meta.dir, '..');
+
+function makeCtx(host: 'claude' | 'codex'): TemplateContext {
+ return {
+ skillName: 'test-skill',
+ tmplPath: 'test.tmpl',
+ host,
+ paths: HOST_PATHS[host],
+ preambleTier: 2,
+ };
+}
+
+describe('question-tuning registry path is absolute (#2489)', () => {
+ test('claude host renders the installed registry path', () => {
+ const out = generateQuestionTuning(makeCtx('claude'));
+ expect(out).toContain('`~/.claude/skills/gstack/scripts/question-registry.ts`');
+ });
+
+ test('env-var host renders $GSTACK_ROOT-anchored registry path', () => {
+ const out = generateQuestionTuning(makeCtx('codex'));
+ expect(out).toContain('`$GSTACK_ROOT/scripts/question-registry.ts`');
+ });
+
+ test('no host renders a bare relative registry path', () => {
+ for (const host of ['claude', 'codex'] as const) {
+ const out = generateQuestionTuning(makeCtx(host));
+ // A backtick immediately before `scripts/` means the path renders
+ // relative — exactly the shape that never resolves from a project cwd.
+ expect(out).not.toContain('`scripts/question-registry.ts`');
+ }
+ });
+
+ test('the interpolated path points at a file that exists in the install tree', () => {
+ expect(fs.existsSync(path.join(ROOT, 'scripts', 'question-registry.ts'))).toBe(true);
+ });
+
+ test('rendered SKILL.md carries the absolute path', () => {
+ const rendered = fs.readFileSync(path.join(ROOT, 'plan-eng-review', 'SKILL.md'), 'utf-8');
+ expect(rendered).toContain('~/.claude/skills/gstack/scripts/question-registry.ts');
+ expect(rendered).not.toContain('`scripts/question-registry.ts`');
+ });
+});
diff --git a/test/redact-engine.test.ts b/test/redact-engine.test.ts
index 33771f904..ab910463f 100644
--- a/test/redact-engine.test.ts
+++ b/test/redact-engine.test.ts
@@ -166,6 +166,52 @@ describe("MEDIUM demoted credential-shaped patterns (TENSION-1)", () => {
expect(ids("API_KEY=${MY_VAR}")).not.toContain("env.kv");
});
+ // #1946 gap 3: the uppercase-`=`-only shape made lowercase and YAML/JSON
+ // colon assignments invisible — the exact config shapes people actually
+ // push. Each closed detection fail-open gets a pinned case.
+ test("env.kv fires on lowercase = assignment (#1946)", () => {
+ expect(ids("api_key=8Fk2pQ9vXz4wL7mN3rT6yB1cD5eG0hJ")).toContain("env.kv");
+ });
+ test("env.kv fires on YAML colon assignment (#1946)", () => {
+ expect(ids("password: 8Fk2pQ9vXz4wL7mN3rT6yB1cD5eG0hJ")).toContain("env.kv");
+ });
+ test("env.kv fires on quoted JSON key colon assignment (#1946)", () => {
+ expect(ids('"apiKey": "8Fk2pQ9vXz4wL7mN3rT6yB1cD5eG0hJ"')).toContain("env.kv");
+ });
+ test("env.kv colon/lowercase forms stay entropy-gated and placeholder-safe", () => {
+ expect(ids("password: changeme")).not.toContain("env.kv");
+ expect(ids("apiKey: YOUR_API_KEY_HERE")).not.toContain("env.kv");
+ expect(ids("api_key=${MY_VAR}")).not.toContain("env.kv");
+ });
+ // T1 calibration: the zero-or-more-prefix net matched ANY identifier ending
+ // in a suffix, so ordinary code (`cacheKey: <entropic id>`) hit a MEDIUM
+ // confirm prompt. Name shape must be credential-semantic to count.
+ test("env.kv ignores non-credential names ending in a suffix (entropic values)", () => {
+ const v = "8Fk2pQ9vXz4wL7mN3rT6yB1cD5eG0hJ";
+ expect(ids(`cacheKey: ${v}`)).not.toContain("env.kv");
+ expect(ids(`sortKey: ${v}`)).not.toContain("env.kv");
+ expect(ids(`partitionKey: ${v}`)).not.toContain("env.kv");
+ expect(ids(`hotkey: ${v}`)).not.toContain("env.kv");
+ expect(ids(`monkey: ${v}`)).not.toContain("env.kv");
+ expect(ids(`idempotencyKey: ${v}`)).not.toContain("env.kv");
+ });
+ test("env.kv still fires on every credential-shaped name form", () => {
+ const v = "8Fk2pQ9vXz4wL7mN3rT6yB1cD5eG0hJ";
+ expect(ids(`api_key=${v}`)).toContain("env.kv"); // (i) separator
+ expect(ids(`API_KEY=${v}`)).toContain("env.kv"); // (i) + ALL-CAPS
+ expect(ids(`x-access-key: ${v}`)).toContain("env.kv"); // (i) dash separator
+ expect(ids(`key: ${v}`)).toContain("env.kv"); // (ii) bare suffix
+ expect(ids(`APIKEY=${v}`)).toContain("env.kv"); // (iii) ALL-CAPS compound
+ expect(ids(`apiKey: ${v}`)).toContain("env.kv"); // (iv) credential camel
+ expect(ids(`authToken: ${v}`)).toContain("env.kv"); // (iv) credential camel
+ expect(ids(`clientSecret: ${v}`)).toContain("env.kv"); // (iv) credential camel
+ });
+ test("env.kv stays MEDIUM (calibration: generic net, not a blocker)", () => {
+ const f = scan("api_key=8Fk2pQ9vXz4wL7mN3rT6yB1cD5eG0hJ", { repoVisibility: "private" })
+ .findings.find((x) => x.id === "env.kv");
+ expect(f?.tier).toBe("MEDIUM");
+ });
+
// #1946 — Bearer is the most FP-prone shape in the wave: docs and examples
// are full of "Authorization: Bearer <token>". MEDIUM + header proximity +
// the env.kv entropy recipe keep it calibrated.
diff --git a/test/redact-parcel-id-false-positive.test.ts b/test/redact-parcel-id-false-positive.test.ts
new file mode 100644
index 000000000..9f34bf420
--- /dev/null
+++ b/test/redact-parcel-id-false-positive.test.ts
@@ -0,0 +1,77 @@
+/**
+ * pii.phone.e164 vs county tax-map parcel IDs (APNs).
+ *
+ * A parcel ID reads as a national-format phone number to the e164 pattern —
+ * the same collision class as the digit-only UUID `insideUuid` already guards.
+ * Land, title and property-tax repos carry these by the hundred, so the noise
+ * is not incidental; it arrives on every branch that touches the domain.
+ *
+ * The guard has to be narrow, so this file pins BOTH directions: parcels stay
+ * clean, and every real phone shape stays flagged. The negative controls are
+ * the point — a guard that exempted long digit runs wholesale would pass the
+ * "parcels clean" half and quietly gut the pattern.
+ */
+import { describe, test, expect } from "bun:test";
+import { scan } from "../lib/redact-engine";
+import { looksLikeParcelId } from "../lib/redact-patterns";
+
+const flagsPhone = (s: string): boolean =>
+ scan(s, { repoVisibility: "private" }).findings.some((f) => f.id === "pii.phone.e164");
+
+describe("pii.phone.e164 — real phone numbers stay flagged", () => {
+ const REAL_PHONES: [string, string][] = [
+ ["US dashed", "call 415-555-0123 now"],
+ ["US parens", "phone: (415) 555-0123"],
+ ["US dotted", "p 415.555.0123"],
+ ["E.164 US", "tel: +14155550123"],
+ ["E.164 US spaced", "contact +1 415 555 0123"],
+ ["E.164 UK", "ring +44 20 7946 0958"],
+ ["E.164 DE", "fon +49 30 901820"],
+ ["E.164 PT 12-digit", "reach +351912345678"],
+ ["bare 11-digit", "operator 14155550123 ext"],
+ ];
+ for (const [label, input] of REAL_PHONES) {
+ test(label, () => {
+ expect(flagsPhone(input)).toBe(true);
+ });
+ }
+});
+
+describe("pii.phone.e164 — parcel IDs are not phone numbers", () => {
+ test("dotted APN is exempt on shape alone", () => {
+ expect(flagsPhone(' parcel_id: "12-3456789.000",')).toBe(false);
+ });
+
+ test("a normalized APN is exempt when paired with its punctuated form", () => {
+ expect(
+ flagsPhone(' parcel_id: "12-3456789.000",\n norm: "123456789000",'),
+ ).toBe(false);
+ });
+
+ test("8-digit middle is still an APN", () => {
+ expect(flagsPhone('apn "30-00414123.0001"')).toBe(false);
+ });
+});
+
+describe("pii.phone.e164 — the guard stays narrow", () => {
+ /**
+ * The load-bearing control. A bare digit run is phone-shaped in isolation, so
+ * it may only be exempted by EVIDENCE — a punctuated APN in the surrounding
+ * window. With no such twin, the finding must survive. If this ever goes
+ * green-by-exemption, the guard has become a blanket hole in the pattern.
+ */
+ test("a bare digit run with no punctuated APN nearby is still flagged", () => {
+ expect(flagsPhone('norm: "123456789000",')).toBe(true);
+ });
+
+ test("hyphen-only APN variants are NOT exempted by shape", () => {
+ // 22-0001-000 is genuinely phone-shaped; only the dotted form earns a
+ // shape-based pass. This one may only be cleared by the evidence tier.
+ expect(looksLikeParcelId("22-0001-000", /(.*)/.exec("22-0001-000")!)).toBe(false);
+ });
+
+ test("evidence pairing requires an exact digit match, not a prefix", () => {
+ // A near-miss APN in the window must not clear a different digit run.
+ expect(flagsPhone(' parcel_id: "12-3456789.000",\n other: "999888777666",')).toBe(true);
+ });
+});
diff --git a/test/redact-prepush-hook.test.ts b/test/redact-prepush-hook.test.ts
index 489d22d38..16f0f6d4b 100644
--- a/test/redact-prepush-hook.test.ts
+++ b/test/redact-prepush-hook.test.ts
@@ -44,6 +44,24 @@ function runHook(
return { code: r.status ?? 0, stderr: r.stderr ?? "" };
}
+/**
+ * Env override that puts `binDir` first on the search path, for tests that
+ * shadow a real binary with a stub.
+ *
+ * Two portability details, both of which a hardcoded `PATH: "dir:" + ...`
+ * gets wrong (mirrors `prependPath` in test/gstack-brain-context-load.test.ts):
+ * - The separator is `;` on Windows, not `:`. Using the literal produces one
+ * unparseable entry, so the stub is never found and the REAL binary runs —
+ * a test that silently passes through rather than failing loudly.
+ * - Windows env keys are case-insensitive and commonly spelled `Path`. Adding
+ * a second `PATH` key alongside an inherited `Path` leaves which one wins up
+ * to the spawn implementation, so reuse whichever key already exists.
+ */
+function prependPath(binDir: string): Record<string, string> {
+ const pathKey = Object.keys(process.env).find((k) => k.toLowerCase() === "path") || "PATH";
+ return { [pathKey]: `${binDir}${path.delimiter}${process.env[pathKey] || ""}` };
+}
+
const ZERO = "0000000000000000000000000000000000000000";
// Assembled at runtime so the LITERAL never appears in a pushed diff — the
@@ -147,30 +165,44 @@ describe("fail closed on unscannable diffs (#1946)", () => {
expect(stderr).not.toContain("could not compute the pushed diff");
});
- test("a diff killed by a signal (null status — the maxBuffer/kill class) BLOCKS", () => {
- // Stub git: probes delegate to the real git; the diff invocation kills
- // itself, producing spawnSync status === null. This is the exact branch
- // gitStrict's docstring names (oversized-diff overflow is delivered the
- // same way) — pre-landing review flagged it as untested.
- const realGit = Bun.which("git") || "/usr/bin/git";
- const stubDir = fs.mkdtempSync(path.join(os.tmpdir(), "prepush-stubgit-"));
- try {
- const stub = `#!/bin/sh\nif [ "$1" = "diff" ]; then kill -KILL $$; fi\nexec "${realGit}" "$@"\n`;
- fs.writeFileSync(path.join(stubDir, "git"), stub);
- fs.chmodSync(path.join(stubDir, "git"), 0o755);
-
- const base = git(["rev-parse", "HEAD"]);
- const head = commit("clean.txt", "clean content\n", "clean commit");
- const { code, stderr } = runHook(`refs/heads/main ${head} refs/heads/main ${base}\n`, {
- PATH: `${stubDir}:${process.env.PATH}`,
- });
- expect(code).toBe(1);
- expect(stderr).toContain("could not compute the pushed diff");
- expect(stderr).toContain("GSTACK_REDACT_PREPUSH=skip");
- } finally {
- fs.rmSync(stubDir, { recursive: true, force: true });
- }
- });
+ // POSIX-only, for two independent reasons. `spawnSync` reports
+ // `status === null` only when a child dies from a signal, and Windows has no
+ // equivalent — a force-killed process surfaces a non-zero exit code there — so
+ // the branch this test names is unreachable. The stub below is also a
+ // `#!/bin/sh` file named `git`, which Windows will not execute at all, since
+ // process creation resolves commands through PATHEXT (.exe/.cmd/.bat) and
+ // ignores the shebang. A Windows variant would have to assert the non-zero
+ // exit path instead, i.e. a different branch than the name claims, so it is
+ // skipped rather than rewritten. Gate style follows
+ // test/session-runner-timeout.test.ts and test/setup-emoji-font.test.ts.
+ test.skipIf(process.platform === "win32")(
+ "a diff killed by a signal (null status — the maxBuffer/kill class) BLOCKS",
+ () => {
+ // Stub git: probes delegate to the real git; the diff invocation kills
+ // itself, producing spawnSync status === null. This is the exact branch
+ // gitStrict's docstring names (oversized-diff overflow is delivered the
+ // same way) — pre-landing review flagged it as untested.
+ const realGit = Bun.which("git") || "/usr/bin/git";
+ const stubDir = fs.mkdtempSync(path.join(os.tmpdir(), "prepush-stubgit-"));
+ try {
+ const stub = `#!/bin/sh\nif [ "$1" = "diff" ]; then kill -KILL $$; fi\nexec "${realGit}" "$@"\n`;
+ fs.writeFileSync(path.join(stubDir, "git"), stub);
+ fs.chmodSync(path.join(stubDir, "git"), 0o755);
+
+ const base = git(["rev-parse", "HEAD"]);
+ const head = commit("clean.txt", "clean content\n", "clean commit");
+ const { code, stderr } = runHook(
+ `refs/heads/main ${head} refs/heads/main ${base}\n`,
+ prependPath(stubDir),
+ );
+ expect(code).toBe(1);
+ expect(stderr).toContain("could not compute the pushed diff");
+ expect(stderr).toContain("GSTACK_REDACT_PREPUSH=skip");
+ } finally {
+ fs.rmSync(stubDir, { recursive: true, force: true });
+ }
+ },
+ );
});
describe("install UX surfaces (#1946 / eng review D3+D10)", () => {
@@ -189,6 +221,82 @@ describe("install UX surfaces (#1946 / eng review D3+D10)", () => {
expect(tmpl).toContain(".redact-prepush-prompted");
expect(tmpl).toContain("redact_prepush_hook");
});
+
+ // #1946 / maintainer decision 6: setup asks ONCE for consent on a real TTY,
+ // records the answer to the existing redact_prepush_hook key, and keeps the
+ // hint-only posture everywhere else. Default stays FALSE; setup never
+ // installs the hook itself (the assertion above pins that).
+ describe("one-time consent prompt in setup (#1946, decision 6)", () => {
+ const setup = fs.readFileSync(path.join(ROOT, "setup"), "utf8");
+ const block = setup.slice(setup.indexOf("# ─── Redact pre-push guard consent"));
+
+ test("prompt is gated on key ABSENCE and a real TTY, with a timed default-N read", () => {
+ expect(block).toContain("grep -q '^redact_prepush_hook:'");
+ expect(block).toContain('[ -t 0 ] && [ -t 1 ]');
+ expect(block).toContain("[y/N]");
+ expect(block).toContain('read -t "$_REDACT_PROMPT_TIMEOUT"');
+ });
+
+ test("an explicit answer persists true/false; timeout persists NOTHING", () => {
+ expect(block).toContain("set redact_prepush_hook true");
+ expect(block).toContain("set redact_prepush_hook false");
+ // The timeout branch must not write the key (a silent decline would
+ // permanently suppress the ask without the user ever seeing it). The
+ // branch's hint TEXT mentions the command; the executable invocation is
+ // the quoted "$GSTACK_CONFIG" form.
+ const timeoutBranch = block.slice(block.indexOf("*)"), block.indexOf("esac"));
+ expect(timeoutBranch).not.toContain('"$GSTACK_CONFIG" set redact_prepush_hook');
+ });
+
+ test("non-interactive setup keeps the hint-only posture (no prompt, no key write)", () => {
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), "gstack-consent-"));
+ try {
+ const script = [
+ "QUIET=0",
+ 'log() { echo "$@"; }',
+ `GSTACK_CONFIG="${path.join(ROOT, "bin", "gstack-config")}"`,
+ block,
+ ].join("\n");
+ const r = spawnSync("bash", ["-c", script], {
+ encoding: "utf8",
+ stdio: ["ignore", "pipe", "pipe"], // stdin not a TTY
+ env: { ...process.env, GSTACK_HOME: home },
+ timeout: 15_000,
+ });
+ expect(r.status).toBe(0);
+ expect(r.stdout).toContain("Tip:");
+ expect(r.stdout).not.toContain("[y/N]");
+ const cfg = path.join(home, "config.yaml");
+ const cfgText = fs.existsSync(cfg) ? fs.readFileSync(cfg, "utf8") : "";
+ expect(cfgText).not.toContain("redact_prepush_hook");
+ } finally {
+ fs.rmSync(home, { recursive: true, force: true });
+ }
+ });
+
+ test("a recorded answer is never re-asked (key present → silent)", () => {
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), "gstack-consent-set-"));
+ try {
+ fs.writeFileSync(path.join(home, "config.yaml"), "redact_prepush_hook: false\n");
+ const script = [
+ "QUIET=0",
+ 'log() { echo "$@"; }',
+ `GSTACK_CONFIG="${path.join(ROOT, "bin", "gstack-config")}"`,
+ block,
+ ].join("\n");
+ const r = spawnSync("bash", ["-c", script], {
+ encoding: "utf8",
+ stdio: ["ignore", "pipe", "pipe"],
+ env: { ...process.env, GSTACK_HOME: home },
+ timeout: 15_000,
+ });
+ expect(r.status).toBe(0);
+ expect(r.stdout.trim()).toBe("");
+ } finally {
+ fs.rmSync(home, { recursive: true, force: true });
+ }
+ });
+ });
});
describe("escape valve", () => {
diff --git a/test/redact-prepush-rebase-force-push.test.ts b/test/redact-prepush-rebase-force-push.test.ts
new file mode 100644
index 000000000..d1852b641
--- /dev/null
+++ b/test/redact-prepush-rebase-force-push.test.ts
@@ -0,0 +1,154 @@
+/**
+ * gstack-redact-prepush — the REBASED FORCE-PUSH shape (#2573).
+ *
+ * After `git rebase origin/main`, the remote tip of the feature branch still
+ * exists locally (it is the pre-rebase tip) but is no longer an ancestor of
+ * HEAD. The old `remoteSha..localSha` range therefore swept in every upstream
+ * commit rebased onto — content already published and already scanned when it
+ * reached the remote. Reported as #2573: a 23-commit branch rebased onto a
+ * main that advanced 23 commits scanned 1.14 MiB instead of 0.27 MiB, tripped
+ * the engine's 1 MiB cap, and blocked the push with engine.input_too_large —
+ * a HIGH that was the engine saying it never ran, not a finding.
+ *
+ * The catch-up-merge narrowing (`rev-list localSha --not remoteSha --remotes`)
+ * covers this shape too: the upstream commits are reachable from origin/main's
+ * remote-tracking ref, which exists by construction — you cannot have rebased
+ * onto origin/main without it. These tests PROVE that, end-to-end through the
+ * actual hook binary with the real pre-push stdin protocol, in both
+ * directions: upstream content is not re-scanned (a HIGH-shaped credential
+ * someone else already published does not block a clean rebased push), and
+ * narrowing does not narrow coverage (a HIGH in a rebased commit of our own
+ * still blocks).
+ *
+ * Analyzed non-gap, recorded for the next reader: a rebased force-push where
+ * the upstream commits sit in NO remote-tracking ref cannot arise from the
+ * standard flow — rebasing onto origin/<branch> requires the tracking ref,
+ * and rebasing onto a purely local branch means the "upstream" commits were
+ * never published, so scanning them is correct, not a false positive.
+ */
+import { describe, test, expect, beforeEach, afterEach } from "bun:test";
+import * as fs from "fs";
+import * as os from "os";
+import * as path from "path";
+import { spawnSync } from "child_process";
+
+const PREPUSH = path.resolve(import.meta.dir, "..", "bin", "gstack-redact-prepush");
+
+let repo: string;
+let remote: string;
+
+function git(args: string[], cwd = repo): string {
+ const r = spawnSync("git", args, { cwd, encoding: "utf8" });
+ if (r.status !== 0) throw new Error(`git ${args.join(" ")}\n${r.stderr}`);
+ return r.stdout?.trim() ?? "";
+}
+
+function commit(file: string, content: string, msg: string): string {
+ fs.mkdirSync(path.dirname(path.join(repo, file)), { recursive: true });
+ fs.writeFileSync(path.join(repo, file), content);
+ git(["add", file]);
+ git(["commit", "-q", "-m", msg]);
+ return git(["rev-parse", "HEAD"]);
+}
+
+function runHook(stdinLines: string): { code: number; stderr: string } {
+ const r = spawnSync("bun", [PREPUSH], {
+ cwd: repo,
+ input: Buffer.from(stdinLines),
+ encoding: "utf8",
+ env: { ...process.env },
+ });
+ return { code: r.status ?? 0, stderr: r.stderr ?? "" };
+}
+
+// Assembled at runtime so the LITERAL never appears in a pushed diff — the
+// repo's own pre-push scanner (correctly) blocks live-format AWS key shapes.
+const FAKE_AWS_KEY = ["AKIA", "1234567890ABCDEF"].join("");
+
+/**
+ * Build the #2573 shape:
+ * 1. feature branch pushed → remote + tracking ref hold the pre-rebase tip
+ * 2. main advances with someone else's already-published HIGH-shaped
+ * fixture, pushed and fetched
+ * 3. feature rebases onto origin/main
+ * Returns the pre-rebase tip (what git hands the hook as remoteSha on the
+ * force-push) — it still EXISTS locally but is no longer an ancestor of HEAD.
+ */
+function buildRebasedForcePush(): { preRebaseTip: string } {
+ git(["checkout", "-q", "-b", "feature"]);
+ commit("mine.ts", "export const mine = 1;\n", "my clean work");
+ git(["push", "-q", "-u", "origin", "feature"]);
+ const preRebaseTip = git(["rev-parse", "HEAD"]);
+
+ // Someone else lands a HIGH-shaped placeholder on main. It is published:
+ // pushed to the remote, fetched into origin/main.
+ git(["checkout", "-q", "main"]);
+ commit("fixtures/foreign.txt", `key ${FAKE_AWS_KEY}\n`, "someone else's fixture");
+ git(["push", "-q", "origin", "main"]);
+ git(["fetch", "-q", "origin"]);
+
+ git(["checkout", "-q", "feature"]);
+ git(["rebase", "-q", "origin/main"]);
+ return { preRebaseTip };
+}
+
+beforeEach(() => {
+ repo = fs.mkdtempSync(path.join(os.tmpdir(), "prepush-rebase-"));
+ remote = fs.mkdtempSync(path.join(os.tmpdir(), "prepush-rebase-remote-"));
+ git(["init", "-q", "--bare", "-b", "main"], remote);
+ git(["init", "-q", "-b", "main"]);
+ git(["config", "user.email", "[email protected]"]);
+ git(["config", "user.name", "T"]);
+ commit("README.md", "seed\n", "seed");
+ git(["remote", "add", "origin", remote]);
+ git(["push", "-q", "-u", "origin", "main"]);
+});
+
+afterEach(() => {
+ fs.rmSync(repo, { recursive: true, force: true });
+ fs.rmSync(remote, { recursive: true, force: true });
+});
+
+describe("rebased force-push does not re-scan upstream commits (#2573)", () => {
+ test("fixture sanity: the old two-dot range WOULD have swept in the upstream credential", () => {
+ const { preRebaseTip } = buildRebasedForcePush();
+ // The rebased tip exists locally and is NOT an ancestor of HEAD — the
+ // exact condition #2573 identified as the untested third branch.
+ expect(git(["cat-file", "-t", preRebaseTip])).toBe("commit");
+ const isAncestor = spawnSync("git", ["merge-base", "--is-ancestor", preRebaseTip, "HEAD"], { cwd: repo });
+ expect(isAncestor.status).not.toBe(0);
+ // What the OLD range would scan: upstream's published fixture included.
+ const oldDiff = git(["diff", "--unified=0", `${preRebaseTip}..HEAD`]);
+ expect(oldDiff).toContain(FAKE_AWS_KEY);
+ });
+
+ test("a clean rebased force-push passes: the published upstream credential does not block", () => {
+ const { preRebaseTip } = buildRebasedForcePush();
+ const head = git(["rev-parse", "HEAD"]);
+ const { code, stderr } = runHook(`refs/heads/feature ${head} refs/heads/feature ${preRebaseTip}\n`);
+ expect(stderr).not.toContain("BLOCKED");
+ expect(code).toBe(0);
+ });
+
+ test("narrowing does not narrow coverage: a HIGH in a REBASED commit of our own still blocks", () => {
+ const { preRebaseTip } = buildRebasedForcePush();
+ commit("leak.txt", `key ${FAKE_AWS_KEY}\n`, "oops, my own leak");
+ const head = git(["rev-parse", "HEAD"]);
+ const { code, stderr } = runHook(`refs/heads/feature ${head} refs/heads/feature ${preRebaseTip}\n`);
+ expect(code).toBe(1);
+ expect(stderr).toContain("BLOCKED");
+ });
+
+ test("the scanned commit set is exactly the rebased own commits, none of upstream's", () => {
+ // Pin the range arithmetic itself (the #2573 measurement, in miniature):
+ // the narrowed set excludes every commit reachable from a remote-tracking
+ // ref, so the 1.14 MiB-vs-0.27 MiB pathology cannot recur — scan size is
+ // proportional to OUR commits, not to how busy main was.
+ const { preRebaseTip } = buildRebasedForcePush();
+ const narrowed = git(["rev-list", "HEAD", "--not", preRebaseTip, "--remotes"])
+ .split("\n").filter(Boolean);
+ expect(narrowed).toHaveLength(1); // the rebased copy of "my clean work"
+ const subject = git(["log", "-1", "--format=%s", narrowed[0]]);
+ expect(subject).toBe("my clean work");
+ });
+});
diff --git a/test/redact-prepush-scan-range.test.ts b/test/redact-prepush-scan-range.test.ts
new file mode 100644
index 000000000..f44df28c4
--- /dev/null
+++ b/test/redact-prepush-scan-range.test.ts
@@ -0,0 +1,276 @@
+/**
+ * gstack-redact-prepush — WHICH commits get scanned.
+ *
+ * `remoteSha..localSha` is "everything new on this branch", not "everything new
+ * to the remote". Merge origin/main into a feature branch and every commit main
+ * gained since the last push becomes an added line: already published, already
+ * scanned, not this push's doing. That produces false HIGH findings on other
+ * people's merged fixtures, and blows the engine's size cap on busy repos.
+ *
+ * These tests build real repositories on disk, because the behaviour under test
+ * IS the git plumbing — a mocked `git` would test the mock. Each asserts on the
+ * added-line text the hook would scan.
+ *
+ * The direction that matters most is the LAST describe block: narrowing the
+ * range must not narrow COVERAGE. A secret in a new commit, or introduced while
+ * resolving a merge, still has to be seen.
+ */
+import { describe, test, expect, beforeEach, afterEach } from "bun:test";
+import { spawnSync } from "child_process";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "fs";
+import { tmpdir } from "os";
+import { dirname, join } from "path";
+
+let dir: string;
+const run = (args: string[], cwd = dir): string => {
+ const r = spawnSync("git", args, { cwd, encoding: "utf8" });
+ if (r.status !== 0) throw new Error(`git ${args.join(" ")}\n${r.stderr}`);
+ return r.stdout ?? "";
+};
+const commit = (file: string, body: string, msg: string, cwd = dir) => {
+ mkdirSync(dirname(join(cwd, file)), { recursive: true });
+ writeFileSync(join(cwd, file), body);
+ run(["add", file], cwd);
+ run(["commit", "-q", "-m", msg], cwd);
+};
+
+/**
+ * The range the fixed hook uses: commits reachable from HEAD and from no
+ * remote-tracking ref, each diffed alone with --cc.
+ */
+function addedLinesFromNewCommits(cwd: string): string {
+ const listed = run(["rev-list", "HEAD", "--not", "--remotes"], cwd).trim();
+ if (!listed) return "";
+ const out: string[] = [];
+ for (const sha of listed.split("\n").filter(Boolean)) {
+ out.push(run([
+ "show", "--unified=0", "--no-color", "--no-ext-diff", "--no-textconv",
+ "--cc", "--format=", sha,
+ ], cwd));
+ }
+ return out.join("\n");
+}
+
+/** The old behaviour, for contrast. */
+function addedLinesFromTwoDot(cwd: string, remoteRef: string): string {
+ return run([
+ "diff", "--unified=0", "--no-color", "--no-ext-diff", "--no-textconv",
+ `${remoteRef}..HEAD`,
+ ], cwd);
+}
+
+const addedOnly = (diff: string): string =>
+ diff.split("\n")
+ .filter((l) => l.startsWith("+") && !l.startsWith("+++"))
+ .join("\n");
+
+beforeEach(() => {
+ dir = mkdtempSync(join(tmpdir(), "gstack-prepush-"));
+ run(["init", "-q", "-b", "main"]);
+ run(["config", "user.email", "[email protected]"]);
+ run(["config", "user.name", "T"]);
+ commit("README.md", "seed\n", "seed");
+});
+afterEach(() => rmSync(dir, { recursive: true, force: true }));
+
+// Live-FORMAT fakes assembled at runtime so the pushed diff of THIS file never
+// contains a credential-shaped literal — the pre-push guard scans diff bytes,
+// and the v1.64 wave's dogfood rule stands: assemble the fixture, never bypass
+// the guard. The runtime strings stay live-format for the hook under test.
+const FAKE_DB_URL = ["postgresql://user:pass", "@db.example.com/x"].join("");
+const FAKE_AWS_SECRETX = ["AKIA", "IOSFODNN7SECRETX"].join("");
+const FAKE_AWS_RESOLV = ["AKIA", "IOSFODNN7RESOLV"].join("");
+const FAKE_AWS_NOREMOT = ["AKIA", "IOSFODNN7NOREMOT"].join("");
+
+/** Give the repo an "origin" whose main carries a fixture we did not write. */
+function setUpRemoteWithForeignFixture(): void {
+ const remote = mkdtempSync(join(tmpdir(), "gstack-prepush-remote-"));
+ run(["init", "-q", "--bare", "-b", "main"], remote);
+ run(["remote", "add", "origin", remote]);
+ run(["push", "-q", "origin", "main"]);
+ // Someone else lands a placeholder connection string on main.
+ commit("fixtures/db.ts", `export const URL = "${FAKE_DB_URL}";\n`, "someone else's fixture");
+ run(["push", "-q", "origin", "main"]);
+ run(["fetch", "-q", "origin"]);
+}
+
+describe("a catch-up merge does not re-scan already-published content", () => {
+ test("the foreign fixture is absent from the scanned text", () => {
+ setUpRemoteWithForeignFixture();
+ // Branch from BEFORE that fixture, then merge main in to catch up.
+ run(["checkout", "-q", "-b", "feature", "HEAD~1"]);
+ commit("mine.ts", "export const mine = 1;\n", "my work");
+ run(["merge", "-q", "--no-edit", "main"]);
+
+ const scanned = addedOnly(addedLinesFromNewCommits(dir));
+ expect(scanned).toContain("export const mine = 1;");
+ expect(scanned).not.toContain(FAKE_DB_URL);
+ });
+
+ test("the old two-dot range DID re-scan it — this is the bug", () => {
+ setUpRemoteWithForeignFixture();
+ run(["checkout", "-q", "-b", "feature", "HEAD~1"]);
+ commit("mine.ts", "export const mine = 1;\n", "my work");
+ run(["merge", "-q", "--no-edit", "main"]);
+
+ // origin/feature does not exist yet, so the old code diffed against the
+ // remote's main — dragging in every catch-up commit.
+ const scanned = addedOnly(addedLinesFromTwoDot(dir, "HEAD~2"));
+ expect(scanned).toContain(FAKE_DB_URL);
+ });
+});
+
+describe("narrowing the range does not narrow coverage", () => {
+ test("a secret in a new commit is still scanned", () => {
+ setUpRemoteWithForeignFixture();
+ run(["checkout", "-q", "-b", "feature", "main"]);
+ commit("leak.ts", `const k = "${FAKE_AWS_SECRETX}";\n`, "oops");
+
+ expect(addedOnly(addedLinesFromNewCommits(dir))).toContain(FAKE_AWS_SECRETX);
+ });
+
+ test("a secret introduced while RESOLVING a merge is still scanned", () => {
+ // A combined diff shows only content present in no parent — exactly the
+ // conflict resolution — so this must not slip through.
+ //
+ // Note for anyone hardening this later: removing `--cc` from the
+ // implementation does NOT fail this test, because `git show` already
+ // defaults to a combined diff for merge commits. The explicit flag is
+ // self-documenting, not load-bearing, and no test can pin it. What this
+ // test does pin is the coverage itself.
+ setUpRemoteWithForeignFixture();
+ run(["checkout", "-q", "-b", "feature", "HEAD~1"]);
+ commit("conflict.txt", "mine\n", "mine");
+ run(["checkout", "-q", "main"]);
+ commit("conflict.txt", "theirs\n", "theirs");
+ run(["push", "-q", "origin", "main"]);
+ run(["fetch", "-q", "origin"]);
+ run(["checkout", "-q", "feature"]);
+ spawnSync("git", ["merge", "--no-edit", "main"], { cwd: dir, encoding: "utf8" }); // conflicts
+ writeFileSync(join(dir, "conflict.txt"), `resolved ${FAKE_AWS_RESOLV}\n`);
+ run(["add", "conflict.txt"]);
+ run(["commit", "-q", "--no-edit"]);
+
+ expect(addedOnly(addedLinesFromNewCommits(dir))).toContain(FAKE_AWS_RESOLV);
+ });
+
+ test("everything is scanned when no remote exists at all", () => {
+ commit("leak.ts", `const k = "${FAKE_AWS_NOREMOT}";\n`, "no remote");
+ expect(addedOnly(addedLinesFromNewCommits(dir))).toContain(FAKE_AWS_NOREMOT);
+ });
+});
+
+// ── S1: the exclusion is scoped to the PUSH TARGET's remote ─────────────────
+//
+// A bare `--remotes` excludes commits reachable from ANY remote-tracking ref,
+// so a secret that had only ever reached a private/local-path remote was never
+// scanned when pushed to a PUBLIC remote. Git hands pre-push the push remote's
+// name as $1; the hook now scopes the exclusion to `--remotes=<name>/*`.
+// These run END-TO-END through the hook binary with the real argv + stdin
+// protocol, because the behavior under test is the argv threading itself.
+describe("S1: exclusion scoped to the push-target remote", () => {
+ const PREPUSH = join(import.meta.dir, "..", "bin", "gstack-redact-prepush");
+ const FAKE_AWS_OTHERREM = ["AKIA", "IOSFODNN7OTHERRM"].join("");
+
+ function runHook(stdinLines: string, argv: string[]): { code: number; stderr: string } {
+ const r = spawnSync("bun", [PREPUSH, ...argv], {
+ cwd: dir,
+ input: Buffer.from(stdinLines),
+ encoding: "utf8",
+ env: { ...process.env },
+ });
+ return { code: r.status ?? 0, stderr: r.stderr ?? "" };
+ }
+
+ /**
+ * Build the S1 shape. Returns the feature branch's last-pushed origin tip
+ * (what git hands the hook as remoteSha):
+ * 1. main + feature pushed to origin (T0 = feature's origin tip)
+ * 2. a HIGH-shaped secret commit reaches a SECOND remote only
+ * (pushed there, fetched back → other/leaky tracking ref)
+ * 3. feature merges the secret commit — the next push to origin is
+ * the first time this content heads anywhere public
+ */
+ function buildSecretOnSecondRemote(): { originTip: string } {
+ const origin = mkdtempSync(join(tmpdir(), "gstack-prepush-origin-"));
+ run(["init", "-q", "--bare", "-b", "main"], origin);
+ run(["remote", "add", "origin", origin]);
+ run(["push", "-q", "origin", "main"]);
+ run(["checkout", "-q", "-b", "feature"]);
+ commit("mine.ts", "export const mine = 1;\n", "my work");
+ run(["push", "-q", "-u", "origin", "feature"]);
+ const originTip = run(["rev-parse", "HEAD"]).trim();
+
+ const other = mkdtempSync(join(tmpdir(), "gstack-prepush-other-"));
+ run(["init", "-q", "--bare", "-b", "main"], other);
+ run(["remote", "add", "other", other]);
+ run(["checkout", "-q", "-b", "leaky"]);
+ commit("leak.ts", `const k = "${FAKE_AWS_OTHERREM}";\n`, "secret to private remote only");
+ run(["push", "-q", "other", "leaky"]);
+ run(["fetch", "-q", "other"]);
+
+ run(["checkout", "-q", "feature"]);
+ // --no-ff: a fast-forward would make the secret commit the branch TIP,
+ // where the remoteSha two-dot fallback catches it regardless of the
+ // --remotes exclusion. The hole shape needs a real merge commit, so the
+ // narrowed path (per-commit --cc diffs) is what decides coverage.
+ run(["merge", "-q", "--no-ff", "--no-edit", "leaky"]);
+ return { originTip };
+ }
+
+ test("a commit known only to a SECOND remote IS scanned when pushing to origin", () => {
+ const { originTip } = buildSecretOnSecondRemote();
+ const head = run(["rev-parse", "HEAD"]).trim();
+ const { code, stderr } = runHook(
+ `refs/heads/feature ${head} refs/heads/feature ${originTip}\n`,
+ ["origin", "file:///ignored"],
+ );
+ expect(code).toBe(1);
+ expect(stderr).toContain("BLOCKED");
+ expect(stderr).toContain("aws.access_key");
+ });
+
+ test("origin-published commits still are NOT re-scanned (catch-up merge, #2592 kept)", () => {
+ setUpRemoteWithForeignFixture();
+ run(["checkout", "-q", "-b", "feature", "HEAD~1"]);
+ commit("mine.ts", "export const mine = 1;\n", "my work");
+ run(["push", "-q", "-u", "origin", "feature"]);
+ const originTip = run(["rev-parse", "HEAD"]).trim();
+ run(["merge", "-q", "--no-edit", "main"]); // catch-up merge brings the foreign fixture
+
+ const head = run(["rev-parse", "HEAD"]).trim();
+ const { code, stderr } = runHook(
+ `refs/heads/feature ${head} refs/heads/feature ${originTip}\n`,
+ ["origin", "file:///ignored"],
+ );
+ expect(stderr).not.toContain("BLOCKED");
+ expect(code).toBe(0);
+ });
+
+ test("no argv (stdin/CLI invocation) falls back to the historical all-remotes exclusion", () => {
+ // Documented contract, not a gap being celebrated: without the remote
+ // name there is nothing to scope to, and the fallback scans exactly what
+ // the hook always scanned. The installed hook wrapper forwards "$@", so
+ // real pushes always carry the name.
+ const { originTip } = buildSecretOnSecondRemote();
+ const head = run(["rev-parse", "HEAD"]).trim();
+ const { code, stderr } = runHook(
+ `refs/heads/feature ${head} refs/heads/feature ${originTip}\n`,
+ [],
+ );
+ expect(stderr).not.toContain("BLOCKED");
+ expect(code).toBe(0);
+ });
+
+ test("an unconfigured name (URL push) also falls back rather than erroring", () => {
+ const { originTip } = buildSecretOnSecondRemote();
+ const head = run(["rev-parse", "HEAD"]).trim();
+ const url = "file:///not-a-configured-remote";
+ const { code, stderr } = runHook(
+ `refs/heads/feature ${head} refs/heads/feature ${originTip}\n`,
+ [url, url],
+ );
+ expect(stderr).not.toContain("could not");
+ expect(code).toBe(0);
+ });
+});
diff --git a/test/relink.test.ts b/test/relink.test.ts
index 5e7ec809c..767db6006 100644
--- a/test/relink.test.ts
+++ b/test/relink.test.ts
@@ -215,9 +215,15 @@ describe('gstack-relink (#578)', () => {
const aliasSkill = path.join(aliasDir, 'SKILL.md');
expect(fs.lstatSync(aliasDir).isDirectory()).toBe(true);
expect(fs.lstatSync(aliasDir).isSymbolicLink()).toBe(false);
- expect(fs.lstatSync(aliasSkill).isSymbolicLink()).toBe(true);
- expect(fs.readlinkSync(aliasSkill)).toBe(path.join(installDir, 'SKILL.md'));
- expect(fs.readFileSync(aliasSkill, 'utf-8')).toContain('name: gstack');
+ // #2511: the alias is a rewritten COPY, never a symlink. A symlinked
+ // alias re-serves the canonical `name: gstack`; Claude Code refuses
+ // duplicate skill names and drops the entire personal-skills set.
+ expect(fs.lstatSync(aliasSkill).isSymbolicLink()).toBe(false);
+ const aliasContent = fs.readFileSync(aliasSkill, 'utf-8');
+ expect(aliasContent).toContain('name: _gstack-command');
+ expect(aliasContent).not.toContain('name: gstack\n');
+ // The rewrite happened on the COPY: the canonical source keeps its name.
+ expect(fs.readFileSync(path.join(installDir, 'SKILL.md'), 'utf-8')).toContain('name: gstack');
run(`${path.join(installDir, 'bin', 'gstack-config')} set skill_prefix true`, {
GSTACK_INSTALL_DIR: installDir,
@@ -226,6 +232,72 @@ describe('gstack-relink (#578)', () => {
expect(fs.existsSync(aliasSkill)).toBe(true);
});
+ // #2201: connect-chrome ships as a dir SYMLINK to open-gstack-browser. The
+ // discovery loop used to link it under its own basename while its SKILL.md
+ // carried `name: open-gstack-browser` — a duplicate name that silently
+ // shadows the real skill (readdir-order roulette). Symlinked source dirs
+ // must be skipped; setup owns the rewritten-copy alias.
+ test('symlinked skill dirs are skipped, so no duplicate frontmatter names (#2201)', () => {
+ setupMockInstall(['open-gstack-browser', 'qa']);
+ fs.symlinkSync(
+ path.join(installDir, 'open-gstack-browser'),
+ path.join(installDir, 'connect-chrome'),
+ );
+ run(`${path.join(installDir, 'bin', 'gstack-config')} set skill_prefix false`, {
+ GSTACK_INSTALL_DIR: installDir,
+ GSTACK_SKILLS_DIR: skillsDir,
+ });
+ run(`${path.join(installDir, 'bin', 'gstack-relink')}`, {
+ GSTACK_INSTALL_DIR: installDir,
+ GSTACK_SKILLS_DIR: skillsDir,
+ });
+
+ expect(fs.existsSync(path.join(skillsDir, 'open-gstack-browser'))).toBe(true);
+ expect(fs.existsSync(path.join(skillsDir, 'connect-chrome'))).toBe(false);
+
+ // No two installed SKILL.md files may share a frontmatter name.
+ const names: string[] = [];
+ for (const entry of fs.readdirSync(skillsDir)) {
+ const skillMd = path.join(skillsDir, entry, 'SKILL.md');
+ if (!fs.existsSync(skillMd)) continue;
+ const m = fs.readFileSync(skillMd, 'utf-8').match(/^name:\s*(\S+)/m);
+ if (m) names.push(m[1]);
+ }
+ expect(new Set(names).size).toBe(names.length);
+ });
+
+ // #2569: rendered :user variants live in ${GSTACK_HOME}/render/claude.
+ // relink must serve the render when present — otherwise any config change
+ // silently flips every skill back to the canonical (blockless) source.
+ test('prefers a rendered SKILL.md from GSTACK_HOME/render/claude (#2569)', () => {
+ setupMockInstall(['qa', 'ship']);
+ const renderDir = path.join(tmpDir, 'render', 'claude', 'qa');
+ fs.mkdirSync(renderDir, { recursive: true });
+ fs.writeFileSync(
+ path.join(renderDir, 'SKILL.md'),
+ '---\nname: qa\ndescription: test\n---\nrendered brain-aware qa',
+ );
+
+ run(`${path.join(installDir, 'bin', 'gstack-config')} set skill_prefix false`, {
+ GSTACK_INSTALL_DIR: installDir,
+ GSTACK_SKILLS_DIR: skillsDir,
+ GSTACK_HOME: tmpDir,
+ });
+ run(`${path.join(installDir, 'bin', 'gstack-relink')}`, {
+ GSTACK_INSTALL_DIR: installDir,
+ GSTACK_SKILLS_DIR: skillsDir,
+ GSTACK_HOME: tmpDir,
+ });
+
+ const qaLink = path.join(skillsDir, 'qa', 'SKILL.md');
+ expect(fs.readlinkSync(qaLink)).toBe(path.join(renderDir, 'SKILL.md'));
+ expect(fs.readFileSync(qaLink, 'utf-8')).toContain('rendered brain-aware qa');
+ // ship has no render — canonical source link.
+ expect(fs.readlinkSync(path.join(skillsDir, 'ship', 'SKILL.md'))).toBe(
+ path.join(installDir, 'ship', 'SKILL.md'),
+ );
+ });
+
// FIRST INSTALL: --no-prefix must create ONLY flat names, zero gstack-* pollution
test('first install --no-prefix: only flat names exist, zero gstack-* entries', () => {
setupMockInstall(['qa', 'ship', 'review', 'plan-ceo-review', 'gstack-upgrade']);
diff --git a/test/routing-probe.test.ts b/test/routing-probe.test.ts
new file mode 100644
index 000000000..fd5d13df3
--- /dev/null
+++ b/test/routing-probe.test.ts
@@ -0,0 +1,116 @@
+/**
+ * Routing probe + team-init install resolution — gate-tier tests (#2500).
+ *
+ * 1. The preamble's HAS_ROUTING probe must check AGENTS.md as well as
+ * CLAUDE.md. Non-Claude hosts (Codex, Cursor, generic harnesses) route
+ * skills via AGENTS.md — the cross-harness convention file. Before this
+ * fix, a repo with AGENTS.md routing but no CLAUDE.md reported
+ * 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
+ * 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
+ * can't silently fall out of team-mode enforcement.
+ *
+ * Re-derived from community PR #2500 by @gamerey43.
+ */
+import { describe, test, expect } from 'bun:test';
+import { execSync } from 'child_process';
+import * as fs from 'fs';
+import * as os from 'os';
+import * as path from 'path';
+import { HOST_PATHS } from '../scripts/resolvers/types';
+import type { TemplateContext } from '../scripts/resolvers/types';
+import { generatePreambleBash } from '../scripts/resolvers/preamble/generate-preamble-bash';
+import { ALL_HOST_CONFIGS } from '../hosts/index';
+
+const ROOT = path.join(import.meta.dir, '..');
+
+function makeCtx(host: 'claude' | 'codex'): TemplateContext {
+ return {
+ skillName: 'test-skill',
+ tmplPath: 'test.tmpl',
+ host,
+ paths: HOST_PATHS[host],
+ preambleTier: 2,
+ };
+}
+
+/** Extract the routing-probe block from the rendered preamble bash. */
+function extractRoutingProbe(rendered: string): string {
+ const start = rendered.indexOf('_HAS_ROUTING="no"');
+ expect(start).toBeGreaterThan(-1);
+ const end = rendered.indexOf('done', start);
+ expect(end).toBeGreaterThan(start);
+ return rendered.slice(start, end + 'done'.length);
+}
+
+describe('routing probe checks AGENTS.md too (#2500)', () => {
+ for (const host of ['claude', 'codex'] as const) {
+ test(`rendered preamble probes CLAUDE.md AND AGENTS.md (${host})`, () => {
+ const rendered = generatePreambleBash(makeCtx(host));
+ const probe = extractRoutingProbe(rendered);
+ expect(probe).toContain('CLAUDE.md');
+ expect(probe).toContain('AGENTS.md');
+ });
+ }
+
+ test('live probe block: AGENTS.md-only repo reports HAS_ROUTING=yes', () => {
+ const rendered = generatePreambleBash(makeCtx('claude'));
+ const probe = extractRoutingProbe(rendered);
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'routing-probe-'));
+ try {
+ fs.writeFileSync(
+ path.join(dir, 'AGENTS.md'),
+ '## Skill routing\n\n- Bugs → /investigate\n',
+ );
+ const out = execSync(
+ `bash -c '${probe.replace(/'/g, `'\\''`)}\necho "HAS_ROUTING: $_HAS_ROUTING"'`,
+ { cwd: dir, encoding: 'utf-8' },
+ );
+ expect(out).toContain('HAS_ROUTING: yes');
+ } finally {
+ fs.rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ test('live probe block: repo with neither file reports HAS_ROUTING=no', () => {
+ const rendered = generatePreambleBash(makeCtx('claude'));
+ const probe = extractRoutingProbe(rendered);
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'routing-probe-'));
+ try {
+ const out = execSync(
+ `bash -c '${probe.replace(/'/g, `'\\''`)}\necho "HAS_ROUTING: $_HAS_ROUTING"'`,
+ { cwd: dir, encoding: 'utf-8' },
+ );
+ expect(out).toContain('HAS_ROUTING: no');
+ } finally {
+ fs.rmSync(dir, { recursive: true, force: true });
+ }
+ });
+});
+
+describe('team-init resolves GSTACK_ROOT across every host (#2500)', () => {
+ const teamInit = fs.readFileSync(path.join(ROOT, 'bin', 'gstack-team-init'), 'utf-8');
+
+ test('probe list covers GSTACK_ROOT env + every registered host globalRoot + migrated repo', () => {
+ expect(teamInit).toContain('"${GSTACK_ROOT:-}"');
+ for (const config of ALL_HOST_CONFIGS) {
+ expect(teamInit).toContain(`$HOME/${config.globalRoot}`);
+ }
+ expect(teamInit).toContain('$HOME/.gstack/repos/gstack');
+ });
+
+ test('enforcement no longer hardcodes the Claude path as the only gate', () => {
+ expect(teamInit).not.toContain('test -d ~/.claude/skills/gstack/bin');
+ expect(teamInit).not.toContain('if [ ! -d "$HOME/.claude/skills/gstack/bin" ]');
+ });
+
+ 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');
+ });
+});
diff --git a/test/setup-alias-name-uniqueness.test.ts b/test/setup-alias-name-uniqueness.test.ts
new file mode 100644
index 000000000..c05d1d6d6
--- /dev/null
+++ b/test/setup-alias-name-uniqueness.test.ts
@@ -0,0 +1,164 @@
+/**
+ * Alias name uniqueness (#2511 / #2201).
+ *
+ * setup installs two back-compat alias dirs — `_gstack-command` (root router)
+ * and `connect-chrome` (→ open-gstack-browser). Both used to symlink the
+ * canonical SKILL.md verbatim, so the alias carried the canonical frontmatter
+ * `name:`. Claude Code keys skills on that name and requires global
+ * uniqueness: the `connect-chrome` duplicate silently shadowed
+ * /open-gstack-browser (readdir-order roulette), and the `_gstack-command`
+ * duplicate could drop the ENTIRE personal-skills set.
+ *
+ * The fix is copy-then-rewrite: sed reads the SOURCE and writes a fresh copy
+ * with `name:` set to the alias dir's own name. Eng review E2 pinned the
+ * hazard this suite guards hardest: on Unix the old install path was a
+ * SYMLINK to the repo source, so an in-place sed through it would have
+ * corrupted the generated SKILL.md — the source files must stay byte-intact.
+ */
+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
+import { spawnSync } from 'child_process';
+import * as fs from 'fs';
+import * as os from 'os';
+import * as path from 'path';
+
+const ROOT = path.resolve(import.meta.dir, '..');
+const SETUP_SRC = fs.readFileSync(path.join(ROOT, 'setup'), 'utf-8');
+
+function extractFn(name: string): string {
+ const start = SETUP_SRC.indexOf(`${name}() {`);
+ const end = SETUP_SRC.indexOf('\n}\n', start);
+ if (start < 0 || end < 0) throw new Error(`Could not locate ${name}() in setup`);
+ return SETUP_SRC.slice(start, end + 2);
+}
+
+const installDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-alias-install-'));
+
+const sourceRootSkill = fs.readFileSync(path.join(ROOT, 'SKILL.md'), 'utf-8');
+const sourceOgbSkill = fs.readFileSync(
+ path.join(ROOT, 'open-gstack-browser', 'SKILL.md'),
+ 'utf-8',
+);
+
+beforeAll(() => {
+ const installOnce = [
+ `link_claude_skill_dirs "${ROOT}" "${installDir}"`,
+ `link_claude_root_skill_alias "${ROOT}" "${installDir}"`,
+ // The connect-chrome back-compat alias, exactly as the install section does it.
+ `_install_alias_skill_md "${ROOT}/open-gstack-browser/SKILL.md" "${installDir}/connect-chrome" "connect-chrome"`,
+ ].join('\n');
+ const script = [
+ 'set -e',
+ 'IS_WINDOWS=0',
+ 'SKILL_PREFIX=0',
+ 'QUIET=1',
+ '_WINDOWS_COPY_NOTE_PRINTED=1',
+ extractFn('_link_or_copy'),
+ extractFn('_print_windows_copy_note_once'),
+ extractFn('_link_skill_runtime_assets'),
+ extractFn('link_claude_skill_dirs'),
+ extractFn('_install_alias_skill_md'),
+ extractFn('link_claude_root_skill_alias'),
+ // Run TWICE: the second pass proves re-runs refresh instead of corrupting
+ // (the historical failure mode was sed'ing through a symlink on re-run).
+ installOnce,
+ installOnce,
+ ].join('\n');
+ const result = spawnSync('bash', ['-c', script], { encoding: 'utf-8', timeout: 60_000 });
+ if (result.status !== 0) {
+ throw new Error(`alias install failed: ${result.stderr}\n${result.stdout}`);
+ }
+}, 30_000);
+
+afterAll(() => {
+ fs.rmSync(installDir, { recursive: true, force: true });
+});
+
+function frontmatterName(skillMdPath: string): string | null {
+ const m = fs.readFileSync(skillMdPath, 'utf-8').match(/^name:\s*(\S+)/m);
+ return m ? m[1] : null;
+}
+
+describe('alias installs are rewritten copies (#2511, #2201)', () => {
+ test('_gstack-command alias is NOT a symlink and carries its own name', () => {
+ const aliasDir = path.join(installDir, '_gstack-command');
+ const aliasSkill = path.join(aliasDir, 'SKILL.md');
+ expect(fs.lstatSync(aliasDir).isSymbolicLink()).toBe(false);
+ expect(fs.lstatSync(aliasSkill).isSymbolicLink()).toBe(false);
+ expect(frontmatterName(aliasSkill)).toBe('_gstack-command');
+ });
+
+ test('connect-chrome alias is NOT a symlink and carries its own name', () => {
+ const aliasDir = path.join(installDir, 'connect-chrome');
+ const aliasSkill = path.join(aliasDir, 'SKILL.md');
+ expect(fs.lstatSync(aliasDir).isSymbolicLink()).toBe(false);
+ expect(fs.lstatSync(aliasSkill).isSymbolicLink()).toBe(false);
+ expect(frontmatterName(aliasSkill)).toBe('connect-chrome');
+ });
+
+ test('alias body is the canonical content — only the name: line differs', () => {
+ const alias = fs.readFileSync(
+ path.join(installDir, '_gstack-command', 'SKILL.md'),
+ 'utf-8',
+ );
+ expect(alias.replace(/^name:.*$/m, 'name: gstack')).toBe(sourceRootSkill);
+
+ const ogbAlias = fs.readFileSync(
+ path.join(installDir, 'connect-chrome', 'SKILL.md'),
+ 'utf-8',
+ );
+ expect(ogbAlias.replace(/^name:.*$/m, 'name: open-gstack-browser')).toBe(sourceOgbSkill);
+ });
+
+ test('the SOURCE files are byte-intact (E2: sed never wrote through a symlink)', () => {
+ expect(fs.readFileSync(path.join(ROOT, 'SKILL.md'), 'utf-8')).toBe(sourceRootSkill);
+ expect(
+ fs.readFileSync(path.join(ROOT, 'open-gstack-browser', 'SKILL.md'), 'utf-8'),
+ ).toBe(sourceOgbSkill);
+ expect(frontmatterName(path.join(ROOT, 'SKILL.md'))).toBe('gstack');
+ expect(frontmatterName(path.join(ROOT, 'open-gstack-browser', 'SKILL.md'))).toBe(
+ 'open-gstack-browser',
+ );
+ });
+
+ test('every installed skill name is globally unique', () => {
+ const names: string[] = [];
+ for (const entry of fs.readdirSync(installDir)) {
+ const skillMd = path.join(installDir, entry, 'SKILL.md');
+ if (!fs.existsSync(skillMd)) continue;
+ const name = frontmatterName(skillMd);
+ if (name) names.push(name);
+ }
+ expect(names.length).toBeGreaterThan(10);
+ const dupes = names.filter((n, i) => names.indexOf(n) !== i);
+ expect(dupes).toEqual([]);
+ });
+
+ test('a legacy symlinked alias is replaced, not written through', () => {
+ // Simulate a pre-fix install: alias SKILL.md is a symlink to the source.
+ const legacyDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-alias-legacy-'));
+ try {
+ const aliasDir = path.join(legacyDir, '_gstack-command');
+ fs.mkdirSync(aliasDir);
+ fs.symlinkSync(path.join(ROOT, 'SKILL.md'), path.join(aliasDir, 'SKILL.md'));
+
+ const script = [
+ 'set -e',
+ 'IS_WINDOWS=0',
+ extractFn('_link_or_copy'),
+ extractFn('_install_alias_skill_md'),
+ extractFn('link_claude_root_skill_alias'),
+ `link_claude_root_skill_alias "${ROOT}" "${legacyDir}"`,
+ ].join('\n');
+ const result = spawnSync('bash', ['-c', script], { encoding: 'utf-8', timeout: 30_000 });
+ expect(result.status).toBe(0);
+
+ const aliasSkill = path.join(aliasDir, 'SKILL.md');
+ expect(fs.lstatSync(aliasSkill).isSymbolicLink()).toBe(false);
+ expect(frontmatterName(aliasSkill)).toBe('_gstack-command');
+ // The source the legacy symlink pointed at is untouched.
+ expect(fs.readFileSync(path.join(ROOT, 'SKILL.md'), 'utf-8')).toBe(sourceRootSkill);
+ } finally {
+ fs.rmSync(legacyDir, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/test/setup-bun-cmd-and-pipe-bugs.test.ts b/test/setup-bun-cmd-and-pipe-bugs.test.ts
index 695a1d447..098597d55 100644
--- a/test/setup-bun-cmd-and-pipe-bugs.test.ts
+++ b/test/setup-bun-cmd-and-pipe-bugs.test.ts
@@ -45,16 +45,19 @@ describe('setup: gen:skill-docs:user exit-code propagation (pipe-masking fix)',
expect(r.stdout).not.toContain('LOG: warning');
});
- test('setup: the live gbrain regen block has no pipe before the || guard', () => {
+ test('setup: the live gbrain render block has no pipe masking its exit code', () => {
// Slice the exact block from setup and confirm the fix is in place
- // without resorting to a fragile line-number check.
- const start = SETUP_SRC.indexOf('gbrain detected — regenerating');
+ // without resorting to a fragile line-number check. (#2569 renamed the
+ // block from "regenerating" to "rendering ... into $_GSTACK_RENDER_DIR" —
+ // the exit-code-propagation invariant is unchanged.)
+ const start = SETUP_SRC.indexOf('gbrain detected — rendering');
expect(start).toBeGreaterThan(-1);
- const end = SETUP_SRC.indexOf('|| log', start);
+ const end = SETUP_SRC.indexOf('warning: gen:skill-docs:user failed', start);
expect(end).toBeGreaterThan(start);
const block = SETUP_SRC.slice(start, end);
expect(block).toContain('bun_cmd run gen:skill-docs:user --host claude');
- // The bug shape: `... | tail -N` between the call and the `|| log` guard.
+ // The bug shape: `... | tail -N` between the call and the failure guard —
+ // a pipe would replace the render's exit code with tail's.
expect(block).not.toMatch(/gen:skill-docs:user[^\n]*\|\s*tail/);
});
});
diff --git a/test/setup-claude-skill-assets.test.ts b/test/setup-claude-skill-assets.test.ts
new file mode 100644
index 000000000..8cabfadab
--- /dev/null
+++ b/test/setup-claude-skill-assets.test.ts
@@ -0,0 +1,225 @@
+/**
+ * Claude installer runtime-asset coverage (#2317 / #2454).
+ *
+ * `link_claude_skill_dirs` historically installed only SKILL.md (+ sections/)
+ * per skill, so every skill that reads a sibling runtime file at
+ * `.claude/skills/<name>/<file>` — review's checklist.md + specialists/, qa's
+ * templates/ + references/, gstack-upgrade's migrations/, careful/freeze's
+ * bin/ — was broken on a fresh Claude install. This suite runs the REAL
+ * installer functions (extracted from `setup`) against the live repo into a
+ * temp skills dir and asserts the install is complete.
+ *
+ * Two-class referenced-paths assertion (eng review ENG-OV7):
+ * - Class 1 (alias-relative): a `.claude/skills/<name>/<relpath>` reference
+ * in an INSTALLED SKILL.md must resolve under the install dir. These are
+ * runtime reads against the flattened alias — a miss is a broken skill.
+ * - Class 2 (repo-anchored): a `~/.claude/skills/gstack/<relpath>`
+ * reference must exist in the source tree, EXCEPT built artifacts
+ * (browse/dist, design/dist, make-pdf/dist, the compiled
+ * bin/gstack-global-discover) — the free suite never builds binaries, so
+ * a naive "every path exists" either false-fails on dist or gets watered
+ * down to uselessness.
+ */
+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
+import { spawnSync } from 'child_process';
+import * as fs from 'fs';
+import * as os from 'os';
+import * as path from 'path';
+
+const ROOT = path.resolve(import.meta.dir, '..');
+const SETUP_SRC = fs.readFileSync(path.join(ROOT, 'setup'), 'utf-8');
+
+/** Built-at-setup artifacts: allowed to be absent from a fresh clone. */
+const BUILT_ARTIFACT_ALLOWLIST = [
+ 'browse/dist/',
+ 'design/dist/',
+ 'make-pdf/dist/',
+ 'bin/gstack-global-discover', // compiled from bin/gstack-global-discover.ts at build time
+];
+
+/**
+ * Repo-anchored references that are KNOWN BROKEN on the current tree.
+ * Each entry must name the fix that removes it. An empty list is the goal —
+ * do not add entries without an issue + a scheduled fix.
+ */
+const KNOWN_BROKEN_CLASS2: Record<string, string> = {
+ // (empty — #2250's bare bin names were the last entries; keep it that way)
+};
+
+/** Extract a named shell function body (through its closing brace) from setup. */
+function extractFn(name: string): string {
+ const start = SETUP_SRC.indexOf(`${name}() {`);
+ const end = SETUP_SRC.indexOf('\n}\n', start);
+ if (start < 0 || end < 0) throw new Error(`Could not locate ${name}() in setup`);
+ return SETUP_SRC.slice(start, end + 2);
+}
+
+const installDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-claude-install-'));
+
+beforeAll(() => {
+ const script = [
+ 'set -e',
+ 'IS_WINDOWS=0',
+ 'SKILL_PREFIX=0',
+ 'QUIET=1',
+ '_WINDOWS_COPY_NOTE_PRINTED=1',
+ extractFn('_link_or_copy'),
+ extractFn('_print_windows_copy_note_once'),
+ extractFn('_link_skill_runtime_assets'),
+ extractFn('link_claude_skill_dirs'),
+ `link_claude_skill_dirs "${ROOT}" "${installDir}"`,
+ ].join('\n');
+ const result = spawnSync('bash', ['-c', script], { encoding: 'utf-8', timeout: 60_000 });
+ if (result.status !== 0) {
+ throw new Error(`installer functions failed: ${result.stderr}\n${result.stdout}`);
+ }
+});
+
+afterAll(() => {
+ // rmSync does not follow symlinks — the repo sources the links point at survive.
+ fs.rmSync(installDir, { recursive: true, force: true });
+});
+
+function installedSkillDirs(): string[] {
+ return fs
+ .readdirSync(installDir, { withFileTypes: true })
+ .filter((e) => e.isDirectory())
+ .map((e) => e.name)
+ .filter((name) => fs.existsSync(path.join(installDir, name, 'SKILL.md')));
+}
+
+describe('link_claude_skill_dirs installs every runtime asset (#2317, #2454)', () => {
+ test('review skill ships its full runtime asset set', () => {
+ const review = path.join(installDir, 'review');
+ for (const asset of [
+ 'checklist.md',
+ 'design-checklist.md',
+ 'greptile-triage.md',
+ 'TODOS-format.md',
+ 'specialists',
+ ]) {
+ expect(fs.existsSync(path.join(review, asset))).toBe(true);
+ }
+ // specialists/ resolves to real content, not an empty shell
+ const specialists = fs.readdirSync(path.join(review, 'specialists'));
+ expect(specialists.length).toBeGreaterThan(0);
+ expect(specialists).toContain('testing.md');
+ });
+
+ test('the #2454 affected-skills table is fully installed', () => {
+ const expected: Array<[string, string]> = [
+ ['qa', 'references'],
+ ['qa', 'templates'],
+ ['plan-devex-review', 'dx-hall-of-fame.md'],
+ ['gstack-upgrade', 'migrations'],
+ ['careful', 'bin'],
+ ['freeze', 'bin'],
+ ];
+ for (const [skill, asset] of expected) {
+ expect(fs.existsSync(path.join(installDir, skill, asset))).toBe(true);
+ }
+ });
+
+ test('sections/ still installs for carved skills', () => {
+ expect(fs.existsSync(path.join(installDir, 'ship', 'sections'))).toBe(true);
+ expect(
+ fs.readdirSync(path.join(installDir, 'ship', 'sections')).length,
+ ).toBeGreaterThan(0);
+ });
+
+ test('exclusion list holds: no node_modules, dist, test, or .tmpl installed', () => {
+ for (const skill of installedSkillDirs()) {
+ const entries = fs.readdirSync(path.join(installDir, skill));
+ expect(entries).not.toContain('node_modules');
+ expect(entries).not.toContain('dist');
+ expect(entries).not.toContain('test');
+ const tmpl = entries.filter((e) => e.endsWith('.tmpl'));
+ expect(tmpl).toEqual([]);
+ }
+ });
+
+ test('hidden files are not installed', () => {
+ for (const skill of installedSkillDirs()) {
+ const hidden = fs
+ .readdirSync(path.join(installDir, skill))
+ .filter((e) => e.startsWith('.'));
+ expect(hidden).toEqual([]);
+ }
+ });
+});
+
+// ---------------------------------------------------------------------------
+// Two-class referenced-paths assertion (ENG-OV7)
+// ---------------------------------------------------------------------------
+
+interface Ref {
+ fromSkill: string;
+ skillName: string;
+ rel: string;
+}
+
+const REF_RE = /~?\.claude\/skills\/([A-Za-z0-9_-]+)\/([A-Za-z0-9_.\/-]+)/g;
+
+/** Placeholder-ish captures (globs, template vars, <angle> examples) are prose, not paths. */
+function isConcretePath(raw: string): boolean {
+ return !/[<>*$(){}|]/.test(raw) && !raw.includes('..');
+}
+
+function collectRefs(): Ref[] {
+ const refs: Ref[] = [];
+ for (const skill of installedSkillDirs()) {
+ const content = fs.readFileSync(path.join(installDir, skill, 'SKILL.md'), 'utf-8');
+ for (const m of content.matchAll(REF_RE)) {
+ const rel = m[2].replace(/[.,:;/]+$/, '');
+ if (!rel || !isConcretePath(rel)) continue;
+ refs.push({ fromSkill: skill, skillName: m[1], rel });
+ }
+ }
+ return refs;
+}
+
+describe('two-class referenced-paths (ENG-OV7)', () => {
+ test('class 1: alias-relative references resolve under the install dir', () => {
+ const missing: string[] = [];
+ for (const { fromSkill, skillName, rel } of collectRefs()) {
+ if (skillName === 'gstack') continue; // class 2
+ // Prefix-mode prose may reference gstack-<name>; the flat install dir
+ // is the unprefixed name.
+ const candidates = [skillName, skillName.replace(/^gstack-/, '')];
+ const found = candidates.some((c) => fs.existsSync(path.join(installDir, c, rel)));
+ if (!found) missing.push(`${fromSkill}/SKILL.md → .claude/skills/${skillName}/${rel}`);
+ }
+ expect(missing).toEqual([]);
+ });
+
+ test('class 2: repo-anchored references exist in the tree (modulo built artifacts)', () => {
+ const missing: string[] = [];
+ for (const { fromSkill, skillName, rel } of collectRefs()) {
+ if (skillName !== 'gstack') continue; // class 1
+ if (rel.startsWith('.')) continue; // runtime state markers (.feature-prompted-*, .git)
+ if (BUILT_ARTIFACT_ALLOWLIST.some((a) => rel === a || rel.startsWith(a))) continue;
+ if (KNOWN_BROKEN_CLASS2[rel]) continue;
+ if (!fs.existsSync(path.join(ROOT, rel))) {
+ missing.push(`${fromSkill}/SKILL.md → ~/.claude/skills/gstack/${rel}`);
+ }
+ }
+ expect(missing).toEqual([]);
+ });
+
+ test('the referenced-path scan actually sees the review checklist refs (self-check)', () => {
+ // Guard against the extraction regex silently rotting: the review skill is
+ // KNOWN to carry alias-relative refs; if the scanner stops seeing them the
+ // class-1 assertion is vacuous.
+ const class1 = collectRefs().filter((r) => r.skillName !== 'gstack');
+ expect(class1.length).toBeGreaterThan(0);
+ expect(class1.some((r) => r.skillName === 'review' && r.rel === 'checklist.md')).toBe(true);
+ });
+
+ test('KNOWN_BROKEN_CLASS2 entries are still actually broken (ratchet)', () => {
+ // When a fix lands, its entry MUST be removed so the class-2 assertion
+ // guards the path again.
+ for (const rel of Object.keys(KNOWN_BROKEN_CLASS2)) {
+ expect(fs.existsSync(path.join(ROOT, rel))).toBe(false);
+ }
+ });
+});
diff --git a/test/setup-gbrain-bin-invocation-paths.test.ts b/test/setup-gbrain-bin-invocation-paths.test.ts
new file mode 100644
index 000000000..259f2542c
--- /dev/null
+++ b/test/setup-gbrain-bin-invocation-paths.test.ts
@@ -0,0 +1,133 @@
+// setup-gbrain bin invocation path lint.
+//
+// Pins the correct bun-run + .ts invocation form for gstack-memory-ingest
+// and gstack-gbrain-sync wherever setup-gbrain's docs instruct the agent
+// to run them. Regression coverage for #2393 / #2250: both scripts are
+// .ts files with no package.json bin alias stripping the extension, so a
+// bare name (no `bun run` prefix, no `.ts` suffix) fails with "No such
+// file or directory" the moment an agent follows the doc literally.
+//
+// Why a structural test instead of a full Agent SDK E2E:
+// - The failure is entirely in the prose an agent reads, not in
+// runtime behavior a service test could exercise. A grep-based
+// regression on the template/reference-doc text is fast (<200ms),
+// free, and catches the same drift a full E2E would, without the
+// token cost. Same rationale as test/setup-gbrain-path4-structure.test.ts.
+// - The correct invocation form and the stale one differ only by
+// `bun run ` + `.ts`, right next to each other in the same files —
+// exactly the kind of drift a cheap structural check exists to catch,
+// matching this repo's convention (e.g. test/memory-ingest-no-put_page.test.ts
+// pinning fix #1346).
+
+import { describe, test, expect } from 'bun:test';
+import * as fs from 'fs';
+import * as path from 'path';
+
+const ROOT = path.resolve(import.meta.dir, '..');
+const TMPL = path.join(ROOT, 'setup-gbrain', 'SKILL.md.tmpl');
+const MEMORY_DOC = path.join(ROOT, 'setup-gbrain', 'memory.md');
+
+const tmpl = fs.readFileSync(TMPL, 'utf-8');
+const memoryDoc = fs.readFileSync(MEMORY_DOC, 'utf-8');
+
+// A "bare invocation" is the tool name immediately followed by a flag/arg
+// with no `.ts` in between — the exact stale shape #2393/#2250 reported.
+// The negative lookahead means `gstack-memory-ingest.ts --probe` (correct)
+// does NOT match, while `gstack-memory-ingest --probe` (stale) does.
+// `(?:\s|\\\r?\n)+` also spans a backslash line-continuation between the
+// name and its flag (e.g. `gstack-memory-ingest \` newline ` --probe`),
+// a style this same template already uses for other commands (see the
+// read_secret_to_env invocation a few hundred lines up) — a plain `\s+`
+// would miss a stale invocation reintroduced in that form.
+const bareMemoryIngest = /\bgstack-memory-ingest\b(?!\.ts)(?:\s|\\\r?\n)+--/;
+const bareGbrainSync = /\bgstack-gbrain-sync\b(?!\.ts)(?:\s|\\\r?\n)+--/;
+
+describe('setup-gbrain/SKILL.md.tmpl — bin invocation paths', () => {
+ test('no bare gstack-memory-ingest invocation remains', () => {
+ expect(tmpl).not.toMatch(bareMemoryIngest);
+ });
+
+ test('no bare gstack-gbrain-sync invocation remains', () => {
+ expect(tmpl).not.toMatch(bareGbrainSync);
+ });
+
+ test('the probe step uses bun run + .ts (R1)', () => {
+ expect(tmpl).toContain(
+ 'bun run ~/.claude/skills/gstack/bin/gstack-memory-ingest.ts --probe'
+ );
+ });
+
+ test('the silent-bulk mention uses bun run + .ts (R2)', () => {
+ expect(tmpl).toContain(
+ 'bun run ~/.claude/skills/gstack/bin/gstack-memory-ingest.ts --bulk --quiet'
+ );
+ });
+
+ test('the post-answer full-sync step uses bun run + .ts (R3)', () => {
+ expect(tmpl).toContain(
+ 'bun run ~/.claude/skills/gstack/bin/gstack-gbrain-sync.ts --full --no-brain-sync'
+ );
+ });
+
+ test('the preamble-hook incremental-sync mention uses bun run + .ts (R4)', () => {
+ expect(tmpl).toContain(
+ 'bun run ~/.claude/skills/gstack/bin/gstack-gbrain-sync.ts --incremental --quiet'
+ );
+ });
+
+ test('the neighboring gstack-config line in the post-answer block is untouched (bash script, no extension)', () => {
+ expect(tmpl).toContain(
+ '~/.claude/skills/gstack/bin/gstack-config set transcript_ingest_mode <choice>'
+ );
+ });
+
+ test('the prose-only mention naming the tool as a sentence subject is left unchanged (KTD4 — not a literal invocation)', () => {
+ expect(tmpl).toContain('gstack-memory-ingest now persists staged transcripts to');
+ });
+});
+
+describe('setup-gbrain/memory.md — bin invocation paths', () => {
+ test('no bare gstack-memory-ingest invocation remains', () => {
+ expect(memoryDoc).not.toMatch(bareMemoryIngest);
+ });
+
+ test('no bare gstack-gbrain-sync invocation remains', () => {
+ expect(memoryDoc).not.toMatch(bareGbrainSync);
+ });
+
+ test('the secret-scanning example uses bun run + .ts (R5)', () => {
+ expect(memoryDoc).toContain('bun run bin/gstack-memory-ingest.ts --bulk --scan-secrets');
+ expect(memoryDoc).toContain(
+ 'GSTACK_MEMORY_INGEST_SCAN_SECRETS=1 bun run bin/gstack-memory-ingest.ts --bulk'
+ );
+ });
+
+ test('the troubleshooting full-pass mention uses bun run + .ts (R5)', () => {
+ expect(memoryDoc).toContain('Run `bun run bin/gstack-gbrain-sync.ts --full` to do a full pass.');
+ });
+
+ test('the troubleshooting incremental-reingest mention uses bun run + .ts (R5)', () => {
+ expect(memoryDoc).toContain(
+ 're-run `bun run bin/gstack-gbrain-sync.ts --incremental` to re-ingest from'
+ );
+ });
+
+ test('the already-correct reference line at the top of the file is unchanged', () => {
+ expect(memoryDoc).toContain('bun run bin/gstack-memory-ingest.ts --probe` (which');
+ });
+});
+
+describe('bare-invocation regex — backslash line-continuation coverage', () => {
+ // This template writes multi-line commands with a trailing backslash
+ // continuation elsewhere (e.g. the read_secret_to_env invocation), so a
+ // stale invocation reintroduced in that same style must still be caught.
+ test('catches a bare invocation split across a backslash continuation', () => {
+ const staleContinuation = 'gstack-memory-ingest \\\n --probe';
+ expect(staleContinuation).toMatch(bareMemoryIngest);
+ });
+
+ test('does not flag a correct invocation split across a backslash continuation', () => {
+ const fixedContinuation = 'bun run bin/gstack-gbrain-sync.ts \\\n --incremental';
+ expect(fixedContinuation).not.toMatch(bareGbrainSync);
+ });
+});
diff --git a/test/setup-sections-linking.test.ts b/test/setup-sections-linking.test.ts
index a6aa516ce..b0558283f 100644
--- a/test/setup-sections-linking.test.ts
+++ b/test/setup-sections-linking.test.ts
@@ -24,12 +24,17 @@ function fnBody(src: string, name: string): string {
}
describe('setup links sections/ for cherry-pick install targets', () => {
- test('link_claude_skill_dirs links sections/ via _link_or_copy', () => {
+ test('link_claude_skill_dirs installs runtime assets (incl. sections/) via the shared helper', () => {
+ // #2317/#2454 generalized the sections/-only install into
+ // _link_skill_runtime_assets, which carries EVERY runtime asset a skill
+ // references (sections/, checklist.md, specialists/, ...). That helper
+ // routes through _link_or_copy internally (windows-safe), so the old
+ // per-directory _link_or_copy assertion moved there.
const body = fnBody(SETUP, 'link_claude_skill_dirs');
- expect(body).toContain('sections');
- // sections install must route through the windows-safe helper, not raw ln.
- expect(body).toMatch(/_link_or_copy\s+"\$gstack_dir\/\$dir_name\/sections"\s+"\$target\/sections"/);
- expect(body).toMatch(/if \[ -d "\$gstack_dir\/\$dir_name\/sections" \]/);
+ expect(body).toMatch(/_link_skill_runtime_assets\s+"\$gstack_dir\/\$dir_name"\s+"\$target"/);
+ const helper = fnBody(SETUP, '_link_skill_runtime_assets');
+ expect(helper).toContain('_link_or_copy');
+ expect(helper).not.toMatch(/\bln -s/);
});
test('kiro per-skill loop rewrites + copies sections/*', () => {
diff --git a/test/setup-windows-rerun-refresh.test.ts b/test/setup-windows-rerun-refresh.test.ts
new file mode 100644
index 000000000..6c60ad47c
--- /dev/null
+++ b/test/setup-windows-rerun-refresh.test.ts
@@ -0,0 +1,356 @@
+/**
+ * Windows re-run refresh (#2444).
+ *
+ * On Windows, _link_or_copy installs REAL directory copies (no Developer
+ * Mode symlinks). The skill-linking guards `[ -L "$target" ] || [ ! -e
+ * "$target" ]` in link_codex_skill_dirs / link_factory_skill_dirs /
+ * link_opencode_skill_dirs / create_agents_sidecar therefore skipped every
+ * re-run: `./setup --host codex` reported "gstack ready" but never refreshed
+ * an already-installed SKILL.md after `git pull`. The fix bypasses the guard
+ * when IS_WINDOWS=1 — _link_or_copy rm -rf's the destination first, so the
+ * copy refreshes in place.
+ *
+ * The behavior fixture drives the REAL link_codex_skill_dirs /
+ * create_agents_sidecar functions (extracted from setup) against a fake
+ * install tree; the static block pins the bypass at all five guard sites so
+ * factory/opencode can't silently regress.
+ */
+import { describe, test, expect } from 'bun:test';
+import { spawnSync } from 'child_process';
+import * as fs from 'fs';
+import * as os from 'os';
+import * as path from 'path';
+
+const ROOT = path.resolve(import.meta.dir, '..');
+const SETUP_SRC = fs.readFileSync(path.join(ROOT, 'setup'), 'utf-8');
+
+function extractFn(name: string): string {
+ const start = SETUP_SRC.indexOf(`${name}() {`);
+ const end = SETUP_SRC.indexOf('\n}\n', start);
+ if (start < 0 || end < 0) throw new Error(`Could not locate ${name}() in setup`);
+ return SETUP_SRC.slice(start, end + 2);
+}
+
+const WINDOWS_BYPASS = '[ "$IS_WINDOWS" -eq 1 ] || [ -L ';
+
+describe('setup: Windows re-run refresh — static guard sites (#2444)', () => {
+ test('no install guard is missing the IS_WINDOWS bypass', () => {
+ // Every `[ -L ...] || [ ! -e ...]` refresh guard in setup must carry the
+ // bypass — a bare guard is a Windows re-run no-op waiting to happen.
+ const bareGuards = SETUP_SRC
+ .split('\n')
+ .filter((l) => /\[ -L "\$[A-Za-z_/${}.]+" \] \|\| \[ ! -e /.test(l) && !l.includes('IS_WINDOWS'));
+ expect(bareGuards).toEqual([]);
+ expect(SETUP_SRC.split(WINDOWS_BYPASS).length - 1).toBeGreaterThanOrEqual(5);
+ });
+
+ test.each([
+ 'link_codex_skill_dirs',
+ 'link_factory_skill_dirs',
+ 'link_opencode_skill_dirs',
+ 'link_cursor_skill_dirs',
+ 'create_agents_sidecar',
+ 'create_cursor_sidecar',
+ ])('%s bypasses the symlink-or-missing guard on Windows', (fn) => {
+ expect(extractFn(fn)).toContain(WINDOWS_BYPASS);
+ });
+
+ // #2142 ownership census: the Windows bypass rm -rf's real dirs, so every
+ // skill-dir installer must gate the replacement on provable gstack
+ // ownership, and every sidecar/runtime-root installer must refuse a
+ // user-owned root. A bypass without its gate deletes user data.
+ test.each([
+ 'link_codex_skill_dirs',
+ 'link_factory_skill_dirs',
+ 'link_opencode_skill_dirs',
+ 'link_cursor_skill_dirs',
+ ])('%s gates the Windows real-dir replacement on _owned_for_windows_refresh', (fn) => {
+ expect(extractFn(fn)).toContain('_owned_for_windows_refresh "$target"');
+ });
+
+ test.each([
+ 'create_agents_sidecar',
+ 'create_cursor_sidecar',
+ 'create_cursor_runtime_root',
+ ])('%s refuses a user-owned root via _sidecar_root_user_owned', (fn) => {
+ expect(extractFn(fn)).toContain('_sidecar_root_user_owned');
+ });
+});
+
+describe('setup: Windows refresh ownership gate — behavior fixture (#2142)', () => {
+ test("IS_WINDOWS=1: a user's own real dir on a gstack* name survives; a bannered install refreshes", () => {
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-owned-'));
+ try {
+ const fake = path.join(tmp, 'gstack');
+ const skills = path.join(tmp, 'skills');
+ const banner = '<!-- AUTO-GENERATED from SKILL.md.tmpl - DO NOT EDIT DIRECTLY -->\n';
+ // Generated tree ships two skills.
+ for (const name of ['gstack-demo', 'gstack-notes']) {
+ const d = path.join(fake, '.agents', 'skills', name);
+ fs.mkdirSync(d, { recursive: true });
+ fs.writeFileSync(path.join(d, 'SKILL.md'), `${banner}upstream-v2\n`);
+ }
+ fs.mkdirSync(skills, { recursive: true });
+ // gstack-demo: a prior gstack install (bannered) — must refresh.
+ fs.mkdirSync(path.join(skills, 'gstack-demo'), { recursive: true });
+ fs.writeFileSync(path.join(skills, 'gstack-demo', 'SKILL.md'), `${banner}installed-v1\n`);
+ // gstack-notes: the USER'S own hand-written skill — must survive.
+ fs.mkdirSync(path.join(skills, 'gstack-notes'), { recursive: true });
+ fs.writeFileSync(path.join(skills, 'gstack-notes', 'SKILL.md'), '# my own notes\n');
+
+ const r = runInstaller(
+ '1',
+ ['_owned_for_windows_refresh', 'link_codex_skill_dirs'],
+ `link_codex_skill_dirs "${tmp}/gstack" "${skills}"`,
+ );
+ expect(r.status).toBe(0);
+ expect(fs.readFileSync(path.join(skills, 'gstack-demo', 'SKILL.md'), 'utf-8')).toContain('upstream-v2');
+ expect(fs.readFileSync(path.join(skills, 'gstack-notes', 'SKILL.md'), 'utf-8')).toBe('# my own notes\n');
+ expect(r.stderr).toContain('left in place');
+ expect(r.stderr).toContain('gstack-notes');
+ } finally {
+ fs.rmSync(tmp, { recursive: true, force: true });
+ }
+ });
+
+ test('IS_WINDOWS=1: create_agents_sidecar refuses a user-owned root and writes nothing into it', () => {
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-owned-sidecar-'));
+ try {
+ const fake = path.join(tmp, 'gstack');
+ fs.mkdirSync(path.join(fake, 'bin'), { recursive: true });
+ fs.writeFileSync(path.join(fake, 'bin', 'tool.sh'), 'v1\n');
+ // The user's own skill squats on .agents/skills/gstack.
+ const root = path.join(fake, '.agents', 'skills', 'gstack');
+ fs.mkdirSync(root, { recursive: true });
+ fs.writeFileSync(path.join(root, 'SKILL.md'), '# hand-written\n');
+
+ const vars = `SOURCE_GSTACK_DIR="${fake}"`;
+ const r = runInstaller(
+ '1',
+ ['_sidecar_root_user_owned', 'create_agents_sidecar'],
+ `create_agents_sidecar "${fake}"`,
+ vars,
+ );
+ expect(r.status).toBe(0);
+ expect(r.stderr).toContain('left in place');
+ expect(fs.existsSync(path.join(root, 'bin'))).toBe(false);
+ expect(fs.readFileSync(path.join(root, 'SKILL.md'), 'utf-8')).toBe('# hand-written\n');
+ } finally {
+ fs.rmSync(tmp, { recursive: true, force: true });
+ }
+ });
+});
+
+interface RunResult {
+ status: number | null;
+ stdout: string;
+ stderr: string;
+}
+
+/** Run the extracted installer functions against a fake tree. */
+function runInstaller(
+ isWindows: '0' | '1',
+ fns: string[],
+ invocation: string,
+ extraVars = '',
+): RunResult {
+ const script = [
+ 'set -e',
+ `IS_WINDOWS=${isWindows}`,
+ extraVars,
+ extractFn('_link_or_copy'),
+ // Ownership gates (#2142) — dependencies of every installer under test.
+ extractFn('_owned_for_windows_refresh'),
+ extractFn('_sidecar_root_user_owned'),
+ ...fns.map(extractFn),
+ invocation,
+ ].join('\n');
+ const r = spawnSync('bash', ['-c', script], { encoding: 'utf-8', timeout: 15_000 });
+ return { status: r.status, stdout: r.stdout, stderr: r.stderr };
+}
+
+describe('setup: Windows re-run refresh — behavior fixture (#2444)', () => {
+ test('IS_WINDOWS=1: link_codex_skill_dirs refreshes an already-installed skill', () => {
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-rerun-'));
+ try {
+ const fake = path.join(tmp, 'gstack');
+ const skills = path.join(tmp, 'skills');
+ const demo = path.join(fake, '.agents', 'skills', 'gstack-demo');
+ fs.mkdirSync(demo, { recursive: true });
+ fs.mkdirSync(skills, { recursive: true });
+ // Generated SKILL.md files always carry the banner — the #2142
+ // ownership gate keys the Windows refresh on it.
+ const banner = '<!-- AUTO-GENERATED from SKILL.md.tmpl - DO NOT EDIT DIRECTLY -->\n';
+ fs.writeFileSync(path.join(demo, 'SKILL.md'), `${banner}v1-original\n`);
+
+ // First run: installs the copy.
+ let r = runInstaller('1', ['link_codex_skill_dirs'], `link_codex_skill_dirs "${fake}" "${skills}"`);
+ expect(r.status).toBe(0);
+ const installed = path.join(skills, 'gstack-demo', 'SKILL.md');
+ expect(fs.readFileSync(installed, 'utf-8')).toBe(`${banner}v1-original\n`);
+ expect(fs.lstatSync(path.join(skills, 'gstack-demo')).isSymbolicLink()).toBe(false);
+
+ // Upstream ships a change (the git pull).
+ fs.writeFileSync(path.join(demo, 'SKILL.md'), `${banner}v2-UPDATED\n`);
+
+ // Second run: pre-#2444 this was a silent no-op on Windows.
+ r = runInstaller('1', ['link_codex_skill_dirs'], `link_codex_skill_dirs "${fake}" "${skills}"`);
+ expect(r.status).toBe(0);
+ expect(fs.readFileSync(installed, 'utf-8')).toBe(`${banner}v2-UPDATED\n`);
+ } finally {
+ fs.rmSync(tmp, { recursive: true, force: true });
+ }
+ });
+
+ test('IS_WINDOWS=1: create_agents_sidecar refreshes copied runtime assets', () => {
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-rerun-sidecar-'));
+ try {
+ const fake = path.join(tmp, 'gstack');
+ fs.mkdirSync(path.join(fake, 'bin'), { recursive: true });
+ fs.writeFileSync(path.join(fake, 'bin', 'tool.sh'), 'v1\n');
+ fs.writeFileSync(path.join(fake, 'ETHOS.md'), 'ethos-v1\n');
+
+ const vars = `SOURCE_GSTACK_DIR="${fake}"`;
+ let r = runInstaller('1', ['create_agents_sidecar'], `create_agents_sidecar "${fake}"`, vars);
+ expect(r.status).toBe(0);
+ const sidecarBin = path.join(fake, '.agents', 'skills', 'gstack', 'bin', 'tool.sh');
+ const sidecarEthos = path.join(fake, '.agents', 'skills', 'gstack', 'ETHOS.md');
+ expect(fs.readFileSync(sidecarBin, 'utf-8')).toBe('v1\n');
+ expect(fs.readFileSync(sidecarEthos, 'utf-8')).toBe('ethos-v1\n');
+
+ fs.writeFileSync(path.join(fake, 'bin', 'tool.sh'), 'v2\n');
+ fs.writeFileSync(path.join(fake, 'ETHOS.md'), 'ethos-v2\n');
+
+ r = runInstaller('1', ['create_agents_sidecar'], `create_agents_sidecar "${fake}"`, vars);
+ expect(r.status).toBe(0);
+ expect(fs.readFileSync(sidecarBin, 'utf-8')).toBe('v2\n');
+ expect(fs.readFileSync(sidecarEthos, 'utf-8')).toBe('ethos-v2\n');
+ } finally {
+ fs.rmSync(tmp, { recursive: true, force: true });
+ }
+ });
+
+ test('IS_WINDOWS=1: nested gitignored build output does NOT survive the runtime-asset copy (P5)', () => {
+ // The exclusion list in _link_skill_runtime_assets filters direct
+ // children only; cp -R swept NESTED node_modules/.build/dist too
+ // (concrete: ios-qa/scripts/gen-accessors-tool/.build, 252MB). The
+ // Windows branch prunes them post-copy; real asset files at every level
+ // survive.
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-rerun-prune-'));
+ try {
+ const src = path.join(tmp, 'skill-src');
+ const dst = path.join(tmp, 'skill-dst');
+ fs.mkdirSync(path.join(src, 'scripts', 'gen-tool', '.build'), { recursive: true });
+ fs.mkdirSync(path.join(src, 'scripts', 'gen-tool', 'node_modules', 'dep'), { recursive: true });
+ fs.mkdirSync(path.join(src, 'scripts', 'gen-tool', 'dist'), { recursive: true });
+ fs.mkdirSync(dst, { recursive: true });
+ fs.writeFileSync(path.join(src, 'scripts', 'runner.sh'), 'echo run\n');
+ fs.writeFileSync(path.join(src, 'scripts', 'gen-tool', 'main.swift'), 'source\n');
+ fs.writeFileSync(path.join(src, 'scripts', 'gen-tool', '.build', 'blob.bin'), '#'.repeat(4096));
+ fs.writeFileSync(path.join(src, 'scripts', 'gen-tool', 'node_modules', 'dep', 'index.js'), 'x\n');
+ fs.writeFileSync(path.join(src, 'scripts', 'gen-tool', 'dist', 'compiled'), 'bin\n');
+
+ const r = runInstaller(
+ '1',
+ ['_link_skill_runtime_assets'],
+ `_link_skill_runtime_assets "${src}" "${dst}"`,
+ );
+ expect(r.status).toBe(0);
+ // Real assets at both levels survive…
+ expect(fs.readFileSync(path.join(dst, 'scripts', 'runner.sh'), 'utf-8')).toBe('echo run\n');
+ expect(fs.readFileSync(path.join(dst, 'scripts', 'gen-tool', 'main.swift'), 'utf-8')).toBe('source\n');
+ // …nested build output does not.
+ expect(fs.existsSync(path.join(dst, 'scripts', 'gen-tool', '.build'))).toBe(false);
+ expect(fs.existsSync(path.join(dst, 'scripts', 'gen-tool', 'node_modules'))).toBe(false);
+ expect(fs.existsSync(path.join(dst, 'scripts', 'gen-tool', 'dist'))).toBe(false);
+ // The source tree is untouched — the prune runs on the COPY only.
+ expect(fs.existsSync(path.join(src, 'scripts', 'gen-tool', '.build', 'blob.bin'))).toBe(true);
+ } finally {
+ fs.rmSync(tmp, { recursive: true, force: true });
+ }
+ });
+
+ test('IS_WINDOWS=0: the Unix symlink path never prunes through into the source', () => {
+ // On Unix the asset is a SYMLINK into the working tree; pruning through
+ // it would delete real build output from the repo. The prune is gated on
+ // the Windows real-copy shape ([ -d ] && [ ! -L ]).
+ // Not runnable ON Windows: this sub-case models the UNIX shape, but Git
+ // Bash's `ln -snf` produces a real copy there (no Developer Mode on CI),
+ // so the symlink assertion is false by platform, not by regression. The
+ // Unix lanes (macOS dev boxes + Linux CI) own this case.
+ if (process.platform === 'win32') return;
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-rerun-prune-unix-'));
+ try {
+ const src = path.join(tmp, 'skill-src');
+ const dst = path.join(tmp, 'skill-dst');
+ fs.mkdirSync(path.join(src, 'scripts', 'gen-tool', '.build'), { recursive: true });
+ fs.mkdirSync(dst, { recursive: true });
+ fs.writeFileSync(path.join(src, 'scripts', 'gen-tool', '.build', 'blob.bin'), 'keep');
+
+ const r = runInstaller(
+ '0',
+ ['_link_skill_runtime_assets'],
+ `_link_skill_runtime_assets "${src}" "${dst}"`,
+ );
+ expect(r.status).toBe(0);
+ expect(fs.lstatSync(path.join(dst, 'scripts')).isSymbolicLink()).toBe(true);
+ expect(fs.existsSync(path.join(src, 'scripts', 'gen-tool', '.build', 'blob.bin'))).toBe(true);
+ } finally {
+ fs.rmSync(tmp, { recursive: true, force: true });
+ }
+ });
+
+ test('IS_WINDOWS=1: the gstack sidecar dir is still skipped by the skill loop', () => {
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-rerun-skip-'));
+ try {
+ const fake = path.join(tmp, 'gstack');
+ const skills = path.join(tmp, 'skills');
+ const sidecar = path.join(fake, '.agents', 'skills', 'gstack');
+ fs.mkdirSync(sidecar, { recursive: true });
+ fs.mkdirSync(skills, { recursive: true });
+ fs.writeFileSync(path.join(sidecar, 'SKILL.md'), 'sidecar\n');
+
+ const r = runInstaller('1', ['link_codex_skill_dirs'], `link_codex_skill_dirs "${fake}" "${skills}"`);
+ expect(r.status).toBe(0);
+ expect(fs.existsSync(path.join(skills, 'gstack'))).toBe(false);
+ } finally {
+ fs.rmSync(tmp, { recursive: true, force: true });
+ }
+ });
+});
+
+// On real Windows, `ln -snf` under Git Bash silently produces copies, so the
+// Unix-mode symlink assertions are meaningless there — the same skip the
+// _link_or_copy behavior matrix uses (test/setup-windows-fallback.test.ts).
+describe.skipIf(process.platform === 'win32')(
+ 'setup: Unix path unchanged by the #2444 bypass',
+ () => {
+ test('IS_WINDOWS=0: installs a symlink and re-runs still refresh through it', () => {
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-rerun-unix-'));
+ try {
+ const fake = path.join(tmp, 'gstack');
+ const skills = path.join(tmp, 'skills');
+ const demo = path.join(fake, '.agents', 'skills', 'gstack-demo');
+ fs.mkdirSync(demo, { recursive: true });
+ fs.mkdirSync(skills, { recursive: true });
+ fs.writeFileSync(path.join(demo, 'SKILL.md'), 'v1-original\n');
+
+ let r = runInstaller('0', ['link_codex_skill_dirs'], `link_codex_skill_dirs "${fake}" "${skills}"`);
+ expect(r.status).toBe(0);
+ const target = path.join(skills, 'gstack-demo');
+ expect(fs.lstatSync(target).isSymbolicLink()).toBe(true);
+
+ // A symlink serves updates without any re-run at all…
+ fs.writeFileSync(path.join(demo, 'SKILL.md'), 'v2-UPDATED\n');
+ expect(fs.readFileSync(path.join(target, 'SKILL.md'), 'utf-8')).toBe('v2-UPDATED\n');
+
+ // …and the re-run keeps it a symlink (guard still passes via -L).
+ r = runInstaller('0', ['link_codex_skill_dirs'], `link_codex_skill_dirs "${fake}" "${skills}"`);
+ expect(r.status).toBe(0);
+ expect(fs.lstatSync(target).isSymbolicLink()).toBe(true);
+ } finally {
+ fs.rmSync(tmp, { recursive: true, force: true });
+ }
+ });
+ },
+);
diff --git a/test/ship-review-loop.test.ts b/test/ship-review-loop.test.ts
new file mode 100644
index 000000000..88d919cb5
--- /dev/null
+++ b/test/ship-review-loop.test.ts
@@ -0,0 +1,49 @@
+/**
+ * /ship review fix loop stays in one invocation (#2391).
+ *
+ * The pre-landing review used to commit its fixes, STOP, and tell the user
+ * to run /ship again — 5-10 manual invocations on a branch with a few
+ * auto-fixable findings, violating the skill's fully-automated contract.
+ * The rendered section must instruct a bounded in-invocation loop
+ * (re-test, re-review, max 3 fix cycles) and must never terminate an
+ * AUTO-FIX result with a rerun request.
+ */
+import { describe, test, expect } from 'bun:test';
+import * as fs from 'fs';
+import * as path from 'path';
+
+const ROOT = path.join(import.meta.dir, '..');
+
+const RENDERED_SITES = [
+ path.join(ROOT, 'ship', 'sections', 'review-army.md'),
+ path.join(ROOT, 'test', 'fixtures', 'golden', 'claude-ship-SKILL.md'),
+ path.join(ROOT, 'test', 'fixtures', 'golden', 'codex-ship-SKILL.md'),
+ path.join(ROOT, 'test', 'fixtures', 'golden', 'factory-ship-SKILL.md'),
+];
+
+describe('/ship review fix loop (#2391)', () => {
+ test('no rendered ship surface instructs a STOP-and-rerun after fixes', () => {
+ // The pre-fix instruction: "then **STOP** and tell the user to run
+ // `/ship` again". The fixed text mentions the phrase only inside a
+ // NEVER-do-this prohibition, so match the imperative STOP shape.
+ const rerunRequest = /\*\*STOP\*\*[^\n]*run `\/ship` again/;
+ for (const file of RENDERED_SITES) {
+ const content = fs.readFileSync(file, 'utf-8');
+ expect(rerunRequest.test(content)).toBe(false);
+ }
+ });
+
+ test('rendered section instructs the bounded in-invocation loop', () => {
+ const content = fs.readFileSync(RENDERED_SITES[0], 'utf-8');
+ expect(content).toContain('stay in this invocation and loop');
+ expect(content).toContain('3 fix cycles');
+ // The loop re-runs tests AND the review, and only a converged pass continues.
+ expect(content).toContain('re-run the test suite (Step 5)');
+ expect(content).toContain('re-run this review (Step 9 items 2-6)');
+ });
+
+ test('the non-convergence stop is a blocker report, not a rerun request', () => {
+ const content = fs.readFileSync(RENDERED_SITES[0], 'utf-8');
+ expect(content).toContain('report which findings keep reappearing');
+ });
+});
diff --git a/test/skill-census.test.ts b/test/skill-census.test.ts
index b9bb21578..f2ea7e5c8 100644
--- a/test/skill-census.test.ts
+++ b/test/skill-census.test.ts
@@ -11,7 +11,7 @@ import * as fs from 'fs';
import * as path from 'path';
import { frontmatterName, skillCensus } from './helpers/skill-census';
-const ROOT = path.resolve(new URL(import.meta.url).pathname, '..', '..');
+const ROOT = path.resolve(import.meta.path, '..', '..');
const census = skillCensus(ROOT);
describe('skillCensus', () => {
diff --git a/test/skill-e2e-cso.test.ts b/test/skill-e2e-cso.test.ts
index 64aa18bde..9bd0ed380 100644
--- a/test/skill-e2e-cso.test.ts
+++ b/test/skill-e2e-cso.test.ts
@@ -161,9 +161,14 @@ IMPORTANT:
- Focus on changes in the current branch vs main.
- The webhook.ts file was added on this branch — it should be analyzed.`,
workingDirectory: csoDiffDir,
- maxTurns: 25,
+ maxTurns: 40,
allowedTools: ['Bash', 'Read', 'Write', 'Edit', 'Grep', 'Glob', 'Agent'],
- timeout: 240_000,
+ // 360s/40 turns: the v1.67 wave grew the audit session legitimately —
+ // transcript-verified, the agent finds the webhook vuln, spawns the
+ // verification subagent, and writes the report, then gets killed at
+ // ~215s in its CLOSING telemetry under the old 240s/25-turn budget.
+ // The full-audit sibling already runs at 300s.
+ timeout: 360_000,
});
logCost('cso', result);
@@ -176,7 +181,7 @@ IMPORTANT:
).toBe(true);
recordE2E(evalCollector, 'cso-diff-mode', 'e2e-cso', result);
- }, 240_000);
+ }, 400_000);
});
describeIfSelected('CSO v2 — infra scope', ['cso-infra-scope'], () => {
diff --git a/test/timeline-stop-hook.test.ts b/test/timeline-stop-hook.test.ts
new file mode 100644
index 000000000..b64eb33bb
--- /dev/null
+++ b/test/timeline-stop-hook.test.ts
@@ -0,0 +1,252 @@
+/**
+ * Timeline Stop hook (#2553) — fail-open contract (F5).
+ *
+ * The preamble writes event:"started" at every skill start; the completion
+ * write is end-of-workflow prose and unenforceable, so interrupted sessions
+ * leaked started > completed forever. The Stop hook closes dangling entries.
+ *
+ * Contract under test: ALWAYS exits 0 (corrupt timeline, missing timeline,
+ * garbage stdin), append-only, and the normal path appends event:"completed"
+ * with outcome "unknown" + source "stop-hook" for every un-closed "started".
+ */
+import { describe, test, expect, beforeEach, afterEach } from 'bun:test';
+import { spawnSync } from 'child_process';
+import * as fs from 'fs';
+import * as os from 'os';
+import * as path from 'path';
+
+const ROOT = path.resolve(import.meta.dir, '..');
+const HOOK = path.join(ROOT, 'hosts', 'claude', 'hooks', 'timeline-stop-hook');
+
+const SLUG = 'stop-hook-test-project';
+
+let tmpHome: string;
+let projectDir: string;
+let timelinePath: string;
+
+beforeEach(() => {
+ tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-stop-hook-home-'));
+ projectDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-stop-hook-proj-'));
+ fs.mkdirSync(path.join(tmpHome, 'projects', SLUG), { recursive: true });
+ timelinePath = path.join(tmpHome, 'projects', SLUG, 'timeline.jsonl');
+});
+
+afterEach(() => {
+ fs.rmSync(tmpHome, { recursive: true, force: true });
+ fs.rmSync(projectDir, { recursive: true, force: true });
+});
+
+function runHook(stdin: string): { exitCode: number; stdout: string; stderr: string } {
+ const r = spawnSync('bash', [HOOK], {
+ input: stdin,
+ encoding: 'utf-8',
+ env: {
+ ...process.env,
+ GSTACK_HOME: tmpHome,
+ GSTACK_PROJECT_SLUG: SLUG, // deterministic slug, no git required
+ },
+ timeout: 15_000,
+ });
+ return { exitCode: r.status ?? 1, stdout: r.stdout, stderr: r.stderr };
+}
+
+function stopPayload(): string {
+ return JSON.stringify({
+ session_id: 'sess-abc',
+ hook_event_name: 'Stop',
+ cwd: projectDir,
+ });
+}
+
+function timelineEntries(): any[] {
+ if (!fs.existsSync(timelinePath)) return [];
+ return fs
+ .readFileSync(timelinePath, 'utf-8')
+ .split('\n')
+ .filter((l) => l.trim())
+ .map((l) => {
+ try {
+ return JSON.parse(l);
+ } catch {
+ return { __corrupt: l };
+ }
+ });
+}
+
+describe('timeline-stop-hook (#2553, F5 fail-open)', () => {
+ test('normal path: closes dangling started entries, leaves closed pairs alone', () => {
+ fs.writeFileSync(
+ timelinePath,
+ [
+ JSON.stringify({ skill: 'review', event: 'started', branch: 'main', session: '11-1' }),
+ JSON.stringify({ skill: 'ship', event: 'started', session: '22-2' }),
+ JSON.stringify({ skill: 'ship', event: 'completed', session: '22-2', outcome: 'success' }),
+ ].join('\n') + '\n',
+ );
+
+ const r = runHook(stopPayload());
+ expect(r.exitCode).toBe(0);
+
+ const entries = timelineEntries();
+ // Append-only: the three originals survive verbatim in order.
+ expect(entries[0]).toMatchObject({ skill: 'review', event: 'started' });
+ expect(entries[2]).toMatchObject({ skill: 'ship', event: 'completed', outcome: 'success' });
+
+ const repairs = entries.filter((e) => e.source === 'stop-hook');
+ expect(repairs).toHaveLength(1);
+ expect(repairs[0]).toMatchObject({
+ skill: 'review',
+ event: 'completed',
+ outcome: 'unknown',
+ branch: 'main',
+ session: '11-1',
+ });
+ expect(typeof repairs[0].ts).toBe('string');
+ });
+
+ test('idempotent: a second Stop appends nothing new', () => {
+ fs.writeFileSync(
+ timelinePath,
+ JSON.stringify({ skill: 'qa', event: 'started', session: '33-3' }) + '\n',
+ );
+ expect(runHook(stopPayload()).exitCode).toBe(0);
+ const afterFirst = timelineEntries().length;
+ expect(runHook(stopPayload()).exitCode).toBe(0);
+ expect(timelineEntries().length).toBe(afterFirst);
+ });
+
+ test('count semantics: two runs under one key, one completed — the dangler is still repaired', () => {
+ // Legacy entries carry no session field, so both runs share the same
+ // skill+session key (same-second "$$-epoch" ids collide the same way).
+ // With set semantics the first run's completion masked the second run's
+ // dangler forever; counting closes the difference.
+ fs.writeFileSync(
+ timelinePath,
+ [
+ JSON.stringify({ skill: 'review', event: 'started' }),
+ JSON.stringify({ skill: 'review', event: 'completed', outcome: 'success' }),
+ JSON.stringify({ skill: 'review', event: 'started' }),
+ ].join('\n') + '\n',
+ );
+
+ expect(runHook(stopPayload()).exitCode).toBe(0);
+ const repairs = timelineEntries().filter((e) => e.source === 'stop-hook');
+ expect(repairs).toHaveLength(1);
+ expect(repairs[0]).toMatchObject({ skill: 'review', event: 'completed', outcome: 'unknown' });
+
+ // Idempotent under count semantics too: started=2, completed=2 → no-op.
+ expect(runHook(stopPayload()).exitCode).toBe(0);
+ expect(timelineEntries().filter((e) => e.source === 'stop-hook')).toHaveLength(1);
+ });
+
+ test('exit 0 on missing timeline (nothing written, nothing created)', () => {
+ const r = runHook(stopPayload());
+ expect(r.exitCode).toBe(0);
+ expect(fs.existsSync(timelinePath)).toBe(false);
+ });
+
+ test('exit 0 on a corrupt timeline; corrupt lines are skipped, valid ones still repaired', () => {
+ fs.writeFileSync(
+ timelinePath,
+ [
+ 'this is not json at all {{{',
+ JSON.stringify({ skill: 'qa', event: 'started', session: '44-4' }),
+ '{"half": "an object"',
+ ].join('\n') + '\n',
+ );
+ const r = runHook(stopPayload());
+ expect(r.exitCode).toBe(0);
+ const repairs = timelineEntries().filter((e) => e.source === 'stop-hook');
+ expect(repairs).toHaveLength(1);
+ expect(repairs[0].skill).toBe('qa');
+ });
+
+ test('exit 0 on a FULLY corrupt timeline (no valid entries → no write)', () => {
+ const garbage = 'garbage\n{{{\n';
+ fs.writeFileSync(timelinePath, garbage);
+ const r = runHook(stopPayload());
+ expect(r.exitCode).toBe(0);
+ expect(fs.readFileSync(timelinePath, 'utf-8')).toBe(garbage);
+ });
+
+ test('exit 0 on garbage stdin', () => {
+ fs.writeFileSync(
+ timelinePath,
+ JSON.stringify({ skill: 'qa', event: 'started', session: '55-5' }) + '\n',
+ );
+ const r = runHook('not json');
+ expect(r.exitCode).toBe(0);
+ });
+
+ test('exit 0 on empty stdin', () => {
+ expect(runHook('').exitCode).toBe(0);
+ });
+
+ test('tail window (P3): a recent dangling entry in a >256KB timeline is still repaired', () => {
+ const lines: string[] = [];
+ // An old dangling entry that falls OUTSIDE the 256KB tail window —
+ // beyond repair interest by design (its session is long gone).
+ lines.push(JSON.stringify({ skill: 'review', event: 'started', session: 'old-1' }));
+ // >512KB of closed pairs pushes the old entry well past the window while
+ // proving windowed parsing still walks real entries.
+ let n = 0;
+ while (lines.length * 100 < 512 * 1024) {
+ lines.push(
+ JSON.stringify({ skill: 'qa', event: 'started', session: `pad-${n}`, pad: '#'.repeat(40) }),
+ );
+ lines.push(JSON.stringify({ skill: 'qa', event: 'completed', session: `pad-${n}`, outcome: 'success' }));
+ n++;
+ }
+ lines.push(JSON.stringify({ skill: 'ship', event: 'started', session: 'recent-9' }));
+ fs.writeFileSync(timelinePath, lines.join('\n') + '\n');
+ expect(fs.statSync(timelinePath).size).toBeGreaterThan(256 * 1024);
+
+ const r = runHook(stopPayload());
+ expect(r.exitCode).toBe(0);
+ const repairs = timelineEntries().filter((e) => e.source === 'stop-hook');
+ expect(repairs).toHaveLength(1);
+ expect(repairs[0]).toMatchObject({
+ skill: 'ship',
+ event: 'completed',
+ outcome: 'unknown',
+ session: 'recent-9',
+ });
+ });
+
+ test('oversized timeline is skipped, untouched, and still exits 0 (fail-open size cap)', () => {
+ const line = JSON.stringify({ skill: 'qa', event: 'started', session: '66-6' }) + '\n';
+ const filler = '#'.repeat(1024 * 1024);
+ fs.writeFileSync(timelinePath, line + filler.repeat(11));
+ const sizeBefore = fs.statSync(timelinePath).size;
+ const r = runHook(stopPayload());
+ expect(r.exitCode).toBe(0);
+ expect(fs.statSync(timelinePath).size).toBe(sizeBefore);
+ });
+});
+
+describe('timeline-stop-hook wiring', () => {
+ test('setup registers the Stop hook with its own source tag and tears it down on --no-team', () => {
+ const setup = fs.readFileSync(path.join(ROOT, 'setup'), 'utf-8');
+ expect(setup).toContain('--event Stop');
+ expect(setup).toContain('--source gstack-timeline-stop');
+ expect(setup).toContain('hosts/claude/hooks/timeline-stop-hook');
+ // --no-team teardown removes it alongside the plan-tune hooks.
+ const teardown = setup.slice(setup.indexOf('# Also tear down plan-tune'));
+ expect(teardown).toContain('remove-source --source gstack-timeline-stop');
+ });
+
+ test('gstack-uninstall removes the Stop hook registration', () => {
+ const uninstall = fs.readFileSync(path.join(ROOT, 'bin', 'gstack-uninstall'), 'utf-8');
+ expect(uninstall).toContain('remove-source --source gstack-timeline-stop');
+ });
+
+ test('the bash shim is fail-open: exits 0 even when bun is unavailable', () => {
+ const r = spawnSync('bash', [HOOK], {
+ input: '{}',
+ encoding: 'utf-8',
+ env: { HOME: tmpHome, PATH: '/usr/bin:/bin', GSTACK_HOME: tmpHome },
+ timeout: 15_000,
+ });
+ expect(r.status).toBe(0);
+ });
+});
diff --git a/test/uninstall-windows-copies.test.ts b/test/uninstall-windows-copies.test.ts
new file mode 100644
index 000000000..3e2caa699
--- /dev/null
+++ b/test/uninstall-windows-copies.test.ts
@@ -0,0 +1,257 @@
+/**
+ * gstack-uninstall: real-directory installs are removed, gated on provenance
+ * (#2563, F8, ENG-OV10).
+ *
+ * On Windows, setup installs skills as REAL directory copies (no symlinks).
+ * gstack-uninstall's per-skill loop filtered on `[ -L ]`, so every copy was
+ * skipped: the tool exited 0, printed "gstack uninstalled.", and left ~52
+ * gstack-* directories behind. The same filter also missed the standard Unix
+ * shape (real dir + symlinked SKILL.md).
+ *
+ * Deletion gate for real-file installs (F8): the directory name must be in
+ * gstack's skill inventory AND its SKILL.md must carry the existing generated
+ * banner `<!-- AUTO-GENERATED from` (ENG-OV10 — every pre-v1.67 copy already
+ * carries it; a NEW marker would refuse legitimate old installs). Anything
+ * that fails a gate is listed to stderr and NEVER deleted.
+ */
+import { describe, test, expect, beforeEach, afterEach } from 'bun:test';
+import { spawnSync } from 'child_process';
+import * as fs from 'fs';
+import * as os from 'os';
+import * as path from 'path';
+
+const ROOT = path.resolve(import.meta.dir, '..');
+const UNINSTALL = path.join(ROOT, 'bin', 'gstack-uninstall');
+
+const BANNER = '<!-- AUTO-GENERATED from SKILL.md.tmpl - DO NOT EDIT DIRECTLY -->\n';
+
+function skillMd(name: string, withBanner = true): string {
+ return `---\nname: ${name}\ndescription: test\n---\n${withBanner ? BANNER : ''}# ${name}\n`;
+}
+
+let tmpDir: string;
+let mockHome: string;
+let skillsDir: string;
+let installRoot: string;
+
+beforeEach(() => {
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-uninstall-copies-'));
+ mockHome = path.join(tmpDir, 'home');
+ skillsDir = path.join(mockHome, '.claude', 'skills');
+ installRoot = path.join(skillsDir, 'gstack');
+
+ // Mock install root: the source-of-truth skill dirs the inventory reads.
+ for (const skill of ['review', 'ship', 'qa']) {
+ fs.mkdirSync(path.join(installRoot, skill), { recursive: true });
+ fs.writeFileSync(path.join(installRoot, skill, 'SKILL.md'), skillMd(skill));
+ }
+ fs.writeFileSync(path.join(installRoot, 'SKILL.md'), skillMd('gstack'));
+ fs.mkdirSync(path.join(mockHome, '.gstack'), { recursive: true });
+});
+
+afterEach(() => {
+ fs.rmSync(tmpDir, { recursive: true, force: true });
+});
+
+function runUninstall(): { status: number | null; stdout: string; stderr: string } {
+ const r = spawnSync('bash', [UNINSTALL, '--force'], {
+ stdio: 'pipe',
+ encoding: 'utf-8',
+ env: {
+ ...process.env,
+ HOME: mockHome,
+ GSTACK_DIR: installRoot,
+ GSTACK_STATE_DIR: path.join(mockHome, '.gstack'),
+ },
+ cwd: tmpDir, // not a git repo — per-project paths inert
+ timeout: 20_000,
+ });
+ return { status: r.status, stdout: r.stdout, stderr: r.stderr };
+}
+
+/** Create a Windows-shape install entry: real dir + real-file SKILL.md. */
+function realDirEntry(name: string, content: string): string {
+ const dir = path.join(skillsDir, name);
+ fs.mkdirSync(dir, { recursive: true });
+ fs.writeFileSync(path.join(dir, 'SKILL.md'), content);
+ return dir;
+}
+
+describe('gstack-uninstall removes Windows real-dir copies (#2563)', () => {
+ test('inventory name + banner → removed (flat, prefixed, and alias forms)', () => {
+ const review = realDirEntry('review', skillMd('review'));
+ const prefixedShip = realDirEntry('gstack-ship', skillMd('gstack-ship'));
+ const alias = realDirEntry('_gstack-command', skillMd('_gstack-command'));
+ const ogbAlias = realDirEntry('connect-chrome', skillMd('connect-chrome'));
+
+ const r = runUninstall();
+ expect(r.status).toBe(0);
+ expect(fs.existsSync(review)).toBe(false);
+ expect(fs.existsSync(prefixedShip)).toBe(false);
+ expect(fs.existsSync(alias)).toBe(false);
+ expect(fs.existsSync(ogbAlias)).toBe(false);
+ expect(fs.existsSync(installRoot)).toBe(false);
+ });
+
+ test('name NOT in inventory → kept and listed to stderr, even with a banner', () => {
+ const foreign = realDirEntry('my-notes', skillMd('my-notes'));
+
+ const r = runUninstall();
+ expect(r.status).toBe(0);
+ expect(fs.existsSync(foreign)).toBe(true);
+ expect(r.stderr).toContain('my-notes');
+ expect(r.stderr).toContain('left in place');
+ });
+
+ test('no banner → kept and listed, even when the name collides with a gstack skill', () => {
+ // F8's name-collision row: a user's own hand-written ~/.claude/skills/ship.
+ const usersOwn = realDirEntry('ship', skillMd('ship', false));
+
+ const r = runUninstall();
+ expect(r.status).toBe(0);
+ expect(fs.existsSync(usersOwn)).toBe(true);
+ expect(fs.readFileSync(path.join(usersOwn, 'SKILL.md'), 'utf-8')).toContain('name: ship');
+ // Separator-insensitive: the bash uninstall prints POSIX paths even on
+ // Windows (Git Bash), where path.join would demand a backslash.
+ expect(r.stderr.replace(/\\/g, '/')).toContain('skills/ship');
+ });
+
+ test('real dir without any SKILL.md is untouched and unlisted', () => {
+ const plain = path.join(skillsDir, 'other-tool');
+ fs.mkdirSync(plain, { recursive: true });
+
+ const r = runUninstall();
+ expect(r.status).toBe(0);
+ expect(fs.existsSync(plain)).toBe(true);
+ expect(r.stderr).not.toContain('other-tool');
+ });
+
+ test('a clean sweep reports the removed entries', () => {
+ realDirEntry('review', skillMd('review'));
+ const r = runUninstall();
+ expect(r.status).toBe(0);
+ expect(r.stdout).toContain('claude/review');
+ expect(r.stdout).toContain('gstack uninstalled.');
+ });
+});
+
+// symlinkSync needs Developer Mode on Windows runners; the Unix install shape
+// can't be constructed there. The shape is Unix-only in practice anyway.
+describe.skipIf(process.platform === 'win32')(
+ 'gstack-uninstall removes the Unix real-dir + symlinked-SKILL.md shape',
+ () => {
+ test('SKILL.md symlink pointing into gstack → removed', () => {
+ const dir = path.join(skillsDir, 'qa');
+ fs.mkdirSync(dir, { recursive: true });
+ fs.symlinkSync(path.join(installRoot, 'qa', 'SKILL.md'), path.join(dir, 'SKILL.md'));
+
+ const r = runUninstall();
+ expect(r.status).toBe(0);
+ expect(fs.existsSync(dir)).toBe(false);
+ });
+
+ test('SKILL.md symlink into a gstack-SUBSTRING path (gstack-fork) → kept and listed', () => {
+ // DM5: the shape-2 gate must match "gstack" as an anchored path
+ // segment, not a substring — a user's own skill whose SKILL.md links
+ // into ~/tools/gstack-fork/ is NOT ours, even when the dir name
+ // collides with a real gstack skill (here: review, in the inventory).
+ // The anchored gate only matches a literal /gstack/ path segment, so
+ // the tmpdir must not carry one (shared-process shard runs can leave
+ // $TMPDIR pointing into a gstack worktree — same hazard as the
+ // "pointing elsewhere" test below). Fall back to a fixed neutral root
+ // and ASSERT the precondition.
+ let neutralRoot = os.tmpdir();
+ if (neutralRoot.split(path.sep).includes('gstack')) neutralRoot = '/private' + path.sep + 'tmp';
+ const forkRoot = fs.mkdtempSync(path.join(neutralRoot, 'tools-'));
+ expect(forkRoot.split(path.sep).includes('gstack')).toBe(false);
+ const forkSrc = path.join(forkRoot, 'gstack-fork', 'review');
+ fs.mkdirSync(forkSrc, { recursive: true });
+ fs.writeFileSync(path.join(forkSrc, 'SKILL.md'), skillMd('review'));
+ const dir = path.join(skillsDir, 'review');
+ fs.mkdirSync(dir, { recursive: true });
+ fs.symlinkSync(path.join(forkSrc, 'SKILL.md'), path.join(dir, 'SKILL.md'));
+
+ try {
+ const r = runUninstall();
+ expect(r.status).toBe(0);
+ expect(fs.existsSync(dir)).toBe(true);
+ expect(r.stderr).toContain('left in place');
+ expect(r.stderr).toContain(path.join('skills', 'review'));
+ } finally {
+ fs.rmSync(forkRoot, { recursive: true, force: true });
+ }
+ });
+
+ test('SKILL.md symlink into gstack but name NOT in inventory → kept and listed', () => {
+ // Shape 2 now carries the same inventory gate as shape 3: a dir whose
+ // name setup could never have created is skipped even when its
+ // SKILL.md target resolves into the install root.
+ const dir = path.join(skillsDir, 'my-custom-wrapper');
+ fs.mkdirSync(dir, { recursive: true });
+ fs.symlinkSync(path.join(installRoot, 'qa', 'SKILL.md'), path.join(dir, 'SKILL.md'));
+
+ const r = runUninstall();
+ expect(r.status).toBe(0);
+ expect(fs.existsSync(dir)).toBe(true);
+ expect(r.stderr).toContain('my-custom-wrapper');
+ });
+
+ test('SKILL.md symlink pointing elsewhere → kept and listed', () => {
+ // Target path must not contain a gstack path segment (the provenance
+ // match is anchored: gstack/*|*/gstack/*; keeping the stricter
+ // no-substring precondition costs nothing) — the suite
+ // tmpdir prefix does, so use a separate neutral tmpdir. os.tmpdir()
+ // reads $TMPDIR at CALL time, and in shared-process shard runs a
+ // neighboring test can leave it pointing at a gstack-containing path —
+ // observed once in a full-suite shard (the "neutral" target then
+ // matched the provenance substring and the dir was wrongly deleted by
+ // the test's own expectations). Fall back to a fixed neutral root and
+ // ASSERT neutrality so the precondition can never silently rot.
+ let neutralRoot = os.tmpdir();
+ // realpath'd literal /tmp: /private/tmp on macOS, /tmp on Linux. The
+ // hardcoded '/private/tmp' fallback ENOENT'd on Linux CI, where the
+ // shard runner's TMPDIR is the gstack-containing path that forces this
+ // branch. (Never taken on Windows — its TMPDIR carries no 'gstack'.)
+ if (neutralRoot.includes('gstack')) neutralRoot = fs.realpathSync('/tmp');
+ const neutral = fs.mkdtempSync(path.join(neutralRoot, 'other-skill-src-'));
+ expect(neutral.includes('gstack')).toBe(false);
+ const elsewhere = path.join(neutral, 'elsewhere.md');
+ fs.writeFileSync(elsewhere, '# not ours\n');
+ const dir = path.join(skillsDir, 'someone-elses');
+ fs.mkdirSync(dir, { recursive: true });
+ fs.symlinkSync(elsewhere, path.join(dir, 'SKILL.md'));
+
+ try {
+ const r = runUninstall();
+ expect(r.status).toBe(0);
+ expect(fs.existsSync(dir)).toBe(true);
+ expect(r.stderr).toContain('someone-elses');
+ } finally {
+ fs.rmSync(neutral, { recursive: true, force: true });
+ }
+ });
+ },
+);
+
+describe('every installable skill SKILL.md carries the generated banner (ENG-OV10)', () => {
+ // The uninstall provenance gate is only sound if the banner is universal:
+ // a bannerless generated skill would be stranded on Windows forever.
+ test('all top-level skill SKILL.md files contain the AUTO-GENERATED banner', () => {
+ const missing: string[] = [];
+ for (const entry of fs.readdirSync(ROOT, { withFileTypes: true })) {
+ if (!entry.isDirectory() && !entry.isSymbolicLink()) continue;
+ const md = path.join(ROOT, entry.name, 'SKILL.md');
+ if (!fs.existsSync(md)) continue;
+ if (!fs.readFileSync(md, 'utf-8').includes('<!-- AUTO-GENERATED from')) {
+ missing.push(entry.name);
+ }
+ }
+ expect(missing).toEqual([]);
+ });
+
+ test('the root router SKILL.md carries the banner too (alias copies inherit it)', () => {
+ expect(fs.readFileSync(path.join(ROOT, 'SKILL.md'), 'utf-8')).toContain(
+ '<!-- AUTO-GENERATED from',
+ );
+ });
+});
diff --git a/test/uninstall.test.ts b/test/uninstall.test.ts
index a7208e877..1ed3edf83 100644
--- a/test/uninstall.test.ts
+++ b/test/uninstall.test.ts
@@ -161,5 +161,73 @@ describe('gstack-uninstall', () => {
// Non-gstack should survive
expect(fs.existsSync(path.join(mockHome, '.claude', 'skills', 'other-tool'))).toBe(true);
});
+
+ test('--force removes Cursor gstack skills and leaves other Cursor skills', () => {
+ // Cursor installs are rendered real dirs, so removal is gated on the
+ // generated banner in SKILL.md (S5) — the managed fixtures carry it.
+ const banner = '<!-- AUTO-GENERATED from SKILL.md.tmpl - DO NOT EDIT DIRECTLY -->\n# x\n';
+ fs.mkdirSync(path.join(mockHome, '.cursor', 'skills', 'gstack'), { recursive: true });
+ fs.writeFileSync(path.join(mockHome, '.cursor', 'skills', 'gstack', 'SKILL.md'), banner);
+ fs.mkdirSync(path.join(mockHome, '.cursor', 'skills', 'gstack-review'), { recursive: true });
+ fs.writeFileSync(path.join(mockHome, '.cursor', 'skills', 'gstack-review', 'SKILL.md'), banner);
+ fs.mkdirSync(path.join(mockHome, '.cursor', 'skills', 'frontend-design'), { recursive: true });
+ fs.writeFileSync(path.join(mockHome, '.cursor', 'skills', 'frontend-design', 'SKILL.md'), 'keep');
+
+ fs.mkdirSync(path.join(mockGitRoot, '.cursor', 'skills', 'gstack-ship'), { recursive: true });
+ fs.writeFileSync(path.join(mockGitRoot, '.cursor', 'skills', 'gstack-ship', 'SKILL.md'), banner);
+ fs.mkdirSync(path.join(mockGitRoot, '.cursor', 'rules'), { recursive: true });
+ fs.writeFileSync(path.join(mockGitRoot, '.cursor', 'rules', 'keep.md'), 'keep');
+
+ const result = spawnSync('bash', [UNINSTALL, '--force'], {
+ stdio: 'pipe',
+ env: {
+ ...process.env,
+ HOME: mockHome,
+ GSTACK_DIR: path.join(mockHome, '.claude', 'skills', 'gstack'),
+ GSTACK_STATE_DIR: path.join(mockHome, '.gstack'),
+ },
+ cwd: mockGitRoot,
+ });
+
+ expect(result.status).toBe(0);
+
+ expect(fs.existsSync(path.join(mockHome, '.cursor', 'skills', 'gstack'))).toBe(false);
+ expect(fs.existsSync(path.join(mockHome, '.cursor', 'skills', 'gstack-review'))).toBe(false);
+ expect(fs.existsSync(path.join(mockHome, '.cursor', 'skills', 'frontend-design'))).toBe(true);
+ expect(fs.existsSync(path.join(mockGitRoot, '.cursor', 'skills', 'gstack-ship'))).toBe(false);
+ expect(fs.existsSync(path.join(mockGitRoot, '.cursor', 'rules', 'keep.md'))).toBe(true);
+ });
+
+ test("a user's own gstack-prefixed Cursor dir (no banner) survives and is listed", () => {
+ // S5: the bare gstack* glob must not sweep a dir that merely starts
+ // with "gstack" — provenance comes from the generated banner, and a
+ // hand-written SKILL.md never carries it.
+ const foreign = path.join(mockHome, '.cursor', 'skills', 'gstack-fork-notes');
+ fs.mkdirSync(foreign, { recursive: true });
+ fs.writeFileSync(path.join(foreign, 'SKILL.md'), '# my own notes\n');
+
+ const foreignLocal = path.join(mockGitRoot, '.cursor', 'skills', 'gstack-my-rules');
+ fs.mkdirSync(foreignLocal, { recursive: true });
+ fs.writeFileSync(path.join(foreignLocal, 'SKILL.md'), '# hand-written\n');
+
+ const result = spawnSync('bash', [UNINSTALL, '--force'], {
+ stdio: 'pipe',
+ env: {
+ ...process.env,
+ HOME: mockHome,
+ GSTACK_DIR: path.join(mockHome, '.claude', 'skills', 'gstack'),
+ GSTACK_STATE_DIR: path.join(mockHome, '.gstack'),
+ },
+ cwd: mockGitRoot,
+ });
+
+ expect(result.status).toBe(0);
+ expect(fs.existsSync(foreign)).toBe(true);
+ expect(fs.existsSync(foreignLocal)).toBe(true);
+ const stderr = result.stderr.toString();
+ expect(stderr).toContain('left in place');
+ expect(stderr).toContain('gstack-fork-notes');
+ expect(stderr).toContain('gstack-my-rules');
+ });
});
});
diff --git a/test/user-render-out-dir-install.test.ts b/test/user-render-out-dir-install.test.ts
new file mode 100644
index 000000000..4c0980d23
--- /dev/null
+++ b/test/user-render-out-dir-install.test.ts
@@ -0,0 +1,273 @@
+/**
+ * :user render never dirties the global-git install (#2569).
+ *
+ * Pre-v1.67, gbrain-enabled setups ran `gen:skill-docs:user --host claude`
+ * IN PLACE inside the install checkout, rewriting ~16 tracked SKILL.md files.
+ * The checkout stayed permanently dirty and every upgrade stashed a redundant
+ * snapshot of generated content. The fix renders to an untracked out-dir
+ * (~/.gstack/render/claude) and makes the Claude installers — setup's
+ * link_claude_skill_dirs AND bin/gstack-relink — prefer rendered files when
+ * present. A one-time migration (v1.67.0.0.sh) restores the legacy dirt.
+ *
+ * (The render mechanism itself — worktree byte-unchanged, section repointing —
+ * is pinned by test/gen-skill-docs-out-dir.test.ts.)
+ */
+import { describe, test, expect } from 'bun:test';
+import { spawnSync } from 'child_process';
+import * as fs from 'fs';
+import * as os from 'os';
+import * as path from 'path';
+
+const ROOT = path.resolve(import.meta.dir, '..');
+const SETUP_SRC = fs.readFileSync(path.join(ROOT, 'setup'), 'utf-8');
+const CONFIG_SRC = fs.readFileSync(path.join(ROOT, 'bin', 'gstack-config'), 'utf-8');
+const RELINK_SRC = fs.readFileSync(path.join(ROOT, 'bin', 'gstack-relink'), 'utf-8');
+const MIGRATION = path.join(ROOT, 'gstack-upgrade', 'migrations', 'v1.67.0.0.sh');
+
+function extractFn(src: string, name: string): string {
+ const start = src.indexOf(`${name}() {`);
+ const end = src.indexOf('\n}\n', start);
+ if (start < 0 || end < 0) throw new Error(`Could not locate ${name}()`);
+ return src.slice(start, end + 2);
+}
+
+describe(':user render targets the out-dir, never the checkout (#2569)', () => {
+ test('setup renders gen:skill-docs:user with --out-dir only', () => {
+ const sites = SETUP_SRC.split('gen:skill-docs:user').length - 1;
+ const outDirSites = SETUP_SRC.split('gen:skill-docs:user --host claude --out-dir').length - 1;
+ // Every executable :user invocation carries --out-dir. (Prose/log
+ // mentions don't pair with `bun_cmd run`.)
+ const executableSites = SETUP_SRC.split('run gen:skill-docs:user').length - 1;
+ expect(executableSites).toBeGreaterThan(0);
+ expect(outDirSites).toBe(executableSites);
+ expect(sites).toBeGreaterThanOrEqual(outDirSites);
+ });
+
+ test('setup renders into a TMP dir, swaps on success, repoints after (never wipes first)', () => {
+ const block = SETUP_SRC.slice(
+ SETUP_SRC.indexOf('# ─── GBrain detection + conditional SKILL.md render'),
+ SETUP_SRC.indexOf('# 11. Plan-tune cathedral hook install'),
+ );
+ // The live render dir is symlinked into by installed skills — it may only
+ // be replaced AFTER a successful render (a pre-render wipe left every
+ // brain-aware SKILL.md link dangling on a transient render failure).
+ expect(block).toContain('--out-dir "$_GSTACK_RENDER_TMP"');
+ expect(block).not.toContain('--out-dir "$_GSTACK_RENDER_DIR"');
+ expect(block).toContain('_swap_in_render "$_GSTACK_RENDER_DIR" "$_GSTACK_RENDER_TMP"');
+ expect(block).toContain('link_claude_skill_dirs "$SOURCE_GSTACK_DIR" "$INSTALL_SKILLS_DIR"');
+ // Stale-render cleanup on the gbrain-gone path (a deliberate wipe).
+ expect(block).toContain('gbrain not detected');
+ expect(block).toContain('rm -rf "$_GSTACK_RENDER_DIR"');
+ });
+
+ test('gstack-config gbrain-refresh renders to a TMP out-dir, swaps on success', () => {
+ expect(CONFIG_SRC).toContain('gen:skill-docs:user --host claude --out-dir');
+ expect(CONFIG_SRC).not.toContain("this dirties the install's git tree");
+ expect(CONFIG_SRC).toContain('gstack-relink');
+ expect(CONFIG_SRC).toContain('--out-dir "$RENDER_TMP"');
+ expect(CONFIG_SRC).not.toContain('--out-dir "$RENDER_DIR"');
+ expect(CONFIG_SRC).toContain('_swap_in_render "$RENDER_DIR" "$RENDER_TMP"');
+ });
+
+ test('_swap_in_render behavior: success replaces, and the shape means failure never touches the live dir', () => {
+ // Both files carry the same-contract helper — drive each for real.
+ for (const src of [SETUP_SRC, CONFIG_SRC]) {
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-render-swap-'));
+ try {
+ const live = path.join(tmp, 'claude');
+ const fresh = path.join(tmp, 'claude.tmp.123');
+ fs.mkdirSync(path.join(live, 'ship'), { recursive: true });
+ fs.writeFileSync(path.join(live, 'ship', 'SKILL.md'), 'old-render\n');
+ fs.mkdirSync(path.join(fresh, 'ship'), { recursive: true });
+ fs.writeFileSync(path.join(fresh, 'ship', 'SKILL.md'), 'new-render\n');
+
+ const script = [
+ 'set -e',
+ extractFn(src, '_swap_in_render'),
+ `_swap_in_render "${live}" "${fresh}"`,
+ ].join('\n');
+ const r = spawnSync('bash', ['-c', script], { encoding: 'utf-8', timeout: 15_000 });
+ expect(r.status).toBe(0);
+ // Live dir now serves the fresh render at the SAME path (links into
+ // it stay valid), tmp and .old are gone.
+ expect(fs.readFileSync(path.join(live, 'ship', 'SKILL.md'), 'utf-8')).toBe('new-render\n');
+ expect(fs.existsSync(fresh)).toBe(false);
+ expect(fs.readdirSync(tmp)).toEqual(['claude']);
+ } finally {
+ fs.rmSync(tmp, { recursive: true, force: true });
+ }
+ }
+ });
+
+ test('a FAILED render leaves the previous render dir fully intact (gstack-config path, end-to-end shape)', () => {
+ // Reconstruct the exact failure branch: render into tmp fails → tmp is
+ // removed, the live dir (and the symlinks into it) are untouched, and
+ // _swap_in_render is never called.
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-render-fail-'));
+ try {
+ const live = path.join(tmp, 'claude');
+ fs.mkdirSync(path.join(live, 'ship'), { recursive: true });
+ fs.writeFileSync(path.join(live, 'ship', 'SKILL.md'), 'previous-render\n');
+ // An installed skill symlinks into the live render dir.
+ const installed = path.join(tmp, 'installed-ship-SKILL.md');
+ fs.symlinkSync(path.join(live, 'ship', 'SKILL.md'), installed);
+
+ const script = [
+ 'set -u',
+ extractFn(CONFIG_SRC, '_swap_in_render'),
+ `RENDER_DIR="${live}"`,
+ 'RENDER_TMP="$RENDER_DIR.tmp.$$"',
+ 'rm -rf "$RENDER_TMP"',
+ // The render fails (broken template, bun error, disk full).
+ 'if ( mkdir -p "$RENDER_TMP" && false ); then',
+ ' _swap_in_render "$RENDER_DIR" "$RENDER_TMP"',
+ 'else',
+ ' rm -rf "$RENDER_TMP"',
+ ' echo "render failed — previous render left in place" >&2',
+ 'fi',
+ ].join('\n');
+ const r = spawnSync('bash', ['-c', script], { encoding: 'utf-8', timeout: 15_000 });
+ expect(r.status).toBe(0);
+ expect(fs.readFileSync(path.join(live, 'ship', 'SKILL.md'), 'utf-8')).toBe('previous-render\n');
+ // The installed symlink still resolves — the skill set did not vanish.
+ expect(fs.readFileSync(installed, 'utf-8')).toBe('previous-render\n');
+ expect(fs.readdirSync(tmp).sort()).toEqual(['claude', 'installed-ship-SKILL.md']);
+ } finally {
+ fs.rmSync(tmp, { recursive: true, force: true });
+ }
+ });
+
+ test('gstack-relink prefers the render dir when a rendered SKILL.md exists', () => {
+ expect(RELINK_SRC).toContain('render/claude');
+ expect(RELINK_SRC).toContain('[ -f "$RENDER_DIR/$skill/SKILL.md" ] && skill_md_src="$RENDER_DIR/$skill/SKILL.md"');
+ });
+});
+
+describe('link_claude_skill_dirs prefers rendered SKILL.md (behavior)', () => {
+ test('a rendered variant is served; skills without one fall back to source', () => {
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-render-pref-'));
+ try {
+ const src = path.join(tmp, 'src');
+ const skills = path.join(tmp, 'skills');
+ const home = path.join(tmp, 'gstack-home');
+ // Source tree: two skills.
+ for (const s of ['alpha', 'beta']) {
+ fs.mkdirSync(path.join(src, s), { recursive: true });
+ fs.writeFileSync(
+ path.join(src, s, 'SKILL.md'),
+ `---\nname: ${s}\ndescription: t\n---\ncanonical-${s}\n`,
+ );
+ }
+ // Render exists for alpha only.
+ fs.mkdirSync(path.join(home, 'render', 'claude', 'alpha'), { recursive: true });
+ fs.writeFileSync(
+ path.join(home, 'render', 'claude', 'alpha', 'SKILL.md'),
+ '---\nname: alpha\ndescription: t\n---\nrendered-alpha with Brain Context Load\n',
+ );
+ fs.mkdirSync(skills, { recursive: true });
+
+ const script = [
+ 'set -e',
+ 'IS_WINDOWS=0',
+ 'SKILL_PREFIX=0',
+ '_WINDOWS_COPY_NOTE_PRINTED=1',
+ `GSTACK_HOME="${home}"`,
+ extractFn(SETUP_SRC, '_link_or_copy'),
+ extractFn(SETUP_SRC, '_print_windows_copy_note_once'),
+ extractFn(SETUP_SRC, '_link_skill_runtime_assets'),
+ extractFn(SETUP_SRC, 'link_claude_skill_dirs'),
+ `link_claude_skill_dirs "${src}" "${skills}"`,
+ ].join('\n');
+ const r = spawnSync('bash', ['-c', script], { encoding: 'utf-8', timeout: 15_000 });
+ expect(r.status).toBe(0);
+
+ expect(fs.readFileSync(path.join(skills, 'alpha', 'SKILL.md'), 'utf-8')).toContain('rendered-alpha');
+ expect(fs.readFileSync(path.join(skills, 'beta', 'SKILL.md'), 'utf-8')).toContain('canonical-beta');
+ // The SOURCE stayed canonical — the render is served via the link only.
+ expect(fs.readFileSync(path.join(src, 'alpha', 'SKILL.md'), 'utf-8')).toContain('canonical-alpha');
+ } finally {
+ fs.rmSync(tmp, { recursive: true, force: true });
+ }
+ });
+});
+
+describe('migration v1.67.0.0 — legacy in-place render cleanup (F12)', () => {
+ function git(cwd: string, ...args: string[]): void {
+ const r = spawnSync('git', args, { cwd, encoding: 'utf-8' });
+ if (r.status !== 0) throw new Error(`git ${args.join(' ')} failed: ${r.stderr}`);
+ }
+
+ function makeLegacyInstall(tmp: string): string {
+ const install = path.join(tmp, 'install');
+ fs.mkdirSync(path.join(install, 'ship', 'sections'), { recursive: true });
+ fs.writeFileSync(path.join(install, 'VERSION'), '1.66.0.0\n');
+ fs.writeFileSync(path.join(install, 'ship', 'SKILL.md'), 'canonical ship\n');
+ fs.writeFileSync(path.join(install, 'ship', 'sections', 'tests.md'), 'canonical section\n');
+ fs.writeFileSync(path.join(install, 'README.md'), 'readme\n');
+ git(install, 'init', '-b', 'main');
+ git(install, 'config', 'user.email', '[email protected]');
+ git(install, 'config', 'user.name', 't');
+ git(install, 'add', '-A');
+ git(install, 'commit', '-m', 'base', '-q');
+ return install;
+ }
+
+ function runMigration(install: string): { status: number | null; stdout: string } {
+ const r = spawnSync('bash', [MIGRATION], {
+ encoding: 'utf-8',
+ env: { ...process.env, GSTACK_INSTALL_DIR: install },
+ timeout: 15_000,
+ });
+ return { status: r.status, stdout: r.stdout };
+ }
+
+ test('restores render-class dirt, leaves user changes alone, idempotent', () => {
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-migration-'));
+ try {
+ const install = makeLegacyInstall(tmp);
+ // Legacy render dirt + a genuine user edit + an untracked file.
+ fs.writeFileSync(path.join(install, 'ship', 'SKILL.md'), 'brain-aware rendered ship\n');
+ fs.writeFileSync(path.join(install, 'ship', 'sections', 'tests.md'), 'brain-aware section\n');
+ fs.writeFileSync(path.join(install, 'README.md'), 'user edit\n');
+ fs.writeFileSync(path.join(install, 'notes.txt'), 'untracked\n');
+
+ const r1 = runMigration(install);
+ expect(r1.status).toBe(0);
+ expect(r1.stdout).toContain('restored 2 tracked file(s)');
+ expect(fs.readFileSync(path.join(install, 'ship', 'SKILL.md'), 'utf-8')).toBe('canonical ship\n');
+ expect(fs.readFileSync(path.join(install, 'ship', 'sections', 'tests.md'), 'utf-8')).toBe('canonical section\n');
+ // The user's own edits are NOT the render footprint — untouched, reported.
+ expect(fs.readFileSync(path.join(install, 'README.md'), 'utf-8')).toBe('user edit\n');
+ expect(fs.existsSync(path.join(install, 'notes.txt'))).toBe(true);
+ expect(r1.stdout).toContain('left');
+
+ // Idempotent: nothing left in the footprint on the second run.
+ const r2 = runMigration(install);
+ expect(r2.status).toBe(0);
+ expect(r2.stdout).not.toContain('restored');
+ } finally {
+ fs.rmSync(tmp, { recursive: true, force: true });
+ }
+ });
+
+ test('clean checkout, missing dir, and symlinked install are all silent no-ops', () => {
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-migration-noop-'));
+ try {
+ const install = makeLegacyInstall(tmp);
+ const clean = runMigration(install);
+ expect(clean.status).toBe(0);
+ expect(clean.stdout.trim()).toBe('');
+
+ const missing = runMigration(path.join(tmp, 'does-not-exist'));
+ expect(missing.status).toBe(0);
+
+ const link = path.join(tmp, 'symlinked-install');
+ fs.symlinkSync(install, link);
+ const sym = runMigration(link);
+ expect(sym.status).toBe(0);
+ expect(sym.stdout.trim()).toBe('');
+ } finally {
+ fs.rmSync(tmp, { recursive: true, force: true });
+ }
+ });
+});