Merge origin/main (v1.67.0.0) — reconcile convergent iOS Release-guard fixes

main's v1.67.0.0 independently landed the DebugBridgeTouch Release compile-out
with a stronger shape (`#if !defined(DEBUG)` short-circuit before the platform
gate, measured via nm -j on a real Release binary) than this branch's
`#if TARGET_OS_IOS && DEBUG`. Resolution: take main's templates/fixtures, keep
this branch's free-tier static tripwire and adapt it to pin main's shape
(short-circuit present, ordered before the platform branch, cSettings DEBUG
define intact, no bare platform-only gate). VERSION/package.json stay 1.67.1.0;
CHANGELOG keeps both entries with 1.67.1.0 on top, its iOS claims reworded to
the residual contribution (the tripwire, not the compile-out itself).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Garry Tan
2026-08-16 20:18:43 -07:00
co-authored by Claude Fable 5
246 changed files with 13732 additions and 2289 deletions
+1
View File
@@ -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.
+5
View File
@@ -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/*
+1 -1
View File
@@ -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/actionlint@v1.7.11 (a Docker
+6 -6
View File
@@ -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
+2 -2
View File
@@ -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
+8 -8
View File
@@ -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
+10 -10
View File
@@ -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
@@ -341,7 +341,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
@@ -362,12 +362,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
+4 -4
View File
@@ -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
+1 -1
View File
@@ -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:
+1 -1
View File
@@ -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
+1 -1
View File
@@ -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
+1 -1
View File
@@ -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
+1 -1
View File
@@ -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
+1 -1
View File
@@ -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 }}
+7 -4
View File
@@ -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
+3 -3
View File
@@ -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') }}
+8 -8
View File
@@ -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
+39 -11
View File
@@ -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 (1000060000), generates a bearer token, writes the state
file (chmod 600), starts accepting requests. ~3 seconds.
random port (1000049151, 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 (1000060000) |
| `/code/project-b` | `/code/project-b/.gstack/browse.json` | random (1000060000) |
| `/code/project-a` | `/code/project-a/.gstack/browse.json` | random (1000049151) |
| `/code/project-b` | `/code/project-b/.gstack/browse.json` | random (1000049151) |
---
@@ -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 (1000060000) |
| `/code/project-b` | `/code/project-b/.gstack/browse.json` | random (1000060000) |
| `/code/project-a` | `/code/project-a/.gstack/browse.json` | random (1000049151) |
| `/code/project-b` | `/code/project-b/.gstack/browse.json` | random (1000049151) |
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 1000060000) | Fixed port for the HTTP server (debug override) |
| `BROWSE_PORT` | 0 (random 1000049151) | 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
+194 -3
View File
@@ -7,7 +7,7 @@
gstack ran an explicit security sweep over all external-contributor code merged since mid-June: the seven directly-merged `time-attack` PRs, the two fork-port squash waves, and the roughly fifty absorbed community PRs. About 38,000 lines across ~500 files, read with an adversarial eye. The verdict up front: no backdoor, no exfiltration path, no live secret leak. The contributions are net security-strengthening. This release hardens the six real findings the sweep confirmed and locks each one behind a regression test, so the property it protects holds by construction, not by luck.
The pre-push secret scanner now catches all-caps database passwords. Persisted browser sessions stay out of git whether or not your repo has a `.gitignore`. The App Store Connect key the release flow mints is scoped to the one app you are shipping, and the exit report tells you it exists and how to revoke it. The iOS test bridge's private touch APIs compile out of Release builds. The browser server's Node spawn shim has its `exited`/drain/memory-cap contract back. Bearer-token comparison is constant-time.
The pre-push secret scanner now catches all-caps database passwords. Persisted browser sessions stay out of git whether or not your repo has a `.gitignore`. The App Store Connect key the release flow mints is scoped to the one app you are shipping, and the exit report tells you it exists and how to revoke it. The iOS test bridge's Release compile-out (shipped in v1.67.0.0) is now pinned by a free-tier tripwire that fails CI on any regression to a platform-only gate. The browser server's Node spawn shim has its `exited`/drain/memory-cap contract back. Bearer-token comparison is constant-time.
### The numbers that matter
@@ -19,7 +19,7 @@ Source: a two-wave read-only audit (72 agents, two independent verifiers per fin
| `postgresql://USER:PASSWORD@host` doc placeholder | skipped | still skipped (pinned) |
| Persisted session cookies in a `.gitignore`-less repo | git-committable | ignored by construction |
| Minted App Store Connect key scope | every app on the team | the one app being shipped |
| iOS private-API touch code in a Release build | compiled in | compiled out (`#if DEBUG`) |
| iOS Release compile-out guard (shipped v1.67.0.0) | unpinned | CI tripwire on any regression |
| `await proc.exited` on the Windows Node fallback | resolved `undefined` | resolves the real exit code |
| Loopback bearer-token comparison | byte-by-byte `===` | constant-time |
@@ -35,7 +35,7 @@ If you run gstack from a build that pulled in community or fork-ported code, thi
- The pre-push credential scanner blocks a DSN whose password is a real all-caps secret (`PROD2026SECRET`-style) at the HIGH tier. The `USER:PASSWORD` documentation convention still suppresses, pinned in both directions with a table-driven test over the full placeholder set. (`lib/redact-patterns.ts`)
- The browse state directory (`.gstack/`) carries a self-contained `.gitignore` written unconditionally when the directory is created, so persisted `session-state.json` cookies and `browse-network.log` / `browse-audit.jsonl` request headers can never be committed, regardless of the project's own `.gitignore`. (`browse/src/config.ts`)
- The Node `Bun.spawn` polyfill regains its `exited` promise, eager stdout/stderr drain, and 16MB output cap, restoring correct child-process handling on the Windows Node fallback (cookie import, browser-skill children). (`browse/src/bun-polyfill.cjs`)
- The iOS QA touch bridge's private UIKit/IOKit synthesis is gated `#if TARGET_OS_IOS && DEBUG` with a matching `cSettings` DEBUG define, so it compiles out of Release builds. (`ios-qa/templates/`)
- The iOS QA touch bridge's Release compile-out (the `#if !defined(DEBUG)` short-circuit plus the `cSettings` DEBUG define, shipped in v1.67.0.0) is pinned by a free-tier static tripwire: any regression to a platform-only gate, a reordered guard, or a dropped define fails CI on every PR. (`test/ios-debug-bridge-release-guard.test.ts`)
- Loopback bearer-token comparison in the browse server is constant-time. (`browse/src/server.ts`)
#### Changed
@@ -44,6 +44,197 @@ If you run gstack from a build that pulled in community or fork-ported code, thi
#### For contributors
- New regression guards pin each security property against a silent revert: a static tripwire for the constant-time `validateAuth`, a table-driven suppression test over the exported `URL_PASSWORD_PLACEHOLDER_WORDS`, an unconditional-write test for the state-dir ignore, a static tripwire for the iOS Release compile-out, and the restored `Bun.spawn` contract tests.
## [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
+29 -7
View File
@@ -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
+13 -6
View File
@@ -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
+18 -3
View File
@@ -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.
+12 -6
View File
@@ -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
+179 -30
View File
@@ -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)
### P3: Residuals from the 2026-08-14 tracker-audit waves (mostly shipped in v1.67.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.
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:
**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.
- 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.
+26 -14
View File
@@ -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"
+10 -4
View File
@@ -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"
+12 -6
View File
@@ -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
+12 -6
View File
@@ -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
+11
View File
@@ -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"},
+77 -4
View File
@@ -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
+212 -21
View File
@@ -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
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
# #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
compute_paths_to_stage "$mode" > "$paths_file"
# 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; }
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" "$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
+113 -4
View File
@@ -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"
+53 -16
View File
@@ -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
;;
*)
+174 -72
View File
@@ -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
# 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 ;;
*.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
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"
# Prompts: prompt builders, system prompts, generation services
case "$f" in
*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
# 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
+22 -18
View File
@@ -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();
+38 -2
View File
@@ -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
+127 -39
View File
@@ -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);
+14 -2
View File
@@ -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++;
}
}
}
+152 -47
View File
@@ -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) {
+128 -7
View File
@@ -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));
+21 -2
View File
@@ -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
+9 -1
View File
@@ -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
+3 -1
View File
@@ -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;
+12 -2
View File
@@ -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)
+17 -3
View File
@@ -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.
#
# 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 [ ! -d "$HOME/.claude/skills/gstack/bin" ]; then
if [ -z "$_GSTACK_ROOT" ]; then
cat >&2 <<'MSG'
BLOCKED: gstack is not installed globally.
+130 -9
View File
@@ -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[*]}"
+323 -47
View File
@@ -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);
const pin = join(cwd, ".gstack", "version-path");
if (existsSync(pin)) {
const p = readFileSync(pin, "utf-8").trim();
if (p) return join(cwd, p);
/**
* 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);
}
return join(cwd, "VERSION");
}
function readVersionFile(p: string): string {
/**
* 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").split("\n")[0]?.trim() ?? "";
if (p) {
assertRepoContained(cwd, p, ".gstack/version-path");
return p;
}
}
return "VERSION";
}
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"));
writeFileSync(versionPath, version + "\n");
if (existsSync(join(cwd, "package.json"))) {
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 {
writePkgVersion(cwd, version!);
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(
"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.",
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");
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(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(
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).
+24 -6
View File
@@ -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
+12
View File
@@ -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
+6
View File
@@ -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..."
+1 -1
View File
@@ -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');
+37 -6
View File
@@ -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.`;
+117 -65
View File
@@ -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) ───────────────────────
/**
+1 -1
View File
@@ -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;
+41 -3
View File
@@ -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,
+7
View File
@@ -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',
+265 -24
View File
@@ -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);
}
// Truly dead (or health never recovered) → restart.
if (action === 'report-busy') {
reportDaemonBusyAndExit(oldState!.pid);
}
// #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
+30 -16
View File
@@ -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';
}
}
+1
View File
@@ -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;
+1 -1
View File
@@ -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;
+2 -2
View File
@@ -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;
+140
View File
@@ -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);
}
+1 -1
View File
@@ -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 {
+3
View File
@@ -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");
+13 -94
View File
@@ -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.
+23 -121
View File
@@ -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
@@ -2005,10 +1904,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
+32 -5
View File
@@ -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);
});
+438
View File
@@ -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;
}
}
@@ -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);
});
});
+12 -2
View File
@@ -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);
});
+232
View File
@@ -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);
});
+12
View File
@@ -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.
+8
View File
@@ -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 });
+135
View File
@@ -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 });
}
});
});
+74
View File
@@ -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');
});
});
+62
View File
@@ -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');
});
});
+22 -16
View File
@@ -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.
+7 -57
View File
@@ -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 ───────────────────────────────────
@@ -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);
});
});
+7 -1
View File
@@ -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.
});
+144
View File
@@ -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);
});
@@ -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\)/);
});
});
+68 -2
View File
@@ -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([]);
});
});
+457
View File
@@ -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:');
});
});
@@ -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');
+16 -153
View File
@@ -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": {
"playwright-core@1.62.1": "patches/playwright-core@1.62.1.patch",
},
"overrides": {
"basic-ftp": "5.3.1",
"adm-zip": "^0.6.0",
},
"packages": {
"@anthropic-ai/claude-agent-sdk": ["@anthropic-ai/claude-agent-sdk@0.2.117", "", { "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/tokenizers@0.1.3", "", {}, "sha512-8rF/RRT10u+kn7YuUbUg0OF30K8rjTc78aHpxT+qJ1uWSqxT1MHi8+9ltwYfkFYJzT/oS+qw3JVfHtNMGAdqyA=="],
"@huggingface/transformers": ["@huggingface/transformers@4.1.0", "", { "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/transformers@4.2.0", "", { "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/colour@1.1.0", "", {}, "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ=="],
@@ -166,54 +169,22 @@
"@protobufjs/utf8": ["@protobufjs/utf8@1.1.0", "", {}, "sha512-Vvn3zZrhQZkkBE8LSuW3em98c0FwgO4nxzv6OdSxPKJIEKY2bGbHn+mhGIPerzI4twdxaP8/0+06HBpwf345Lw=="],
"@puppeteer/browsers": ["@puppeteer/browsers@2.13.0", "", { "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/quickjs-emscripten@0.23.0", "", {}, "sha512-C5Mc6rdnsaJDjO3UpGW/CQTHtCKaYlScZTly4JIu97Jxo/odCiH0ITnDXSJPTOrEKk/ycSZ0AOgTmkDtkOsvIA=="],
"@types/node": ["@types/node@25.5.0", "", { "dependencies": { "undici-types": "~7.18.0" } }, "sha512-jp2P3tQMSxWugkCUKLRPVUpGaL5MVFwF8RDuSRztfwgN1wmqJeMSbKlnEtQqU8UrhTmzEmZdu2I6v2dpp7XIxw=="],
"@types/yauzl": ["@types/yauzl@2.10.3", "", { "dependencies": { "@types/node": "*" } }, "sha512-oJoftv0LSuaDZE3Le4DbKX+KS9G36NzOeSap90UIK0yMA/NhKJhqlSGtNDORNRaIbQfzjXDrQa0ytJ6mNRGz/Q=="],
"accepts": ["accepts@2.0.0", "", { "dependencies": { "mime-types": "^3.0.0", "negotiator": "^1.0.0" } }, "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng=="],
"adm-zip": ["adm-zip@0.5.17", "", {}, "sha512-+Ut8d9LLqwEvHHJl1+PIHqoyDxFgVN847JTVM3Izi3xHDWPE4UtzzXysMZQs64DMcrJfBeS/uoEP4AD3HQHnQQ=="],
"agent-base": ["agent-base@7.1.4", "", {}, "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ=="],
"adm-zip": ["adm-zip@0.6.0", "", {}, "sha512-XleryMhbuksdKtofnWZ9Sk+4CUTbms4Mb/EU32SZwToAyZ5RgVos/ki8n+yr0LWHOGKuakbXTuuYNHLQjhddgg=="],
"ajv": ["ajv@8.18.0", "", { "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": ["ajv-formats@3.0.1", "", { "dependencies": { "ajv": "^8.0.0" } }, "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ=="],
"ansi-regex": ["ansi-regex@5.0.1", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="],
"ansi-styles": ["ansi-styles@4.3.0", "", { "dependencies": { "color-convert": "^2.0.1" } }, "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg=="],
"ast-types": ["ast-types@0.13.4", "", { "dependencies": { "tslib": "^2.0.1" } }, "sha512-x1FCFnFifvYDDzTaLII71vG5uvDwgtmDTEVWAxrgeiR8VjMONcCXJx7E+USjDtHlwFmt9MysbqgF9b9Vjr6w+w=="],
"b4a": ["b4a@1.8.0", "", { "peerDependencies": { "react-native-b4a": "*" }, "optionalPeers": ["react-native-b4a"] }, "sha512-qRuSmNSkGQaHwNbM7J78Wwy+ghLEYF1zNrSeMxj4Kgw6y33O3mXcQ6Ie9fRvfU/YnxWkOchPXbaLb73TkIsfdg=="],
"bare-events": ["bare-events@2.8.2", "", { "peerDependencies": { "bare-abort-controller": "*" }, "optionalPeers": ["bare-abort-controller"] }, "sha512-riJjyv1/mHLIPX4RwiK+oW9/4c3TEUeORHKefKAKnZ5kyslbN+HXowtbaVEqt4IMUB7OXlfixcs6gsFeo/jhiQ=="],
"bare-fs": ["bare-fs@4.5.6", "", { "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": ["bare-os@3.8.1", "", {}, "sha512-6g8rIdyQqYL6XbghpOgS8AOSvWQUf0zT0XaYUrJIX5VugpCGUyJaz1zfcKCecOnUkI76oVJXuHg1LMGYVXTvKw=="],
"bare-path": ["bare-path@3.0.0", "", { "dependencies": { "bare-os": "^3.0.1" } }, "sha512-tyfW2cQcB5NN8Saijrhqn0Zh7AnFNsnczRcuWODH0eYAXBsJ5gVxAUuNr7tsHSC6IZ77cA0SitzT+s47kot8Mw=="],
"bare-stream": ["bare-stream@2.11.0", "", { "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": ["bare-url@2.4.0", "", { "dependencies": { "bare-path": "^3.0.0" } }, "sha512-NSTU5WN+fy/L0DDenfE8SXQna4voXuW0FHM7wH8i3/q9khUSchfPbPezO4zSFMnDGIf9YE+mt/RWhZgNRKRIXA=="],
"basic-ftp": ["basic-ftp@5.3.1", "", {}, "sha512-bopVNp6ugyA150DDuZfPFdt1KZ5a94ZDiwX4hMgZDzF+GttD80lEy8kj98kbyhLXnPvhtIo93mdnLIjpCAeeOw=="],
"body-parser": ["body-parser@2.2.2", "", { "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": ["boolean@3.2.0", "", {}, "sha512-d0II/GO9uf9lfUHH2BQsjxzRJZBdsjgsBiW4BvhWk/3qoKwQFjIDVN19PfX8F2D/r9PCMTtLWjYVCFrpeYUzsw=="],
"browser-split": ["browser-split@0.0.1", "", {}, "sha512-JhvgRb2ihQhsljNda3BI8/UcRHVzrVwo3Q+P8vDtSiyobXuFpuZ9mq+MbRGMnC22CjW3RrfXdg6j6ITX8M+7Ow=="],
"buffer-crc32": ["buffer-crc32@0.2.13", "", {}, "sha512-VO9Ht/+p3SN7SKWqcrgEzjGbRSJYTx+Q1pTQC0wrWqHx0vpJraQ6GtHx8tvcg1rlK1byhU5gccxgOgj7B0TDkQ=="],
"bytes": ["bytes@3.1.2", "", {}, "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg=="],
"call-bind-apply-helpers": ["call-bind-apply-helpers@1.0.2", "", { "dependencies": { "es-errors": "^1.3.0", "function-bind": "^1.1.2" } }, "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ=="],
@@ -222,12 +193,6 @@
"camelize": ["camelize@1.0.1", "", {}, "sha512-dU+Tx2fsypxTgtLoE36npi3UqcjSSMNYfkqgmoEhtZrraP5VWq0K7FkWVTYa8eMPtnU/G2txVsfdCJTn9uzpuQ=="],
"chromium-bidi": ["chromium-bidi@14.0.0", "", { "dependencies": { "mitt": "^3.0.1", "zod": "^3.24.1" }, "peerDependencies": { "devtools-protocol": "*" } }, "sha512-9gYlLtS6tStdRWzrtXaTMnqcM4dudNegMXJxkR0I/CXObHalYeYcAMPrL19eroNZHtJ8DQmu1E+ZNOYu/IXMXw=="],
"cliui": ["cliui@8.0.1", "", { "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": ["color-convert@2.0.1", "", { "dependencies": { "color-name": "~1.1.4" } }, "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ=="],
"color-name": ["color-name@1.1.4", "", {}, "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA=="],
"content-disposition": ["content-disposition@1.1.0", "", {}, "sha512-5jRCH9Z/+DRP7rkvY83B+yGIGX96OYdJmzngqnw2SBSxqCFPd0w2km3s5iawpGX8krnwSGmF0FW5Nhr0Hfai3g=="],
@@ -244,24 +209,18 @@
"cross-spawn": ["cross-spawn@7.0.6", "", { "dependencies": { "path-key": "^3.1.0", "shebang-command": "^2.0.0", "which": "^2.0.1" } }, "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA=="],
"data-uri-to-buffer": ["data-uri-to-buffer@6.0.2", "", {}, "sha512-7hvf7/GW8e86rW0ptuwS3OcBGDjIi6SZva7hCyWC0yYry2cOPmLIjXAUHI6DK2HsnwJd9ifmt57i8eV2n4YNpw=="],
"debug": ["debug@4.4.3", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="],
"define-data-property": ["define-data-property@1.1.4", "", { "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": ["define-properties@1.2.1", "", { "dependencies": { "define-data-property": "^1.0.1", "has-property-descriptors": "^1.0.0", "object-keys": "^1.1.1" } }, "sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg=="],
"degenerator": ["degenerator@5.0.1", "", { "dependencies": { "ast-types": "^0.13.4", "escodegen": "^2.1.0", "esprima": "^4.0.1" } }, "sha512-TllpMR/t0M5sqCXfj85i4XaAzxmS5tVA16dqvdkMwGmzI+dXLXnw3J+3Vdv7VKw+ThlTMboK6i9rnZ6Nntj5CQ=="],
"depd": ["depd@2.0.0", "", {}, "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw=="],
"detect-libc": ["detect-libc@2.1.2", "", {}, "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ=="],
"detect-node": ["detect-node@2.1.0", "", {}, "sha512-T0NIuQpnTvFDATNuHN5roPwSBG83rFsuO+MXXH9/3N1eFbn4wcPjttvjMLEPWJ0RGUYgQE7cGgS3tNxbqCGM7g=="],
"devtools-protocol": ["devtools-protocol@0.0.1581282", "", {}, "sha512-nv7iKtNZQshSW2hKzYNr46nM/Cfh5SEvE2oV0/SEGgc9XupIY5ggf84Cz8eJIkBce7S3bmTAauFD6aysMpnqsQ=="],
"diff": ["diff@9.0.0", "", {}, "sha512-svtcdpS8CgJyqAjEQIXdb3OjhFVVYjzGAPO8WGCmRbrml64SPw/jJD4GoE98aR7r25A0XcgrK3F02yw9R/vhQw=="],
"dom-serializer": ["dom-serializer@0.2.2", "", { "dependencies": { "domelementtype": "^2.0.1", "entities": "^2.0.0" } }, "sha512-2/xPb3ORsQ42nHYiSunXkDjPLBaEj/xTwUO4B7XCZQTRk7EBtTOPaygh10YAAh2OI1Qrp6NWfpAhzswj0ydt9g=="],
@@ -278,12 +237,8 @@
"ee-first": ["ee-first@1.1.1", "", {}, "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow=="],
"emoji-regex": ["emoji-regex@8.0.0", "", {}, "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A=="],
"encodeurl": ["encodeurl@2.0.0", "", {}, "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg=="],
"end-of-stream": ["end-of-stream@1.4.5", "", { "dependencies": { "once": "^1.4.0" } }, "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg=="],
"ent": ["ent@2.2.2", "", { "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": ["entities@1.1.2", "", {}, "sha512-f2LZMYl1Fzu7YSBKg+RoROelpOaNrcGmE9AZubeDfrCEia483oW4MI4VyFd5VNHIgQ/7qm1I0wUHK1eJnn2y2w=="],
@@ -298,26 +253,14 @@
"es6-error": ["es6-error@4.1.1", "", {}, "sha512-Um/+FxMr9CISWh0bi5Zv0iOD+4cFh5qLeks1qhAopKVAJw3drgKbKySikp7wGhDL0HPeaja0P5ULZrxLkniUVg=="],
"escalade": ["escalade@3.2.0", "", {}, "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA=="],
"escape-html": ["escape-html@1.0.3", "", {}, "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow=="],
"escape-string-regexp": ["escape-string-regexp@4.0.0", "", {}, "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA=="],
"escodegen": ["escodegen@2.1.0", "", { "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": ["esprima@4.0.1", "", { "bin": { "esparse": "./bin/esparse.js", "esvalidate": "./bin/esvalidate.js" } }, "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A=="],
"estraverse": ["estraverse@5.3.0", "", {}, "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA=="],
"esutils": ["esutils@2.0.3", "", {}, "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g=="],
"etag": ["etag@1.8.1", "", {}, "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg=="],
"ev-store": ["ev-store@7.0.0", "", { "dependencies": { "individual": "^3.0.0" } }, "sha512-otazchNRnGzp2YarBJ+GXKVGvhxVATB1zmaStxJBYet0Dyq7A9VhH8IUEB/gRcL6Ch52lfpgPTRJ2m49epyMsQ=="],
"events-universal": ["events-universal@1.0.1", "", { "dependencies": { "bare-events": "^2.7.0" } }, "sha512-LUd5euvbMLpwOF8m6ivPCbhQeSiYVNb8Vs0fQ8QjXo0JTkEHpz8pxdQf0gStltaPpw0Cca8b39KxvK9cfKRiAw=="],
"eventsource": ["eventsource@3.0.7", "", { "dependencies": { "eventsource-parser": "^3.0.1" } }, "sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA=="],
"eventsource-parser": ["eventsource-parser@3.0.8", "", {}, "sha512-70QWGkr4snxr0OXLRWsFLeRBIRPuQOvt4s8QYjmUlmlkyTZkRqS7EDVRZtzU3TiyDbXSzaOeF0XUKy8PchzukQ=="],
@@ -326,16 +269,10 @@
"express-rate-limit": ["express-rate-limit@8.3.2", "", { "dependencies": { "ip-address": "10.1.0" }, "peerDependencies": { "express": ">= 4.11" } }, "sha512-77VmFeJkO0/rvimEDuUC5H30oqUC4EyOhyGccfqoLebB0oiEYfM7nwPrsDsBL1gsTpwfzX8SFy2MT3TDyRq+bg=="],
"extract-zip": ["extract-zip@2.0.1", "", { "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": ["fast-deep-equal@3.1.3", "", {}, "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q=="],
"fast-fifo": ["fast-fifo@1.3.2", "", {}, "sha512-/d9sfos4yxzpwkDkuN7k2SqFKtYNmCTzgfEpz82x34IM9/zc8KGxQoXg1liNC/izpRM/MBdt44Nmx41ZWqk+FQ=="],
"fast-uri": ["fast-uri@3.1.0", "", {}, "sha512-iPeeDKJSWf4IEOasVVrknXpaBV0IApz/gp7S2bb7Z4Lljbl2MGJRqInZiUrQwV16cpzw/D3S5j5Julj/gT52AA=="],
"fd-slicer": ["fd-slicer@1.1.0", "", { "dependencies": { "pend": "~1.2.0" } }, "sha512-cE1qsB/VwyQozZ+q1dGxR8LBYNZeofhEdUNGSMbQD3Gw2lAzX9Zb3uIU6Ebc/Fmyjo9AWWfnn0AUCHqtevs/8g=="],
"finalhandler": ["finalhandler@2.1.1", "", { "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": ["flatbuffers@25.9.23", "", {}, "sha512-MI1qs7Lo4Syw0EOzUl0xjs2lsoeqFku44KpngfIduHBYvzm8h2+7K8YMQh1JtVVVrUvhLpNwqVi4DERegUJhPQ=="],
@@ -348,16 +285,10 @@
"function-bind": ["function-bind@1.1.2", "", {}, "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA=="],
"get-caller-file": ["get-caller-file@2.0.5", "", {}, "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg=="],
"get-intrinsic": ["get-intrinsic@1.3.0", "", { "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": ["get-proto@1.0.1", "", { "dependencies": { "dunder-proto": "^1.0.1", "es-object-atoms": "^1.0.0" } }, "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g=="],
"get-stream": ["get-stream@5.2.0", "", { "dependencies": { "pump": "^3.0.0" } }, "sha512-nBF+F1rAZVCu/p7rjzgA+Yb4lfYXrpl7a6VmJrU8wF9I1CKvP/QwPNZHnOlwbTkY6dvtFIzFMSyQXbLoTQPRpA=="],
"get-uri": ["get-uri@6.0.5", "", { "dependencies": { "basic-ftp": "^5.0.2", "data-uri-to-buffer": "^6.0.2", "debug": "^4.3.4" } }, "sha512-b1O07XYq8eRuVzBNgJLstU6FYc1tS6wnMtF1I1D9lE8LxZSOGZ7LhxN54yPP6mGw5f2CkXY2BQUL9Fx41qvcIg=="],
"global": ["global@4.4.0", "", { "dependencies": { "min-document": "^2.19.0", "process": "^0.11.10" } }, "sha512-wv/LAoHdRE3BeTGz53FAamhGlPLhlssK45usmGFThIi4XqnBmjKQ16u+RNbP7WvigRZDxUsM0J3gcQ5yicaL0w=="],
"global-agent": ["global-agent@3.0.0", "", { "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": ["http-errors@2.0.1", "", { "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": ["http-proxy-agent@7.0.2", "", { "dependencies": { "agent-base": "^7.1.0", "debug": "^4.3.4" } }, "sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig=="],
"https-proxy-agent": ["https-proxy-agent@7.0.6", "", { "dependencies": { "agent-base": "^7.1.2", "debug": "4" } }, "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw=="],
"iconv-lite": ["iconv-lite@0.7.2", "", { "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" } }, "sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw=="],
"image-size": ["image-size@1.2.1", "", { "dependencies": { "queue": "6.0.2" }, "bin": { "image-size": "bin/image-size.js" } }, "sha512-rH+46sQJ2dlwfjfhCyNx5thzrv+dtmBIhPHk0zgRUukHzZ/kRueTJXoYYsclBaKcSMBWuGbOFXtioLpzTb5euw=="],
@@ -408,8 +335,6 @@
"ipaddr.js": ["ipaddr.js@1.9.1", "", {}, "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g=="],
"is-fullwidth-code-point": ["is-fullwidth-code-point@3.0.0", "", {}, "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg=="],
"is-object": ["is-object@1.0.2", "", {}, "sha512-2rRIahhZr2UWb45fIOuvZGpFtz0TyOZLf32KxBbSoUCeZR495zCKlWUKKUByk3geS2eAs7ZAABt0Y/Rx0GiQGA=="],
"is-promise": ["is-promise@4.0.0", "", {}, "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ=="],
@@ -438,9 +363,7 @@
"long": ["long@5.3.2", "", {}, "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA=="],
"lru-cache": ["lru-cache@7.18.3", "", {}, "sha512-jumlc0BIUrS3qJGgIkWZsyfAM7NCWiBcCDhnd+3NNM5KbBmLTgHVfWBcg6W+rLUsIpzpERPsvwUP7CckAQSOoA=="],
"marked": ["marked@18.0.2", "", { "bin": { "marked": "bin/marked.js" } }, "sha512-NsmlUYBS/Zg57rgDWMYdnre6OTj4e+qq/JS2ot3KrYLSoHLw+sDu0Nm1ZGpRgYAq6c+b1ekaY5NzVchMCQnzcg=="],
"marked": ["marked@18.0.9", "", { "bin": { "marked": "bin/marked.js" } }, "sha512-/Sa4qiiHZxf0/FQdBBowr9q4r10krCwMvpK48FUBdXdUXScDxiQGR9zCPrFgRVR5LU3iySOiIjy09ZQvADir1w=="],
"matcher": ["matcher@3.0.0", "", { "dependencies": { "escape-string-regexp": "^4.0.0" } }, "sha512-OkeDaAZ/bQCxeFAozM55PKcKU0yJMPGifLwV4Qgjitu+5MoAfSQN4lsLJeXZ1b8w0x+/Emda6MZgXS1jvsapng=="],
@@ -456,16 +379,12 @@
"min-document": ["min-document@2.19.2", "", { "dependencies": { "dom-walk": "^0.1.0" } }, "sha512-8S5I8db/uZN8r9HSLFVWPdJCvYOejMcEC82VIzNUc6Zkklf/d1gg2psfE79/vyhWOj4+J8MtwmoOz3TmvaGu5A=="],
"mitt": ["mitt@3.0.1", "", {}, "sha512-vKivATfr97l2/QBCYAkXYDbrIWPM2IIKEl7YPhjCvKlG3kE2gm+uBo6nEXK3M5/Ffh/FLpKExzOQ3JJoJGFKBw=="],
"ms": ["ms@2.1.3", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="],
"nanoid": ["nanoid@3.3.12", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-ZB9RH/39qpq5Vu6Y+NmUaFhQR6pp+M2Xt76XBnEwDaGcVAqhlvxrl3B2bKS5D3NH3QR76v3aSrKaF/Kiy7lEtQ=="],
"negotiator": ["negotiator@1.0.0", "", {}, "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg=="],
"netmask": ["netmask@2.0.2", "", {}, "sha512-dBpDMdxv9Irdq66304OLfEmQ9tbNRFnFTuZiLo+bD+r332bBmMJ8GBLXklIXXgxd3+v9+KUnZaUR5PJMa75Gsg=="],
"next-tick": ["next-tick@0.2.2", "", {}, "sha512-f7h4svPtl+QidoBv4taKXUjJ70G2asaZ8G28nS0OkqaalX8dwwrtWtyxEDPK62AC00ur/+/E0pUwBwY5EPn15Q=="],
"node-fetch": ["node-fetch@2.7.0", "", { "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": ["onnxruntime-node@1.24.3", "", { "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": ["onnxruntime-web@1.26.0-dev.20260410-5e55544225", "", { "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": ["pac-proxy-agent@7.2.0", "", { "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": ["pac-resolver@7.0.1", "", { "dependencies": { "degenerator": "^5.0.0", "netmask": "^2.0.2" } }, "sha512-5NPgf87AT2STgwa2ntRMr45jTKrYBGkVU36yT0ig/n/GMAa3oPqhZfIQ2kMEimReg0+t9kZViDVZ83qfVUlckg=="],
"onnxruntime-web": ["onnxruntime-web@1.26.0-dev.20260416-b7804b056c", "", { "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": ["pako@1.0.11", "", {}, "sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw=="],
@@ -498,36 +413,24 @@
"path-to-regexp": ["path-to-regexp@8.4.2", "", {}, "sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA=="],
"pend": ["pend@1.2.0", "", {}, "sha512-F3asv42UuXchdzt+xXqfW1OGlVBe+mxa2mqI0pg5yAHZPvFmY3Y6drSf/GQ1A86WgWEN9Kzh/WrgKa6iGcHXLg=="],
"pkce-challenge": ["pkce-challenge@5.0.1", "", {}, "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ=="],
"platform": ["platform@1.3.6", "", {}, "sha512-fnWVljUchTro6RiCFvCXBbNhJc2NijN7oIQxbwsyL0buWJPG85v81ehlHI9fXrJsMNgTofEoWIQeClKpgxFLrg=="],
"playwright": ["playwright@1.58.2", "", { "dependencies": { "playwright-core": "1.58.2" }, "optionalDependencies": { "fsevents": "2.3.2" }, "bin": { "playwright": "cli.js" } }, "sha512-vA30H8Nvkq/cPBnNw4Q8TWz1EJyqgpuinBcHET0YVJVFldr8JDNiU9LaWAE1KqSkRYazuaBhTpB5ZzShOezQ6A=="],
"playwright": ["playwright@1.62.1", "", { "dependencies": { "playwright-core": "1.62.1" }, "optionalDependencies": { "fsevents": "2.3.2" }, "bin": { "playwright": "cli.js" } }, "sha512-0M+L3LAD8/nm554LOla9Ayx0j0tmFZ0FBcoQ7F1VuVHpM/XpiC8RcDzBQB8W5+hA8L22THxELzeF+2WcUzvcLg=="],
"playwright-core": ["playwright-core@1.58.2", "", { "bin": { "playwright-core": "cli.js" } }, "sha512-yZkEtftgwS8CsfYo7nm0KE8jsvm6i/PTgVtB8DL726wNf6H2IMsDuxCpJj59KDaxCtSnrWan2AeDqM7JBaultg=="],
"playwright-core": ["playwright-core@1.62.1", "", { "bin": { "playwright-core": "cli.js" } }, "sha512-wPYSwEBJY9GHraISXqyqtx0na0LpO3XEX7jNDhntbex7tzUS7kLnZsOlFruFJB4Hi/rhDMjXGqHewDZ68nYZVw=="],
"process": ["process@0.11.10", "", {}, "sha512-cdGef/drWFoydD1JsMzuFf8100nZl+GT+yacc2bEced5f9Rjk4z+WtFUTBu9PhOi9j/jfmBPu0mMEY4wIdAF8A=="],
"process-nextick-args": ["process-nextick-args@2.0.1", "", {}, "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag=="],
"progress": ["progress@2.0.3", "", {}, "sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA=="],
"protobufjs": ["protobufjs@7.5.5", "", { "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": ["proxy-addr@2.0.7", "", { "dependencies": { "forwarded": "0.2.0", "ipaddr.js": "1.9.1" } }, "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg=="],
"proxy-agent": ["proxy-agent@6.5.0", "", { "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": ["proxy-from-env@1.1.0", "", {}, "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg=="],
"pump": ["pump@3.0.4", "", { "dependencies": { "end-of-stream": "^1.1.0", "once": "^1.3.1" } }, "sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA=="],
"punycode": ["punycode@1.4.1", "", {}, "sha512-jmYNElW7yvO7TV33CjSmvSiE2yco3bV2czu/OzDKdMNVZQWfxCblURLhf+47syQRBntjfLdd/H0egrzIG+oaFQ=="],
"puppeteer-core": ["puppeteer-core@24.40.0", "", { "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": ["qs@6.15.1", "", { "dependencies": { "side-channel": "^1.1.0" } }, "sha512-6YHEFRL9mfgcAvql/XhwTvf5jKcOiiupt2FiJxHkiX1z4j7WL8J/jRHYLluORvc1XxB5rV20KoeK00gVJamspg=="],
"queue": ["queue@6.0.2", "", { "dependencies": { "inherits": "~2.0.3" } }, "sha512-iHZWu+q3IdFZFX36ro/lKBkSvfkztY5Y7HMiPlOUjhupPcG2JMfst2KKEpu5XndviX/3UhFbRngUPNKtgvtZiA=="],
@@ -538,8 +441,6 @@
"readable-stream": ["readable-stream@2.3.8", "", { "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": ["require-directory@2.1.1", "", {}, "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q=="],
"require-from-string": ["require-from-string@2.0.2", "", {}, "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw=="],
"roarr": ["roarr@2.15.4", "", { "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": ["smart-buffer@4.2.0", "", {}, "sha512-94hK0Hh8rPqQl2xXc3HsaBoOXKV20MToPkcXvwbISWLEs+64sBq5kFgn2kJDHb1Pry9yrP0dxrCI9RRci7RXKg=="],
"socks": ["socks@2.8.8", "", { "dependencies": { "ip-address": "^10.1.1", "smart-buffer": "^4.2.0" } }, "sha512-NlGELfPrgX2f1TAAcz0WawlLn+0r3FyhhCRpFFK2CemXenPYvzMWWZINv3eDNo9ucdwme7oCHRY0Jnbs4aIkog=="],
"socks-proxy-agent": ["socks-proxy-agent@8.0.5", "", { "dependencies": { "agent-base": "^7.1.2", "debug": "^4.3.4", "socks": "^2.8.3" } }, "sha512-HehCEsotFqbPW9sJ8WVYB6UbmIMv7kUUORIF2Nncq4VQvBfNBLibW9YZR5dlYCSUhwcD628pRllm7n+E+YTzJw=="],
"source-map": ["source-map@0.6.1", "", {}, "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g=="],
"socks": ["socks@2.8.9", "", { "dependencies": { "ip-address": "^10.1.1", "smart-buffer": "^4.2.0" } }, "sha512-LJhUYUvItdQ0LkJTmPeaEObWXAqFyfmP85x0tch/ez9cahmhlBBLbIqDFnvBnUJGagb0JbIQrkBs1wJ+yRYpEw=="],
"sprintf-js": ["sprintf-js@1.1.3", "", {}, "sha512-Oo+0REFV59/rz3gfJNKQiBlwfHaSESl1pcGyABQsnnIfWOFt6JNj5gCog2U6MLZ//IGYD+nA8nI+mTShREReaA=="],
"statuses": ["statuses@2.0.2", "", {}, "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw=="],
"streamx": ["streamx@2.25.0", "", { "dependencies": { "events-universal": "^1.0.0", "fast-fifo": "^1.3.2", "text-decoder": "^1.1.0" } }, "sha512-0nQuG6jf1w+wddNEEXCF4nTg3LtufWINB5eFEN+5TNZW7KWJp6x87+JFL43vaAUPyCfH1wID+mNVyW6OHtFamg=="],
"string-template": ["string-template@0.2.1", "", {}, "sha512-Yptehjogou2xm4UJbxJ4CxgZx12HBfeystp0y3x7s4Dj32ltVVG1Gg8YhKjHZkHicuKpZX/ffilA8505VbUbpw=="],
"string-width": ["string-width@4.2.3", "", { "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": ["string_decoder@1.1.1", "", { "dependencies": { "safe-buffer": "~5.1.0" } }, "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg=="],
"strip-ansi": ["strip-ansi@6.0.1", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="],
"tar-fs": ["tar-fs@3.1.2", "", { "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": ["tar-stream@3.1.8", "", { "dependencies": { "b4a": "^1.6.4", "bare-fs": "^4.5.5", "fast-fifo": "^1.2.0", "streamx": "^2.15.0" } }, "sha512-U6QpVRyCGHva435KoNWy9PRoi2IFYCgtEhq9nmrPPpbRacPs9IH4aJ3gbrFC8dPcXvdSZ4XXfXT5Fshbp2MtlQ=="],
"teex": ["teex@1.0.1", "", { "dependencies": { "streamx": "^2.12.5" } }, "sha512-eYE6iEI62Ni1H8oIa7KlDU6uQBtqr4Eajni3wX7rpfXD8ysFx8z0+dri+KWEPWpBsxXfxu58x/0jvTVT1ekOSg=="],
"text-decoder": ["text-decoder@1.2.7", "", { "dependencies": { "b4a": "^1.6.4" } }, "sha512-vlLytXkeP4xvEq2otHeJfSQIRyWxo/oZGEbXrtEEF9Hnmrdly59sUbzZ/QgyWuLYHctCHxFF4tRQZNQ9k60ExQ=="],
"toidentifier": ["toidentifier@1.0.1", "", {}, "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA=="],
"tr46": ["tr46@0.0.3", "", {}, "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw=="],
@@ -622,8 +505,6 @@
"type-is": ["type-is@2.0.1", "", { "dependencies": { "content-type": "^1.0.5", "media-typer": "^1.1.0", "mime-types": "^3.0.0" } }, "sha512-OZs6gsjF4vMp32qrCbiVSkrFmXtG/AZhY3t0iAMrMBiAZyV9oALtXO8hsrHbMXF9x6L3grlFuwW2oAz7cav+Gw=="],
"typed-query-selector": ["typed-query-selector@2.12.1", "", {}, "sha512-uzR+FzI8qrUEIu96oaeBJmd9E7CFEiQ3goA5qCVgc4s5llSubcfGHq9yUstZx/k4s9dXHVKsE35YWoFyvEqEHA=="],
"undici-types": ["undici-types@7.18.2", "", {}, "sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w=="],
"unpipe": ["unpipe@1.0.0", "", {}, "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ=="],
@@ -634,20 +515,14 @@
"virtual-dom": ["virtual-dom@2.1.1", "", { "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": ["webdriver-bidi-protocol@0.4.1", "", {}, "sha512-ARrjNjtWRRs2w4Tk7nqrf2gBI0QXWuOmMCx2hU+1jUt6d00MjMxURrhxhGbrsoiZKJrhTSTzbIrc554iKI10qw=="],
"webidl-conversions": ["webidl-conversions@3.0.1", "", {}, "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ=="],
"whatwg-url": ["whatwg-url@5.0.0", "", { "dependencies": { "tr46": "~0.0.3", "webidl-conversions": "^3.0.0" } }, "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw=="],
"which": ["which@2.0.2", "", { "dependencies": { "isexe": "^2.0.0" }, "bin": { "node-which": "./bin/node-which" } }, "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA=="],
"wrap-ansi": ["wrap-ansi@7.0.0", "", { "dependencies": { "ansi-styles": "^4.0.0", "string-width": "^4.1.0", "strip-ansi": "^6.0.0" } }, "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q=="],
"wrappy": ["wrappy@1.0.2", "", {}, "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ=="],
"ws": ["ws@8.20.0", "", { "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": ["x-is-array@0.1.0", "", {}, "sha512-goHPif61oNrr0jJgsXRfc8oqtYzvfiMJpTqwE7Z4y9uH+T3UozkGqQ4d2nX9mB9khvA8U2o/UbPOFjgC7hLWIA=="],
"x-is-string": ["x-is-string@0.1.0", "", {}, "sha512-GojqklwG8gpzOVEVki5KudKNoq7MbbjYZCbyWzEz7tyPA7eleiE0+ePwOWQQRb5fm86rD3S8Tc0tSFf3AOv50w=="],
@@ -660,14 +535,6 @@
"xterm-addon-fit": ["xterm-addon-fit@0.8.0", "", { "peerDependencies": { "xterm": "^5.0.0" } }, "sha512-yj3Np7XlvxxhYF/EJ7p3KHaMt6OdwQ+HDu573Vx1lRXsVxOcnVJs51RgjZOouIZOczTsskaS+CpXspK81/DLqw=="],
"y18n": ["y18n@5.0.8", "", {}, "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA=="],
"yargs": ["yargs@17.7.2", "", { "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": ["yargs-parser@21.1.1", "", {}, "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw=="],
"yauzl": ["yauzl@2.10.0", "", { "dependencies": { "buffer-crc32": "~0.2.3", "fd-slicer": "~1.1.0" } }, "sha512-p4a9I6X6nu6IhoGmBqAcbJy1mlC4j27vEPZX9F4L4/vZT3Lyq1VkFHw/V/PUcB9Buo+DG3iHkT0x3Qya58zc3g=="],
"zod": ["zod@3.25.76", "", {}, "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ=="],
"zod-to-json-schema": ["zod-to-json-schema@3.25.2", "", { "peerDependencies": { "zod": "^3.25.28 || ^4" } }, "sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA=="],
@@ -696,8 +563,6 @@
"send/mime-types": ["mime-types@3.0.2", "", { "dependencies": { "mime-db": "^1.54.0" } }, "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A=="],
"socks-proxy-agent/socks": ["socks@2.8.7", "", { "dependencies": { "ip-address": "^10.0.1", "smart-buffer": "^4.2.0" } }, "sha512-HLpt+uLy/pxB+bum/9DzAgiKS8CX1EvbWxI4zlmgGCExImLdiad2iCwXT5Z4c9c3Eq8rP2318mPW2c+QbtjK8A=="],
"type-is/mime-types": ["mime-types@3.0.2", "", { "dependencies": { "mime-db": "^1.54.0" } }, "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A=="],
"xmlbuilder2/@oozcitak/dom": ["@oozcitak/dom@1.15.5", "", { "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": ["mime-db@1.54.0", "", {}, "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ=="],
"socks-proxy-agent/socks/ip-address": ["ip-address@10.1.0", "", {}, "sha512-XXADHxXmvT9+CRxhXg56LJovE+bmWnEWB78LB83VZTprKTmaC5QfruXocxzTZ2Kl0DNwKuBdlIhjL8LeY8Sf8Q=="],
"type-is/mime-types/mime-db": ["mime-db@1.54.0", "", {}, "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ=="],
"xmlbuilder2/@oozcitak/dom/@oozcitak/util": ["@oozcitak/util@8.0.0", "", {}, "sha512-+9Hq6yuoq/3TRV/n/xcpydGBq2qN2/DEDMqNTG7rm95K6ZE2/YY/sPyx62+1n8QsE9O26e5M1URlXsk+AnN9Jw=="],
+16 -10
View File
@@ -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`.
+57 -22
View File
@@ -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:
+41 -12
View File
@@ -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:
+16 -10
View File
@@ -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`.
+16 -10
View File
@@ -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`.
+16 -10
View File
@@ -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`.
+17 -11
View File
@@ -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
+16 -10
View File
@@ -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`.
+17 -11
View File
@@ -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
+16 -10
View File
@@ -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`.
+16 -10
View File
@@ -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`.
+12 -6
View File
@@ -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
+16 -10
View File
@@ -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`.
+16 -10
View File
@@ -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`.

Some files were not shown because too many files have changed in this diff Show More