Use Garry Tan's exact Claude Code setup: 23 opinionated tools that serve as CEO, Designer, Eng Manager, Release Manager, Doc Engineer, and QA
TypeScript
v1.65.0.0 feat: fork port wave 2 — feature fixes, session persistence, Apple releases, supply-chain CI (#2577)
Garry Tan2be6c06ba83d
diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.mdnew file mode 100644index 000000000..bfcc4a2e2--- /dev/null+++ b/.github/PULL_REQUEST_TEMPLATE.md@@ -0,0 +1,44 @@+<!--+gstack is AI-coded and proud of it. The bar is EVIDENCE OF REAL USE, not lines+of code. A PR with no proof behind it gets closed, no matter how clean it looks.+Fill every section below. See CONTRIBUTING.md → "The evidence bar".+-->++## Why (in your own words)++<!-- One paragraph: what breaks for a user today, and what this change does about+it. Not a restatement of the diff. -->++## Live evidence++<!-- REQUIRED. Paste the command(s) you ran and their real output — before and+after. For a bug: the reproduction, failing then fixed. For a skill change: the+actual transcript / `claude -p` output. For anything visual: before/after+screenshots. "bun test passes" alone is not enough — show the behavior you+changed. -->++```+# what you ran + what it produced+```++## Scope++- **Changed:**+- **Verified live by:**+- **Did NOT test:**++## Liveness proof (required)++<!-- Attach a screenshot of your own machine with the text `GSTACK PR` typed LIVE+into a real surface — terminal prompt, a shell command, your browser+address/search bar, an editor buffer. It must be TYPED INTO A LIVE UI, not drawn,+overlaid, or edited onto the image. A painted-on `GSTACK PR` is an automatic+close. This confirms a human opened this PR. -->++## Checklist++- [ ] Liveness screenshot attached: `GSTACK PR` typed live into a real surface (not edited onto the image)+- [ ] This is not a generated-file-only diff (I edited the source/template and regenerated)+- [ ] No ETHOS.md edits, and no changes to voice / founder perspective / YC references+- [ ] New public command / external service / host adapter has an accepted issue linked (or N/A)+- [ ] Linked issue or reproduction: #diff --git a/.github/dependabot.yml b/.github/dependabot.ymlnew file mode 100644index 000000000..d6b53e48d--- /dev/null+++ b/.github/dependabot.yml@@ -0,0 +1,25 @@+version: 2++updates:+ - package-ecosystem: "bun"+ directory: "/"+ schedule:+ interval: "weekly"+ day: "monday"+ groups:+ production-dependencies:+ dependency-type: "production"+ development-dependencies:+ dependency-type: "development"+ open-pull-requests-limit: 5++ - package-ecosystem: "github-actions"+ directory: "/"+ schedule:+ interval: "weekly"+ day: "monday"+ groups:+ github-actions:+ patterns:+ - "*"+ open-pull-requests-limit: 2diff --git a/.github/scripts/gate-secret-scan.mjs b/.github/scripts/gate-secret-scan.mjsnew file mode 100644index 000000000..11a139f30--- /dev/null+++ b/.github/scripts/gate-secret-scan.mjs@@ -0,0 +1,46 @@+#!/usr/bin/env node+import { spawn } from "node:child_process";++const child = spawn("bun", [+ "bin/gstack-redact",+ "--repo-visibility", "public",+ "--json",+ "--max-bytes", "16000000",+], { shell: false, windowsHide: true, stdio: ["pipe", "pipe", "inherit"] });+let diff = "";+process.stdin.setEncoding("utf8");+process.stdin.on("data", (chunk) => { diff += chunk; });+process.stdin.once("end", () => {+ const additions = diff+ .split(/\r?\n/)+ .filter((line) => line.startsWith("+") && !line.startsWith("+++"))+ .map((line) => line.slice(1))+ .join("\n");+ // The scanner may exit before consuming an oversize payload (it refuses+ // stdin over --max-bytes and reports oversize:true). EPIPE here is that+ // refusal in flight, not a failure — the report + exit code carry the verdict.+ child.stdin.on("error", (error) => {+ if (error.code !== "EPIPE") throw error;+ });+ child.stdin.end(additions);+});+let stdout = "";+child.stdout.setEncoding("utf8");+child.stdout.on("data", (chunk) => { stdout += chunk; });+child.once("error", (error) => { throw error; });+child.once("close", (code) => {+ let report;+ try {+ report = JSON.parse(stdout);+ } catch {+ // No parseable report: the oversize refusal prints only to stderr and+ // exits 3, and a crashed scanner emits nothing. Both fail closed.+ console.log(`credential scan: 1 high, 0 advisory (scanner emitted no report, exit ${code} — fail-closed)`);+ process.exitCode = 1;+ return;+ }+ const high = Number(report.counts?.HIGH ?? 0);+ const medium = Number(report.counts?.MEDIUM ?? 0);+ console.log(`credential scan: ${high} high, ${medium} advisory`);+ process.exitCode = high > 0 || report.oversize || ![0, 2, 3].includes(code) ? 1 : 0;+});diff --git a/.github/workflows/dependency-review.yml b/.github/workflows/dependency-review.ymlnew file mode 100644index 000000000..c69dad8d1--- /dev/null+++ b/.github/workflows/dependency-review.yml@@ -0,0 +1,32 @@+name: Dependency Review++on:+ pull_request:+ paths:+ - 'package.json'+ - 'bun.lock'+ - '**/package.json'+ - '**/bun.lock'+ - '.github/workflows/**'++concurrency:+ group: dependency-review-${{ github.event.pull_request.number }}+ cancel-in-progress: true++permissions:+ contents: read++jobs:+ dependency-review:+ runs-on: ubicloud-standard-8+ timeout-minutes: 10+ permissions:+ contents: read+ pull-requests: write+ steps:+ - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4+ - uses: actions/dependency-review-action@2031cfc080254a8a887f58cffee85186f0e49e48 # v4.9.0+ with:+ fail-on-severity: high+ fail-on-scopes: runtime, development+ comment-summary-in-pr: on-failurediff --git a/.github/workflows/evals.yml b/.github/workflows/evals.ymlindex 3b30271e6..d90ad365f 100644--- a/.github/workflows/evals.yml+++ b/.github/workflows/evals.yml@@ -15,6 +15,12 @@ env:jobs:# Build Docker image with pre-baked toolchain (cached — only rebuilds on Dockerfile/lockfile change)build-image:+ # Dependabot-triggered pull_request runs get a read-only GITHUB_TOKEN, so+ # a lockfile bump = new hash = failed ghcr push = permanently red check+ # (EV6, fork port wave 2). Skip the build for dependabot; the evals job's+ # needs-chain tolerates it because no eval test selects on a lockfile-only+ # diff — a maintainer's next push rebuilds the image with real perms.+ if: github.actor != 'dependabot[bot]'runs-on: ubicloud-standard-8permissions:contents: readdiff --git a/.github/workflows/osv-scanner.yml b/.github/workflows/osv-scanner.ymlnew file mode 100644index 000000000..22b8ae6eb--- /dev/null+++ b/.github/workflows/osv-scanner.yml@@ -0,0 +1,26 @@+name: OSV Scanner++on:+ schedule:+ - cron: '23 7 * * 1'+ workflow_dispatch:++permissions:+ contents: read++concurrency:+ group: osv-scanner+ cancel-in-progress: true++jobs:+ scan:+ permissions:+ actions: read+ contents: read+ security-events: write+ uses: google/osv-scanner-action/.github/workflows/osv-scanner-reusable.yml@3adb4b14a2b0623876d18d863a498b785fb3752d # v2.3.8+ with:+ scan-args: |-+ --include-git-root+ --recursive+ ./diff --git a/.github/workflows/quality-gate.yml b/.github/workflows/quality-gate.ymlnew file mode 100644index 000000000..af1c6fb12--- /dev/null+++ b/.github/workflows/quality-gate.yml@@ -0,0 +1,77 @@+# Quality gate (fork port wave 2, adapted from time-attack/gstack GStack 2).+#+# Three generic hygiene checks the repo previously had nowhere in CI:+# 1. Credential scan of the PR diff's ADDED lines through our own+# bin/gstack-redact (HIGH fails the check; MEDIUM is an advisory count —+# there is no human in CI to confirm, so it never fails here).+# 2. bun audit at critical severity.+# 3. ShellCheck (errors only) on the setup/build shell boundary.+#+# Trigger is `pull_request`, NEVER `pull_request_target`: fork PRs must not+# get secret-bearing contexts. Diff excludes cover the planted-bug fixtures+# and eval baselines that intentionally contain credential-shaped strings.+name: Quality gate++on:+ pull_request:+ branches: [main]+ push:+ branches: [main]+ workflow_dispatch:++permissions:+ contents: read++concurrency:+ group: quality-gate-${{ github.workflow }}-${{ github.ref }}+ cancel-in-progress: true++jobs:+ quality:+ runs-on: ubicloud-standard-8+ timeout-minutes: 20+ steps:+ - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4+ with:+ fetch-depth: 0+ - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2+ with:+ bun-version: latest++ - name: Install frozen dependencies+ run: bun install --frozen-lockfile --ignore-scripts++ - name: Scan changed text for credentials (added lines, own redact engine)+ env:+ BASE_SHA: ${{ github.event.pull_request.base.sha || github.event.before }}+ HEAD_SHA: ${{ github.event.pull_request.head.sha || github.sha }}+ run: |+ set -euo pipefail+ if ! git cat-file -e "${BASE_SHA}^{commit}" 2>/dev/null; then+ BASE_SHA=$(git rev-parse HEAD^)+ fi+ git diff --unified=0 --no-color "$BASE_SHA" "$HEAD_SHA" -- \+ . \+ ':(exclude)test/fixtures/**' \+ ':(exclude)browse/test/fixtures/**' \+ ':(exclude)docs/evals/**' \+ ':(exclude)test/helpers/security-bench*' \+ | node .github/scripts/gate-secret-scan.mjs++ - name: Gate critical dependency advisories+ run: bun audit --audit-level=critical++ - name: Install ShellCheck+ run: |+ sudo apt-get update+ sudo apt-get install -y shellcheck+ shellcheck --version++ - name: ShellCheck setup and build boundaries+ run: >-+ shellcheck --severity=error+ setup+ scripts/build.sh+ scripts/build-app.sh+ scripts/write-version-files.sh+ browse/scripts/build-node-server.shdiff --git a/.github/workflows/windows-free-tests.yml b/.github/workflows/windows-free-tests.ymlindex c05a7d002..7435814cc 100644--- a/.github/workflows/windows-free-tests.yml+++ b/.github/workflows/windows-free-tests.yml@@ -111,6 +111,8 @@ jobs:browse/test/claude-bin.test.ts \test/test-free-shards.test.ts \browse/test/file-permissions.test.ts \+ browse/test/bun-polyfill.test.ts \+ browse/test/windows-spawn-hide.test.ts \browse/test/security.test.ts \browse/test/server-sanitize-surrogates.test.ts \test/setup-windows-fallback.test.ts \diff --git a/.gitignore b/.gitignoreindex 5196c0d05..ee813182c 100644--- a/.gitignore+++ b/.gitignore@@ -44,3 +44,8 @@ docs/throughput-*.json# gbrain local source-staging dir (capability checks, source clones) — runtime artifact.sources/++# SPM build output from the gen-accessors tool (built in place by+# skill-e2e-ios-swift-build; regenerates on every run — never commit)+ios-qa/scripts/gen-accessors-tool/.build/+ios-qa/scripts/gen-accessors-tool/Package.resolveddiff --git a/.osv-scanner.toml b/.osv-scanner.tomlnew file mode 100644index 000000000..56ca32123--- /dev/null+++ b/.osv-scanner.toml@@ -0,0 +1,15 @@+# OSV-Scanner configuration.+# Direct/transitive dependency versions are pinned to their fixed releases via+# the `overrides` block in package.json; this file only records advisories we+# have assessed as not-reachable or not-fixable without disproportionate risk.++[[IgnoredVulns]]+id = "GHSA-frvp-7c67-39w9"+# @hono/node-server 1.19.x. Reachable only through @modelcontextprotocol/sdk,+# which is an unused transitive dependency (no source file imports it) and never+# starts a Hono HTTP server, so the advisory's request path is not exercised.+# The only fix is @hono/node-server 2.0.5, a major bump the MCP SDK pins against+# (^1.19.9); forcing it via override risks breaking the SDK at runtime for a+# vulnerability we do not expose. Re-evaluate if the MCP SDK becomes a direct,+# server-hosting dependency.+reason = "Unreachable transitive (unused @modelcontextprotocol/sdk); fix requires a risky major override on a pinned peer dep."diff --git a/BROWSER.md b/BROWSER.mdindex 046395080..1ab7a1e60 100644--- a/BROWSER.md+++ b/BROWSER.md@@ -1091,6 +1091,19 @@ $B state load my-session # restoreIn-memory `load-html` content is intentionally NOT persisted (avoid leakingsecrets to disk).+Manual save/load is one-shot. For state that survives daemon restarts+automatically, opt in with `BROWSE_PERSIST_STATE=1` in the daemon's+environment: the headless daemon snapshots cookies + per-tab+URL/localStorage/sessionStorage to `<stateDir>/session-state.json` (0600,+atomic writes) every 30 seconds and at clean shutdown, then restores it off+the boot path on the next launch. Default OFF — cookies on disk are a real+cost, so the user opts in. Headless only (headed mode's persistent Chromium+profile already owns its state). Loaded HTML and tab ownership are never+persisted, cookies for localhost, `.internal`, loopback IP literals+(127.0.0.0/8, `::1`), and link-local/cloud-metadata addresses+(169.254.0.0/16) are dropped on restore, and a corrupt snapshot is quarantined to+`session-state.json.corrupt` so persistence can never block a launch.+### Watch```bashdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex f30522fe4..ec29ae520 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,195 @@# Changelog+## [1.65.0.0] - 2026-08-14++**/autoplan, /codex on macOS, and memory ingest work again.**+**And every consent gate now means what it says.**++This is the second and final wave of the GStack 2 fork port. Wave one (v1.63.0.0)+took the audit infrastructure; this wave takes the fixes and the features. Three+skills that failed silently on every run now work: /autoplan's task aggregation+emits real tasks instead of zero, /codex creates its temp files on macOS instead+of dying on BSD mktemp, and memory ingest actually imports pages on current+gbrain builds, and prints the count so you can see it. On top of that: your+browser auth can now survive a daemon restart, /ship can take an iOS app from+working tree to Submit for Review, and four supply-chain gates now run on every+PR. Nearly all of it traces back to Sina Matian's time-attack/gstack fork, ported+with tests and attribution.++### The numbers that matter++Source: this branch (`git log 1.63.0.0..HEAD`, `git diff main...HEAD --stat`,+`bun test`), plus the GitHub issues the release closes.++| What | Before | After |+|------|--------|-------|+| /autoplan Phase 4 task output (#2018) | 0 tasks, every run | every task |+| /codex on macOS (#2091) | broken on every install | works |+| Memory ingest on gbrain 0.42+ (#2144) | 0 pages, reported success | full corpus, count printed |+| Headed browse on macOS 26 (#2242) | GPU crash, poisoned cache | launches, heals old caches |+| Auth after a browse daemon restart (#778) | logged out | restored (opt-in) |+| CI secret scanning on PR diffs | none | every PR, fail-closed |+| GitHub issues closed | | 24 |+| Community PRs landed with authorship | | 4 |++The stark one is the first three rows: those aren't degraded features, they were+features returning empty results with a green checkmark. If you ran /autoplan in+the last two months, the task list it handed off was empty and nothing told you.++### What this means for gstack users++Run /autoplan and the pipeline hands real tasks to the executor. Run /codex on a+Mac and it just works. Set `BROWSE_PERSIST_STATE=1` and a daemon restart no+longer logs you out of every site. If you ship an iOS app, `/ship` now knows the+whole App Store journey, session-minted upload keys, the price-schedule API that+replaced the broken fastlane path, error -22938 triage, one authorization moment+instead of five. Upgrade with `/gstack-upgrade`; the migration cleans any+Chromium bundle an older gstack broke and verifies the replacement download+before it claims success.++### Itemized changes++#### Added++- **Opt-in browser session persistence** (#778, #2193): `BROWSE_PERSIST_STATE=1`+ snapshots cookies and tabs (atomic writes, 0600, never page HTML or+ ownership), restores them off the boot path on the next start, and quarantines+ a corrupt snapshot instead of crashing. Portions from time-attack/gstack.+- **Apple App Store release journey for /ship**: `ship/sections/apple-release.md`+ loads before the repo-landing gates when the target is an Apple app. Encodes+ session-minted App Store Connect keys, `appPriceSchedules` over the broken+ fastlane `price_tier`, expanded age-rating attributes, -22938 classification,+ and a one-authorization-moment flow. Refined across 21 live releases on the+ fork. Portions copyright Sina Matian, MIT.+- **Code-intelligence provider contract, Phase 1**: `gstack-code-intelligence`+ wraps GBrain, Sourcebot, and Graphify behind one interface with an ask-once+ indexing offer for large repos (1,000+ tracked files, decline persisted).+ Consent is explicit per repo (`consent <repo> yes|no`), the per-repo trust+ policy's deny and read-only tiers veto write-class operations no matter what+ consent was recorded, and every off-machine send writes an egress receipt that+ records the consent state actually checked. Portions from time-attack/gstack.+- **Supply-chain CI**: a quality gate that runs `bin/gstack-redact` over every+ PR diff (HIGH findings fail, MEDIUM annotates), dependency review on+ lockfile changes, weekly OSV scans, grouped dependabot updates, and an+ evidence-bar PR template. Every third-party action in the new workflows is+ pinned to a commit SHA.+- **Third-party web-actions contract** in tier-2+ skills: when a workflow needs+ a vendor-site step (API key signup, OAuth app), gstack offers to drive the+ browser itself, hands credentials and CAPTCHAs to you, stores secrets+ owner-only, and verifies with a read-only call before claiming success.+- **Design docs land in your repo** (#703, #2000): office-hours writes+ `docs/designs/<topic>.md` as a concise decision record (one bullet per+ decision with its why), redaction-scanned before anything touches your git+ history. Plan reviews prefer the repo-local doc when both exist.+- **`gstack-verify-gate`** (opt-in Stop hook): blocks turn-end until the+ CLAUDE.md-declared verify command passes. A command runs only after you trust+ it once per repo (`--trust`), re-trust is required when it changes, every+ grant is audit-logged, and re-entries re-run the check instead of waving it+ through.+- **"Never show me these again"** for the founder-resources pitch (#538): the+ opt-out verifies its own config write before promising anything. Re-enable+ with `gstack-config set founder_resources true`.+- **Claimed limitations need evidence**: every tier-2+ skill now treats "the+ API can't do this" as a material claim requiring the verbatim error, the+ documented statement, or a live probe, and runs the ten-second check before+ declaring anything blocked.++#### Fixed++- **/autoplan Phase 4 emitted zero tasks on every run** (#2018): a jq context+ rebind dropped every aggregated task; the error was hidden by stderr+ suppression. Six-fixture regression suite pins it.+- **/codex was broken on every macOS install** (#2091): BSD mktemp rejects+ suffixed templates; all temp files now use portable templates and a static+ test bans the pattern repo-wide.+- **Memory ingest imported nothing on gbrain 0.42+** (#2144): the staging dir+ sits under a gitignored tree, so git-aware collectors saw zero files. Fixed+ with `--include-gitignored` (community PR #2560) plus a `GIT_CEILING_DIRECTORIES`+ second layer, Windows-safe, and a loud ingested-page count.+- **Headed mode on macOS 26** (#2242, #2138, #2139): gstack no longer rewrites+ the signed Chrome-for-Testing bundle (the rebrand broke its code signature;+ GPU processes refused to start). Launch self-heals poisoned caches, on both+ headed entry points, by removing the whole revision directory so the re-fetch+ actually re-downloads, and the upgrade migration does the same for existing+ installs, verifying a working Chromium exists before recording success.+ Branding stays on the GStack Browser wrapper app.+- **`browse stop` restarted the daemon it was told to stop**: the CLI now gets+ an acknowledgment before shutdown, and the shutdown snapshot has a hard+ deadline so a wedged page can never hold the port.+- **Session cookies from internal networks never reach a restored browser**:+ the restore-time hygiene filter drops loopback and link-local IP literals+ (127.0.0.1, ::1, 169.254.*) alongside localhost and *.internal, shared by+ both the persistence path and `state load`.+- **ios-qa stopped handing out raw bearer tokens**: `/auth/sessions` returns+ salted-hash token ids with revoke-by-id support, the boot token left os_log+ entirely, and the IPv4 listener pins to loopback at the socket.+- **make-pdf's no-network promise holds against obfuscation**: `<style>`+ @import, inline style URLs (quoted, unquoted, CSS-escaped, and+ HTML-entity-encoded), srcset, and media sources are all neutralized when+ rendering untrusted HTML without `--allow-network`.+- **pair-agent tunnels are consent-gated** (`gstack-config set pair_agent on`):+ the tunnel cannot start without the recorded opt-in, the receipts that always+ claimed consent now reflect a check that exists, and a disabled gate tells+ you the real remedy instead of ngrok install instructions.+- **The per-repo gbrain trust policy is enforced at the code-import chokepoint**+ (#2140, sync path): deny refuses, read-only skips code ingest, an unreadable+ policy store fails closed, and the egress receipt names the decision.+- **Handoff no longer disarms the tunnel-orphan reaper** (community PR #2565+ plus hardening): promoting a daemon to headed suppresses only the+ headed-shutdown branch; a daemon with an active tunnel still dies with its+ parent.+- **Windows**: broken DACLs on state dirs self-repair (#1605), every+ Windows-reachable spawn passes windowsHide (#1835, community PRs #2523 and+ #2539), and decision files no longer land under a project named "unknown".+- **Setup no longer hangs on first run** (#2136): the Chromium probe gets a+ 90-second deadline that reaps the whole wedged process tree, installs are+ single-flight across concurrent setups, and EXIT cleanup traps chain instead+ of clobbering each other.+- **Paper cuts**: `gh pr edit` falls back to the REST API when the+ Projects-classic GraphQL deprecation bites (#1079); the v1.27 migration never+ auto-proceeds without a TTY and never records a failed rename as done+ (#1383); model benchmarks recognize macOS Keychain auth (#1890); voyage+ embedding flags survive zsh (#1798); `--supersede` keeps the replacement+ decision it was given; brain context no longer disables itself after one slow+ cold-start probe; lock acquisition reports the real error instead of phantom+ contention (#1084); plan verification probes the dev server your project+ declares instead of a hardcoded port list.++#### Changed++- **Telemetry defaults to off everywhere**: the browse daemon now reads the+ same persistent consent the rest of gstack does; an absent key means+ disabled, matching `gstack-config get telemetry`.+- **Test-command detection covers Django and config-less projects**: a working+ `manage.py test` or `*_test.go` suite is recognized instead of being offered+ a bootstrap it doesn't need.+- **Base-branch detection everywhere**: the bins that hardcoded `main` now+ probe origin/HEAD, origin/main, and origin/master in order.+- **Eval model resolution is host-neutral**: `GSTACK_EVAL_MODEL` (and per-kind+ variants) override the hardcoded model ids at all six call sites.+- Dead bins removed (`chrome-cdp`, `gstack-open-url`, `gstack-platform-detect`);+ the stale-reference scan now covers docs/ so removals like these fail CI when+ documentation still cites them.++#### For contributors++- 23 new test files (+5,499 test lines): behavioral suites for session+ persistence, the poisoned-bundle probe, both migrations, the consent CLI,+ verify-gate trust, telemetry opt-out, the offline-gate bypass corpus, the+ secret-scan exit contract, and lock-acquisition edge branches. The ios-qa+ daemon suite (10 files) is now wired into `bun test` and the sharded runner;+ it had never run in CI.+- `lib/gbrain-repo-policy-client.ts` is the one place repo-policy tiers are+ read; both enforcement points route through it.+- `lib/context-bill.ts` no longer double-counts nested skills in totalMd, and+ `gstack-context-bill` works under Conductor env-shims.+- Egress receipts: `bin/gstack-egress verify` passes with the chain intact;+ code-intelligence adapters registered as fail-closed sinks.+- Credits: this release ports work by **Sina Matian** (time-attack/gstack, MIT)+ across nearly every cluster. Community PRs absorbed with authorship:+ **Gawie van Blerk** (#2560), **Shawn Reddy** (#2565), **Jake Wilk** (#2523),+ **Jerry Nichols** (#2539). Thank you all.+## [1.64.1.0] - 2026-08-15**Every guard in the pipeline now provably fires.**diff --git a/CLAUDE.md b/CLAUDE.mdindex eed012557..4546e9275 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -157,11 +157,11 @@ 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)+├── lib/ # Shared libraries (worktree.ts, egress-receipt.ts, context-bill.ts, redact-engine.ts, code-intelligence/)├── docs/designs/ # Design documents├── setup-deploy/ # /setup-deploy skill (one-time deploy config)├── .github/ # CI workflows + Docker image-│ ├── workflows/ # evals.yml (E2E on Ubicloud), skill-docs.yml, actionlint.yml+│ ├── 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)│ └── docker/ # Dockerfile.ci (pre-baked toolchain + Playwright/Chromium)├── contrib/ # Contributor-only tools (never installed for users)│ └── add-host/ # /gstack-contrib-add-host skilldiff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 99aeb8673..16d3183ca 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -271,6 +271,15 @@ Each dimension is scored 1-5. Threshold: every dimension must score **≥ 4**. TA GitHub Action (`.github/workflows/skill-docs.yml`) runs `bun run gen:skill-docs --dry-run` on every push and PR. If the generated SKILL.md files differ from what's committed, CI fails. This catches stale docs before they merge.+Supply-chain gates run alongside it:++- **Quality gate** (`.github/workflows/quality-gate.yml`, every PR and push) — scans the diff's added lines for credentials using gstack's own redact engine (`.github/scripts/gate-secret-scan.mjs`). HIGH findings fail the job; MEDIUM findings surface as an advisory count. Fails closed if the scan can't produce a report. Also gates critical dependency advisories and runs ShellCheck on the setup/build boundaries.+- **Dependency review** (`.github/workflows/dependency-review.yml`) — reviews dependency changes on PRs that touch lockfiles or workflow files.+- **OSV scanner** (`.github/workflows/osv-scanner.yml`) — weekly vulnerability scan against the OSV database (config in `.osv-scanner.toml`).+- **Dependabot** (`.github/dependabot.yml`) — grouped dependency update PRs.++The supply-chain workflows pin their third-party actions to commit SHAs. The PR template (`.github/PULL_REQUEST_TEMPLATE.md`) asks for evidence — tests run, eval output — not promises.+Tests run against the browse binary directly — they don't require dev mode.## Editing SKILL.md filesdiff --git a/README.md b/README.mdindex 9ef4b0851..d7478897d 100644--- a/README.md+++ b/README.md@@ -245,6 +245,8 @@ Beyond the slash-command skills, gstack ships standalone CLIs for workflows that| `gstack-taste-update` | **Design taste learning** — writes approvals and rejections from `/design-shotgun` into a persistent per-project taste profile. Decays 5%/week. Feeds back into future variant generation so the system learns what you actually pick. || `gstack-egress` | **Egress receipt auditor** — every gstack-initiated off-machine send writes a tamper-evident, hash-chained receipt to `~/.gstack/security/egress.jsonl` before the send. `list` shows what gstack attempted to send and to which host, `grants` shows the standing consent settings plus the exact command that revokes each, `verify` recomputes the hash chain and exits 3 on tamper. || `gstack-context-bill` | **Token bill-of-materials** — read-only, offline audit of what an installed skills tree costs in tokens: always-on frontmatter every session pays vs per-invocation SKILL.md + forced references. `--diff` compares two trees, `--budget` enforces a ceiling, `--exact` opts into Anthropic `count_tokens` (sends file text off-machine; writes an egress receipt first, degrades to the offline estimate if the receipt can't be written). |+| `gstack-code-intelligence` | **Code-intelligence provider picker** — wraps GBrain, Sourcebot, and Graphify behind one interface: `options`/`status` to see what's available, `select` to pick one, `index`/`search` to use it, `suggest` to check whether the one-time indexing offer should fire here. The offer triggers on large repos (1,000+ tracked files; a decline is persisted). Non-local providers refuse to index *or search* until you record per-repo consent (`consent <repo> yes\|no` — the query text is repo-derived content), the per-repo trust policy's deny and read-only tiers veto write-class operations regardless of consent, and every off-machine send writes an egress receipt. Fully optional — with nothing selected, gstack falls back to grep. |+| `gstack-verify-gate` | **Verification stop hook (opt-in)** — blocks a Claude Code turn from ending until the project's declared verify command passes (after 3 blocked re-entries it yields with a loud still-RED warning instead of looping forever). Declare it on one line in CLAUDE.md: `<!-- gstack:verify: bun test -->`. Hooks bypass the permission system, so a declared command never runs until you trust it once per repo (`gstack-verify-gate --trust`); editing the command invalidates trust until re-granted, and every grant is audit-logged. `./setup` never registers it for you — opt in with `gstack-settings-hook add-event --event Stop --command ~/.claude/skills/gstack/bin/gstack-verify-gate --source verify-gate`, remove with `gstack-settings-hook remove-source --source verify-gate`. || `gstack-ios-qa-daemon` | **iOS QA daemon** — Mac-side broker between an agent and a connected iPhone over USB CoreDevice. Loopback by default; `--tailnet` opens a Tailscale-facing listener with identity-gated capability tiers. Single-instance via flock on `~/.gstack/ios-qa-daemon.pid`. See [docs/howto-ios-testing-with-gstack.md](docs/howto-ios-testing-with-gstack.md). || `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. |diff --git a/TODOS.md b/TODOS.mdindex 24f7edcf0..43fc6c81d 100644--- a/TODOS.md+++ b/TODOS.md@@ -2,6 +2,88 @@## NEXT PRIORITY+### P2: Persona-fleet hostile-user harness (fork port wave 2 deferral)++**What:** Port the methodology behind time-attack/gstack's 87-hostile-user+field run (418 findings): machine-written t0 in an append-only run.jsonl+(elapsed time measured, never self-reported), every metric resolving to an+artifact, and a mandatory-quit contract with machine-checkable caps (300s to+first useful output, 900s total, 40K context tokens, 3 consecutive dead ends)+so abandonment is a computable outcome. Specs: fork `evals/fleet/METRICS.md`++ `evals/fleet/ABANDONMENT.md` (methodology only — no runner code exists to+port; this is a build).++**Why:** A periodic hostile-user round against OUR 44-skill tree would surface+the same first-five-minutes failure class the fork closed 418 of. Fits the+existing eval-store/e2e harness as a new runner.++**Effort:** L (human ~2wk) → M with CC. **Priority:** P2.+**Depends on:** decisions on cost ceilings + journal storage.++### P3: Answer-key eval methodology (rides the persona-fleet work)++**What:** Pre-registered answer keys (fork `evals/answer-keys/` —+codex-decorrelation, health-trending) grading our /codex and /health surfaces+against planted ground truth instead of judge vibes.++**Why:** Deterministic scoring for surfaces where LLM-judge drift is the+known failure mode. **Effort:** M → S with CC. **Priority:** P3.+**Depends on:** persona-fleet harness (shared runner shape).++### P3: Quarterly Apple-journey live re-verification++**What:** Run the /ship Apple release adapter against a real (TestFlight-only)+release once a quarter, or on first user bug report, and fix drift. Apple's+APIs move (the fork caught fastlane price_tier breaking live); the adapter's+claims are evidence-backed today and must stay that way per its own+evidence-before-claimed-limitations rule.++**Effort:** S per run. **Priority:** P3. **Depends on:** a paid ADP account.++### P2: office-hours design-doc dual-write functional E2E (fork port wave 2 review shortfall)++**What:** A paid E2E (claude -p) that runs the office-hours Phase 5 handoff in+a tmp repo and asserts BOTH write paths (docs/designs/<topic>.md + the+~/.gstack copy) land and that `bin/gstack-redact` was invoked at the sink.+Today only a static prose pin exists (test/skill-validation.test.ts) — the+plan's R9 asked for the functional shape.++**Why:** The dual-write is an egress path into the user's repo; prose drift+that skips the redact scan-at-sink would ship user PII into git history with+nothing failing. **Effort:** M → S with CC. **Priority:** P2.+**Tier:** periodic (quality, non-deterministic).++### P2: migration runners honor per-migration skip state++**What:** Both migration runners (setup's post-setup block and+/gstack-upgrade Step 4.75) select migrations purely by version window, so a+migration that exits via the non-interactive default-skip (v1.27's+GSTACK_MIGRATE_ASSUME_YES gate) is never offered again — the version marker+advances past it. The remediation text now prints the honest direct+invocation, but the runners should track per-migration .done/.skipped+touchfiles and re-offer pending ones on the next interactive run.++**Why:** Every remaining pre-v1.27 user upgrading via an agent session ([ -t 0 ]+false) permanently misses the artifacts-rename migration unless they paste the+manual command. **Effort:** M. **Priority:** P2.++### P2: periodic tier — three documented-red tests need structural repair++**What:** (1) The sidebar E2E trio (navigate, url-accuracy, css-interaction)+POSTs to /sidebar-command and /sidebar-chat — endpoints removed on every tree+when the PTY terminal replaced the chat queue (server.ts tombstone ~2671);+rewrite them against the PTY surface or delete them. (2)+skill-e2e-ship-idempotency: the PTY child sits at the Claude Code welcome+screen in plan mode for the full budget — the typed /ship never lands+(readiness/typing race vs CLI v2.1.233's welcome screen); never green since+it was born in v1.63. (3) skill-e2e-brain-privacy-gate: never green anywhere;+the artifacts-sync stop-gate preconditions don't survive the hermetic env+even with per-test HOME/GSTACK_HOME injection — needs a transcript-level+debug of what the child's preamble actually echoes.++**Why:** every red periodic run costs triage time; two of these have burned+three triage passes across two releases. **Effort:** M. **Priority:** P2.+### P1: #1882 — portable skill-install prefix (non-`gstack` install dirs break silently)**What:** Every generated SKILL.md hardcodes the literal `~/.claude/skills/gstack/...`@@ -25,6 +107,9 @@ So #1882 is now purely the body-preamble portability work.invocation-time failures.**Cons:** Touches the most load-bearing bash in the repo (every skill's preamble);a silent mistake breaks all 52 skills. High blast radius — needs its own focused PR.+**Note (fork port wave 2):** the Apple release adapter (ship/sections/+apple-release.md) added template surface with `~/.claude/skills/gstack/bin`+references — include it in this fix's coverage list.**Context / where to start:**- Rewire `ctx.paths.binDir` (and browse/design dir paths) + the ~9 resolvers thatdiff --git a/VERSION b/VERSIONindex 362038af8..acfd5a8ce 100644--- a/VERSION+++ b/VERSION@@ -1 +1 @@-1.64.1.0+1.65.0.0diff --git a/autoplan/SKILL.md b/autoplan/SKILL.mdindex 6c4a143b5..f24a1cdcb 100644--- a/autoplan/SKILL.md+++ b/autoplan/SKILL.md@@ -682,6 +682,10 @@ When options differ in coverage, include `Completeness: X/10` (10 = all edge casFor high-stakes ambiguity (architecture, data model, destructive scope, missing context), STOP. Name it in one sentence, present 2-3 options with tradeoffs, and ask. Do not use for routine coding or obvious changes.+## Claimed Limitations Need Evidence++A claimed limitation or requirement ("the API can't do this", "X requires a credential", "that's impossible on this platform") is a material claim. State one only with the verbatim error, the documented statement, or a live probe in hand — pattern-matching a failure to a familiar story is not evidence. When a cheap probe settles the question, run it BEFORE asking the user anything or declaring a step blocked.+## Continuous Checkpoint ModeIf `CHECKPOINT_MODE` is `"continuous"`: auto-commit completed logical units with `WIP:` prefix.@@ -900,8 +904,21 @@ After /office-hours completes, re-run the design doc check:setopt +o nomatch 2>/dev/null || true # zsh compatSLUG=$(~/.claude/skills/gstack/browse/bin/remote-slug 2>/dev/null || basename "$(git rev-parse --show-toplevel 2>/dev/null || pwd)")BRANCH=$(git rev-parse --abbrev-ref HEAD 2>/dev/null | tr '/' '-' || echo 'no-branch')-DESIGN=$(ls -t ~/.gstack/projects/$SLUG/*-$BRANCH-design-*.md 2>/dev/null | head -1)-[ -z "$DESIGN" ] && DESIGN=$(ls -t ~/.gstack/projects/$SLUG/*-design-*.md 2>/dev/null | head -1)+_LOCALDOC=$(ls -t ~/.gstack/projects/$SLUG/*-$BRANCH-design-*.md 2>/dev/null | head -1)+[ -z "$_LOCALDOC" ] && _LOCALDOC=$(ls -t ~/.gstack/projects/$SLUG/*-design-*.md 2>/dev/null | head -1)+# Repo-local docs win when at least as fresh (#703): office-hours dual-writes+# docs/designs/ alongside ~/.gstack, and the committed copy is what teammates+# see. A stale old repo doc never shadows a newer private session.+_REPOTOP=$(git rev-parse --show-toplevel 2>/dev/null || echo "")+_REPODOC=""+if [ -n "$_REPOTOP" ]; then+ [ -f "$_REPOTOP/DESIGN.md" ] && _REPODOC="$_REPOTOP/DESIGN.md"+ [ -z "$_REPODOC" ] && _REPODOC=$(ls -t "$_REPOTOP"/docs/designs/*.md 2>/dev/null | head -1)+fi+DESIGN="$_LOCALDOC"+if [ -n "$_REPODOC" ] && { [ -z "$_LOCALDOC" ] || [ "$_REPODOC" -nt "$_LOCALDOC" ]; }; then+ DESIGN="$_REPODOC"+fi[ -n "$DESIGN" ] && echo "Design doc found: $DESIGN" || echo "No design doc found"```@@ -1676,12 +1693,12 @@ if command -v jq >/dev/null 2>&1; then# Filter to current branch + recent commits, then keep records for the# latest run_id only. (Single phase may have multiple files if the user# re-ran the review; aggregator takes the newest.)- # NOTE: bind .commit BEFORE the split pipe. Inside ($commits | split(...))- # the "." context is the resulting ARRAY, so a bare .commit there raises- # "Cannot index array with string" on every record — and the 2>/dev/null- # below swallows it, so the whole aggregation silently yields zero tasks.+ # .commit must be bound BEFORE piping to the split commit array: a+ # pipe rebinds jq's context, so a bare .commit after it indexes the+ # ARRAY with a string, every line errors into 2>/dev/null, and the+ # aggregate is empty forever — the #2018 zero-tasks bug.jq -c --arg branch "$BRANCH" --arg commits "$COMMITS_RECENT" \- 'select(.branch == $branch and ((.commit) as $c | ($commits | split("|") | index($c)) != null))' \+ '.commit as $c | select(.branch == $branch and ($commits | split("|") | index($c) != null))' \"$f" 2>/dev/null >> "$ALL_JSONL" || truedone < <(find "$TASKS_DIR" -maxdepth 1 -name "tasks-$phase-*.jsonl" 2>/dev/null | sort)# Reduce to latest run_id per phasediff --git a/bin/chrome-cdp b/bin/chrome-cdpdeleted file mode 100755index 35f34a405..000000000--- a/bin/chrome-cdp+++ /dev/null@@ -1,70 +0,0 @@-#!/bin/bash-# Launch Chrome with CDP (remote debugging) enabled.-# Usage: chrome-cdp [port]-#-# Chrome refuses --remote-debugging-port on its default data directory.-# We create a separate data dir with a symlink to the user's real profile,-# so Chrome thinks it's non-default but uses the same cookies/extensions.--PORT="${1:-9222}"-CHROME="/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"-REAL_PROFILE="$HOME/Library/Application Support/Google/Chrome"-CDP_DATA_DIR="$HOME/.gstack/cdp-profile/chrome"--if ! [ -f "$CHROME" ]; then- echo "Chrome not found at $CHROME" >&2- exit 1-fi--# Check if Chrome is running-if pgrep -f "Google Chrome" >/dev/null 2>&1; then- echo "Chrome is still running. Quitting..."- osascript -e 'tell application "Google Chrome" to quit' 2>/dev/null-- # Wait for it to fully exit- for i in $(seq 1 20); do- pgrep -f "Google Chrome" >/dev/null 2>&1 || break- sleep 0.5- done-- if pgrep -f "Google Chrome" >/dev/null 2>&1; then- echo "Chrome won't quit. Force-killing..." >&2- pkill -f "Google Chrome"- sleep 1- fi-fi--# Set up CDP data dir with symlinked profile-# Chrome requires a "non-default" data dir for --remote-debugging-port.-# We symlink the real Default profile so cookies/extensions carry over.-mkdir -p "$CDP_DATA_DIR"-if [ -d "$REAL_PROFILE/Default" ] && ! [ -e "$CDP_DATA_DIR/Default" ]; then- ln -s "$REAL_PROFILE/Default" "$CDP_DATA_DIR/Default"- echo "Linked real Chrome profile into CDP data dir"-fi-# Also link Local State (contains crypto keys for cookie decryption, etc.)-if [ -f "$REAL_PROFILE/Local State" ] && ! [ -e "$CDP_DATA_DIR/Local State" ]; then- ln -s "$REAL_PROFILE/Local State" "$CDP_DATA_DIR/Local State"-fi--echo "Launching Chrome with CDP on port $PORT..."-"$CHROME" \- --remote-debugging-port="$PORT" \- --remote-debugging-address=127.0.0.1 \- --remote-allow-origins="http://127.0.0.1:$PORT" \- --user-data-dir="$CDP_DATA_DIR" \- --restore-last-session &-disown--# Wait for CDP to be available-for i in $(seq 1 30); do- if curl -s "http://127.0.0.1:$PORT/json/version" >/dev/null 2>&1; then- echo "CDP ready on port $PORT"- echo "Run: \$B connect chrome"- exit 0- fi- sleep 1-done--echo "CDP not available after 30s." >&2-exit 1diff --git a/bin/gstack-brain-context-load.ts b/bin/gstack-brain-context-load.tsindex 8ad4eb63c..9a8efe998 100644--- a/bin/gstack-brain-context-load.ts+++ b/bin/gstack-brain-context-load.ts@@ -34,9 +34,9 @@* gstack-brain-context-load --quiet*/-import { existsSync, readFileSync, statSync, readdirSync } from "fs";-import { join, dirname, basename, resolve } from "path";-import { execFileSync, spawnSync } from "child_process";+import { existsSync, readFileSync, statSync, readdirSync, accessSync, constants } from "fs";+import { join, dirname, basename, resolve, delimiter } from "path";+import { spawnSync } from "child_process";import { homedir } from "os";import { parseSkillManifest, type GbrainManifest, type GbrainManifestQuery, withErrorContext } from "../lib/gstack-memory-helpers";@@ -68,7 +68,9 @@ interface QueryResult {const HOME = homedir();const GSTACK_HOME = process.env.GSTACK_HOME || join(HOME, ".gstack");-const MCP_TIMEOUT_MS = 500;+// 500ms hard cap per Section 1C; overridable for slow/loaded environments+// (test harnesses under CI load, cold CLI starts).+const MCP_TIMEOUT_MS = Math.max(1, parseInt(process.env.GSTACK_BRAIN_TIMEOUT_MS || "", 10) || 500);const PAGE_SIZE_CAP = 10 * 1024; // 10KB per query result before truncation// ── CLI ────────────────────────────────────────────────────────────────────@@ -190,16 +192,28 @@ function resolveSkillFile(args: CliArgs): string | null {// ── Dispatchers ────────────────────────────────────────────────────────────+let gbrainOnPath: boolean | null = null;+function gbrainAvailable(): boolean {- try {- execFileSync("gbrain", ["--version"], {- stdio: "ignore",- timeout: MCP_TIMEOUT_MS,- });- return true;- } catch {- return false;- }+ // Stat-based PATH scan, memoized. Spawning `gbrain --version` under the+ // 500ms budget misreported gbrain as missing whenever a cold process spawn+ // exceeded the timeout (loaded machine, node-based CLI cold start), and+ // re-probing per query burned 3x the budget before any real work.+ if (gbrainOnPath !== null) return gbrainOnPath;+ const exts = process.platform === "win32"+ ? (process.env.PATHEXT || ".COM;.EXE;.BAT;.CMD").split(";")+ : [""];+ gbrainOnPath = (process.env.PATH || "").split(delimiter).some((dir) =>+ dir !== "" && exts.some((ext) => {+ try {+ accessSync(join(dir, `gbrain${ext}`), constants.X_OK);+ return true;+ } catch {+ return false;+ }+ })+ );+ return gbrainOnPath;}function dispatchVector(q: GbrainManifestQuery, args: CliArgs): QueryResult {diff --git a/bin/gstack-code-intelligence b/bin/gstack-code-intelligencenew file mode 100755index 000000000..dbe765e13--- /dev/null+++ b/bin/gstack-code-intelligence@@ -0,0 +1,284 @@+#!/usr/bin/env bun+/**+ * gstack-code-intelligence — pick a code-intelligence provider and use it to+ * index and search this repo. OPTIONAL: with nothing selected, gstack works+ * fine and callers use grep / the file-only decision store.+ *+ * Portions copyright (c) 2026 Sina Matian, time-attack/gstack (GStack 2), MIT.+ *+ * Usage:+ * gstack-code-intelligence suggest [repo] [--json] # should the one-time indexing offer be made here?+ * gstack-code-intelligence options # list providers (GBrain first) + availability+ * gstack-code-intelligence status # current selection + availability+ * gstack-code-intelligence consent [repo-path] <yes|no> # record per-repo indexing consent (value REQUIRED)+ * gstack-code-intelligence select <gbrain|sourcebot|graphify|none>+ * gstack-code-intelligence index [repo-path] # index the repo with the selected provider+ * gstack-code-intelligence search <query...> # search via the selected provider+ *+ * Non-local providers (GBrain, or a Sourcebot on a remote host) refuse to index+ * until you consent for that repo. Graphify and a localhost Sourcebot are local:+ * nothing leaves the machine, so no consent is needed. Graphify is never+ * auto-installed.+ */++import { createHash } from "crypto";+import { realpathSync } from "fs";+import { hostname } from "os";+import { basename, resolve } from "path";+import {+ CodeProviderError,+ RECOMMENDED_ORDER,+ detectAvailable,+ getRoot,+ hasConsent,+ providerById,+ readSelection,+ resolveSelectedProvider,+ setConsent,+ setProvider,+ setRoot,+ shouldOfferIndexing,+ type CodeProviderId,+} from "../lib/code-intelligence";++const PROVIDER_IDS = new Set<CodeProviderId>(["gbrain", "sourcebot", "graphify"]);+const LABEL: Record<CodeProviderId, string> = { gbrain: "GBrain", sourcebot: "Sourcebot", graphify: "Graphify" };+const NOTE: Record<CodeProviderId, string> = {+ gbrain: "recommended; federated memory + code (sends content to your GBrain DB)",+ sourcebot: "self-hosted whole-repo regex search (local when on localhost)",+ graphify: "local tree-sitter code graph, nothing leaves the machine (install it yourself)",+};++function out(s: string): void {+ process.stdout.write(`${s}\n`);+}+function fail(s: string): never {+ process.stderr.write(`gstack-code-intelligence: ${s}\n`);+ process.exit(1);+}++async function cmdOptions(): Promise<void> {+ out("Code-intelligence providers (indexing is optional; GBrain recommended):\n");+ const avail = await detectAvailable();+ const byId = new Map(avail.map((a) => [a.id, a]));+ for (const id of RECOMMENDED_ORDER) {+ const a = byId.get(id);+ const mark = a?.available ? "available" : "not available";+ out(` ${id === "gbrain" ? "*" : " "} ${LABEL[id].padEnd(10)} [${mark}] — ${NOTE[id]}`);+ if (a?.detail) out(` ${a.detail}`);+ }+ out("\nSelect one with: gstack-code-intelligence select <provider>");+}++async function cmdStatus(): Promise<void> {+ const sel = readSelection();+ out(`selected: ${sel.provider ?? "none (grep / file-only fallback)"}`);+ const avail = await detectAvailable();+ for (const a of avail) out(` ${LABEL[a.id]}: ${a.available ? "available" : "unavailable"} (${a.detail})`);+}++/**+ * The one-time session-start offer gate. Prints (or emits as JSON) whether an+ * agent should ask the user about indexing this repo, and when it should, the+ * provider options with their reasons so the question is self-contained.+ */+async function cmdSuggest(rest: string[]): Promise<void> {+ const json = rest.includes("--json");+ const pathArg = rest.find((a) => !a.startsWith("--"));+ const repoPath = resolve(pathArg ?? process.cwd());+ const suggestion = shouldOfferIndexing(repoPath);+ if (!suggestion.offer) {+ if (json) {+ out(JSON.stringify({ ...suggestion, repoPath }));+ } else {+ out(`no offer (${suggestion.reason}${suggestion.fileCount != null ? `, ${suggestion.fileCount} tracked files` : ""})`);+ }+ return;+ }+ const avail = await detectAvailable();+ if (json) {+ out(JSON.stringify({+ ...suggestion,+ repoPath,+ options: avail.map((a) => ({+ id: a.id,+ label: LABEL[a.id],+ reason: NOTE[a.id],+ local: providerById(a.id).local,+ available: a.available,+ detail: a.detail,+ })),+ }));+ return;+ }+ out(`offer indexing: ${suggestion.fileCount} tracked files (threshold ${suggestion.threshold}) and no prior decision`);+ await cmdOptions();+}++function cmdSelect(arg: string | undefined): void {+ if (arg === "none") {+ setProvider(null);+ out("code-intelligence declined; gstack uses grep / file-only fallback and will not ask again");+ return;+ }+ if (!arg || !PROVIDER_IDS.has(arg as CodeProviderId)) {+ fail("Usage: select <gbrain|sourcebot|graphify|none>");+ }+ const id = arg as CodeProviderId;+ setProvider(id);+ out(`selected ${LABEL[id]}.`);+ const provider = providerById(id);+ if (!provider.local) out(`${LABEL[id]} sends repo content off this machine — run \`consent\` in a repo before indexing it.`);+}++/**+ * Record per-repo indexing consent: `consent [repo-path] <yes|no>`.+ *+ * The yes|no value is REQUIRED (true/false also accepted). It is never+ * defaulted: an agent recording a user's "no" must persist consent DENIED,+ * and a missing/unknown value must record NOTHING — a consent gate that+ * assumes "yes" is a consent gate that lies.+ */+function cmdConsent(rest: string[]): void {+ const positional = rest.filter((a) => !a.startsWith("--"));+ const CONSENT_USAGE = "Usage: consent [repo-path] <yes|no> — the yes/no value is required; consent is never assumed";+ if (positional.length < 1 || positional.length > 2) fail(CONSENT_USAGE);+ const value = positional[positional.length - 1].toLowerCase();+ let consented: boolean;+ if (value === "yes" || value === "true") consented = true;+ else if (value === "no" || value === "false") consented = false;+ else fail(CONSENT_USAGE);+ const repoPath = resolve(positional.length === 2 ? positional[0] : process.cwd());+ setConsent(repoPath, consented);+ out(consented ? `indexing consent recorded for ${repoPath}` : `indexing consent DENIED for ${repoPath} (recorded)`);+}++/**+ * Host+path-hashed source id for GBrain/Sourcebot — the same approach as+ * deriveCodeSourceId in bin/gstack-gbrain-sync.ts. A bare basename collides:+ * two repos both named "api" (or the same repo on two machines against a+ * federated brain) would silently share one source. Suffix = first 8 hex of+ * sha1(`${hostname}::${realpath}`); base sanitized to gbrain's source-id+ * charset (lowercase alnum + interior hyphens) and capped so the whole id+ * stays within gbrain's 32-char limit.+ */+function hashedSourceId(repoPath: string): string {+ let real = repoPath;+ try {+ real = realpathSync(repoPath);+ } catch {+ // path may not exist yet at id-derivation time — hash the resolved form+ }+ const host = process.env.GSTACK_HOSTNAME || hostname();+ const suffix = createHash("sha1").update(`${host}::${real}`).digest("hex").slice(0, 8);+ const base =+ basename(real)+ .toLowerCase()+ .replace(/[^a-z0-9]+/g, "-")+ .replace(/^-+|-+$/g, "")+ .slice(0, 23)+ .replace(/-+$/, "") || "repo";+ return `${base}-${suffix}`;+}++async function cmdIndex(pathArg: string | undefined): Promise<void> {+ const provider = resolveSelectedProvider();+ if (!provider) fail("no provider selected; run `select <provider>` first");+ const repoPath = resolve(pathArg ?? process.cwd());+ // Indexing is write-class: hasConsent's default op class applies, so a+ // `deny` OR `read-only` repo trust policy vetoes it (code indexing writes+ // pages — same semantics as gstack-gbrain-sync's runCodeImport).+ const consented = hasConsent(repoPath);+ if (!provider!.local && !consented) {+ const recorded = readSelection().consents[repoPath] === true;+ fail(recorded+ ? `${provider!.label} indexing is blocked by the repo trust policy (deny or read-only — code indexing writes pages). Change with: gstack-gbrain-repo-policy set <origin-url> read-write`+ : `${provider!.label} would send this repo's content off the machine. Run \`gstack-code-intelligence consent ${repoPath} yes\` first.`);+ }+ // Graphify keys sources on the repo path; GBrain/Sourcebot on a short+ // host+path-hashed id (bare basenames collide across same-named repos).+ const sourceId = provider!.id === "graphify" ? repoPath : hashedSourceId(repoPath);+ const repo = { id: sourceId, path: repoPath };+ try {+ const registered = await provider!.registerSource(repo, { consented });+ out(`registered ${repo.id} with ${provider!.label} (${registered.state})`);+ const refreshed = await provider!.refresh({ id: registered.id }, { consented });+ // Remember which repo this provider indexed so `search` reads the same graph.+ setRoot(provider!.id, repoPath);+ out(`indexed: ${refreshed.state}${refreshed.itemCount != null ? ` (${refreshed.itemCount} items)` : ""}`);+ } catch (err) {+ handleProviderError(err, provider!.label);+ }+}++async function cmdSearch(terms: string[]): Promise<void> {+ const query = terms.join(" ").trim();+ if (!query) fail("Usage: search <query...>");+ const provider = resolveSelectedProvider();+ if (!provider) fail("no provider selected; run `select <provider>` first (or use grep)");+ // Search is read-class: a read-only repo trust policy still allows it+ // (mirrors gstack-gbrain-sync: search allowed, page writes never), but a+ // deny tier — or no recorded consent at all — still refuses for non-local+ // providers, because the query text itself is repo-derived content. The+ // consent repo is the one this provider indexed (search reads that graph);+ // loopback providers need no consent, so their path is unchanged.+ const searchRoot = getRoot(provider!.id) ?? resolve(process.cwd());+ const consented = hasConsent(searchRoot, undefined, "read");+ // Honest pre-flight (mirrors cmdIndex): the adapter enforces the same gate+ // (assertEgressConsent throws PROVIDER_NOT_CONSENTED before any bytes or+ // receipt exist), but the CLI names WHY — missing consent vs a deny repo+ // trust policy — instead of surfacing a generic provider error.+ if (!provider!.local && !consented) {+ const recorded = readSelection().consents[searchRoot] === true;+ fail(recorded+ ? `${provider!.label} search is blocked by the repo trust policy (deny — the query text is repo-derived content). Change with: gstack-gbrain-repo-policy set <origin-url> read-only (search allowed) or read-write`+ : `${provider!.label} would send the query text (repo-derived content) off this machine. Run \`gstack-code-intelligence consent ${searchRoot} yes\` first.`);+ }+ try {+ const hits = await provider!.search(query, { limit: 10, consented });+ if (!hits.length) {+ out("(no results)");+ return;+ }+ for (const h of hits) out(`${h.score != null ? `[${h.score.toFixed(2)}] ` : ""}${h.ref}${h.snippet ? ` — ${h.snippet}` : ""}`);+ } catch (err) {+ handleProviderError(err, provider!.label);+ }+}++function handleProviderError(err: unknown, label: string): never {+ if (err instanceof CodeProviderError) {+ if (err.code === "PROVIDER_UNAVAILABLE") {+ fail(`${label} is unavailable (${err.message}). gstack still works — fall back to grep / file-only.`);+ }+ if (err.code === "PROVIDER_NOT_CONSENTED") {+ fail(`${label} ${err.code}: ${err.message} Run \`gstack-code-intelligence consent <repo-path> yes\` first (a deny repo trust policy overrides recorded consent).`);+ }+ fail(`${label} ${err.code}: ${err.message}`);+ }+ fail(err instanceof Error ? err.message : String(err));+}++async function main(): Promise<void> {+ const [action, ...rest] = process.argv.slice(2);+ switch (action) {+ case "suggest":+ return cmdSuggest(rest);+ case "options":+ return cmdOptions();+ case "status":+ return cmdStatus();+ case "select":+ return cmdSelect(rest[0]);+ case "consent":+ return cmdConsent(rest);+ case "index":+ return cmdIndex(rest[0]);+ case "search":+ return cmdSearch(rest);+ default:+ fail("Usage: suggest [path] [--json] | options | status | select <provider> | consent [path] <yes|no> | index [path] | search <query...>");+ }+}++main().catch((err) => fail(err instanceof Error ? err.message : String(err)));diff --git a/bin/gstack-config b/bin/gstack-configindex c2f8cfb24..575f93523 100755--- a/bin/gstack-config+++ b/bin/gstack-config@@ -133,6 +133,8 @@ lookup_default() {redact_repo_visibility) echo "" ;; # empty → fall through to gh/glab detectionredact_prepush_hook) echo "false" ;;+ pair_agent) echo "off" ;; # remote tunnel consent — fail-closed until /pair-agent asks+ founder_resources) echo "true" ;; # office-hours resource pitch — #538 permanent opt-out sets false# Brain-aware planning (v1.48 / T5+T10+T16). Defaults documented inline:# brain_trust_policy@<endpoint-id> — unset on fresh install; setup-gbrain# writes 'personal' for local engines,@@ -319,6 +321,14 @@ case "${1:-}" inecho "Warning: redact_prepush_hook '$VALUE' not recognized. Valid values: true, false. Using false." >&2VALUE="false"fi+ if [ "$KEY" = "pair_agent" ] && [ "$VALUE" != "on" ] && [ "$VALUE" != "off" ]; then+ echo "Warning: pair_agent '$VALUE' not recognized. Valid values: on, off. Using off." >&2+ VALUE="off"+ fi+ if [ "$KEY" = "founder_resources" ] && [ "$VALUE" != "true" ] && [ "$VALUE" != "false" ]; then+ echo "Warning: founder_resources '$VALUE' not recognized. Valid values: true, false. Using true." >&2+ VALUE="true"+ fiif [ "$KEY" = "plan_tune_hooks" ] && [ "$VALUE" != "prompt" ] && [ "$VALUE" != "yes" ] && [ "$VALUE" != "no" ]; thenecho "Warning: plan_tune_hooks '$VALUE' not recognized. Valid values: prompt, yes, no. Using prompt." >&2VALUE="prompt"diff --git a/bin/gstack-context-bill b/bin/gstack-context-billindex 50b085700..a0cac12a7 100755--- a/bin/gstack-context-bill+++ b/bin/gstack-context-bill@@ -2,6 +2,7 @@// gstack-context-bill — token bill-of-materials for an installed skills tree.// All behavior lives in lib/context-bill.ts; this is the CLI shim.+import '../lib/conductor-env-shim'; // --exact needs GSTACK_ANTHROPIC_API_KEY promotion inside Conductorimport { contextBillMain } from '../lib/context-bill';process.exit(await contextBillMain(process.argv.slice(2)));diff --git a/bin/gstack-decision-log b/bin/gstack-decision-logindex 17708980b..6ee838955 100755--- a/bin/gstack-decision-log+++ b/bin/gstack-decision-log@@ -51,39 +51,64 @@ if (args.includes("--compact")) {process.exit(0);}+// The payload is identified by its leading `{`, not by "first non-flag arg" — a+// `--supersede <id> '{...}'` call would otherwise mistake the target id for the payload.+const jsonArg = args.find((a) => a.trimStart().startsWith("{"));++/** Parse + validate a decision payload. Exits 1 (nothing persisted) when it's bad. */+function validPayload(raw: string): DecisionEvent {+ let obj: Partial<DecisionEvent>;+ try {+ obj = JSON.parse(raw);+ } catch {+ process.stderr.write("gstack-decision-log: invalid JSON\n");+ process.exit(1);+ }+ if (obj.scope === "branch" && !obj.branch) obj.branch = gitBranch();+ const res = validateDecide(obj);+ if (!res.ok) {+ process.stderr.write(`gstack-decision-log: ${res.error}\n`);+ process.exit(1);+ }+ return res.event;+}+const supersedeId = flagValue(args, "--supersede");const redactId = flagValue(args, "--redact");if (supersedeId || redactId) {const kind = supersedeId ? "supersede" : "redact";const targetId = (supersedeId || redactId) as string;+ if (targetId.trimStart().startsWith("{")) {+ process.stderr.write(`gstack-decision-log: --${kind} needs the target decision id before the replacement JSON\n`);+ process.exit(1);+ }+ if (kind === "redact" && jsonArg) {+ process.stderr.write(+ "gstack-decision-log: --redact expunges and takes no replacement; log the replacement in its own call so it isn't dropped\n",+ );+ process.exit(1);+ }+ // Validate the replacement BEFORE anything is written, then append it FIRST and+ // retire the old one SECOND. Appends are individually atomic, so the only visible+ // interleaving is "both active" (recoverable); the reverse order could retire the+ // old decision and lose the replacement the user was recording.+ const replacement = jsonArg ? { ...validPayload(jsonArg), supersedes: targetId } : undefined;+ if (replacement) appendEvent(paths, replacement);appendEvent(paths, makeRefEvent(kind, targetId, { source: "agent" }));rebuildSnapshot(paths);enqueue();- console.log(`${kind}: ${targetId}`);+ console.log(replacement ? `${kind}: ${targetId} -> ${replacement.id}` : `${kind}: ${targetId}`);process.exit(0);}-const jsonArg = args.find((a) => !a.startsWith("--"));if (!jsonArg) {process.stderr.write("gstack-decision-log: provide a JSON decision, or --supersede/--redact <id>, or --compact\n",);process.exit(1);}-let obj: Partial<DecisionEvent>;-try {- obj = JSON.parse(jsonArg);-} catch {- process.stderr.write("gstack-decision-log: invalid JSON\n");- process.exit(1);-}-if (obj.scope === "branch" && !obj.branch) obj.branch = gitBranch();-const res = validateDecide(obj);-if (!res.ok) {- process.stderr.write(`gstack-decision-log: ${res.error}\n`);- process.exit(1);-}-appendEvent(paths, res.event);+const event = validPayload(jsonArg);+appendEvent(paths, event);rebuildSnapshot(paths);enqueue();-console.log(res.event.id);+console.log(event.id);diff --git a/bin/gstack-diff-scope b/bin/gstack-diff-scopeindex bf1b4af84..38450e6b1 100755--- a/bin/gstack-diff-scope+++ b/bin/gstack-diff-scope@@ -4,7 +4,15 @@# Or: gstack-diff-scope main → prints SCOPE_*=... linesset -euo pipefail-BASE="${1:-main}"+# Detect the repo's default branch when no arg is given (#703-class+# platform-agnostic rule): origin/HEAD -> origin/main -> origin/master -> main.+_default_base() {+ git symbolic-ref refs/remotes/origin/HEAD 2>/dev/null | sed 's|refs/remotes/origin/||' && return+ git rev-parse --verify -q origin/main >/dev/null 2>&1 && { echo "main"; return; }+ git rev-parse --verify -q origin/master >/dev/null 2>&1 && { echo "master"; return; }+ echo "main"+}+BASE="${1:-$(_default_base)}"# Get changed file listFILES=$(git diff "${BASE}...HEAD" --name-only 2>/dev/null || git diff "${BASE}" --name-only 2>/dev/null || echo "")diff --git a/bin/gstack-distill-free-text b/bin/gstack-distill-free-textindex 4f0688dcb..fe75c45a4 100755--- a/bin/gstack-distill-free-text+++ b/bin/gstack-distill-free-text@@ -197,8 +197,13 @@ RESULT=$(EVENTS_JSON="$EVENTS_JSON" DISTILL_PROMPT="$DISTILL_PROMPT" \const INPUT_PER_TOKEN = 1e-6;const OUTPUT_PER_TOKEN = 5e-6;+ // Host-neutral model resolution (mirrors lib/eval-model.ts — this inline+ // bun -e script cannot import repo-relative libs from an arbitrary cwd).+ const distillModel = process.env.GSTACK_EVAL_MODEL_DISTILL+ || process.env.GSTACK_EVAL_MODEL+ || "claude-haiku-4-5-20251001";const resp = await client.messages.create({- model: "claude-haiku-4-5-20251001",+ model: distillModel,max_tokens: 4096,messages: [{ role: "user", content: prompt }],});diff --git a/bin/gstack-gbrain-sync.ts b/bin/gstack-gbrain-sync.tsindex 8aa703e4b..4cf6709df 100644--- a/bin/gstack-gbrain-sync.ts+++ b/bin/gstack-gbrain-sync.ts@@ -42,6 +42,7 @@ import { detectAutopilot, decideSourceRemove, decideCodeSync } from "../lib/gbraimport { 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 { repoPolicyTier as sharedRepoPolicyTier } from "../lib/gbrain-repo-policy-client";import { checkOwnedStagingDir } from "../lib/staging-guard";// ── Types ──────────────────────────────────────────────────────────────────@@ -778,6 +779,40 @@ function warnProbeTimeout(stage: "code" | "memory" | "dream"): void {}+/**+ * Per-repo trust tier from ~/.gstack/gbrain-repo-policy.json, read through+ * the bin/gstack-gbrain-repo-policy CLI (which owns URL normalization and+ * schema migration — do not reimplement either here).+ *+ * The tier was previously enforced only in /sync-gbrain skill prose, so a+ * direct or cron invocation of this script ingested repo code regardless of+ * a `deny`/`read-only` setting — and the egress receipt below cited this+ * chokepoint as consent before it existed (#2140 sync path). This check+ * closes both gaps.+ *+ * Fail-open ONLY when no policy store exists (nothing was ever set — same+ * behavior as before for every non-policy user, and skips the subprocess).+ * Fail-closed ("error") when a store exists but can't be read: a policy the+ * user set must not be silently bypassed by a broken store or missing jq.+ *+ * Reads through the shared lib/gbrain-repo-policy-client.ts (same client as+ * the code-intelligence consent veto — the two gates can never drift, and+ * win32 gets the invoke-via-bash path). A spawn failure is still fail-closed+ * but says so, instead of the misleading "store could not be read".+ */+export function repoPolicyTier(url: string | null): "read-write" | "read-only" | "deny" | "unset" | "error" {+ const res = sharedRepoPolicyTier(url, process.env);+ if (res.error === "spawn-failed") {+ process.stderr.write(+ "[gstack-gbrain-sync] the repo-policy helper could not be spawned (bash missing from PATH?) — " ++ "refusing ingest rather than bypassing a possibly-set policy\n",+ );+ return "error";+ }+ if (res.error) return "error";+ return res.tier === "none" ? "unset" : res.tier;+}+async function runCodeImport(args: CliArgs): Promise<StageResult> {const t0 = Date.now();const root = repoRoot();@@ -787,6 +822,36 @@ async function runCodeImport(args: CliArgs): Promise<StageResult> {const sourceId = deriveCodeSourceId(root);+ // Per-repo trust tier — checked BEFORE the dry-run branch so previews report+ // the refusal honestly instead of claiming they would sync.+ const policyUrl = originUrl();+ const tier = repoPolicyTier(policyUrl);+ if (tier === "read-only") {+ // Honoring an explicit user setting (search allowed, page writes never) is+ // a clean skip, not a stage failure — code ingest writes pages.+ return {+ name: "code",+ ran: false,+ ok: true,+ duration_ms: Date.now() - t0,+ summary: `skipped — repo policy is read-only for ${policyUrl} (code ingest writes pages). Change with: gstack-gbrain-repo-policy set ${policyUrl} read-write`,+ detail: { source_id: sourceId, source_path: root, status: "skipped-policy-read-only" },+ };+ }+ if (tier === "deny" || tier === "error") {+ const why = tier === "deny"+ ? `repo policy is deny for ${policyUrl} — no gbrain ingest for this repo. Change with: gstack-gbrain-repo-policy set ${policyUrl} read-write`+ : "repo policy store exists but could not be read (gstack-gbrain-repo-policy get failed) — refusing ingest rather than bypassing a set policy";+ return {+ name: "code",+ ran: true,+ ok: false,+ duration_ms: Date.now() - t0,+ summary: `refused: ${why}`,+ detail: { source_id: sourceId, source_path: root, status: tier === "deny" ? "refused-policy-deny" : "refused-policy-unreadable" },+ };+ }+// dry-run preview always shows the would-do steps, regardless of local// engine state. Useful for "what would /sync-gbrain do" without probing// the engine.diff --git a/bin/gstack-memory-ingest.ts b/bin/gstack-memory-ingest.tsindex f5d92b20d..4aeba0b69 100644--- a/bin/gstack-memory-ingest.ts+++ b/bin/gstack-memory-ingest.ts@@ -52,8 +52,9 @@ import {readSync,closeSync,rmSync,+ realpathSync,} from "fs";-import { join, basename, dirname } from "path";+import { join, basename, dirname, delimiter } from "path";import { execFileSync, spawnSync, spawn, type ChildProcess } from "child_process";import { homedir } from "os";import { createHash } from "crypto";@@ -1458,13 +1459,40 @@ function runGbrainImportOnce(// still reporting `written: N` from the staged count. Silent data loss// on every run. A working run logs `import.collect_files done ... files=N`// with N > 0 and takes minutes, not seconds.- const child = spawnGbrainAsync([- "import",- stagingDir,- "--no-embed",- ...(includeGitignored ? ["--include-gitignored"] : []),- "--json",- ]);+ //+ // GIT_CEILING_DIRECTORIES is the second layer of the same #2144 defense:+ // it stops git's upward repo discovery at the staging dir's parent, so a+ // git-enumerating collector fails cleanly out of the git fast path and+ // falls back to its plain FS walk even on gbrain builds whose flag+ // semantics drift. The ceiling must be the REAL path — git compares+ // canonicalized directories during discovery, and a staging dir reached+ // through a symlink (macOS /var -> /private/var, symlinked $GSTACK_HOME)+ // otherwise never matches the ceiling entry. Scoped to this one child;+ // no on-disk state, staging-guard/resume contracts untouched.+ let ceiling: string;+ try {+ ceiling = realpathSync(dirname(stagingDir));+ } catch {+ ceiling = dirname(stagingDir); // staging parent vanished mid-run; spawn will fail loudly anyway+ }+ const baseEnv: NodeJS.ProcessEnv = {+ ...process.env,+ // path.delimiter, not ':' — git splits this on ';' on Windows, and+ // drive-letter paths contain ':' themselves.+ GIT_CEILING_DIRECTORIES: process.env.GIT_CEILING_DIRECTORIES+ ? `${ceiling}${delimiter}${process.env.GIT_CEILING_DIRECTORIES}`+ : ceiling,+ };+ const child = spawnGbrainAsync(+ [+ "import",+ stagingDir,+ "--no-embed",+ ...(includeGitignored ? ["--include-gitignored"] : []),+ "--json",+ ],+ { baseEnv },+ );_activeImportChild = child;let stdout = "";let stderr = "";@@ -1941,6 +1969,18 @@ async function ingestPass(args: CliArgs): Promise<BulkResult> {: ""),);}+ // Silent-zero pathology detector (#2144's other half): pages were staged+ // but NOTHING imported or skipped-as-unchanged. That shape hid the dead+ // ingest for months — it must be loud even under --quiet, because a run+ // that indexes nothing is otherwise indistinguishable from a healthy one.+ const importedCount = (importJson.imported ?? 0) + (importJson.skipped ?? 0);+ if (prep.prepared.length > 0 && importedCount === 0 && (importJson.errors ?? 0) === 0) {+ console.error(+ `[memory-ingest] WARNING: ${prep.prepared.length} page(s) staged but gbrain collected ZERO ` ++ `(no imports, no unchanged-skips, no errors). This is the #2144 silent-zero shape — ` ++ `check gbrain's import.collect_files log line and your gbrain version.`,+ );+ }} finally {// #1802 D1: in remote-http mode `stagingDir` is the PERSISTENT transcript// dir (makePersistentTranscriptDir, under ~/.gstack/transcripts/) thatdiff --git a/bin/gstack-next-version b/bin/gstack-next-versionindex 455dd72f2..76879ddbd 100755--- a/bin/gstack-next-version+++ b/bin/gstack-next-version@@ -405,7 +405,32 @@ function parseArgs(argv: string[]): { base: string; bump: Bump; current: string;else if (a === "-h" || a === "--help") help = true;}if (help) return { base: "", bump: "micro", current: "", excludePR: null, help: true };- if (!base) base = "main";+ if (!base) {+ // Detect the default branch instead of assuming main (local-only repos+ // on trunk/master work like GitHub repos on main). Same probe order as+ // the canonical chain in bin/gstack-diff-scope and {{BASE_BRANCH_DETECT}}+ // (scripts/resolvers/utility.ts): origin/HEAD -> origin/main ->+ // origin/master -> literal "main". origin/HEAD is unset on plain clones+ // that never ran `git remote set-head`, so the rev-parse probes matter.+ try {+ const head = execFileSync("git", ["symbolic-ref", "refs/remotes/origin/HEAD"], { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] }).trim();+ base = head.replace("refs/remotes/origin/", "");+ } catch {+ // fall through to the rev-parse probes+ }+ if (!base) {+ for (const candidate of ["main", "master"]) {+ try {+ execFileSync("git", ["rev-parse", "--verify", "-q", `origin/${candidate}`], { stdio: ["ignore", "ignore", "ignore"] });+ base = candidate;+ break;+ } catch {+ // probe failed; try the next candidate+ }+ }+ }+ if (!base) base = "main";+ }if (!bump) {console.error("Error: --bump is required (major|minor|patch|micro)");process.exit(2);diff --git a/bin/gstack-paths b/bin/gstack-pathsindex ad89c6dcf..5b66e3102 100755--- a/bin/gstack-paths+++ b/bin/gstack-paths@@ -61,6 +61,12 @@ elif [ -n "${TMP:-}" ]; thenelse_tmp_root=".gstack/tmp"fi+# macOS exports TMPDIR with a trailing slash; mktemp templates built as+# "$TMP_ROOT/name-XXXXXX" would then carry "//", and any consumer comparing+# paths gets a spurious mismatch. Strip it (never strips a bare "/"). #2091+case "$_tmp_root" in+ */) [ "$_tmp_root" != "/" ] && _tmp_root="${_tmp_root%/}" ;;+esac# Strip any trailing slash so consumers can safely concatenate "$TMP_ROOT/name"# without producing a double slash. On macOS $TMPDIR ends in `/` by defaultdiff --git a/bin/gstack-telemetry-log b/bin/gstack-telemetry-logindex f94e25462..20febd32e 100755--- a/bin/gstack-telemetry-log+++ b/bin/gstack-telemetry-log@@ -210,6 +210,13 @@ fiSTEP_FIELD="null"[ -n "$FAILED_STEP" ] && STEP_FIELD="\"$(json_safe "$FAILED_STEP")\""+# Integrity first: a non-numeric duration would splice raw text into the+# JSON line ("duration_s":%s) and corrupt the whole JSONL stream — the range+# caps below silently no-op on non-integers because both test(1) comparisons+# fail. Reject anything that isn't a plain integer.+case "$DURATION" in+ ''|*[!0-9]*) DURATION="" ;;+esac# Cap unreasonable durationsif [ -n "$DURATION" ] && [ "$DURATION" -gt 86400 ] 2>/dev/null; thenDURATION="" # null if > 24hdiff --git a/bin/gstack-telemetry-sync b/bin/gstack-telemetry-syncindex 172fed623..1a4ac02b8 100755--- a/bin/gstack-telemetry-sync+++ b/bin/gstack-telemetry-sync@@ -81,15 +81,27 @@ while IFS= read -r LINE; do[ -z "$LINE" ] && continueecho "$LINE" | grep -q '^{' || continue- # Strip local-only fields (keep v, ts, sessions as-is for edge function)- CLEAN="$(echo "$LINE" | sed \- -e 's/,"_repo_slug":"[^"]*"//g' \- -e 's/,"_branch":"[^"]*"//g' \- -e 's/,"repo":"[^"]*"//g')"-- # If anonymous tier, strip installation_id- if [ "$TIER" = "anonymous" ]; then- CLEAN="$(echo "$CLEAN" | sed 's/,"installation_id":"[^"]*"//g; s/,"installation_id":null//g')"+ # Strip local-only fields (keep v, ts, sessions as-is for edge function).+ # jq del() is structural — a value containing an escaped quote (repo names,+ # branch names) can't smuggle the field past a regex or corrupt the strip.+ # The sed path stays only as a jq-less fallback.+ if command -v jq >/dev/null 2>&1; then+ if [ "$TIER" = "anonymous" ]; then+ CLEAN="$(printf '%s' "$LINE" | jq -c 'del(._repo_slug, ._branch, .repo, .installation_id)' 2>/dev/null)" || CLEAN=""+ else+ CLEAN="$(printf '%s' "$LINE" | jq -c 'del(._repo_slug, ._branch, .repo)' 2>/dev/null)" || CLEAN=""+ fi+ # A line jq can't parse is malformed telemetry — drop it rather than+ # forwarding bytes the strip never touched.+ [ -z "$CLEAN" ] && continue+ else+ CLEAN="$(echo "$LINE" | sed \+ -e 's/,"_repo_slug":"[^"]*"//g' \+ -e 's/,"_branch":"[^"]*"//g' \+ -e 's/,"repo":"[^"]*"//g')"+ if [ "$TIER" = "anonymous" ]; then+ CLEAN="$(echo "$CLEAN" | sed 's/,"installation_id":"[^"]*"//g; s/,"installation_id":null//g')"+ fifiif [ "$FIRST" = "true" ]; thendiff --git a/bin/gstack-verify-gate b/bin/gstack-verify-gatenew file mode 100755index 000000000..41f02cb5a--- /dev/null+++ b/bin/gstack-verify-gate@@ -0,0 +1,214 @@+#!/usr/bin/env bash+# gstack-verify-gate — Stop hook. Blocks the turn from ending until the+# project's declared verification command passes.+#+# Declare the command on one line in the project's CLAUDE.md:+# <!-- gstack:verify: bun test -->+#+# Read-or-ask: gstack never invents this command. No declaration, no gate.+# Fails open on every absence (no CLAUDE.md, no declaration, empty value).+#+# Trust boundary: hooks bypass the permission system, so a declared command+# NEVER runs until the user records it in the per-repo trust store:+# gstack-verify-gate --trust (run from inside the repo)+# The store maps realpath(repo root) -> sha256(command) at+# ${GSTACK_HOME:-$HOME/.gstack}/verify-gate-trust (flat "path<TAB>hash",+# 0600, atomic rewrite). Any edit to the declared command invalidates trust+# until --trust is run again. Untrusted commands never block the turn.+#+# Exit 0 = allow the turn to end, one-line reason on stdout.+# Exit 2 = block, Claude Code feeds stderr back to the agent.+#+# Remove with: gstack-settings-hook remove-source --source verify-gate+set -uo pipefail++TAB="$(printf '\t')"+STORE="${GSTACK_HOME:-$HOME/.gstack}/verify-gate-trust"++_sha256() {+ if command -v shasum >/dev/null 2>&1; then+ printf '%s' "$1" | shasum -a 256 | cut -d' ' -f1+ elif command -v sha256sum >/dev/null 2>&1; then+ printf '%s' "$1" | sha256sum | cut -d' ' -f1+ else+ printf '%s' "$1" | openssl dgst -sha256 | awk '{print $NF}'+ fi+}++# Resolve the project root: CLAUDE_PROJECT_DIR, else walk up from $PWD to+# the first directory containing CLAUDE.md. Sets ROOT (may lack CLAUDE.md).+_resolve_root() {+ ROOT="${CLAUDE_PROJECT_DIR:-$PWD}"+ while [ ! -f "$ROOT/CLAUDE.md" ] && [ "$ROOT" != "/" ]; do+ ROOT="$(dirname "$ROOT")"+ done+}++# Extract the declared command from $ROOT/CLAUDE.md into CMD (may be empty).+# Accepts both `<!-- gstack:verify: cmd -->` and bare `gstack:verify: cmd`.+_extract_cmd() {+ CMD="$(sed -n 's/^[[:space:]]*\(<!--[[:space:]]*\)\{0,1\}gstack:verify:[[:space:]]*\(.*\)$/\2/p' "$ROOT/CLAUDE.md" | head -1)"+ CMD="${CMD%%-->*}"+ CMD="$(printf '%s' "$CMD" | tr -d '`' | sed 's/[[:space:]]*$//')"+}++# Symlink-stable store key for the root.+_trust_key() {+ (cd "$ROOT" 2>/dev/null && pwd -P) || printf '%s' "$ROOT"+}++# Print the stored hash for key $1, or return 1 when absent.+_trusted_hash() {+ [ -f "$STORE" ] || return 1+ local p h+ while IFS="$TAB" read -r p h; do+ if [ "$p" = "$1" ]; then+ printf '%s' "$h"+ return 0+ fi+ done <"$STORE"+ return 1+}++# Record key $1 -> hash $2, replacing any prior entry. Atomic, 0600.+_record_trust() {+ local store_dir tmp p h+ store_dir="$(dirname "$STORE")"+ mkdir -p "$store_dir"+ tmp="$STORE.tmp.$$"+ : >"$tmp"+ chmod 600 "$tmp"+ if [ -f "$STORE" ]; then+ while IFS="$TAB" read -r p h; do+ [ "$p" = "$1" ] || printf '%s\t%s\n' "$p" "$h" >>"$tmp"+ done <"$STORE"+ fi+ printf '%s\t%s\n' "$1" "$2" >>"$tmp"+ mv -f "$tmp" "$STORE"+}++# Minimal JSON string escaping (backslash + double quote). CMD and paths are+# single-line by construction, so control characters never appear.+_json_escape() {+ printf '%s' "$1" | sed -e 's/\\/\\\\/g' -e 's/"/\\"/g'+}++# Forensic audit of trust grants. --trust stays agent-runnable (guardrail+# posture: catch accidents, not determined actors — same as the redaction+# guard), but a grant is never invisible: append {ts, root, cmd_sha256,+# cmd verbatim, tty} to a 0600 JSONL under GSTACK_HOME/security/.+# Args: $1 = root key, $2 = cmd sha256, $3 = cmd verbatim.+_log_trust_grant() {+ local sec_dir log tty ts+ sec_dir="${GSTACK_HOME:-$HOME/.gstack}/security"+ log="$sec_dir/verify-gate-trust-grants.jsonl"+ tty=false+ [ -t 0 ] && tty=true+ ts="$(date -u +%Y-%m-%dT%H:%M:%SZ)"+ mkdir -p "$sec_dir"+ [ -f "$log" ] || : >"$log"+ chmod 600 "$log" 2>/dev/null || true+ printf '{"ts":"%s","root":"%s","cmd_sha256":"%s","cmd":"%s","tty":%s}\n' \+ "$ts" "$(_json_escape "$1")" "$2" "$(_json_escape "$3")" "$tty" >>"$log"+}++if [ "${1:-}" = "--trust" ]; then+ _resolve_root+ if [ ! -f "$ROOT/CLAUDE.md" ]; then+ echo "verify-gate: no CLAUDE.md above $PWD, nothing to trust." >&2+ exit 1+ fi+ _extract_cmd+ if [ -z "$CMD" ]; then+ echo "verify-gate: $ROOT/CLAUDE.md declares no 'gstack:verify:' command, nothing to trust." >&2+ exit 1+ fi+ KEY="$(_trust_key)"+ HASH="$(_sha256 "$CMD")"+ _record_trust "$KEY" "$HASH"+ _log_trust_grant "$KEY" "$HASH" "$CMD"+ echo "verify-gate: trusted '$CMD' for $ROOT."+ exit 0+fi++INPUT=""+[ -t 0 ] || INPUT="$(cat)"++# Claude Code re-runs Stop hooks after a block (stop_hook_active=true). A+# re-entry is NOT a free pass: the gate re-runs the trusted check so an agent+# can't clear a red verification by simply stopping again. Re-entry blocks are+# bounded per episode (MAX_REENTRY_BLOCKS) so a stuck check can't loop forever;+# at the bound the gate allows with a loud warning.+REENTRY=0+if printf '%s' "$INPUT" | grep -q '"stop_hook_active"[[:space:]]*:[[:space:]]*true'; then+ REENTRY=1+fi++_resolve_root++if [ ! -f "$ROOT/CLAUDE.md" ]; then+ echo "verify-gate: no CLAUDE.md above $PWD, no check declared, allowing."+ exit 0+fi++_extract_cmd++if [ -z "$CMD" ]; then+ echo "verify-gate: $ROOT/CLAUDE.md declares no 'gstack:verify:' command, allowing."+ exit 0+fi++# Trust gate: never execute a declared command the user has not recorded.+# Applies on re-entry too — untrusted commands keep the exit-0-with-hint path.+if [ "$(_trusted_hash "$(_trust_key)" || true)" != "$(_sha256 "$CMD")" ]; then+ echo "verify-gate: found '$CMD' in $ROOT/CLAUDE.md but it is not trusted yet, skipping; enable with: cd $ROOT && $0 --trust" >&2+ echo "verify-gate: declared command not trusted, allowing."+ exit 0+fi++# Episode-scoped re-entry attempt counter. Keyed by the hook-input session_id+# when present, else ppid+root — stale entries are fine to overwrite.+MAX_REENTRY_BLOCKS=3+_session_key() {+ local sid+ sid="$(printf '%s' "$INPUT" | sed -n 's/.*"session_id"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' | head -1)"+ [ -n "$sid" ] || sid="ppid-$PPID"+ _sha256 "$sid|$(_trust_key)"+}+ATTEMPTS_DIR="${GSTACK_HOME:-$HOME/.gstack}/verify-gate-attempts"+COUNTER="$ATTEMPTS_DIR/$(_session_key)"++# A first entry (stop_hook_active=false) starts a fresh blocking episode.+if [ "$REENTRY" -eq 0 ]; then+ rm -f "$COUNTER" 2>/dev/null || true+fi++OUT="$(cd "$ROOT" && eval "$CMD" 2>&1)"+STATUS=$?++if [ "$STATUS" -eq 0 ]; then+ rm -f "$COUNTER" 2>/dev/null || true+ echo "verify-gate: declared check passed ($CMD)."+ exit 0+fi++if [ "$REENTRY" -eq 1 ]; then+ COUNT="$(cat "$COUNTER" 2>/dev/null || echo 0)"+ case "$COUNT" in+ ''|*[!0-9]*) COUNT=0 ;;+ esac+ if [ "$COUNT" -ge "$MAX_REENTRY_BLOCKS" ]; then+ rm -f "$COUNTER" 2>/dev/null || true+ WARN="verify-gate: WARNING — allowing after $MAX_REENTRY_BLOCKS blocked re-entries but the declared check is still FAILING ($CMD). Verification is RED; do not treat this turn as verified."+ echo "$WARN"+ echo "$WARN" >&2+ exit 0+ fi+ mkdir -p "$ATTEMPTS_DIR"+ echo $((COUNT + 1)) >"$COUNTER"+fi++echo "verify-gate: declared check FAILED with exit $STATUS: $CMD" >&2+printf '%s\n' "$OUT" | tail -20 >&2+echo "Fix the failure, or drop the gstack:verify line from $ROOT/CLAUDE.md." >&2+exit 2diff --git a/browse/SKILL.md b/browse/SKILL.mdindex 43a0188bb..d977f363f 100644--- a/browse/SKILL.md+++ b/browse/SKILL.md@@ -769,6 +769,28 @@ should route through `browse` — `screenshot --selector` for visual output,`npm i puppeteer` and downloading a second Chromium that drifts out of version sync.One install to pin, one daemon's lifecycle to manage.+## Session Persistence (opt-in)++By default the headless daemon's cookies and tab state die with it — a crash,+version auto-restart, or `browse stop` logs you out of everything (#778).+Opt in to persistence with `BROWSE_PERSIST_STATE=1` in the daemon's+environment: the daemon then snapshots cookies + per-tab+URL/localStorage/sessionStorage to `<stateDir>/session-state.json` (0600)+every 30 seconds and at clean shutdown, and restores it on the next launch.++Facts that matter:+- **Default OFF.** Cookies on disk are a real cost; the user opts in.+- **Headless only.** Headed mode's persistent Chromium profile already owns+ its state; replaying tabs would clobber the user's window.+- **Never persisted:** loaded HTML and tab ownership — a tampered state file+ cannot smuggle content past load-html's checks or forge ownership. Cookies+ for localhost, `.internal`, and cloud-metadata addresses are dropped on+ restore.+- **Corrupt state** is moved to `session-state.json.corrupt` (kept for+ diagnosis) and the daemon boots fresh — persistence can never block a+ launch. The boot log says which happened: `Session state restored: N+ cookies / M tabs` or `fresh session`.+## User HandoffWhen you hit something you can't handle in headless mode (CAPTCHA, complex auth, multi-factordiff --git a/browse/SKILL.md.tmpl b/browse/SKILL.md.tmplindex 9a159e4c9..1da7698b2 100644--- a/browse/SKILL.md.tmpl+++ b/browse/SKILL.md.tmpl@@ -216,6 +216,28 @@ should route through `browse` — `screenshot --selector` for visual output,`npm i puppeteer` and downloading a second Chromium that drifts out of version sync.One install to pin, one daemon's lifecycle to manage.+## Session Persistence (opt-in)++By default the headless daemon's cookies and tab state die with it — a crash,+version auto-restart, or `browse stop` logs you out of everything (#778).+Opt in to persistence with `BROWSE_PERSIST_STATE=1` in the daemon's+environment: the daemon then snapshots cookies + per-tab+URL/localStorage/sessionStorage to `<stateDir>/session-state.json` (0600)+every 30 seconds and at clean shutdown, and restores it on the next launch.++Facts that matter:+- **Default OFF.** Cookies on disk are a real cost; the user opts in.+- **Headless only.** Headed mode's persistent Chromium profile already owns+ its state; replaying tabs would clobber the user's window.+- **Never persisted:** loaded HTML and tab ownership — a tampered state file+ cannot smuggle content past load-html's checks or forge ownership. Cookies+ for localhost, `.internal`, and cloud-metadata addresses are dropped on+ restore.+- **Corrupt state** is moved to `session-state.json.corrupt` (kept for+ diagnosis) and the daemon boots fresh — persistence can never block a+ launch. The boot log says which happened: `Session state restored: N+ cookies / M tabs` or `fresh session`.+## User HandoffWhen you hit something you can't handle in headless mode (CAPTCHA, complex auth, multi-factordiff --git a/browse/src/browser-manager.ts b/browse/src/browser-manager.tsindex 109771c7b..af601b5d1 100644--- a/browse/src/browser-manager.ts+++ b/browse/src/browser-manager.ts@@ -73,6 +73,82 @@ export function shouldEnableChromiumSandbox(): boolean {return !(process.env.CI || process.env.CONTAINER || isRoot);}+/**+ * Thrown by probePoisonedChromiumBundle() when it finds — and removes — a+ * Chromium bundle poisoned by the pre-v1.64 in-place rebrand (#2242).+ * Call sites rethrow on `instanceof` (never message-string sniffing) so the+ * actionable remediation reaches the user instead of being swallowed by the+ * probe's fall-through-on-failure catch.+ */+export class PoisonedBundleError extends Error {+ constructor(message: string) {+ super(message);+ this.name = 'PoisonedBundleError';+ }+}++/**+ * Self-heal probe for bundles the OLD (pre-v1.64) rebrand code already+ * poisoned (#2242): the mutation lives in the SHARED Playwright cache, so+ * deleting the rebrand code fixes fresh installs only, and the documented+ * deploy paths never run upgrade migrations. Detect the mutated plist and+ * remove the bundle so the next `playwright install chromium` (or the+ * upgrade migration) re-fetches a clean one.+ *+ * Removal scope: when the .app sits in the standard Playwright cache layout+ * (chromium-<rev>/chrome-mac/<name>.app), the WHOLE chromium-<rev> revision+ * dir is removed — Playwright's INSTALLATION_COMPLETE marker lives there,+ * and `playwright install chromium` treats its presence as "is already+ * downloaded", so removing only the .app would turn our own remediation+ * command into a no-op that leaves the user with no browser at all. Outside+ * that layout, the .app plus any sibling INSTALLATION_COMPLETE /+ * DEPENDENCIES_VALIDATED markers are removed.+ *+ * Caller contract: pass ONLY Playwright-cache executables+ * (chromium.executablePath()). A bundle supplied via GSTACK_CHROMIUM_PATH+ * belongs to the wrapper/embedder — its plist legitimately says "GStack+ * Browser" — and must never be deleted. Both call sites (launchHeaded and+ * handoff) honor this, and as a second belt the probe refuses to act on the+ * GSTACK_CHROMIUM_PATH executable itself.+ *+ * @param chromiumExecutablePath the Chromium binary inside the .app+ * (…/<name>.app/Contents/MacOS/<name>), as returned by+ * chromium.executablePath().+ * @throws PoisonedBundleError after removing a poisoned bundle — the+ * message carries the re-fetch command for the user.+ */+export function probePoisonedChromiumBundle(chromiumExecutablePath: string): void {+ const fs = require('fs');+ const path = require('path');++ // Belt to the caller contract: never act on the custom/embedder bundle.+ const customPath = process.env.GSTACK_CHROMIUM_PATH;+ if (customPath && path.resolve(chromiumExecutablePath) === path.resolve(customPath)) {+ return;+ }++ const chromeContentsDir = path.resolve(path.dirname(chromiumExecutablePath), '..');+ const chromePlist = path.join(chromeContentsDir, 'Info.plist');+ if (!fs.existsSync(chromePlist)) return;+ if (!fs.readFileSync(chromePlist, 'utf-8').includes('GStack Browser')) return;++ const appDir = path.resolve(chromeContentsDir, '..');+ const revisionDir = path.resolve(appDir, '..', '..');+ if (/^chromium-\d+$/.test(path.basename(revisionDir))) {+ fs.rmSync(revisionDir, { recursive: true, force: true });+ } else {+ fs.rmSync(appDir, { recursive: true, force: true });+ for (const marker of ['INSTALLATION_COMPLETE', 'DEPENDENCIES_VALIDATED']) {+ fs.rmSync(path.join(path.dirname(appDir), marker), { force: true });+ }+ }+ throw new PoisonedBundleError(+ 'Chromium bundle was mutated by a previous gstack version (broken codesign seal — ' ++ 'GPU exit_code=5 on macOS 26). The poisoned bundle has been removed. ' ++ 'Re-fetch a clean one with: bunx playwright install chromium — then retry.',+ );+}+/*** Resolve why the underlying Chromium ChildProcess is going away.*@@ -199,6 +275,15 @@ export class BrowserManager {// ─── Headed State ────────────────────────────────────────private connectionMode: 'launched' | 'headed' = 'launched';++ /**+ * Fired when a RUNNING daemon is promoted to headed mode (see handoff()),+ * as opposed to starting headed. The server uses it to cancel the+ * parent-process watchdog, which was registered on the assumption that mode+ * is fixed at boot and would otherwise kill the freshly handed-off browser+ * the next time the spawning shell exits.+ */+ onHeadedPromotion?: () => void;private intentionalDisconnect = false;// ─── Tab Count Guardrail (D5 + Codex single-tab flag) ───────@@ -504,46 +589,32 @@ export class BrowserManager {// Used by GStack Browser.app to point at the bundled Chromium.const executablePath = process.env.GSTACK_CHROMIUM_PATH || undefined;- // Rebrand Chromium → GStack Browser in macOS menu bar / Dock / Cmd+Tab.- // Patch the Chromium .app's Info.plist so macOS shows our name.- // This works for both dev mode (system Playwright cache) and .app bundle.- const chromePath = executablePath || chromium.executablePath();- try {- // Walk up from binary to the .app's Info.plist- // e.g. .../Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing- // → .../Google Chrome for Testing.app/Contents/Info.plist- const chromeContentsDir = path.resolve(path.dirname(chromePath), '..');- const chromePlist = path.join(chromeContentsDir, 'Info.plist');- if (fs.existsSync(chromePlist)) {- const plistContent = fs.readFileSync(chromePlist, 'utf-8');- if (plistContent.includes('Google Chrome for Testing')) {- const patched = plistContent- .replace(/Google Chrome for Testing/g, 'GStack Browser');- fs.writeFileSync(chromePlist, patched);- }- // Replace Chromium's Dock icon with ours (Chromium's process owns the Dock icon)- const iconCandidates = [- path.join(__dirname, '..', '..', 'scripts', 'app', 'icon.icns'), // repo dev mode- path.join(process.env.HOME || '', '.claude', 'skills', 'gstack', 'scripts', 'app', 'icon.icns'), // global install- ];- const iconSrc = iconCandidates.find(p => fs.existsSync(p));- if (iconSrc) {- const chromeResources = path.join(chromeContentsDir, 'Resources');- // Read original icon name from plist- const iconMatch = plistContent.match(/<key>CFBundleIconFile<\/key>\s*<string>([^<]+)<\/string>/);- let origIcon = iconMatch ? iconMatch[1] : 'app';- if (!origIcon.endsWith('.icns')) origIcon += '.icns';- const destIcon = path.join(chromeResources, origIcon);- try {- fs.copyFileSync(iconSrc, destIcon);- } catch (err: any) {- if (err?.code !== 'ENOENT' && err?.code !== 'EACCES') throw err;- }- }+ // NOTE (#2242): the in-place "rebrand" that patched the Chromium .app's+ // Info.plist (global "Google Chrome for Testing" → "GStack Browser"+ // replace) and overwrote its Resources/*.icns is deliberately GONE.+ // Chrome for Testing is a code-signed bundle: the global replace renamed+ // CFBundleExecutable to a binary that doesn't exist and the plist/icon+ // writes broke the codesign seal — GPU process exit_code=5, headed mode+ // dead on macOS 26 (#2242, #2138, #2139). Branding belongs in the+ // GStack Browser.app wrapper (GSTACK_CHROMIUM_PATH), never in a mutation+ // of the signed bundle. Do not reintroduce writes into the Chromium+ // bundle here — browse/test/rebrand-signed-bundle.test.ts fails CI if+ // you do.+ //+ // Self-heal for bundles the OLD code already poisoned: probe the+ // Playwright-cache bundle and remove it when the mutated plist is+ // present (see probePoisonedChromiumBundle for the removal-scope+ // rationale). Scoped to the Playwright cache copy — a+ // GSTACK_CHROMIUM_PATH bundle belongs to the wrapper/embedder and is+ // never probed.+ if (!executablePath) {+ try {+ probePoisonedChromiumBundle(chromium.executablePath());+ } catch (err: unknown) {+ if (err instanceof PoisonedBundleError) throw err;+ // Probe failures (no bundle yet, EACCES) fall through to launch,+ // which produces its own actionable error.}- } catch (err: any) {- // Non-fatal: app name stays as Chrome for Testing (ENOENT/EACCES expected)- if (err?.code !== 'ENOENT' && err?.code !== 'EACCES') throw err;}// Build custom user agent: report as stock Chrome with the version@@ -1592,6 +1663,20 @@ export class BrowserManager {fs.mkdirSync(userDataDir, { recursive: true });cleanSingletonLocks(userDataDir);+ // Self-heal probe (#2242): handoff always launches the Playwright-cache+ // bundle (this launchPersistentContext call passes no executablePath),+ // so a bundle poisoned by the old in-place rebrand would GPU-crash here+ // exactly like launchHeaded(). Same probe, same contract: a+ // GSTACK_CHROMIUM_PATH bundle is never passed in. The rethrown typed+ // error surfaces through the outer catch as the actionable+ // "Cannot open headed browser" message, headless browser untouched.+ try {+ probePoisonedChromiumBundle(chromium.executablePath());+ } catch (err: unknown) {+ if (err instanceof PoisonedBundleError) throw err;+ // Probe failures (no bundle yet, EACCES) fall through to launch.+ }+// T1: same automation-tell-stripping defaults as launchHeaded().// The handoff path (headless → headed re-launch) takes the same// anti-detection posture.@@ -1624,6 +1709,14 @@ export class BrowserManager {this.tabSessions.clear();this.connectionMode = 'headed';+ // Promotion, not a headed boot. The server registered a parent-process+ // watchdog because this daemon started headless, and that watchdog kills+ // headed daemons when their parent exits — which for a CLI-spawned daemon+ // is immediately. Without this the handed-off browser dies ~15s later,+ // taking whatever the user was mid-way through (a login, an MFA prompt)+ // with it.+ this.onHeadedPromotion?.();+// Same Layer C stealth as launch()/launchHeaded(). Must run BEFORE// restoreState() navigates so the init scripts apply to the restored// pages — without this the handed-off browser had cmdline args but nodiff --git a/browse/src/bun-polyfill.cjs b/browse/src/bun-polyfill.cjsindex 99877471b..89e16c4fd 100644--- a/browse/src/bun-polyfill.cjs+++ b/browse/src/bun-polyfill.cjs@@ -77,7 +77,8 @@ globalThis.Bun = {cwd: options.cwd,// Node defaults windowsHide to false; Bun.spawn hides the console// window. Without this the shim silently inverts the behavior on the- // one platform it exists to serve. See the spawn() note below.+ // one platform it exists to serve — every console child pops a window.+ // Forwarded (not hardcoded) so an explicit windowsHide:false survives.windowsHide: options.windowsHide !== false,});@@ -97,108 +98,17 @@ globalThis.Bun = {cwd: options.cwd,// stdio:'ignore' silences a child's output but does not suppress its// console window on Windows. The terminal-agent respawn (server.ts- // watchdog, 60s ticker) therefore popped a visible bun.exe window on- // every respawn until this was forwarded.+ // watchdog, 60s ticker) popped a visible bun.exe window on every+ // respawn until this was forwarded. Forwarded, not hardcoded, so an+ // explicit windowsHide:false survives.windowsHide: options.windowsHide !== false,});- // Drain stdout/stderr eagerly into in-memory buffers. Bun's spawn buffers- // these for the consumer; Node's Readables are pull-based, so if the caller- // awaits `proc.exited` before reading, anything past the OS pipe buffer- // (~16-64 KB) back-pressures the child until it blocks in write() and- // `exit` never fires. Eager draining keeps the pipes flowing regardless- // of read order; replay below is via fresh Web ReadableStreams.- //- // Cap the buffer so a runaway child can't OOM the server. 16 MB is- // generous: DPAPI outputs are tiny, tasklist is <1 KB, and the- // browser-skill consumer has its own 1 MB readCapped. Once the cap is- // reached we keep draining the pipe (so the child never blocks) but- // discard further bytes. Override via GSTACK_SPAWN_MAX_BUFFER (bytes).- const MAX_BUFFER = Math.max(- 0,- parseInt(process.env.GSTACK_SPAWN_MAX_BUFFER || '', 10) || 16 * 1024 * 1024,- );- const drain = (stream) => {- if (!stream) return { done: Promise.resolve(), chunks: [], truncated: false };- const state = { chunks: [], bytes: 0, truncated: false };- const done = new Promise((resolve) => {- stream.on('data', (chunk) => {- if (state.bytes >= MAX_BUFFER) { state.truncated = true; return; }- if (state.bytes + chunk.length <= MAX_BUFFER) {- state.chunks.push(chunk);- state.bytes += chunk.length;- } else {- const remaining = MAX_BUFFER - state.bytes;- state.chunks.push(chunk.subarray(0, remaining));- state.bytes = MAX_BUFFER;- state.truncated = true;- }- });- // Any terminal event resolves: 'end' on normal close, 'error' on a- // stream-level error, 'close' as the belt-and-suspenders for spawn- // failures where Node fires 'close' but neither 'end' nor 'error'.- stream.once('end', resolve);- stream.once('error', resolve);- stream.once('close', resolve);- });- return { done, chunks: state.chunks };- };- const stdoutDrain = drain(proc.stdout);- const stderrDrain = drain(proc.stderr);-- // Bun's spawn exposes `proc.exited` as a Promise resolving to the exit- // code; several call sites — DPAPI decryption, isBrowserRunning,- // browser-skill-commands — `await proc.exited` directly or via- // Promise.race with a timeout. Without this, those awaits resolve to- // `undefined` immediately and the operation looks like a silent failure.- // Resolve only after both pipes have finished draining so consumers that- // read stdout AFTER awaiting exit see the full output, not a partial buffer.- const exited = new Promise((resolveExited) => {- let exitStatus;- proc.once('exit', (code, signal) => {- // Match Bun: exit code on normal exit; 128 + signal number on signal;- // 0 if neither was reported.- if (code !== null) exitStatus = code;- else if (signal) exitStatus = 128 + (require('os').constants.signals[signal] || 0);- else exitStatus = 0;- });- proc.once('error', () => {- if (exitStatus === undefined) exitStatus = 1;- });- // Wait for either 'exit' (normal child lifecycle) or 'error' (spawn- // failure — Node fires error without exit when the binary is missing).- // Either path resolves the lifecycle promise; without listening to both- // a spawn error hangs `await proc.exited` until the consumer's own- // timeout fires.- const lifecycle = new Promise((r) => {- proc.once('exit', r);- proc.once('error', r);- });- Promise.all([lifecycle, stdoutDrain.done, stderrDrain.done])- .then(() => resolveExited(exitStatus !== undefined ? exitStatus : 0));- });-- // Replay buffered output as a fresh Web ReadableStream. `start()` awaits- // the drain before enqueueing so `new Response(proc.stdout).text()` yields- // the complete output regardless of whether the consumer reads before or- // after awaiting `proc.exited`. Stream is single-shot (locked after one- // read), matching Bun's behavior.- const replay = (d) => new ReadableStream({- async start(controller) {- await d.done;- for (const chunk of d.chunks) {- controller.enqueue(chunk instanceof Uint8Array ? chunk : new Uint8Array(chunk));- }- controller.close();- },- });-return {pid: proc.pid,- stdout: replay(stdoutDrain),- stderr: replay(stderrDrain),+ stdout: proc.stdout,+ stderr: proc.stderr,stdin: proc.stdin,- exited,unref() { proc.unref(); },kill(signal) { proc.kill(signal); },};diff --git a/browse/src/cli.ts b/browse/src/cli.tsindex 887247116..9732053c7 100644--- a/browse/src/cli.ts+++ b/browse/src/cli.ts@@ -14,7 +14,7 @@ import * as path from 'path';import { spawn as nodeSpawn } from 'child_process';import { safeUnlink, safeUnlinkQuiet, safeKill, isProcessAlive } from './error-handling';import { writeSecureFile, mkdirSecure } from './file-permissions';-import { resolveConfig, ensureStateDir, readVersionHash } from './config';+import { resolveConfig, ensureStateDir, readVersionHash, isPairAgentEnabled } from './config';import { parseProxyConfig, computeConfigHash, ProxyConfigError } from './proxy-config';import { redactProxyUrl } from './proxy-redact';import { spawnTerminalAgent } from './terminal-agent-control';@@ -168,7 +168,7 @@ async function killServer(pid: number): Promise<void> {try {Bun.spawnSync(['taskkill', '/PID', String(pid), '/T', '/F'],- { stdout: 'pipe', stderr: 'pipe', timeout: 5000 }+ { stdout: 'pipe', stderr: 'pipe', timeout: 5000, windowsHide: true });} catch (err: any) {if (err?.code !== 'ENOENT') throw err;@@ -348,9 +348,9 @@ async function startServer(extraEnv?: Record<string, string>): Promise<ServerStaconst launcherCode =`const{spawn}=require('child_process');` +`spawn(process.execPath,[${JSON.stringify(NODE_SERVER_SCRIPT)}],` +- `{detached:true,stdio:['ignore','ignore','ignore'],env:Object.assign({},process.env,` ++ `{detached:true,windowsHide:true,stdio:['ignore','ignore','ignore'],env:Object.assign({},process.env,` +`${extraEnvStr})}).unref()`;- Bun.spawnSync(['node', '-e', launcherCode], { stdio: ['ignore', 'ignore', 'ignore'] });+ Bun.spawnSync(['node', '-e', launcherCode], { stdio: ['ignore', 'ignore', 'ignore'], windowsHide: true });} else {// macOS/Linux: Bun.spawn().unref() only removes the child from Bun's event// loop — it does NOT call setsid(), so the spawned server stays in the@@ -365,6 +365,7 @@ async function startServer(extraEnv?: Record<string, string>): Promise<ServerSta// the Windows path's rationale — same root cause, different OS API.nodeSpawn('bun', ['run', SERVER_SCRIPT], {detached: true,+ windowsHide: true,stdio: ['ignore', 'ignore', 'ignore'],env: { ...process.env, BROWSE_STATE_FILE: config.stateFile, BROWSE_PARENT_PID: parentPid, ...extraEnv },}).unref();@@ -408,31 +409,29 @@ async function startServer(extraEnv?: Record<string, string>): Promise<ServerStathrow new Error(`Server failed to start within ${MAX_START_WAIT / 1000}s`);}-function errorCode(err: unknown): string {- if (err && typeof err === 'object' && 'code' in err) {- const code = (err as { code?: unknown }).code;- if (typeof code === 'string' && code.length > 0) return code;+export class ServerLockError extends Error {+ code: string;+ constructor(code: string, lockPath: string, cause: string) {+ super(`E_SERVER_LOCK (${code}): cannot acquire ${lockPath} — ${cause}`);+ this.name = 'ServerLockError';+ this.code = code;}- return 'UNKNOWN';-}--function errorMessage(err: unknown): string {- if (err && typeof err === 'object' && 'message' in err) {- const message = (err as { message?: unknown }).message;- if (typeof message === 'string' && message.length > 0) return message;- }- return String(err);-}--function logServerLockError(action: string, lockPath: string, err: unknown): void {- console.error(`[browse] acquireServerLock: unexpected ${errorCode(err)} while ${action} ${lockPath}: ${errorMessage(err)}`);}/*** Acquire an exclusive lockfile to prevent concurrent ensureServer() races (TOCTOU).- * Returns a cleanup function that releases the lock.+ * Returns a cleanup function that releases the lock, or null when another+ * LIVE process genuinely holds the lock (real contention).+ *+ * Error honesty (#1084): only EEXIST is contention. ENOENT (state dir+ * missing) self-heals with one mkdir retry; every other errno (EACCES,+ * ENOSPC, ...) throws ServerLockError with the real errno instead of+ * reporting phantom "another process holds the lock" contention forever.*/-export function acquireServerLock(lockPath: string = `${config.stateFile}.lock`): (() => void) | null {+export function acquireServerLock(+ lockPath: string = `${config.stateFile}.lock`,+ depth = 0,+): (() => void) | null {try {// 'wx' — create exclusively, fails if file already exists (atomic check-and-create)// Using string flag instead of numeric constants for Bun Windows compatibility@@ -440,36 +439,35 @@ export function acquireServerLock(lockPath: string = `${config.stateFile}.lock`)fs.writeSync(fd, `${process.pid}\n`);fs.closeSync(fd);return () => { safeUnlink(lockPath); };- } catch (err) {- if (errorCode(err) !== 'EEXIST') {- logServerLockError('opening', lockPath, err);- return null;- }-- // Lock already held — check if the holder is still alive- let holderPid: number;- try {- holderPid = parseInt(fs.readFileSync(lockPath, 'utf8').trim(), 10);- } catch (readErr) {- if (errorCode(readErr) === 'ENOENT') {- return acquireServerLock(lockPath);- }- logServerLockError('reading holder PID from', lockPath, readErr);- return null;+ } catch (err: any) {+ if (err?.code === 'ENOENT') {+ // Lock dir missing — create it and retry once.+ if (depth >= 1) throw new ServerLockError('ENOENT', lockPath, 'lock directory could not be created');+ mkdirSecure(path.dirname(lockPath));+ return acquireServerLock(lockPath, depth + 1);}-- if (holderPid && isProcessAlive(holderPid)) {- return null; // Another live process holds the lock+ if (err?.code !== 'EEXIST') {+ throw new ServerLockError(err?.code || 'UNKNOWN', lockPath, err?.message || String(err));}-- // Stale lock — remove and retry+ // EEXIST — real contention. Check if the holder is still alive.+ // Depth cap 5 bounds the stale-lock unlink/retry livelock.try {+ const holderPid = parseInt(fs.readFileSync(lockPath, 'utf8').trim(), 10);+ if (holderPid && isProcessAlive(holderPid)) {+ return null; // Another live process holds the lock+ }+ // Stale lock — remove and retryfs.unlinkSync(lockPath);- } catch (unlinkErr) {- logServerLockError('removing stale', lockPath, unlinkErr);- return null;+ if (depth >= 5) return null;+ return acquireServerLock(lockPath, depth + 1);+ } catch (readErr: any) {+ if (readErr?.code === 'ENOENT') {+ // Lock vanished between open and read (holder released) — retry.+ if (depth >= 5) return null;+ return acquireServerLock(lockPath, depth + 1);+ }+ throw new ServerLockError(readErr?.code || 'UNKNOWN', lockPath, readErr?.message || String(readErr));}- return acquireServerLock(lockPath);}}@@ -656,17 +654,7 @@ async function sendCommand(state: ServerState, command: string, args: string[],process.exit(1);}// Connection error — server may have crashed, OR may just be busy.- // The compiled CLI runs on Bun, whose fetch reports a refused/dropped- // socket as err.code 'ConnectionRefused' / 'ConnectionClosed' (message- // "Unable to connect. Is the computer able to access the url?"), NOT Node's- // ECONNREFUSED/ECONNRESET. Match both, or daemon crashes leak the raw Bun- // error and exit 1 instead of triggering the busy-check/restart below.- const isConnError =- err.code === 'ECONNREFUSED' || err.code === 'ECONNRESET' ||- err.code === 'ConnectionRefused' || err.code === 'ConnectionClosed' ||- err.message?.includes('fetch failed') ||- err.message?.includes('Unable to connect');- if (isConnError) {+ 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@@ -980,8 +968,12 @@ async function handlePairAgent(state: ServerState, args: string[]): Promise<voidif (pairData.tunnel_url) {serverUrl = pairData.tunnel_url;} else if (!localHost) {- // No tunnel active. Check if ngrok is available and auto-start.- const ngrokAvailable = isNgrokAvailable();+ // No tunnel active. Remote tunneling (pair-agent) is opt-in — never+ // auto-start it unless the user explicitly enabled it, even if ngrok is+ // installed and authed. First use goes through the /pair-agent skill's+ // consent question, which sets the key.+ const pairEnabled = isPairAgentEnabled();+ const ngrokAvailable = pairEnabled && isNgrokAvailable();if (ngrokAvailable) {console.log('[browse] ngrok detected. Starting tunnel...');try {@@ -1005,6 +997,14 @@ async function handlePairAgent(state: ServerState, args: string[]): Promise<voidconsole.warn('[browse] Using localhost (same-machine only).\n');serverUrl = pairData.server_url;}+ } else if (!pairEnabled) {+ // Consent gate, not a tooling gap: when pair_agent is off, ngrok+ // setup instructions can never fix it. Name the real remedy, with+ // the same wording as the /tunnel/start 403 body in server.ts.+ console.warn('[browse] No tunnel active: pair-agent is off (tunnel exposes this browser beyond the machine).');+ console.warn('[browse] Instructions will use localhost (same-machine only).');+ console.warn('[browse] For remote agents: enable once with `gstack-config set pair_agent on` — or run /pair-agent, which asks for consent and sets it.\n');+ serverUrl = pairData.server_url;} else {console.warn('[browse] No tunnel active and ngrok is not installed/configured.');console.warn('[browse] Instructions will use localhost (same-machine only).');@@ -1207,7 +1207,6 @@ Refs: After 'snapshot', use @e1, @e2... as selectors:const newPid = spawnTerminalAgent({stateFile: config.stateFile,serverPort: newState.port,- ownerPid: newState.pid,cwd: config.projectDir,});if (newPid) {@@ -1300,7 +1299,6 @@ Refs: After 'snapshot', use @e1, @e2... as selectors:spawnTerminalAgent({stateFile: config.stateFile,serverPort: respawned.port,- ownerPid: respawned.pid,cwd: config.projectDir,});} catch (err: any) {diff --git a/browse/src/config.ts b/browse/src/config.tsindex 1c6a3a3b5..dd6197cf6 100644--- a/browse/src/config.ts+++ b/browse/src/config.ts@@ -187,6 +187,64 @@ export function resolveGstackHome(): string {return process.env.GSTACK_HOME || path.join(os.homedir(), '.gstack');}+/**+ * Read one key from the flat-YAML config store at <gstack home>/config.yaml+ * (the shape bin/gstack-config writes: `key: value` lines). Tolerates+ * optional single/double quotes around the value and a trailing `# comment`.+ * Returns the unquoted value string, or null when the file is missing or+ * unreadable or the key is absent.+ *+ * Single source of truth for flat-YAML key reads — isPairAgentEnabled+ * (pair_agent) and telemetry.ts (telemetry tier) both route through it so+ * the two consent gates can never drift on parsing semantics.+ */+export function readGstackConfigYamlKey(key: string): string | null {+ const escaped = key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');+ try {+ const yaml = fs.readFileSync(path.join(resolveGstackHome(), 'config.yaml'), 'utf-8');+ // Last match wins: bin/gstack-config's `get` reads duplicates with+ // `tail -1`, and both surfaces must agree on the same line.+ const all = [...yaml.matchAll(new RegExp(`^\\s*${escaped}\\s*:\\s*['"]?([^'"#\\n]*?)['"]?\\s*(?:#.*)?$`, 'gm'))];+ return all.length > 0 ? all[all.length - 1][1] : null;+ } catch {+ return null;+ }+}++/**+ * Is the remote pair-agent (ngrok tunnel) surface opt-in enabled?+ *+ * Fail-closed: the tunnel exposes the local browser to the internet, so it+ * stays OFF unless the user explicitly ran `gstack-config set pair_agent on`+ * (the /pair-agent skill asks once on first use and sets it). Any read/parse+ * failure (missing config, malformed JSON) also resolves OFF. The tunnel+ * egress receipts cite this gate as their consent — it must exist and gate+ * every activation point (#B6, fork port wave 2).+ *+ * Env override `GSTACK_PAIR_AGENT=on|off` wins (used by tests and as an+ * emergency knob), mirroring the telemetry env-hint convention.+ */+export function isPairAgentEnabled(): boolean {+ const env = process.env.GSTACK_PAIR_AGENT;+ if (env === 'on') return true;+ if (env === 'off') return false;+ // Canonical store: ~/.gstack/config.yaml (flat `key: value` lines, written+ // by bin/gstack-config — which is what the /pair-agent consent step runs).+ // The fork read config.json; porting that verbatim would have made the gate+ // silently un-enableable on main. JSON kept as a fallback shape only.+ // Anything other than exactly on/off (missing key, malformed value) falls+ // through to the JSON fallback and ultimately fails closed.+ const yamlValue = readGstackConfigYamlKey('pair_agent');+ if (yamlValue === 'on') return true;+ if (yamlValue === 'off') return false;+ try {+ const raw = fs.readFileSync(path.join(resolveGstackHome(), 'config.json'), 'utf-8');+ return JSON.parse(raw)?.pair_agent === 'on';+ } catch {+ return false;+ }+}+/*** Resolve the Chromium profile directory.*diff --git a/browse/src/cookie-import-browser.ts b/browse/src/cookie-import-browser.tsindex 66328432a..19daa196b 100644--- a/browse/src/cookie-import-browser.ts+++ b/browse/src/cookie-import-browser.ts@@ -526,6 +526,7 @@ async function dpapiDecrypt(encryptedBytes: Buffer): Promise<Buffer> {].join('; ');const proc = Bun.spawn(['powershell', '-NoProfile', '-Command', script], {+ windowsHide: true,stdin: 'pipe',stdout: 'pipe',stderr: 'pipe',@@ -778,7 +779,7 @@ function isBrowserRunning(browserName: string): Promise<boolean> {const exe = browserName.toLowerCase().includes('edge') ? 'msedge.exe' : 'chrome.exe';return new Promise((resolve) => {const proc = Bun.spawn(['tasklist', '/FI', `IMAGENAME eq ${exe}`, '/NH'], {- stdout: 'pipe', stderr: 'pipe',+ stdout: 'pipe', stderr: 'pipe', windowsHide: true,});proc.exited.then(async () => {const out = await new Response(proc.stdout).text();diff --git a/browse/src/error-handling.ts b/browse/src/error-handling.tsindex ba6f1b61c..3be921fa2 100644--- a/browse/src/error-handling.ts+++ b/browse/src/error-handling.ts@@ -7,6 +7,8 @@import * as fs from 'fs';+const IS_WINDOWS = process.platform === 'win32';+// ─── Filesystem ────────────────────────────────────────────────/** Remove a file, ignoring ENOENT (already gone). Rethrows other errors. */@@ -34,39 +36,23 @@ export function safeKill(pid: number, signal: NodeJS.Signals | number): void {}}-/**- * Check if a PID is alive. Pure boolean probe — never throws.- *- * Signal 0 on every platform. Node and Bun both map `process.kill(pid, 0)` to- * an OpenProcess existence check on Windows, so the POSIX idiom is portable- * here — no shell-out needed.- *- * Windows used to shell out to `tasklist /FI "PID eq <pid>"` and string-match- * the CSV. That was wrong in two ways, both of which bit in production:- *- * 1. FALSE NEGATIVES UNDER LOAD. `tasklist` takes ~700-1700ms on an idle- * Windows 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 (killAgentByRecord, the terminal-agent watchdog) then- * skipped the kill and respawned around the survivor, leaking one- * terminal-agent per watchdog tick. The leak was self-reinforcing: every- * orphan added memory pressure, which made the next tasklist slower,- * which produced the next false negative.- * 2. A VISIBLE CONSOLE WINDOW per probe (no windowsHide), so a background- * watchdog strobed a terminal into the foreground every 60 seconds.- *- * Signal 0 is ~74,000x faster (0.004ms vs 270ms, measured), spawns nothing,- * and cannot time out.- *- * EPERM means the process EXISTS but we lack rights to signal it. That is- * alive; returning false there would reintroduce failure mode 1.- */+/** Check if a PID is alive. Pure boolean probe — returns false for ALL errors. */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 (err: any) {- return err?.code === 'EPERM';+ } catch {+ return false;}}diff --git a/browse/src/file-permissions.ts b/browse/src/file-permissions.tsindex c5bead026..5a5c5462e 100644--- a/browse/src/file-permissions.ts+++ b/browse/src/file-permissions.ts@@ -117,7 +117,7 @@ export function restrictFilePermissions(filePath: string): void {execFileSync('icacls',[filePath, '/inheritance:r', '/grant:r', `${user}:(F)`],- { stdio: 'ignore' },+ { stdio: 'ignore', windowsHide: true },);} catch (err) {warnIcaclsFailure(filePath, err);@@ -147,7 +147,7 @@ export function restrictDirectoryPermissions(dirPath: string): void {execFileSync('icacls',[dirPath, '/inheritance:r', '/grant:r', `${user}:(OI)(CI)(F)`],- { stdio: 'ignore' },+ { stdio: 'ignore', windowsHide: true },);} catch (err) {warnIcaclsFailure(dirPath, err);@@ -185,14 +185,54 @@ export function appendSecureFile(if (!existed) restrictFilePermissions(filePath);}+/**+ * Windows only: probe whether the current process can actually list the+ * directory. `fs.accessSync` doesn't consult NTFS ACLs on Windows, so a+ * real readdir is the only honest check.+ */+function canListDir(dirPath: string): boolean {+ try { fs.readdirSync(dirPath); return true; } catch { return false; }+}++/**+ * Windows only: repair a broken DACL on a state directory (#1605).+ *+ * `icacls /inheritance:r /grant:r <user>:(F)` is a single command, but the+ * two halves can partially fail: inheritance gets stripped while the user+ * grant doesn't resolve (localized account names, domain accounts, roaming+ * profiles). The result is a DACL with no usable ACE — often just a machine+ * SID — and the client can't read its own state files. `/reset` restores+ * inherited ACLs from the parent, making the directory functional again.+ * Functional-but-unhardened beats hardened-but-unusable.+ */+export function repairBrokenDacl(dirPath: string): void {+ if (process.platform !== 'win32') return;+ try {+ execFileSync('icacls', [dirPath, '/reset', '/T', '/C', '/Q'], { stdio: 'ignore', windowsHide: true });+ } catch (err) {+ warnIcaclsFailure(dirPath, err);+ }+}+/*** `mkdir -p` with owner-only directory permissions, cross-platform.* Replaces `fs.mkdirSync(path, { recursive: true, mode: 0o700 })` + Windows ACL.* Safe to call on an existing directory — re-applies the ACL idempotently.+ *+ * Windows: after applying the restricted ACL, verifies the directory is+ * still listable by this process and repairs a broken DACL (#1605) if not.*/export function mkdirSecure(dirPath: string): void {fs.mkdirSync(dirPath, { recursive: true, mode: 0o700 });restrictDirectoryPermissions(dirPath);+ if (process.platform === 'win32' && !canListDir(dirPath)) {+ repairBrokenDacl(dirPath);+ restrictDirectoryPermissions(dirPath);+ // If re-hardening broke access again, reset once more and leave the+ // directory with inherited ACLs — the client must be able to read+ // its own state.+ if (!canListDir(dirPath)) repairBrokenDacl(dirPath);+ }}/**diff --git a/browse/src/meta-commands.ts b/browse/src/meta-commands.tsindex 2ca080125..521c65a20 100644--- a/browse/src/meta-commands.ts+++ b/browse/src/meta-commands.ts@@ -20,6 +20,7 @@ import * as path from 'path';import { writeSecureFile, mkdirSecure } from './file-permissions';import { TEMP_DIR } from './platform';import { resolveConfig } from './config';+import { filterSessionCookies } from './session-persist';import type { Frame } from 'playwright';/** Tokenize a pipe segment respecting double-quoted strings. */@@ -421,25 +422,18 @@ export async function handleMetaCommand(}case 'stop': {- // Defer shutdown so the response flushes before process.exit() (same- // reason as 'restart' below). Otherwise the CLI sees a dropped socket;- // and now that connection-loss triggers the crash-retry path, that would- // resurrect a fresh daemon only to stop it again. Send the 200, then exit.- setTimeout(() => { void shutdown(); }, 100);+ // Return the acknowledgement before closing the listener. Shutting down+ // inline resets the CLI's fetch, which it reasonably interprets as a+ // crash and then restarts the daemon it was asked to stop.+ setTimeout(() => { void shutdown(); }, 25).unref?.();return 'Server stopped';}case 'restart': {- // Signal that we want a restart — the CLI will detect exit and restart.+ // Signal that we want a restart — the CLI will detect exit and restartconsole.log('[browse] Restart requested. Exiting for CLI to restart.');- // Defer shutdown one tick so this HTTP response actually flushes before- // process.exit(). shutdown() exits inline (server.ts), so the old- // `await shutdown(); return 'Restarting...'` never sent a response — the- // CLI saw a dropped socket and `browse restart` errored out. The daemon- // now exits ~100ms after the CLI gets its 200; the next browse command- // lazily cold-starts a fresh one.- setTimeout(() => { void shutdown(); }, 100);- return 'Restarting... (daemon exiting; next browse command starts a fresh one)';+ setTimeout(() => { void shutdown(); }, 25).unref?.();+ return 'Restarting...';}// ─── Visual ────────────────────────────────────────@@ -939,15 +933,13 @@ export async function handleMetaCommand(if (!Array.isArray(data.cookies) || !Array.isArray(data.pages)) {throw new Error('Invalid state file: expected cookies and pages arrays');}- // Validate and filter cookies — reject malformed or internal-network cookies- const validatedCookies = data.cookies.filter((c: any) => {- if (typeof c !== 'object' || !c) return false;- if (typeof c.name !== 'string' || typeof c.value !== 'string') return false;- if (typeof c.domain !== 'string' || !c.domain) return false;- const d = c.domain.startsWith('.') ? c.domain.slice(1) : c.domain;- if (d === 'localhost' || d.endsWith('.internal') || d === '169.254.169.254') return false;- return true;- });+ // Validate and filter cookies via the shared hygiene filter in+ // session-persist.ts (isInternalCookieDomain): rejects malformed+ // cookies and internal-network domains — localhost, *.internal,+ // loopback literals (127.x, ::1), and link-local/cloud-metadata+ // (169.254.x) — that a tampered state file could use to reach local+ // services or the metadata endpoint.+ const validatedCookies = filterSessionCookies(data.cookies);if (validatedCookies.length < data.cookies.length) {console.warn(`[browse] Filtered ${data.cookies.length - validatedCookies.length} invalid cookies from state file`);}diff --git a/browse/src/server.ts b/browse/src/server.tsindex 64e61b9c5..be6f5438b 100644--- a/browse/src/server.ts+++ b/browse/src/server.ts@@ -35,7 +35,11 @@ import {isRootToken, checkConnectRateLimit, type TokenInfo,} from './token-registry';import { validateTempPath } from './path-security';-import { resolveConfig, ensureStateDir, readVersionHash, resolveChromiumProfile, cleanSingletonLocks } from './config';+import { resolveConfig, ensureStateDir, readVersionHash, resolveChromiumProfile, cleanSingletonLocks, isPairAgentEnabled } from './config';+import {+ isSessionPersistEnabled, persistSessionState, restoreSessionState,+ sessionPersistIntervalMs, SESSION_STATE_FILE,+} from './session-persist';import { emitActivity, subscribe, getActivityAfter, getActivityHistory, getSubscriberCount } from './activity';import { createSseEndpoint } from './sse-helpers';import { initAuditLog, writeAuditEntry } from './audit';@@ -728,6 +732,12 @@ const idleCheckInterval = setInterval(idleCheckTick, 60_000);// dual-instance fix` describe block for usage.export const __testInternals__ = {idleCheckTick,+ // Watchdog seams (watchdog.test.ts): drive the 15s poll against an+ // arbitrary (dead) PID, trigger the handoff-promotion suppression exactly+ // as onHeadedPromotion does, and reset the latches between tests.+ parentWatchdogTick,+ suppressHeadedParentShutdown,+ resetParentWatchdogState: () => { headedParentShutdownSuppressed = false; parentGone = false; },setTunnelActive: (v: boolean) => { tunnelActive = v; },setLastActivity: (t: number) => { lastActivity = t; },formatExplicitPortUnavailableError,@@ -757,40 +767,83 @@ const BROWSE_PARENT_PID = parseInt(process.env.BROWSE_PARENT_PID || '0', 10);// the closure every 15s. The CLI's connect path sets BROWSE_HEADED=1 + PID=0,// so this branch is the normal path for /open-gstack-browser.const IS_HEADED_WATCHDOG = process.env.BROWSE_HEADED === '1';-if (BROWSE_PARENT_PID > 0 && !IS_HEADED_WATCHDOG) {- let parentGone = false;- setInterval(() => {- try {- process.kill(BROWSE_PARENT_PID, 0); // signal 0 = existence check only, no signal sent- } catch {- // Parent exited. Resolution order:- // 1. Active cookie picker (one-time code or session live)? Stay alive- // regardless of mode — tearing down the server mid-import leaves the- // picker UI with a stale "Failed to fetch" error.- // 2. Headed / tunnel mode? Shutdown. The idle timeout doesn't apply in- // these modes (see idleCheckInterval above — both early-return), so- // ignoring parent death here would leak orphan daemons after- // /pair-agent or /open-gstack-browser sessions.- // 3. Normal (headless) mode? Stay alive. Claude Code's Bash tool kills- // the parent shell between invocations. The idle timeout (30 min)- // handles eventual cleanup.- if (hasActivePicker()) return;- const headed = activeBrowserManager.getConnectionMode() === 'headed';- if (headed || tunnelActive) {- console.log(`[browse] Parent process ${BROWSE_PARENT_PID} exited in ${headed ? 'headed' : 'tunnel'} mode, shutting down`);- activeShutdown?.();- } else if (!parentGone) {- parentGone = true;- console.log(`[browse] Parent process ${BROWSE_PARENT_PID} exited (server stays alive, idle timeout will clean up)`);- }+// Runtime promotion to headed (`handoff`) must NOT clear this interval — the+// same tick is the tunnel-orphan reaper, and idle timeout is disabled in+// tunnel mode, so parent death is the ONLY thing that reaps an+// internet-exposed daemon after handoff → resume → /pair-agent. Promotion+// sets this suppress flag instead; the tick re-reads it (and tunnelActive)+// every pass. See suppressHeadedParentShutdown() below.+let headedParentShutdownSuppressed = false;+// Latch for the one-time "parent exited, staying alive" log line.+let parentGone = false;+// Named + parameterized (default: the boot-time env PID) so watchdog.test.ts+// can drive the tick deterministically via __testInternals__, mirroring+// idleCheckTick above. setInterval invokes it with no args in production.+function parentWatchdogTick(parentPid: number = BROWSE_PARENT_PID): void {+ try {+ process.kill(parentPid, 0); // signal 0 = existence check only, no signal sent+ } catch {+ // Parent exited. Resolution order:+ // 1. Active cookie picker (one-time code or session live)? Stay alive+ // regardless of mode — tearing down the server mid-import leaves the+ // picker UI with a stale "Failed to fetch" error.+ // 2. Headed (unless suppressed by a runtime promotion) / tunnel mode?+ // Shutdown. The idle timeout doesn't apply in these modes (see+ // idleCheckInterval above — both early-return), so ignoring parent+ // death here would leak orphan daemons after /pair-agent or+ // /open-gstack-browser sessions.+ // 3. Normal (headless) mode, or headed-by-promotion? Stay alive. Claude+ // Code's Bash tool kills the parent shell between invocations, and a+ // promoted daemon's user owns the window lifecycle. The idle timeout+ // (30 min) handles eventual cleanup.+ if (hasActivePicker()) return;+ const headed = activeBrowserManager.getConnectionMode() === 'headed'+ && !headedParentShutdownSuppressed;+ if (headed || tunnelActive) {+ console.log(`[browse] Parent process ${parentPid} exited in ${headed ? 'headed' : 'tunnel'} mode, shutting down`);+ activeShutdown?.();+ } else if (!parentGone) {+ parentGone = true;+ console.log(`[browse] Parent process ${parentPid} exited (server stays alive, idle timeout will clean up)`);}- }, 15_000);+ }+}+if (BROWSE_PARENT_PID > 0 && !IS_HEADED_WATCHDOG) {+ setInterval(parentWatchdogTick, 15_000);} else if (IS_HEADED_WATCHDOG) {console.log('[browse] Parent-process watchdog disabled (headed mode)');} else if (BROWSE_PARENT_PID === 0) {console.log('[browse] Parent-process watchdog disabled (BROWSE_PARENT_PID=0)');}+/**+ * Suppress the headed-mode parent-death shutdown after a runtime promotion.+ *+ * The watchdog's contract is "headless daemons outlive their parent, headed ones+ * do not" — reasonable at boot, when mode is fixed by env. `handoff` breaks that+ * assumption: it swaps in a headed context on a RUNNING daemon+ * (browser-manager.ts, connectionMode = 'headed') without a restart, so a daemon+ * that legitimately registered a watchdog is suddenly on the fatal side of the+ * branch. The parent is typically a short-lived shell — Claude Code's Bash tool+ * kills one after every invocation — so the next 15s poll shuts the daemon down,+ * discarding whatever the user was handed off to do, such as a login.+ *+ * Once promoted, the user owns the window lifecycle exactly as if the daemon had+ * been started headed, which is the case the env guards already exempt.+ *+ * A flag, NOT clearInterval: the tick doubles as the tunnel-orphan reaper+ * (its `tunnelActive` branch), and idle timeout is disabled in tunnel mode —+ * clearing the whole interval here left handoff → resume → /pair-agent with+ * an internet-exposed daemon nothing could ever reap. After promotion, parent+ * death no longer kills the daemon for BEING HEADED, but still kills it when+ * a tunnel is active.+ */+function suppressHeadedParentShutdown(): void {+ if (headedParentShutdownSuppressed) return;+ headedParentShutdownSuppressed = true;+ console.log('[browse] Parent-death headed shutdown suppressed (promoted to headed at runtime); watchdog stays armed as the tunnel-orphan reaper');+}+// ─── Command Sets (from commands.ts — single source of truth) ───import { READ_COMMANDS, WRITE_COMMANDS, META_COMMANDS } from './commands';export { READ_COMMANDS, WRITE_COMMANDS, META_COMMANDS };@@ -833,6 +886,11 @@ function emitInspectorEvent(event: any): void {// ─── Server ────────────────────────────────────────────────────const browserManager = new BrowserManager();+// Declared here rather than beside suppressHeadedParentShutdown: that function+// sits with the watchdog it gates, which is above this line, and binding it up+// there would touch `browserManager` in its temporal dead zone — aborting+// module evaluation and leaving every later const uninitialized.+browserManager.onHeadedPromotion = suppressHeadedParentShutdown;// Indirection for embedders. Module-level handlers (idleCheckTick, parent// watchdog, SIGTERM) read activeBrowserManager so that buildFetchHandler can// retarget them at a caller-supplied BrowserManager. Symmetric with the@@ -851,6 +909,11 @@ let activeBrowserManager: BrowserManager = browserManager;// any buildFetchHandler call rebinds onDisconnect onto the cfg instance.browserManager.onDisconnect = (code) => activeShutdown?.(code ?? 2);let isShuttingDown = false;+// Session-persist ticker handle. Registered in start() (module scope so the+// factory's shutdown() can reach it), cleared by shutdown() BEFORE the final+// snapshot — a tick landing during browser teardown would otherwise overwrite+// the good final snapshot with a degraded one (zero tabs).+let sessionPersistInterval: ReturnType<typeof setInterval> | null = null;type PortCheckResult =| { available: true }@@ -1692,8 +1755,33 @@ export function buildFetchHandler(cfg: ServerConfig): ServerHandle {clearInterval(flushInterval);clearInterval(idleCheckInterval);if (agentWatchdogInterval) clearInterval(agentWatchdogInterval);+ // Stop the session-persist ticker BEFORE the final snapshot below —+ // paired with the isShuttingDown gate inside the tick, this guarantees+ // no interval snapshot can race the final one during teardown.+ if (sessionPersistInterval) {+ clearInterval(sessionPersistInterval);+ sessionPersistInterval = null;+ }await flushBuffers();+ // Final session snapshot before the browser goes away (#778). Best+ // effort with a hard 2s deadline: shutdown must never hang on a wedged+ // page.evaluate — after the deadline we proceed to browser close and let+ // the previous interval snapshot stand (atomic writes guarantee it's+ // intact). The .catch is attached to the persist promise itself so a+ // late rejection after losing the race can't become an unhandled+ // rejection.+ if (isSessionPersistEnabled()) {+ const finalSnapshot = persistSessionState(cfgBrowserManager, path.join(config.stateDir, SESSION_STATE_FILE))+ .catch((err: any) => {+ console.warn(`[browse] SESSION_PERSIST_FAILED at shutdown: ${err?.message ?? err}`);+ });+ await Promise.race([+ finalSnapshot,+ new Promise<void>((resolve) => setTimeout(resolve, 2_000)),+ ]);+ }+await cfgBrowserManager.close();cleanSingletonLocks(resolveChromiumProfile());@@ -1723,6 +1811,12 @@ export function buildFetchHandler(cfg: ServerConfig): ServerHandle {// after 30 min of HTTP idle because the dead module-level instance still// reports connectionMode === 'launched'.activeBrowserManager = cfgBrowserManager;+ // Same reason as above: the watchdog reads activeBrowserManager, so the+ // instance that can promote itself to headed must be the one that can+ // suppress the headed parent-death branch. An embedder-supplied manager+ // otherwise promotes silently and the watchdog keeps shutting down on a+ // promotion it can no longer see.+ cfgBrowserManager.onHeadedPromotion = suppressHeadedParentShutdown;// Wire the cfg-instance's onDisconnect to run shutdown when the user// closes the headed browser window. CHAIN any caller-provided handler@@ -2435,6 +2529,14 @@ export function buildFetchHandler(cfg: ServerConfig): ServerHandle {status: 403, headers: { 'Content-Type': 'application/json' },});}+ if (!isPairAgentEnabled()) {+ // Consent-on-first-use: the /pair-agent skill asks once and sets the+ // key; a direct API caller gets the same hint instead of a tunnel.+ return new Response(JSON.stringify({+ error: 'pair-agent is off (tunnel exposes this browser beyond the machine)',+ hint: 'enable once with: gstack-config set pair_agent on — or run /pair-agent, which asks for consent and sets it',+ }), { status: 403, headers: { 'Content-Type': 'application/json' } });+ }if (tunnelActive && tunnelUrl && tunnelServer) {// Verify tunnel is still alive before returning cached URL.// Probe GET /connect (the only unauth-reachable path on the tunnel@@ -2471,7 +2573,7 @@ export function buildFetchHandler(cfg: ServerConfig): ServerHandle {const started = await startTunnel({fetchHandler: makeFetchHandler('tunnel'),authtoken,- consent: 'pair_agent=on',+ consent: 'pair_agent=on (isPairAgentEnabled gate at /tunnel/start)',});if (!started.ok) {return new Response(JSON.stringify({@@ -3089,6 +3191,58 @@ export async function start() {browserManager.serverPort = port;+ // ─── Opt-in session persistence (#778 class) ─────────────────+ // BROWSE_PERSIST_STATE=1: restore cookies/storage/tabs from the last+ // snapshot, then keep snapshotting on an interval. Launched mode only —+ // the headed persistent profile owns its own state. The final snapshot at+ // clean shutdown lives in buildFetchHandler's shutdown().+ //+ // Runs AFTER Bun.serve() + the state-file write, in the BACKGROUND:+ // restore re-creates tabs sequentially with up-to-15s goto timeouts while+ // the CLI's readiness probe gives up at 8s — one slow/unreachable saved+ // URL must never make every `$B` command report "Server failed to start".+ // Fire-and-forget: a restore failure is logged and never affects the+ // daemon.+ if (!skipBrowser && isSessionPersistEnabled() && browserManager.getConnectionMode() === 'launched') {+ const sessionStatePath = path.join(config.stateDir, SESSION_STATE_FILE);+ restoreSessionState(browserManager, sessionStatePath)+ .then((restored) => {+ if (restored) {+ // Counts come from the deserialized snapshot itself — no extra+ // saveState() round-trip against pages that may still be loading.+ console.log(`[browse] Session state restored: ${restored.cookies.length} cookies / ${restored.pages.length} tabs (BROWSE_PERSIST_STATE=1)`);+ } else {+ console.log('[browse] Session persistence on; no prior state — fresh session (BROWSE_PERSIST_STATE=1)');+ }+ })+ .catch((err: any) => {+ console.warn(`[browse] SESSION_RESTORE_FAILED: ${err?.message ?? err}`);+ });+ let persistWarned = false;+ // In-flight guard: never start a new snapshot while the previous one is+ // still pending (a slow page.evaluate would otherwise pile up ticks).+ let persistInFlight = false;+ sessionPersistInterval = setInterval(() => {+ // Shutdown gate (belt; shutdown()'s clearInterval is the suspenders):+ // a tick that fires during browser teardown snapshots a degraded state+ // (zero tabs) over the good final snapshot.+ if (isShuttingDown) return;+ if (persistInFlight) return; // skip the tick+ persistInFlight = true;+ persistSessionState(browserManager, sessionStatePath)+ .catch((err: any) => {+ // Warn once — a full disk must not spam the log every 30s, and a+ // snapshot failure must never kill the daemon (R3).+ if (!persistWarned) {+ persistWarned = true;+ console.warn(`[browse] SESSION_PERSIST_FAILED: ${err?.message ?? err} (further failures suppressed)`);+ }+ })+ .finally(() => { persistInFlight = false; });+ }, sessionPersistIntervalMs());+ (sessionPersistInterval as any)?.unref?.();+ }+// Navigate to welcome page if in headed mode and still on about:blankif (browserManager.getConnectionMode() === 'headed') {try {@@ -3130,7 +3284,9 @@ export async function start() {// Start ngrok tunnel if BROWSE_TUNNEL=1 is set. Uses the dual-listener// pattern: bind a dedicated tunnel listener on an ephemeral port and// point ngrok.forward() at IT, not the local daemon port.- if (process.env.BROWSE_TUNNEL === '1') {+ if (process.env.BROWSE_TUNNEL === '1' && !isPairAgentEnabled()) {+ console.error('[browse] BROWSE_TUNNEL=1 ignored: pair-agent is off. Enable once with: gstack-config set pair_agent on');+ } else if (process.env.BROWSE_TUNNEL === '1') {const authtoken = resolveNgrokAuthtoken();if (!authtoken) {console.error('[browse] BROWSE_TUNNEL=1 but no NGROK_AUTHTOKEN found. Set it via env var or ~/.gstack/ngrok.env');@@ -3142,7 +3298,7 @@ export async function start() {const started = await startTunnel({fetchHandler: handle.fetchTunnel,authtoken,- consent: 'pair_agent=on (BROWSE_TUNNEL=1)',+ consent: 'pair_agent=on (isPairAgentEnabled gate, BROWSE_TUNNEL=1)',});if (!started.ok) {console.error(`[browse] Failed to start tunnel: ${started.error.message}`);diff --git a/browse/src/session-persist.ts b/browse/src/session-persist.tsnew file mode 100644index 000000000..3c6627bcb--- /dev/null+++ b/browse/src/session-persist.ts@@ -0,0 +1,178 @@+/**+ * Opt-in session-state persistence (#778, #2193, #1128, #1129).+ *+ * Portions copyright (c) 2026 Sina Matian, time-attack/gstack (GStack 2), MIT.+ *+ * With BROWSE_PERSIST_STATE=1, the headless daemon snapshots cookies ++ * per-tab URL/localStorage/sessionStorage to <stateDir>/session-state.json+ * on an interval and at clean shutdown, and restores it on the next launch.+ * Kills the auth-lost-on-restart class: a crash or binary-version+ * auto-restart no longer silently logs the user out of everything.+ *+ * Default OFF: cookies on disk (0600) are a real cost the user must opt+ * into. Headed mode is excluded — the persistent Chromium profile already+ * owns that state, and replaying tabs would clobber the user's window.+ *+ * Disk shape (version 1): { version, savedAt, cookies, pages[{url,+ * isActive, storage}] }. loadedHtml and owner are NEVER persisted — same+ * in-memory-only invariant as `state save|load` (meta-commands.ts): a+ * tampered file must not smuggle HTML past load-html's checks or forge tab+ * ownership.+ */++import * as fs from 'fs';+import type { BrowserManager, BrowserState } from './browser-manager';+import { writeSecureFile } from './file-permissions';+import { safeUnlinkQuiet } from './error-handling';++/** Rename a corrupt state file to .corrupt (forensic artifact) — best effort. */+function quarantineCorrupt(filePath: string): void {+ try {+ fs.renameSync(filePath, `${filePath}.corrupt`);+ } catch {+ safeUnlinkQuiet(filePath);+ }+}++export const SESSION_STATE_FILE = 'session-state.json';+export const SESSION_STATE_VERSION = 1;++/** Config gate. Documented in browse/SKILL.md ("Session persistence"). */+export function isSessionPersistEnabled(env: NodeJS.ProcessEnv = process.env): boolean {+ return env.BROWSE_PERSIST_STATE === '1';+}++/** Persist interval (ms). Env override exists for tests. */+export function sessionPersistIntervalMs(env: NodeJS.ProcessEnv = process.env): number {+ const parsed = parseInt(env.BROWSE_PERSIST_INTERVAL_MS || '', 10);+ return Number.isFinite(parsed) && parsed > 0 ? parsed : 30_000;+}++/**+ * Serialize a BrowserState to the on-disk v1 shape. Strips loadedHtml,+ * loadedHtmlWaitUntil, and owner (in-memory-only invariants).+ */+export function serializeSessionState(state: BrowserState): string {+ return JSON.stringify({+ version: SESSION_STATE_VERSION,+ savedAt: new Date().toISOString(),+ cookies: state.cookies,+ pages: state.pages.map((p) => ({+ url: p.url,+ isActive: p.isActive,+ storage: p.storage,+ })),+ }, null, 2);+}++/**+ * True when a cookie domain points at an internal-network target a tampered+ * state file could use to reach localhost services, *.internal hosts, or+ * cloud metadata: `localhost`, `*.internal`, IPv4 loopback literals+ * (127.0.0.0/8), IPv6 loopback (`::1`, `[::1]`), and link-local/metadata+ * (169.254.0.0/16, which covers 169.254.169.254). Leading-dot domain+ * variants (`.127.0.0.1`) are normalized before matching. Single source of+ * truth for the persistence restore path here AND `state load`+ * (meta-commands.ts).+ */+export function isInternalCookieDomain(domain: string): boolean {+ const d = domain.startsWith('.') ? domain.slice(1) : domain;+ if (d === 'localhost' || d.endsWith('.internal')) return true;+ if (d === '::1' || d === '[::1]') return true; // IPv6 loopback+ if (/^127\./.test(d)) return true; // IPv4 loopback block+ if (/^169\.254\./.test(d)) return true; // link-local incl. cloud metadata+ return false;+}++/**+ * Cookie hygiene shared with `state load` (meta-commands.ts): drop malformed+ * cookies and internal-network domains (see isInternalCookieDomain).+ */+export function filterSessionCookies(cookies: unknown[]): BrowserState['cookies'] {+ return cookies.filter((c: any) => {+ if (typeof c !== 'object' || !c) return false;+ if (typeof c.name !== 'string' || typeof c.value !== 'string') return false;+ if (typeof c.domain !== 'string' || !c.domain) return false;+ return !isInternalCookieDomain(c.domain);+ }) as BrowserState['cookies'];+}++/**+ * Parse + validate the on-disk shape into a BrowserState. Returns null for+ * anything malformed (corrupt JSON, wrong version, missing arrays).+ * loadedHtml/owner are stripped unconditionally even if present on disk.+ */+export function deserializeSessionState(raw: string): BrowserState | null {+ let data: any;+ try {+ data = JSON.parse(raw);+ } catch {+ return null;+ }+ if (!data || data.version !== SESSION_STATE_VERSION) return null;+ if (!Array.isArray(data.cookies) || !Array.isArray(data.pages)) return null;+ return {+ cookies: filterSessionCookies(data.cookies),+ pages: data.pages.map((p: any) => ({+ url: typeof p?.url === 'string' ? p.url : '',+ isActive: Boolean(p?.isActive),+ storage: p?.storage && typeof p.storage === 'object'+ ? {+ localStorage: typeof p.storage.localStorage === 'object' && p.storage.localStorage ? p.storage.localStorage : {},+ sessionStorage: typeof p.storage.sessionStorage === 'object' && p.storage.sessionStorage ? p.storage.sessionStorage : {},+ }+ : null,+ // NEVER accept loadedHtml / loadedHtmlWaitUntil / owner from disk.+ })),+ };+}++/**+ * Snapshot the live session to disk (0600). No-op outside launched+ * (headless) mode — the headed persistent profile owns its own state.+ */+export async function persistSessionState(bm: BrowserManager, filePath: string): Promise<void> {+ if (bm.getConnectionMode() !== 'launched') return;+ const state = await bm.saveState();+ // Atomic replace: stage the new snapshot beside the target, then rename+ // over it. A crash mid-write must never destroy the previous good+ // snapshot — surviving crashes is the point of this feature.+ const tmpPath = `${filePath}.tmp`;+ writeSecureFile(tmpPath, serializeSessionState(state));+ try {+ fs.renameSync(tmpPath, filePath);+ } catch (err) {+ safeUnlinkQuiet(tmpPath);+ throw err;+ }+}++/**+ * Restore a persisted session into a freshly launched manager. Returns the+ * restored (already-filtered) state so callers can log counts without an+ * extra saveState() round-trip, or null when there was nothing to restore+ * (missing file, or corrupt data — which is warned, quarantined, and skipped+ * rather than blocking launch). restoreState re-validates every URL before+ * navigating.+ */+export async function restoreSessionState(bm: BrowserManager, filePath: string): Promise<BrowserState | null> {+ let raw: string;+ try {+ raw = fs.readFileSync(filePath, 'utf-8');+ } catch (err: any) {+ if (err?.code === 'ENOENT') return null;+ throw err;+ }+ const state = deserializeSessionState(raw);+ if (!state) {+ // Boot fresh, keep the evidence: the corrupt file moves to .corrupt so a+ // 3-week-later bug report is reconstructable from the artifact.+ console.warn(`[browse] SESSION_STATE_INVALID: corrupt ${filePath} moved to .corrupt; starting fresh`);+ quarantineCorrupt(filePath);+ return null;+ }+ // launch() opens one blank tab; replace it rather than restoring alongside.+ await bm.closeAllPages();+ await bm.restoreState(state);+ return state;+}diff --git a/browse/src/telemetry.ts b/browse/src/telemetry.tsindex 8f2604e4e..094f6a2f1 100644--- a/browse/src/telemetry.ts+++ b/browse/src/telemetry.ts@@ -21,6 +21,7 @@import { promises as fs } from 'fs';import * as path from 'path';import * as os from 'os';+import { readGstackConfigYamlKey } from './config';function gstackHome(): string {return process.env.GSTACK_HOME || path.join(os.homedir(), '.gstack');@@ -43,17 +44,51 @@ async function ensureDir(): Promise<void> {}let telemetryDisabled: boolean | null = null;-function isDisabled(): boolean {+/**+ * Is telemetry disabled for this process? Telemetry is OPT-IN: the consent+ * prompt writes a granted tier ('community' | 'anonymous') to+ * ~/.gstack/config.yaml, and only a granted tier enables emission. Tiers,+ * checked in order:+ *+ * 1. Env hint GSTACK_TELEMETRY_OFF=1 (set by preambles and test+ * harnesses): always disabled, even over a granted config tier.+ * 2. Persistent tier via the shared flat-YAML helper in config.ts (same+ * parser as the pair-agent gate, so the two consent gates never drift):+ * explicit `telemetry: off` disables; 'community'/'anonymous' enable.+ * 3. Default: DISABLED. An absent key, absent file, or unrecognized value+ * means consent was never granted — matching bin/gstack-config's+ * DEFAULTS table, which reports 'off' for an unset telemetry key.+ * Anything else would be a split-brain where `gstack-config get+ * telemetry` tells the user 'off' while a direct-$B daemon emits.+ * One escape hatch: GSTACK_TELEMETRY_OFF=0 is a harness-side consent+ * assertion that flips this DEFAULT only (test harnesses exercising the+ * write path against a scratch GSTACK_HOME) — it never overrides an+ * explicit `telemetry: off` the user wrote.+ *+ * Exported so tests can pin the consent gate directly; the cached verdict+ * resets via _resetTelemetryCache.+ */+export function isTelemetryDisabled(): boolean {if (telemetryDisabled !== null) return telemetryDisabled;- // Check env (set by preamble or test harnesses).+ // Env kill switch (set by preamble or test harnesses): beats everything.if (process.env.GSTACK_TELEMETRY_OFF === '1') {telemetryDisabled = true;return true;}- // Conservative default: telemetry ON unless explicitly off. Users opt out via- // gstack-config set telemetry off (preamble reads this; we trust the env hint).- telemetryDisabled = false;- return false;+ // Persistent tier: an explicit user-written value always wins next.+ const tier = readGstackConfigYamlKey('telemetry');+ if (tier === 'off') {+ telemetryDisabled = true;+ return true;+ }+ if (tier === 'community' || tier === 'anonymous') {+ telemetryDisabled = false;+ return false;+ }+ // No granted consent on record (absent key/file, unrecognized value):+ // disabled — unless the harness asserted consent via the env seam.+ telemetryDisabled = process.env.GSTACK_TELEMETRY_OFF !== '0';+ return telemetryDisabled;}export interface TelemetryEvent {@@ -63,7 +98,7 @@ export interface TelemetryEvent {/** Fire-and-forget log. Never throws. */export function logTelemetry(payload: TelemetryEvent): void {- if (isDisabled()) return;+ if (isTelemetryDisabled()) return;const enriched = { ...payload, ts: new Date().toISOString() };ensureDir().then(() => fs.appendFile(telemetryFile(), JSON.stringify(enriched) + '\n', 'utf8'))diff --git a/browse/test/bun-polyfill.test.ts b/browse/test/bun-polyfill.test.tsindex 23df490de..477f6ef27 100644--- a/browse/test/bun-polyfill.test.ts+++ b/browse/test/bun-polyfill.test.ts@@ -1,11 +1,13 @@-import { describe, test, expect, afterAll } from 'bun:test';+import { describe, test, expect, afterAll, setDefaultTimeout } from 'bun:test';import * as path from 'path';+// Every test here spawnSync's a `node` child; Windows CI cold-start (AV scan,+// first-touch of node.exe) alone can blow bun's 5s default — observed 5,007ms+// on a 50ms sleep test. Subprocess budget, not assertion looseness.+setDefaultTimeout(20_000);+// Load the polyfill into a fresh object (don't clobber globalThis.Bun)const polyfillPath = path.resolve(import.meta.dir, '../src/bun-polyfill.cjs');-// Forward slashes so the path survives interpolation into a JS string literal-// on Windows, which is the platform this polyfill exists for.-const requirePath = polyfillPath.replace(/\\/g, '/');describe('bun-polyfill', () => {// We test the polyfill by requiring it in a subprocess under Node.js@@ -13,7 +15,7 @@ describe('bun-polyfill', () => {test('Bun.sleep resolves after delay', async () => {const result = Bun.spawnSync(['node', '-e', `- require('${requirePath}');+ require(${JSON.stringify(polyfillPath)});(async () => {const start = Date.now();await Bun.sleep(50);@@ -27,7 +29,7 @@ describe('bun-polyfill', () => {test('Bun.spawnSync runs a command and returns stdout', () => {const result = Bun.spawnSync(['node', '-e', `- require('${requirePath}');+ require(${JSON.stringify(polyfillPath)});const r = Bun.spawnSync(['echo', 'hello'], { stdout: 'pipe' });console.log(r.stdout.toString().trim());console.log('exit:' + r.exitCode);@@ -39,7 +41,7 @@ describe('bun-polyfill', () => {test('Bun.spawn launches a process with pid', async () => {const result = Bun.spawnSync(['node', '-e', `- require('${requirePath}');+ require(${JSON.stringify(polyfillPath)});const p = Bun.spawn(['echo', 'test'], { stdio: ['pipe', 'pipe', 'pipe'] });console.log(typeof p.pid === 'number' ? 'HAS_PID' : 'NO_PID');console.log(typeof p.kill === 'function' ? 'HAS_KILL' : 'NO_KILL');@@ -51,144 +53,40 @@ describe('bun-polyfill', () => {expect(lines[2]).toBe('HAS_UNREF');});- // Bun.spawn parity: `proc.exited` is a Promise resolving to the exit code.- // The DPAPI helper and isBrowserRunning both `await proc.exited`; without- // it the awaits resolve immediately to `undefined` and the caller reads- // stdout before the child has produced it — surfacing as a silent failure.- test('Bun.spawn exposes proc.exited that resolves to the exit code', async () => {+ test('Bun.serve creates an HTTP server that responds', async () => {const result = Bun.spawnSync(['node', '-e', `- require('${requirePath}');- (async () => {- const p = Bun.spawn(['node', '-e', 'process.exit(0)'], { stdio: ['ignore', 'ignore', 'ignore'] });- console.log(typeof p.exited === 'object' && typeof p.exited.then === 'function' ? 'IS_PROMISE' : 'NOT_PROMISE');- console.log('exit:' + await p.exited);- })();+ require(${JSON.stringify(polyfillPath)});+ const server = Bun.serve({+ port: 0, // Note: polyfill uses port directly, so we pick one+ hostname: '127.0.0.1',+ fetch(req) {+ return new Response(JSON.stringify({ ok: true }), {+ headers: { 'Content-Type': 'application/json' },+ });+ },+ });+ // The polyfill doesn't support port 0, so we test the object shape+ console.log(typeof server.stop === 'function' ? 'HAS_STOP' : 'NO_STOP');+ console.log(typeof server.port === 'number' ? 'HAS_PORT' : 'NO_PORT');+ server.stop();`], { stdout: 'pipe', stderr: 'pipe' });const lines = result.stdout.toString().trim().split('\n');- expect(lines[0]).toBe('IS_PROMISE');- expect(lines[1]).toBe('exit:0');- });-- test('Bun.spawn proc.exited reflects non-zero exit codes', async () => {- const result = Bun.spawnSync(['node', '-e', `- require('${requirePath}');- (async () => {- const p = Bun.spawn(['node', '-e', 'process.exit(3)'], { stdio: ['ignore', 'ignore', 'ignore'] });- console.log('exit:' + await p.exited);- })();- `], { stdout: 'pipe', stderr: 'pipe' });- expect(result.stdout.toString().trim()).toBe('exit:3');- });-- test('Bun.spawn proc.exited resolves before reading stdout (no race)', async () => {- const result = Bun.spawnSync(['node', '-e', `- require('${requirePath}');- (async () => {- // Real-world pattern: write to stdout, then exit. Awaiting proc.exited- // before reading must guarantee the bytes are flushed.- const p = Bun.spawn(['node', '-e', 'process.stdout.write("ready"); process.exit(0)'], {- stdio: ['ignore', 'pipe', 'ignore']- });- const code = await p.exited;- const out = await new Response(p.stdout).text();- console.log(out + ':' + code);- })();- `], { stdout: 'pipe', stderr: 'pipe' });- expect(result.stdout.toString().trim()).toBe('ready:0');- });-- // Spawn-failure case: Node emits 'error' but not 'exit' when the binary- // is missing, so listening only for 'exit' hangs `await proc.exited`- // forever. The lifecycle promise must resolve on either event.- test('Bun.spawn proc.exited resolves on spawn failure (missing binary)', async () => {- const result = Bun.spawnSync(['node', '-e', `- require('${requirePath}');- (async () => {- const p = Bun.spawn(['this-binary-does-not-exist-zzz-' + Date.now()], {- stdio: ['ignore', 'pipe', 'pipe']- });- const code = await Promise.race([- p.exited,- new Promise((_, r) => setTimeout(() => r(new Error('timeout')), 3000))- ]).catch(() => 'TIMEOUT');- console.log('exit:' + code);- })();- `], { stdout: 'pipe', stderr: 'pipe' });- // Anything other than 'TIMEOUT' (and ideally a non-zero number) means the- // lifecycle promise resolved on the spawn error.- const out = result.stdout.toString().trim();- expect(out).not.toBe('exit:TIMEOUT');- expect(out).toMatch(/^exit:\d+$/);- });-- // GSTACK_SPAWN_MAX_BUFFER caps the drain so a runaway child can't OOM the- // server. Past the cap, the pipe keeps flowing (child doesn't block) but- // further bytes are dropped. Set a small cap, write more than that, assert- // the captured stdout equals the cap and the child exits cleanly.- test('Bun.spawn caps buffered output at GSTACK_SPAWN_MAX_BUFFER', async () => {- const result = Bun.spawnSync(['node', '-e', `- process.env.GSTACK_SPAWN_MAX_BUFFER = '${1024}';- require('${requirePath}');- (async () => {- // Child writes 10 KB; cap is 1 KB; drained output should be exactly 1 KB- // and exit should still resolve cleanly (child not back-pressured to death).- const p = Bun.spawn(- ['node', '-e', 'process.stdout.write("y".repeat(10 * 1024)); process.exit(0)'],- { stdio: ['ignore', 'pipe', 'ignore'] }- );- const code = await Promise.race([- p.exited,- new Promise((_, r) => setTimeout(() => r(new Error('timeout')), 3000))- ]).catch(() => 'TIMEOUT');- const out = await new Response(p.stdout).text();- console.log(out.length + ':' + code);- })();- `], { stdout: 'pipe', stderr: 'pipe' });- expect(result.stdout.toString().trim()).toBe('1024:0');+ expect(lines[0]).toBe('HAS_STOP');+ expect(lines[1]).toBe('HAS_PORT');});- // Regression for the pipe-blocking case: if the child writes more than the- // OS pipe buffer (~16-64 KB) and the polyfill doesn't drain eagerly, the- // child blocks in write() and `exit` never fires. 1 MB is well past every- // OS pipe buffer size. Pre-fix this test hangs forever; post-fix it returns- // in <500ms. Bun's default per-test timeout is 5s — generous here.- test('Bun.spawn drains large stdout so proc.exited still resolves', async () => {- const result = Bun.spawnSync(['node', '-e', `- require('${requirePath}');- (async () => {- const ONE_MB = 1024 * 1024;- // Exit in the write callback, not straight after write(): on modern- // Node a pipe write past the OS buffer is async, and process.exit()- // right after write() truncates at ~64 KB even with a live reader.- // The callback only fires once the full MB is flushed — which still- // requires the parent to drain, so the regression (no eager drain →- // child blocks → timeout) is still caught.- const p = Bun.spawn(- ['node', '-e', 'process.stdout.write("x".repeat(' + ONE_MB + '), () => process.exit(0))'],- { stdio: ['ignore', 'pipe', 'ignore'] }- );- const code = await Promise.race([- p.exited,- new Promise((_, r) => setTimeout(() => r(new Error('timeout')), 10000))- ]).catch(e => 'TIMEOUT');- const out = await new Response(p.stdout).text();- console.log(out.length + ':' + code);- })().catch((e) => { console.log('THREW:' + e.message); });- `], { stdout: 'pipe', stderr: 'pipe' });- expect(result.stdout.toString().trim()).toBe('1048576:0');- }, 15000);-// windowsHide is the one option where Node's default is the opposite of// Bun's: Node shows the child's console window, Bun hides it. Dropping it// in translation makes every spawned child pop a window on Windows, which- // is the platform this whole file exists for. Both shims are covered.+ // is the platform this whole file exists for. Both shims are covered, and+ // an explicit windowsHide:false must survive forwarding (#2523 + #2539).test('Bun.spawn defaults windowsHide to true', () => {const result = Bun.spawnSync(['node', '-e', `const cp = require('child_process');const orig = cp.spawn;let seen;cp.spawn = (c, a, o) => { seen = o; return orig(c, a, o); };- require('${requirePath}');+ require(${JSON.stringify(polyfillPath)});Bun.spawn(['node', '-e', ''], { stdio: ['ignore', 'ignore', 'ignore'] });console.log('windowsHide:' + seen.windowsHide);`], { stdout: 'pipe', stderr: 'pipe' });@@ -201,7 +99,7 @@ describe('bun-polyfill', () => {const orig = cp.spawnSync;let seen;cp.spawnSync = (c, a, o) => { seen = o; return orig(c, a, o); };- require('${requirePath}');+ require(${JSON.stringify(polyfillPath)});Bun.spawnSync(['node', '-e', '']);console.log('windowsHide:' + seen.windowsHide);`], { stdout: 'pipe', stderr: 'pipe' });@@ -214,32 +112,10 @@ describe('bun-polyfill', () => {const orig = cp.spawn;let seen;cp.spawn = (c, a, o) => { seen = o; return orig(c, a, o); };- require('${requirePath}');+ require(${JSON.stringify(polyfillPath)});Bun.spawn(['node', '-e', ''], { stdio: ['ignore', 'ignore', 'ignore'], windowsHide: false });console.log('windowsHide:' + seen.windowsHide);`], { stdout: 'pipe', stderr: 'pipe' });expect(result.stdout.toString().trim()).toBe('windowsHide:false');});-- test('Bun.serve creates an HTTP server that responds', async () => {- const result = Bun.spawnSync(['node', '-e', `- require('${requirePath}');- const server = Bun.serve({- port: 0, // Note: polyfill uses port directly, so we pick one- hostname: '127.0.0.1',- fetch(req) {- return new Response(JSON.stringify({ ok: true }), {- headers: { 'Content-Type': 'application/json' },- });- },- });- // The polyfill doesn't support port 0, so we test the object shape- console.log(typeof server.stop === 'function' ? 'HAS_STOP' : 'NO_STOP');- console.log(typeof server.port === 'number' ? 'HAS_PORT' : 'NO_PORT');- server.stop();- `], { stdout: 'pipe', stderr: 'pipe' });- const lines = result.stdout.toString().trim().split('\n');- expect(lines[0]).toBe('HAS_STOP');- expect(lines[1]).toBe('HAS_PORT');- });});diff --git a/browse/test/busy-daemon-recovery.test.ts b/browse/test/busy-daemon-recovery.test.tsnew file mode 100644index 000000000..93f8d079c--- /dev/null+++ b/browse/test/busy-daemon-recovery.test.ts@@ -0,0 +1,134 @@+/**+ * #1781 busy-vs-dead pinning test — the "recover from a busy daemon" leg of+ * the browser-lifecycle contract, previously untested.+ *+ * Wedges a fake daemon: /health answers healthy, but the FIRST POST /command+ * hard-destroys the socket (the CLI sees ECONNRESET — exactly what a+ * single-threaded daemon under beacon load looks like). The daemon "PID"+ * is a live sleep child.+ *+ * Contract under test (cli.ts sendCommand + probeHealthWithBackoff):+ * - CLI must NOT kill the live PID and must NOT restart the daemon+ * (a restart drops tab/cookie state — the original crash-loop bug).+ * - It probes /health, sees alive, and retries the SAME command against+ * the SAME daemon instance.+ *+ * Fails on pre-#1781 code (which killed + restarted on any conn error) and+ * on any regression that reorders the busy-probe before the alive check.+ */++import { describe, test, expect, afterAll } 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';++const BOOT_ID = `boot-${Date.now()}`;++interface FakeDaemon {+ port: number;+ commandRequests: number;+ close: () => Promise<void>;+}++/** /health healthy; first POST /command → socket destroy; then 200 + BOOT_ID. */+async function startWedgedDaemon(): Promise<FakeDaemon> {+ const state = { commandRequests: 0 };+ const server = http.createServer((req, res) => {+ if (req.url === '/health') {+ res.writeHead(200, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({ status: 'healthy' }));+ return;+ }+ if (req.url === '/command' && req.method === 'POST') {+ state.commandRequests += 1;+ if (state.commandRequests === 1) {+ req.socket.destroy(); // wedged: connection dies mid-request+ return;+ }+ res.writeHead(200, { 'Content-Type': 'text/plain' });+ res.end(`RECOVERED ${BOOT_ID}`);+ return;+ }+ res.writeHead(404);+ res.end();+ });+ 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,+ get commandRequests() { return state.commandRequests; },+ close: () => new Promise((r) => server.close(() => r())),+ };+}++function runCli(args: string[], env: Record<string, string>, timeoutMs = 20_000):+ Promise<{ code: number; stdout: string; stderr: string }> {+ const cliPath = path.resolve(__dirname, '../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 }));+ });+}++let daemonPidChild: ChildProcess | null = null;+afterAll(() => { daemonPidChild?.kill('SIGKILL'); });++describe('#1781 busy-daemon recovery (CLI integration)', () => {+ test('retries without kill; same daemon instance, state file untouched', async () => {+ const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'browse-busy-'));+ const stateFile = path.join(tmpDir, 'browse.json');+ const daemon = await startWedgedDaemon();+ try {+ // A live process standing in for the daemon PID. If the CLI takes the+ // dead path it SIGTERMs this child — the aliveness assert catches it.+ daemonPidChild = spawn('sleep', ['60'], { stdio: 'ignore' });+ const daemonPid = daemonPidChild.pid!;++ const stateContent = {+ pid: daemonPid,+ port: daemon.port,+ token: 'busy-test-token',+ startedAt: new Date().toISOString(),+ serverPath: '',+ mode: 'launched' as const,+ };+ fs.writeFileSync(stateFile, JSON.stringify(stateContent, null, 2));++ 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;++ const result = await runCli(['status'], env);++ // Recovered: retried the same command against the same daemon instance.+ expect(result.code).toBe(0);+ expect(result.stdout).toContain(`RECOVERED ${BOOT_ID}`);+ // The fork's CLI announces the busy retry on stderr; ours retries at the+ // probe layer without a message. Either is fine — the load-bearing+ // behavior is retry-without-kill, asserted below.+ expect(daemon.commandRequests).toBe(2); // wedged once, served once++ // Never killed, never restarted — tab/cookie state intact.+ expect(result.stderr).not.toContain('Restarting');+ expect(isProcessAlive(daemonPid)).toBe(true);+ expect(JSON.parse(fs.readFileSync(stateFile, 'utf-8'))).toEqual(stateContent);+ } finally {+ // Cleanup must run even when an assertion throws — otherwise a failed+ // run leaks the wedged fake daemon and the tmp dir.+ await daemon.close();+ fs.rmSync(tmpDir, { recursive: true, force: true });+ }+ }, 30_000);+});diff --git a/browse/test/cli-lock.test.ts b/browse/test/cli-lock.test.tsindex 79f4df8d3..9c6e04c19 100644--- a/browse/test/cli-lock.test.ts+++ b/browse/test/cli-lock.test.ts@@ -1,8 +1,22 @@+/**+ * #1084 diagnostics — merged-design shape.+ *+ * Main's smell wave pinned a log-and-return-null acquireServerLock; this+ * branch keeps the typed ServerLockError + bounded-retry design (fully pinned+ * in server-lock-errors.test.ts). This file re-expresses the non-redundant+ * assertion intents from the wave's test against the kept design:+ * - unexpected open failures surface the REAL errno + lock path (typed+ * throw), never phantom "another process holds the lock" contention;+ * - holder-PID read failures surface errno + lock path the same way;+ * - genuine live contention stays SILENT (null return, no stderr noise).+ * Exact duplicates of server-lock-errors.test.ts coverage (stale-lock+ * reacquire, ENOENT self-heal, EACCES throw) are deliberately not repeated.+ */import { describe, expect, test } from 'bun:test';import * as fs from 'node:fs';import * as os from 'node:os';import * as path from 'node:path';-import { acquireServerLock } from '../src/cli';+import { acquireServerLock, ServerLockError } from '../src/cli';function withTempDir<T>(fn: (dir: string) => T): T {const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'browse-lock-'));@@ -27,14 +41,27 @@ function captureErrors<T>(fn: () => T): { result: T; messages: string[] } {}describe('browse CLI server lock diagnostics (#1084)', () => {- test('logs non-EEXIST open failures instead of reporting phantom lock contention', () => {+ test('unexpected open failures throw ServerLockError with the real errno — not phantom lock contention', () => {+ if (process.platform === 'win32') return; // ENOTDIR errno mapping differs on WindowswithTempDir((dir) => {- const lockPath = path.join(dir, 'missing-parent', 'browse.json.lock');- const { result, messages } = captureErrors(() => acquireServerLock(lockPath));+ // A FILE where a directory is expected: open('wx') fails ENOTDIR — an+ // errno that is neither contention (EEXIST) nor the self-healing+ // missing-dir case (ENOENT). The old code's bare catch would have+ // reported "another process holds the lock" forever.+ const blocker = path.join(dir, 'blocker');+ fs.writeFileSync(blocker, 'not a directory\n');+ const lockPath = path.join(blocker, 'browse.json.lock');- expect(result).toBeNull();- expect(messages.join('\n')).toContain('unexpected ENOENT while opening');- expect(messages.join('\n')).toContain(lockPath);+ let thrown: any = null;+ try {+ acquireServerLock(lockPath);+ } catch (err) {+ thrown = err;+ }+ expect(thrown).toBeInstanceOf(ServerLockError);+ expect(thrown.code).toBe('ENOTDIR');+ expect(thrown.message).toContain('E_SERVER_LOCK (ENOTDIR)');+ expect(thrown.message).toContain(lockPath);});});@@ -50,30 +77,25 @@ describe('browse CLI server lock diagnostics (#1084)', () => {});});- test('logs holder PID read failures with code and lock path', () => {+ test('holder PID read failures throw ServerLockError with code and lock path', () => {withTempDir((dir) => {+ // Lock path exists but is a DIRECTORY: open('wx') → EEXIST (looks like+ // contention), then the holder-PID read fails EISDIR. The kept design+ // surfaces that errno + path in a typed error instead of retrying or+ // reporting phantom contention.const lockPath = path.join(dir, 'browse.json.lock');fs.mkdirSync(lockPath);- const { result, messages } = captureErrors(() => acquireServerLock(lockPath));-- expect(result).toBeNull();- expect(messages.join('\n')).toContain('unexpected EISDIR while reading holder PID from');- expect(messages.join('\n')).toContain(lockPath);- });- });-- test('removes stale lock and reacquires it', () => {- withTempDir((dir) => {- const lockPath = path.join(dir, 'browse.json.lock');- fs.writeFileSync(lockPath, 'not-a-pid\n');-- const release = acquireServerLock(lockPath);-- expect(release).toBeFunction();- expect(fs.readFileSync(lockPath, 'utf-8').trim()).toBe(String(process.pid));- release?.();- expect(fs.existsSync(lockPath)).toBe(false);+ let thrown: any = null;+ try {+ acquireServerLock(lockPath);+ } catch (err) {+ thrown = err;+ }+ expect(thrown).toBeInstanceOf(ServerLockError);+ expect(thrown.code).toBe('EISDIR');+ expect(thrown.message).toContain('E_SERVER_LOCK (EISDIR)');+ expect(thrown.message).toContain(lockPath);});});});diff --git a/browse/test/compare-board.test.ts b/browse/test/compare-board.test.tsindex b9007af7e..90e1c9459 100644--- a/browse/test/compare-board.test.ts+++ b/browse/test/compare-board.test.ts@@ -16,7 +16,7 @@ import { handleReadCommand as _handleReadCommand } from '../src/read-commands';import { handleWriteCommand as _handleWriteCommand } from '../src/write-commands';const handleReadCommand = (cmd: string, args: string[], b: BrowserManager) =>- _handleReadCommand(cmd, args, b.getActiveSession());+ _handleReadCommand(cmd, args, b.getActiveSession(), b);const handleWriteCommand = (cmd: string, args: string[], b: BrowserManager) =>_handleWriteCommand(cmd, args, b.getActiveSession(), b);import { generateCompareHtml } from '../../design/src/compare';diff --git a/browse/test/extension-sender-auth.test.ts b/browse/test/extension-sender-auth.test.tsindex df9fc1cda..ba5d4781c 100644--- a/browse/test/extension-sender-auth.test.ts+++ b/browse/test/extension-sender-auth.test.ts@@ -32,9 +32,13 @@ const CONTENT_SCRIPT_SENDER = { id: OWN_ID, url: 'https://evil.example/page', taconst FOREIGN_SENDER = { id: FOREIGN_ID, url: `chrome-extension://${FOREIGN_ID}/background.html` };const NO_URL_SENDER = { id: OWN_ID };+// 'sidebar-command' is no longer a message type at all — the chat-queue path+// was ripped along with the /sidebar-command endpoint, so background.js now+// rejects it pre-gate as an unknown type (no response, nothing to leak). It is+// pinned separately below as a representative unknown type.const PRIVILEGED = ['getPort', 'setPort', 'getServerUrl', 'getToken', 'fetchRefs',- 'command', 'sidebar-command', 'getTabState',+ 'command', 'getTabState',];// Content-script-originated flows that must keep working.const CONTENT_SCRIPT_TYPES = ['openSidePanel', 'elementPicked', 'pickerCancelled', 'inspectResult'];@@ -208,6 +212,16 @@ describe('background.js onMessage listener (behavioral)', () => {}});+ test('retired sidebar-command type is rejected pre-gate with no response and no leaks', () => {+ // Even from the most-trusted sender shape, a type outside ALLOWED_TYPES+ // never reaches a handler: no sendResponse, no token/port fields possible.+ for (const sender of [PAGE_SENDER, CONTENT_SCRIPT_SENDER, FOREIGN_SENDER, NO_URL_SENDER]) {+ const r = dispatch(listener, { type: 'sidebar-command', message: 'hi' }, sender);+ expect(r.responded).toBe(false);+ expectDenied(r);+ }+ });+test('denied setPort never persists the attacker port', () => {const before = calls.storageSet.length;const r = dispatch(listener, { type: 'setPort', port: 6666 }, CONTENT_SCRIPT_SENDER);diff --git a/browse/test/file-permissions.test.ts b/browse/test/file-permissions.test.tsindex 4a548650c..1d772948b 100644--- a/browse/test/file-permissions.test.ts+++ b/browse/test/file-permissions.test.ts@@ -22,6 +22,7 @@ import {writeSecureFile,appendSecureFile,mkdirSecure,+ repairBrokenDacl,__resetWarnedForTests,} from '../src/file-permissions';@@ -175,4 +176,35 @@ describe('mkdirSecure', () => {expect(fs.existsSync(path.join(tmpDir, 'a', 'b'))).toBe(true);expect(fs.existsSync(d)).toBe(true);});++ test('created directory is listable by the creating process', () => {+ // #1605 contract: whatever ACL hardening happens, the client must be+ // able to read its own state dir immediately after creation.+ const d = path.join(tmpDir, 'state');+ mkdirSecure(d);+ fs.writeFileSync(path.join(d, 'browse.json'), '{}');+ expect(fs.readdirSync(d)).toContain('browse.json');+ });+});++describe('repairBrokenDacl', () => {+ test('is a no-op on non-Windows platforms', () => {+ if (process.platform === 'win32') return;+ const d = path.join(tmpDir, 'dir');+ fs.mkdirSync(d);+ expect(() => repairBrokenDacl(d)).not.toThrow();+ });++ test('on Windows, does not throw and directory stays listable', () => {+ if (process.platform !== 'win32') return;+ const d = path.join(tmpDir, 'dir');+ fs.mkdirSync(d);+ expect(() => repairBrokenDacl(d)).not.toThrow();+ expect(() => fs.readdirSync(d)).not.toThrow();+ });++ test('on Windows, swallows icacls failure on a nonexistent path', () => {+ if (process.platform !== 'win32') return;+ expect(() => repairBrokenDacl(path.join(tmpDir, 'nonexistent'))).not.toThrow();+ });});diff --git a/browse/test/gstack-config.test.ts b/browse/test/gstack-config.test.tsindex 51adbe813..bb8da531a 100644--- a/browse/test/gstack-config.test.ts+++ b/browse/test/gstack-config.test.ts@@ -15,12 +15,20 @@ const SCRIPT = join(import.meta.dir, '..', '..', 'bin', 'gstack-config');let stateDir: string;function run(args: string[] = [], extraEnv: Record<string, string> = {}) {+ // The script resolves its state dir as GSTACK_STATE_ROOT > GSTACK_HOME >+ // GSTACK_STATE_DIR > $HOME/.gstack. Strip the higher-precedence vars so a+ // stray value in the harness env (another test file's leftovers, operator+ // shell) can never outrank the per-test GSTACK_STATE_DIR isolation.+ const env: Record<string, string | undefined> = {+ ...process.env,+ GSTACK_STATE_DIR: stateDir,+ };+ delete env.GSTACK_STATE_ROOT;+ delete env.GSTACK_HOME;+ Object.assign(env, extraEnv); // per-test overrides always win, deliberately+const result = Bun.spawnSync(['bash', SCRIPT, ...args], {- env: {- ...process.env,- GSTACK_STATE_DIR: stateDir,- ...extraEnv,- },+ env,stdout: 'pipe',stderr: 'pipe',});diff --git a/browse/test/gstack-update-check.test.ts b/browse/test/gstack-update-check.test.tsindex 104a2e04b..16bf7b851 100644--- a/browse/test/gstack-update-check.test.ts+++ b/browse/test/gstack-update-check.test.ts@@ -17,14 +17,21 @@ let gstackDir: string;let stateDir: string;function run(extraEnv: Record<string, string> = {}, args: string[] = []) {+ // gstack-config (which this script shells out to for update_check) resolves+ // state as GSTACK_STATE_ROOT > GSTACK_HOME > GSTACK_STATE_DIR > ~/.gstack.+ // Strip the higher-precedence vars so harness-env leftovers can never+ // outrank the per-test GSTACK_STATE_DIR isolation.+ const env: Record<string, string | undefined> = {+ ...process.env,+ GSTACK_DIR: gstackDir,+ GSTACK_STATE_DIR: stateDir,+ GSTACK_REMOTE_URL: `file://${join(gstackDir, 'REMOTE_VERSION')}`,+ };+ delete env.GSTACK_STATE_ROOT;+ delete env.GSTACK_HOME;+ Object.assign(env, extraEnv); // per-test overrides always win, deliberatelyconst result = Bun.spawnSync(['bash', SCRIPT, ...args], {- env: {- ...process.env,- GSTACK_DIR: gstackDir,- GSTACK_STATE_DIR: stateDir,- GSTACK_REMOTE_URL: `file://${join(gstackDir, 'REMOTE_VERSION')}`,- ...extraEnv,- },+ env,stdout: 'pipe',stderr: 'pipe',});diff --git a/browse/test/pair-agent-optin-gate.test.ts b/browse/test/pair-agent-optin-gate.test.tsnew file mode 100644index 000000000..cd795a989--- /dev/null+++ b/browse/test/pair-agent-optin-gate.test.ts@@ -0,0 +1,124 @@+/**+ * Pair-agent opt-in gate.+ *+ * The remote pair-agent (ngrok tunnel) is OFF by default. All three activation+ * points — CLI auto-start, the /tunnel/start route, and the BROWSE_TUNNEL=1+ * startup path — route through the single `isPairAgentEnabled()` guard. This+ * test pins the guard's behavior (the root cause) plus a source-level tripwire+ * that each call site actually consults it.+ */++import { describe, test, expect, afterEach } from 'bun:test';+import * as fs from 'fs';+import * as os from 'os';+import * as path from 'path';+import { isPairAgentEnabled } from '../src/config';++const SERVER_SRC = fs.readFileSync(path.join(import.meta.dir, '../src/server.ts'), 'utf-8');+const CLI_SRC = fs.readFileSync(path.join(import.meta.dir, '../src/cli.ts'), 'utf-8');++const savedEnv = { GSTACK_HOME: process.env.GSTACK_HOME, GSTACK_PAIR_AGENT: process.env.GSTACK_PAIR_AGENT };+const tmpHomes: string[] = [];++function tmpHomeWith(config: Record<string, string> | null): string {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-pair-'));+ tmpHomes.push(dir);+ if (config !== null) {+ // Canonical store: flat YAML lines, the shape bin/gstack-config writes.+ const yaml = Object.entries(config).map(([k, v]) => `${k}: ${v}`).join('\n') + '\n';+ fs.writeFileSync(path.join(dir, 'config.yaml'), yaml);+ }+ process.env.GSTACK_HOME = dir;+ delete process.env.GSTACK_PAIR_AGENT;+ return dir;+}++afterEach(() => {+ for (const k of ['GSTACK_HOME', 'GSTACK_PAIR_AGENT'] as const) {+ if (savedEnv[k] === undefined) delete process.env[k];+ else process.env[k] = savedEnv[k];+ }+ while (tmpHomes.length) fs.rmSync(tmpHomes.pop()!, { recursive: true, force: true });+});++describe('isPairAgentEnabled — fail-closed default', () => {+ test('OFF when no config store exists', () => {+ tmpHomeWith(null);+ expect(isPairAgentEnabled()).toBe(false);+ });++ test('OFF when config has no pair_agent key', () => {+ tmpHomeWith({ telemetry: 'off' });+ expect(isPairAgentEnabled()).toBe(false);+ });++ test('ON via the config.json fallback shape too', () => {+ const dir = tmpHomeWith(null);+ fs.writeFileSync(path.join(dir, 'config.json'), JSON.stringify({ pair_agent: 'on' }));+ expect(isPairAgentEnabled()).toBe(true);+ });++ test('OFF when pair_agent is explicitly "off"', () => {+ tmpHomeWith({ pair_agent: 'off' });+ expect(isPairAgentEnabled()).toBe(false);+ });++ test('ON only when pair_agent is exactly "on"', () => {+ tmpHomeWith({ pair_agent: 'on' });+ expect(isPairAgentEnabled()).toBe(true);+ });++ test('OFF when the store is malformed (fail-closed)', () => {+ const dir = tmpHomeWith(null);+ fs.writeFileSync(path.join(dir, 'config.yaml'), 'pair_agent: banana\n');+ fs.writeFileSync(path.join(dir, 'config.json'), '{ not json');+ expect(isPairAgentEnabled()).toBe(false);+ });++ test('env override wins: GSTACK_PAIR_AGENT=on forces ON even with config off', () => {+ tmpHomeWith({ pair_agent: 'off' });+ process.env.GSTACK_PAIR_AGENT = 'on';+ expect(isPairAgentEnabled()).toBe(true);+ });++ test('env override wins: GSTACK_PAIR_AGENT=off forces OFF even with config on', () => {+ tmpHomeWith({ pair_agent: 'on' });+ process.env.GSTACK_PAIR_AGENT = 'off';+ expect(isPairAgentEnabled()).toBe(false);+ });+});++describe('gate wiring — every tunnel activation point consults the guard', () => {+ test('CLI auto-start is gated (never auto-starts when disabled)', () => {+ // pairEnabled short-circuits the ngrok probe so the tunnel can't auto-start.+ expect(CLI_SRC).toContain('const pairEnabled = isPairAgentEnabled();');+ expect(CLI_SRC).toContain('const ngrokAvailable = pairEnabled && isNgrokAvailable();');+ });++ test('CLI consent-off branch names the real remedy, never ngrok reinstall', () => {+ // When pair_agent is off but ngrok is installed+authed, telling the user+ // to `ngrok config add-authtoken` can never fix it — the gate is consent,+ // not tooling. The consent branch must carry the same remedy wording as+ // the /tunnel/start 403 body, and must not mention ngrok setup.+ const branchAt = CLI_SRC.indexOf('} else if (!pairEnabled) {');+ expect(branchAt).toBeGreaterThan(-1);+ const branchEnd = CLI_SRC.indexOf('} else {', branchAt);+ expect(branchEnd).toBeGreaterThan(branchAt);+ const branch = CLI_SRC.slice(branchAt, branchEnd);+ expect(branch).toContain('gstack-config set pair_agent on');+ expect(branch).toContain('/pair-agent');+ expect(branch).not.toContain('ngrok config add-authtoken');+ expect(branch).not.toContain('install ngrok');+ });++ test('/tunnel/start refuses with the enable hint when disabled', () => {+ const startIdx = SERVER_SRC.indexOf("url.pathname === '/tunnel/start'");+ const block = SERVER_SRC.slice(startIdx, startIdx + 1200);+ expect(block).toContain('if (!isPairAgentEnabled())');+ expect(block).toContain('gstack-config set pair_agent on');+ });++ test('BROWSE_TUNNEL=1 startup skips tunnel bind when disabled', () => {+ expect(SERVER_SRC).toContain("process.env.BROWSE_TUNNEL === '1' && !isPairAgentEnabled()");+ });+});diff --git a/browse/test/poisoned-bundle-probe.test.ts b/browse/test/poisoned-bundle-probe.test.tsnew file mode 100644index 000000000..0ae4a8a5f--- /dev/null+++ b/browse/test/poisoned-bundle-probe.test.ts@@ -0,0 +1,148 @@+/**+ * Unit tests for the extracted poisoned-bundle self-heal probe (#2242).+ *+ * probePoisonedChromiumBundle() detects a Chromium bundle mutated by the+ * pre-v1.64 in-place rebrand (Info.plist contains "GStack Browser"),+ * removes it so `playwright install chromium` actually re-downloads, and+ * throws a typed PoisonedBundleError with the remediation command.+ *+ * Contracts pinned here:+ * - standard cache layout (chromium-<rev>/chrome-mac/<name>.app): the+ * WHOLE revision dir is removed, INSTALLATION_COMPLETE marker included+ * (leaving the marker makes the recommended re-fetch a no-op)+ * - non-cache layout: the .app + sibling install markers are removed,+ * nothing else+ * - clean bundle: untouched, no throw+ * - GSTACK_CHROMIUM_PATH bundles (custom/embedder) are NEVER deleted:+ * the probe refuses to act on that executable, and both call sites+ * (launchHeaded + handoff) only pass chromium.executablePath()+ * - the rethrow guard at the call sites is typed (instanceof), not a+ * fragile message-string match+ */++import { describe, test, expect, beforeEach, afterEach } from 'bun:test';+import * as fs from 'fs';+import * as os from 'os';+import * as path from 'path';+import { probePoisonedChromiumBundle, PoisonedBundleError } from '../src/browser-manager';++const SRC = fs.readFileSync(+ path.join(import.meta.dir, '..', 'src', 'browser-manager.ts'),+ 'utf-8',+);++const POISONED_PLIST =+ '<plist><dict><key>CFBundleName</key><string>GStack Browser</string></dict></plist>';+const CLEAN_PLIST =+ '<plist><dict><key>CFBundleName</key><string>Google Chrome for Testing</string></dict></plist>';++let tmpDir: string;+let savedCustomPath: string | undefined;++/** Build <parentDir>/<name>.app with a plist and executable; return the executable path. */+function makeApp(parentDir: string, plist: string): { appDir: string; exe: string } {+ const appDir = path.join(parentDir, 'Google Chrome for Testing.app');+ const macos = path.join(appDir, 'Contents', 'MacOS');+ fs.mkdirSync(macos, { recursive: true });+ fs.writeFileSync(path.join(appDir, 'Contents', 'Info.plist'), plist);+ const exe = path.join(macos, 'Google Chrome for Testing');+ fs.writeFileSync(exe, '#!/bin/sh\n', { mode: 0o755 });+ return { appDir, exe };+}++beforeEach(() => {+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'poison-probe-'));+ savedCustomPath = process.env.GSTACK_CHROMIUM_PATH;+ delete process.env.GSTACK_CHROMIUM_PATH;+});++afterEach(() => {+ fs.rmSync(tmpDir, { recursive: true, force: true });+ if (savedCustomPath === undefined) delete process.env.GSTACK_CHROMIUM_PATH;+ else process.env.GSTACK_CHROMIUM_PATH = savedCustomPath;+});++describe('probePoisonedChromiumBundle — poisoned cache bundle', () => {+ test('standard cache layout: whole chromium-<rev> dir removed (markers included), typed error thrown', () => {+ const revDir = path.join(tmpDir, 'ms-playwright', 'chromium-1234');+ const { exe } = makeApp(path.join(revDir, 'chrome-mac'), POISONED_PLIST);+ fs.writeFileSync(path.join(revDir, 'INSTALLATION_COMPLETE'), '');+ fs.writeFileSync(path.join(revDir, 'DEPENDENCIES_VALIDATED'), '');++ let caught: unknown;+ try {+ probePoisonedChromiumBundle(exe);+ } catch (err) {+ caught = err;+ }+ expect(caught).toBeInstanceOf(PoisonedBundleError);+ // The message is the user's remediation — it must carry the command.+ expect((caught as Error).message).toContain('playwright install chromium');+ // Whole revision dir gone: leaving INSTALLATION_COMPLETE behind makes+ // `playwright install chromium` no-op ("is already downloaded") and the+ // remediation we just printed would do nothing.+ expect(fs.existsSync(revDir)).toBe(false);+ });++ test('non-cache layout: only the .app + sibling install markers removed, neighbors survive', () => {+ const parentDir = path.join(tmpDir, 'custom-bundles');+ const { appDir, exe } = makeApp(parentDir, POISONED_PLIST);+ fs.writeFileSync(path.join(parentDir, 'INSTALLATION_COMPLETE'), '');+ fs.writeFileSync(path.join(parentDir, 'DEPENDENCIES_VALIDATED'), '');+ fs.writeFileSync(path.join(parentDir, 'unrelated.txt'), 'keep me');++ expect(() => probePoisonedChromiumBundle(exe)).toThrow(PoisonedBundleError);+ expect(fs.existsSync(appDir)).toBe(false);+ expect(fs.existsSync(path.join(parentDir, 'INSTALLATION_COMPLETE'))).toBe(false);+ expect(fs.existsSync(path.join(parentDir, 'DEPENDENCIES_VALIDATED'))).toBe(false);+ // The parent dir itself and unrelated files are NOT swept.+ expect(fs.readFileSync(path.join(parentDir, 'unrelated.txt'), 'utf-8')).toBe('keep me');+ });+});++describe('probePoisonedChromiumBundle — clean and missing bundles', () => {+ test('clean plist: untouched, no throw', () => {+ const revDir = path.join(tmpDir, 'ms-playwright', 'chromium-1234');+ const { appDir, exe } = makeApp(path.join(revDir, 'chrome-mac'), CLEAN_PLIST);+ fs.writeFileSync(path.join(revDir, 'INSTALLATION_COMPLETE'), '');++ expect(() => probePoisonedChromiumBundle(exe)).not.toThrow();+ expect(fs.existsSync(path.join(appDir, 'Contents', 'Info.plist'))).toBe(true);+ expect(fs.existsSync(path.join(revDir, 'INSTALLATION_COMPLETE'))).toBe(true);+ });++ test('no plist at the probed path: no-op, no throw (bundle not installed yet)', () => {+ expect(() =>+ probePoisonedChromiumBundle(path.join(tmpDir, 'nope.app', 'Contents', 'MacOS', 'nope')),+ ).not.toThrow();+ });+});++describe('probePoisonedChromiumBundle — GSTACK_CHROMIUM_PATH is never deleted', () => {+ test('probe refuses to act on the GSTACK_CHROMIUM_PATH executable, even when poisoned', () => {+ // A custom/embedder bundle (GStack Browser.app wrapper) legitimately+ // contains "GStack Browser" in its plist — that is its branding, not+ // cache poison. Deleting it would destroy the embedder's product.+ const { appDir, exe } = makeApp(path.join(tmpDir, 'GStack Browser.app-parent'), POISONED_PLIST);+ process.env.GSTACK_CHROMIUM_PATH = exe;++ expect(() => probePoisonedChromiumBundle(exe)).not.toThrow();+ expect(fs.existsSync(path.join(appDir, 'Contents', 'Info.plist'))).toBe(true);+ expect(fs.existsSync(exe)).toBe(true);+ });++ test('caller contract: both headed launch paths probe chromium.executablePath() only', () => {+ // launchHeaded + handoff each call the probe with the Playwright-cache+ // path. No call site may ever pass the custom-bundle env var.+ const calls = SRC.match(/probePoisonedChromiumBundle\(chromium\.executablePath\(\)\)/g) || [];+ expect(calls.length).toBeGreaterThanOrEqual(2);+ expect(SRC).not.toMatch(/probePoisonedChromiumBundle\([^)]*GSTACK_CHROMIUM_PATH/);+ });+});++describe('typed rethrow guard at the call sites', () => {+ test('instanceof PoisonedBundleError, not message-string sniffing', () => {+ expect(SRC).not.toContain("includes('poisoned bundle')");+ expect(SRC).toMatch(/instanceof PoisonedBundleError/);+ });+});diff --git a/browse/test/process-liveness-windows.test.ts b/browse/test/process-liveness-windows.test.tsindex e0fe1ff5a..d474473dc 100644--- a/browse/test/process-liveness-windows.test.ts+++ b/browse/test/process-liveness-windows.test.ts@@ -54,10 +54,16 @@ describe('process liveness probe (Windows terminal-agent leak)', () => {expect(isProcessAlive(2147483646)).toBe(false);});- test('3. isProcessAlive spawns NO subprocess', () => {+ test('3. isProcessAlive spawns NO subprocess on POSIX (signal-0 path)', () => {// 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;const origSpawn = (Bun as any).spawn;const origSpawnSync = (Bun as any).spawnSync;const spawns: string[] = [];@@ -73,11 +79,16 @@ describe('process liveness probe (Windows terminal-agent leak)', () => {}});- test('4. no source file probes liveness via tasklist', () => {- // Static tripwire: re-introducing a tasklist-based existence check- // anywhere in src/ resurrects the false-negative class.+ 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.const offenders: string[] = [];for (const { file, content } of readAllSourceFiles()) {+ if (file === 'error-handling.ts') continue; // the canonical helperconst code = stripComments(content);// `PID eq` is the existence-probe form specifically. Other tasklist// uses (e.g. IMAGENAME filters for browser detection) are unaffected.diff --git a/browse/test/rebrand-signed-bundle.test.ts b/browse/test/rebrand-signed-bundle.test.tsnew file mode 100644index 000000000..723df131a--- /dev/null+++ b/browse/test/rebrand-signed-bundle.test.ts@@ -0,0 +1,53 @@+/**+ * #2242 bug 1 regression tripwire: never mutate the signed Chrome-for-Testing+ * bundle.+ *+ * The old launchHeaded() "rebrand" ran a global+ * `.replace(/Google Chrome for Testing/g, 'GStack Browser')` over the+ * bundle's Info.plist — which renamed CFBundleExecutable to a binary that+ * doesn't exist — and overwrote Resources/*.icns. Both writes broke the+ * codesign seal: GPU process exit_code=5, headed mode dead on macOS 26+ * (#2242, #2138, #2139).+ *+ * Static invariant (same pattern as cdp-session-cleanup.test.ts): the+ * browser lifecycle code must contain NO write into the Chromium .app+ * bundle. Branding lives in the wrapper .app / custom GBrowser build.+ * These assertions fail on the pre-fix code.+ */++import { describe, test, expect } from 'bun:test';+import * as fs from 'fs';+import * as path from 'path';++const SRC = fs.readFileSync(+ path.join(import.meta.dir, '..', 'src', 'browser-manager.ts'),+ 'utf-8',+);++describe('#2242: signed Chromium bundle is never mutated', () => {+ test('no global Google-Chrome-for-Testing plist replace', () => {+ expect(SRC).not.toContain("replace(/Google Chrome for Testing/g");+ });++ test('no Info.plist write into the Chromium bundle (reads allowed: self-heal probe)', () => {+ // The old code built `Info.plist` under the bundle's Contents dir and+ // wrote it back. Any reappearance of a WRITE is a regression. The+ // launch-time self-heal legitimately READS the plist to detect bundles+ // the old code already poisoned (EV4), so the path construction itself+ // is allowed — writes into it are not.+ expect(SRC).not.toMatch(/writeFileSync\(\s*chromePlist/);+ const plistWrites = SRC.match(/writeFileSync\([^)]*[Pp]list/g) || [];+ expect(plistWrites).toEqual([]);+ });++ test('no icon overwrite into the Chromium bundle Resources dir', () => {+ expect(SRC).not.toMatch(/copyFileSync\([^)]*destIcon/);+ expect(SRC).not.toContain("CFBundleIconFile");+ });++ test('the tombstone comment documenting why stays put', () => {+ // If someone deletes the explanation, the next contributor reintroduces+ // the mutation in good faith. Keep the why next to the where.+ expect(SRC).toContain('#2242');+ });+});diff --git a/browse/test/server-lock-errors.test.ts b/browse/test/server-lock-errors.test.tsnew file mode 100644index 000000000..e62b28b3c--- /dev/null+++ b/browse/test/server-lock-errors.test.ts@@ -0,0 +1,123 @@+/**+ * acquireServerLock error honesty (#1084 regression).+ *+ * The old code wrapped fs.openSync(lockPath, 'wx') in a bare `catch {}` —+ * EVERY errno (EACCES, EIO, ENOSPC, ENOENT) fell into the "lock already+ * held" path and surfaced as "another instance is starting the server",+ * a phantom 15s contention timeout that masked the real filesystem error.+ *+ * New contract:+ * - EEXIST + live holder → null (real contention)+ * - EEXIST + dead holder → stale lock removed, acquired+ * - ENOENT (dir missing) → create dir, retry once, acquired+ * - anything else → ServerLockError with the real errno+ */++import { describe, test, expect, afterAll } from 'bun:test';+import * as fs from 'fs';+// Default (CJS) export — its properties are mutable in Bun, unlike the frozen+// `* as fs` namespace, and mutations propagate to cli.ts's own fs import.+// Used only for the depth-cap livelock simulations below (restored in finally).+import fsMutable from 'fs';+import * as os from 'os';+import * as path from 'path';+import { acquireServerLock, ServerLockError } from '../src/cli';++const tmpRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'browse-lock-'));+afterAll(() => {+ // Restore write perm so cleanup can delete the read-only dir.+ try { fs.chmodSync(path.join(tmpRoot, 'rodir'), 0o700); } catch {}+ fs.rmSync(tmpRoot, { recursive: true, force: true });+});++describe('acquireServerLock (#1084 error honesty)', () => {+ test('happy path: acquires and releases', () => {+ const lockPath = path.join(tmpRoot, 'happy.lock');+ const release = acquireServerLock(lockPath);+ expect(release).not.toBeNull();+ expect(fs.readFileSync(lockPath, 'utf8').trim()).toBe(String(process.pid));+ release!();+ expect(fs.existsSync(lockPath)).toBe(false);+ });++ test('EACCES throws ServerLockError with the real errno — NOT phantom contention', () => {+ if (process.platform === 'win32' || process.getuid?.() === 0) return; // chmod semantics differ+ const rodir = path.join(tmpRoot, 'rodir');+ fs.mkdirSync(rodir, { recursive: true });+ fs.chmodSync(rodir, 0o500); // r-x: open('wx') inside fails EACCES+ const lockPath = path.join(rodir, 'browse.json.lock');+ let thrown: any = null;+ try {+ acquireServerLock(lockPath); // old code: returned null (phantom contention)+ } catch (err) {+ thrown = err;+ }+ expect(thrown).toBeInstanceOf(ServerLockError);+ expect(thrown.code).toBe('EACCES');+ expect(thrown.message).toContain('E_SERVER_LOCK (EACCES)');+ expect(thrown.message).toContain(lockPath);+ });++ test('ENOENT (missing lock dir) creates the dir and acquires', () => {+ const lockPath = path.join(tmpRoot, 'newdir', 'browse.json.lock');+ // old code: openSync ENOENT → bare catch → readFileSync ENOENT → null+ const release = acquireServerLock(lockPath);+ expect(release).not.toBeNull();+ expect(fs.existsSync(lockPath)).toBe(true);+ release!();+ });++ test('EEXIST + dead holder: removes stale lock and acquires', () => {+ const lockPath = path.join(tmpRoot, 'stale.lock');+ fs.writeFileSync(lockPath, '999999999\n'); // PID that cannot be alive+ const release = acquireServerLock(lockPath);+ expect(release).not.toBeNull();+ release!();+ });++ test('EEXIST + live holder: returns null (real contention, no throw)', () => {+ const lockPath = path.join(tmpRoot, 'live.lock');+ fs.writeFileSync(lockPath, `${process.pid}\n`); // this test process is alive+ expect(acquireServerLock(lockPath)).toBeNull();+ fs.unlinkSync(lockPath);+ });++ test('EEXIST + garbage lockfile content: NaN pid is treated as stale, lock acquired', () => {+ const lockPath = path.join(tmpRoot, 'garbage.lock');+ fs.writeFileSync(lockPath, 'not-a-pid\n'); // parseInt → NaN → falsy → stale path+ const release = acquireServerLock(lockPath);+ expect(release).not.toBeNull();+ // Our pid replaced the garbage — the stale lock was removed and re-acquired.+ expect(fs.readFileSync(lockPath, 'utf8').trim()).toBe(String(process.pid));+ release!();+ expect(fs.existsSync(lockPath)).toBe(false);+ });++ // NOTE: the "stale lock that survives unlink" livelock variant is deliberately+ // not simulated here — the source removes locks through safeUnlink's own fs+ // binding, which a test-side fs monkey-patch cannot reliably intercept in Bun.+ // The depth cap itself is exercised by the vanish-race test below.++ test('depth cap: holder that vanishes between open and read returns null after 5 retries', () => {+ // The EEXIST → readFileSync ENOENT race: the lock exists at openSync but+ // is gone by the read (holder released in between). Repeated forever+ // (open/release storm), the same depth cap must bound the retry loop.+ const lockPath = path.join(tmpRoot, 'vanish.lock');+ fs.writeFileSync(lockPath, `${process.pid}\n`);+ const origRead = fsMutable.readFileSync;+ try {+ (fsMutable as any).readFileSync = (p: fs.PathLike | number, ...rest: unknown[]) => {+ if (p === lockPath) {+ const e: NodeJS.ErrnoException = new Error('mock: lock vanished before read');+ e.code = 'ENOENT';+ throw e;+ }+ return (origRead as any)(p, ...rest);+ };+ expect(acquireServerLock(lockPath)).toBeNull();+ } finally {+ (fsMutable as any).readFileSync = origRead;+ fs.unlinkSync(lockPath);+ }+ });+});diff --git a/browse/test/session-persist.test.ts b/browse/test/session-persist.test.tsnew file mode 100644index 000000000..d9eaa5d9f--- /dev/null+++ b/browse/test/session-persist.test.ts@@ -0,0 +1,268 @@+/**+ * Opt-in session-state persistence (#778, #2193, #1128, #1129).+ *+ * Pins the leg of the browser-lifecycle contract that had no coverage:+ * "shut down without losing live session state." Pre-fix, the headless+ * daemon used non-persistent chromium.launch() with zero storage+ * persistence — any crash or binary-version auto-restart silently lost all+ * auth. These tests fail on the old tree (module absent, no wiring).+ *+ * Suites:+ * 1. Pure serialize/deserialize/filter units (free, instant).+ * 2. Real-Chromium round-trip: cookie + localStorage survive a full+ * manager teardown + relaunch via persist/restore.+ * 3. Static wiring tripwire: server.ts restores at launch, snapshots at+ * shutdown, and the gate is BROWSE_PERSIST_STATE (default off).+ */++import { describe, test, expect, afterAll } from 'bun:test';+import * as fs from 'fs';+import * as os from 'os';+import * as path from 'path';+import {+ serializeSessionState, deserializeSessionState, filterSessionCookies,+ isSessionPersistEnabled, persistSessionState, restoreSessionState,+} from '../src/session-persist';+import type { BrowserState } from '../src/browser-manager';++const tmpRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'browse-persist-'));+afterAll(() => { fs.rmSync(tmpRoot, { recursive: true, force: true }); });++describe('session-persist units', () => {+ test('config gate: default off, exactly "1" enables', () => {+ expect(isSessionPersistEnabled({} as NodeJS.ProcessEnv)).toBe(false);+ expect(isSessionPersistEnabled({ BROWSE_PERSIST_STATE: '0' } as any)).toBe(false);+ expect(isSessionPersistEnabled({ BROWSE_PERSIST_STATE: 'true' } as any)).toBe(false);+ expect(isSessionPersistEnabled({ BROWSE_PERSIST_STATE: '1' } as any)).toBe(true);+ });++ test('serialize strips loadedHtml/owner, keeps cookies + storage', () => {+ const state: BrowserState = {+ cookies: [{ name: 'sid', value: 'abc', domain: 'example.com', path: '/', expires: -1, httpOnly: false, secure: false, sameSite: 'Lax' } as any],+ pages: [{+ url: 'https://example.com/app',+ isActive: true,+ storage: { localStorage: { k: 'v' }, sessionStorage: {} },+ loadedHtml: '<script>evil</script>',+ loadedHtmlWaitUntil: 'load',+ owner: 'agent-1',+ }],+ };+ const raw = serializeSessionState(state);+ expect(raw).not.toContain('loadedHtml');+ expect(raw).not.toContain('evil');+ expect(raw).not.toContain('owner');+ const parsed = JSON.parse(raw);+ expect(parsed.version).toBe(1);+ expect(parsed.cookies[0].name).toBe('sid');+ expect(parsed.pages[0].storage.localStorage.k).toBe('v');+ });++ test('deserialize rejects corrupt JSON, wrong version, missing arrays', () => {+ expect(deserializeSessionState('not json{')).toBeNull();+ expect(deserializeSessionState('{"version":99,"cookies":[],"pages":[]}')).toBeNull();+ expect(deserializeSessionState('{"version":1,"cookies":{}}')).toBeNull();+ });++ test('deserialize strips loadedHtml/owner even if tampered onto disk', () => {+ const raw = JSON.stringify({+ version: 1,+ cookies: [],+ pages: [{ url: 'https://x.com', isActive: true, storage: null, loadedHtml: '<h1>x</h1>', owner: 'evil' }],+ });+ const state = deserializeSessionState(raw)!;+ expect((state.pages[0] as any).loadedHtml).toBeUndefined();+ expect((state.pages[0] as any).owner).toBeUndefined();+ });++ test('cookie filter drops malformed + internal-network domains', () => {+ const kept = filterSessionCookies([+ { name: 'ok', value: 'v', domain: 'example.com' },+ { name: 'ok2', value: 'v', domain: '.example.com' }, // leading-dot public domain kept+ { name: 'bad1', value: 'v', domain: 'localhost' },+ { name: 'bad2', value: 'v', domain: '.corp.internal' },+ { name: 'bad3', value: 'v', domain: '169.254.169.254' },+ { name: 'bad4', value: 'v', domain: '169.254.1.2' }, // whole link-local block, not just metadata+ { name: 'bad5', value: 'v', domain: '127.0.0.1' }, // IPv4 loopback literal+ { name: 'bad6', value: 'v', domain: '.127.0.0.1' }, // leading-dot loopback variant+ { name: 'bad7', value: 'v', domain: '::1' }, // IPv6 loopback+ { name: 'bad8', value: 'v', domain: '[::1]' }, // bracketed IPv6 loopback+ { name: 'bad9', value: 42, domain: 'example.com' },+ null,+ ]);+ expect(kept.map((c: any) => c.name)).toEqual(['ok', 'ok2']);+ });++ test('restoreSessionState: missing file → null, corrupt file → quarantined to .corrupt', async () => {+ const bmNeverCalled = { closeAllPages() { throw new Error('must not restore'); } } as any;+ expect(await restoreSessionState(bmNeverCalled, path.join(tmpRoot, 'nope.json'))).toBeNull();+ const corrupt = path.join(tmpRoot, 'corrupt.json');+ fs.writeFileSync(corrupt, '{oops');+ expect(await restoreSessionState(bmNeverCalled, corrupt)).toBeNull();+ expect(fs.existsSync(corrupt)).toBe(false); // moved aside, won't block every future launch+ expect(fs.existsSync(`${corrupt}.corrupt`)).toBe(true); // forensic artifact kept (R3)+ });++ test('persistSessionState is a no-op in headed mode (profile owns state)', async () => {+ const file = path.join(tmpRoot, 'headed.json');+ const bm = {+ getConnectionMode: () => 'headed',+ saveState() { throw new Error('must not snapshot headed session'); },+ } as any;+ await persistSessionState(bm, file);+ expect(fs.existsSync(file)).toBe(false);+ });++ test('persist writes atomically: no .tmp left behind, file parses', async () => {+ const file = path.join(tmpRoot, 'atomic.json');+ const state: BrowserState = {+ cookies: [{ name: 'sid', value: 'abc', domain: 'example.com' } as any],+ pages: [{ url: 'https://example.com', isActive: true, storage: null }],+ };+ const bm = { getConnectionMode: () => 'launched', saveState: async () => state } as any;+ await persistSessionState(bm, file);+ expect(fs.existsSync(`${file}.tmp`)).toBe(false); // staged copy renamed away+ const parsed = JSON.parse(fs.readFileSync(file, 'utf-8'));+ expect(parsed.cookies[0].name).toBe('sid');+ });++ test('a failed snapshot write preserves the previous good snapshot', async () => {+ // chmod-based read-only dirs don't bind on Windows or when running as root.+ if (process.platform === 'win32' || process.getuid?.() === 0) return;+ const dir = path.join(tmpRoot, 'ro');+ fs.mkdirSync(dir);+ const file = path.join(dir, 'session-state.json');+ const goodState: BrowserState = {+ cookies: [],+ pages: [{ url: 'https://good.example', isActive: true, storage: null }],+ };+ const bm = { getConnectionMode: () => 'launched', saveState: async () => goodState } as any;+ await persistSessionState(bm, file);+ fs.chmodSync(dir, 0o500); // next .tmp write throws EACCES mid-persist+ try {+ await expect(persistSessionState(bm, file)).rejects.toThrow();+ // The crash-mid-write scenario the feature exists to survive: the+ // previous good snapshot is untouched and still parses.+ const parsed = JSON.parse(fs.readFileSync(file, 'utf-8'));+ expect(parsed.pages[0].url).toBe('https://good.example');+ } finally {+ fs.chmodSync(dir, 0o700);+ }+ });+});++describe('session-persist round-trip (real Chromium)', () => {+ test('cookie + localStorage + URL survive teardown → relaunch; loopback cookies dropped', async () => {+ const { BrowserManager } = await import('../src/browser-manager');+ const { startTestServer } = await import('./test-server');+ const { server, url } = startTestServer(0);+ const stateFile = path.join(tmpRoot, 'roundtrip.json');++ const bm1 = new BrowserManager();+ await bm1.launch();+ try {+ const page = bm1.getPage();+ await page.goto(`${url}/basic.html`, { waitUntil: 'domcontentloaded' });+ // Real-site cookie: set on the context for a non-loopback domain (the+ // restore hygiene filter deliberately drops loopback/link-local+ // domains, so a 127.0.0.1 test-server cookie can't stand in for it).+ await page.context().addCookies([+ { name: 'session_marker', value: 'alive-after-restart', domain: 'example.com', path: '/' },+ ]);+ await page.evaluate(() => {+ document.cookie = 'loopback_marker=must-be-dropped; path=/'; // 127.0.0.1 host cookie+ localStorage.setItem('auth_marker', 'still-logged-in');+ });+ await persistSessionState(bm1, stateFile);+ } finally {+ await bm1.close();+ }++ // File on disk is owner-only (cookies are secrets).+ if (process.platform !== 'win32') {+ expect(fs.statSync(stateFile).mode & 0o777).toBe(0o600);+ }++ const bm2 = new BrowserManager();+ await bm2.launch();+ try {+ const restored = await restoreSessionState(bm2, stateFile);+ expect(restored).not.toBeNull();+ expect(restored!.pages.length).toBe(1); // counts derivable without a saveState() round-trip+ // Hygiene filter applied at restore: the real-site cookie survives,+ // the loopback cookie does not.+ expect(restored!.cookies.map((c: any) => c.name)).toEqual(['session_marker']);+ const page = bm2.getPage();+ expect(page.url()).toContain('/basic.html');+ const marker = await page.evaluate(() => ({+ cookie: document.cookie,+ auth: localStorage.getItem('auth_marker'),+ }));+ expect(marker.cookie).not.toContain('loopback_marker'); // dropped by isInternalCookieDomain+ expect(marker.auth).toBe('still-logged-in');+ const restoredCookies = await page.context().cookies('https://example.com');+ expect(restoredCookies.map((c) => `${c.name}=${c.value}`)).toContain('session_marker=alive-after-restart');+ } finally {+ await bm2.close();+ server.stop(true);+ }+ }, 60_000);+});++describe('server wiring (static tripwire)', () => {+ const SERVER_SRC = fs.readFileSync(path.join(import.meta.dir, '..', 'src', 'server.ts'), 'utf-8');++ test('start() restores and schedules interval snapshots behind the gate', () => {+ expect(SERVER_SRC).toContain('isSessionPersistEnabled()');+ expect(SERVER_SRC).toContain('restoreSessionState(browserManager');+ expect(SERVER_SRC).toContain('sessionPersistIntervalMs()');+ });++ test('start() restores in the background AFTER the port binds (CLI readiness must not wait)', () => {+ // Restore re-creates tabs with up-to-15s goto timeouts; the CLI gives up+ // at 8s. A restore that runs before Bun.serve() makes every $B command+ // report "Server failed to start" on one slow saved URL.+ const serveAt = SERVER_SRC.indexOf('const server = Bun.serve(');+ const restoreAt = SERVER_SRC.indexOf('restoreSessionState(browserManager');+ expect(serveAt).toBeGreaterThan(-1);+ expect(restoreAt).toBeGreaterThan(serveAt);+ });++ test('interval snapshots carry an in-flight guard (no overlapping persists)', () => {+ expect(SERVER_SRC).toContain('persistInFlight');+ });++ test('interval ticks are gated on isShuttingDown (belt half of the shutdown ordering fix)', () => {+ // A tick that fires during browser teardown snapshots a degraded state+ // (zero tabs) over the good final snapshot. The handle-clear in shutdown()+ // is the suspenders; this gate is the belt for a tick already scheduled.+ const tickerAt = SERVER_SRC.indexOf('sessionPersistInterval = setInterval(');+ expect(tickerAt).toBeGreaterThan(-1);+ const tickerBlock = SERVER_SRC.slice(tickerAt, tickerAt + 500);+ expect(tickerBlock).toContain('if (isShuttingDown) return;');+ });++ test('shutdown() clears the persist ticker BEFORE the final snapshot (suspenders half)', () => {+ const shutdownStart = SERVER_SRC.indexOf('async function shutdown(');+ const clearAt = SERVER_SRC.indexOf('clearInterval(sessionPersistInterval)', shutdownStart);+ const persistAt = SERVER_SRC.indexOf('persistSessionState(cfgBrowserManager', shutdownStart);+ expect(clearAt).toBeGreaterThan(shutdownStart);+ expect(persistAt).toBeGreaterThan(clearAt);+ });++ test('shutdown() takes a final snapshot BEFORE closing the browser', () => {+ const shutdownStart = SERVER_SRC.indexOf('async function shutdown(');+ const persistAt = SERVER_SRC.indexOf('persistSessionState(cfgBrowserManager', shutdownStart);+ const closeAt = SERVER_SRC.indexOf('await cfgBrowserManager.close()', shutdownStart);+ expect(persistAt).toBeGreaterThan(shutdownStart);+ expect(closeAt).toBeGreaterThan(persistAt);+ });++ test('shutdown() snapshot is deadlined — a wedged page.evaluate cannot hang shutdown', () => {+ const shutdownStart = SERVER_SRC.indexOf('async function shutdown(');+ const closeAt = SERVER_SRC.indexOf('await cfgBrowserManager.close()', shutdownStart);+ const raceAt = SERVER_SRC.indexOf('Promise.race', shutdownStart);+ expect(raceAt).toBeGreaterThan(shutdownStart);+ expect(raceAt).toBeLessThan(closeAt);+ });+});diff --git a/browse/test/snapshot.test.ts b/browse/test/snapshot.test.tsindex d3c012eaf..7f509eed0 100644--- a/browse/test/snapshot.test.ts+++ b/browse/test/snapshot.test.ts@@ -14,7 +14,7 @@ import { handleMetaCommand } from '../src/meta-commands';import * as fs from 'fs';const handleReadCommand = (cmd: string, args: string[], b: BrowserManager) =>- _handleReadCommand(cmd, args, b.getActiveSession());+ _handleReadCommand(cmd, args, b.getActiveSession(), b);const handleWriteCommand = (cmd: string, args: string[], b: BrowserManager) =>_handleWriteCommand(cmd, args, b.getActiveSession(), b);diff --git a/browse/test/stop-ack-before-shutdown.test.ts b/browse/test/stop-ack-before-shutdown.test.tsnew file mode 100644index 000000000..05c761675--- /dev/null+++ b/browse/test/stop-ack-before-shutdown.test.ts@@ -0,0 +1,23 @@+import { describe, expect, test } from 'bun:test';+import { handleMetaCommand } from '../src/meta-commands';++describe('server control acknowledgement ordering', () => {+ for (const [command, acknowledgement] of [+ ['stop', 'Server stopped'],+ ['restart', 'Restarting...'],+ ] as const) {+ test(`${command} acknowledges before closing the listener`, async () => {+ let shutdownCalls = 0;+ const manager = { getActiveSession: () => ({}) } as any;++ const result = await handleMetaCommand(command, [], manager, async () => {+ shutdownCalls += 1;+ });++ expect(result).toBe(acknowledgement);+ expect(shutdownCalls).toBe(0);+ await new Promise((resolve) => setTimeout(resolve, 50));+ expect(shutdownCalls).toBe(1);+ });+ }+});diff --git a/browse/test/telemetry-optout.test.ts b/browse/test/telemetry-optout.test.tsnew file mode 100644index 000000000..0c4626c16--- /dev/null+++ b/browse/test/telemetry-optout.test.ts@@ -0,0 +1,175 @@+/**+ * Telemetry consent tiers — the user-consent enforcement point.+ *+ * Telemetry is OPT-IN: it emits only when the user granted a tier through+ * the consent prompt (`telemetry: community` or `telemetry: anonymous` in+ * ~/.gstack/config.yaml). An absent key, an absent config file, an explicit+ * `off`, or any unrecognized value all mean DISABLED — the same default+ * bin/gstack-config's DEFAULTS table reports for an unset key, so a daemon+ * spawned outside a skill preamble (direct $B use, embedders) can never+ * emit while `gstack-config get telemetry` tells the user 'off'.+ *+ * The persistent tier reads through the shared flat-YAML helper in+ * config.ts (readGstackConfigYamlKey), same parser as the pair-agent gate.+ * Env tier: GSTACK_TELEMETRY_OFF=1 always disables; =0 is a harness-side+ * consent assertion that covers the no-config default only — it never+ * overrides an explicit `telemetry: off`.+ *+ * Harness mirrors pair-agent-optin-gate.test.ts: GSTACK_HOME → temp dir,+ * env saved/restored per test, cache reset via _resetTelemetryCache.+ */++import { describe, test, expect, afterEach } from 'bun:test';+import * as fs from 'fs';+import * as os from 'os';+import * as path from 'path';+import { isTelemetryDisabled, logTelemetry, _resetTelemetryCache } from '../src/telemetry';++const savedEnv = {+ GSTACK_HOME: process.env.GSTACK_HOME,+ GSTACK_TELEMETRY_OFF: process.env.GSTACK_TELEMETRY_OFF,+};+const tmpHomes: string[] = [];++/** Fresh GSTACK_HOME with the given config.yaml body (null = no file). */+function tmpHomeWith(configYaml: string | null): string {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-telemetry-optout-'));+ tmpHomes.push(dir);+ if (configYaml !== null) {+ fs.writeFileSync(path.join(dir, 'config.yaml'), configYaml);+ }+ process.env.GSTACK_HOME = dir;+ delete process.env.GSTACK_TELEMETRY_OFF;+ _resetTelemetryCache();+ return dir;+}++afterEach(() => {+ for (const k of ['GSTACK_HOME', 'GSTACK_TELEMETRY_OFF'] as const) {+ if (savedEnv[k] === undefined) delete process.env[k];+ else process.env[k] = savedEnv[k]!;+ }+ _resetTelemetryCache();+ while (tmpHomes.length) fs.rmSync(tmpHomes.pop()!, { recursive: true, force: true });+});++describe('telemetry persistent opt-out tier (config.yaml)', () => {+ test('DISABLED when config.yaml has plain `telemetry: off`', () => {+ tmpHomeWith('telemetry: off\n');+ expect(isTelemetryDisabled()).toBe(true);+ });++ test("DISABLED when the value is single-quoted: telemetry: 'off'", () => {+ tmpHomeWith("telemetry: 'off'\n");+ expect(isTelemetryDisabled()).toBe(true);+ });++ test('DISABLED when the value is double-quoted: telemetry: "off"', () => {+ tmpHomeWith('telemetry: "off"\n');+ expect(isTelemetryDisabled()).toBe(true);+ });++ test('DISABLED with a trailing comment: telemetry: off # user opted out', () => {+ tmpHomeWith('telemetry: off # user opted out\n');+ expect(isTelemetryDisabled()).toBe(true);+ });++ test('DISABLED when the key sits among other keys', () => {+ tmpHomeWith('pair_agent: off\ntelemetry: off\nskill_prefix: none\n');+ expect(isTelemetryDisabled()).toBe(true);+ });++ test('ENABLED when the user granted the `anonymous` tier', () => {+ tmpHomeWith('telemetry: anonymous\n');+ expect(isTelemetryDisabled()).toBe(false);+ });++ test('ENABLED when the user granted the `community` tier', () => {+ tmpHomeWith('telemetry: community\n');+ expect(isTelemetryDisabled()).toBe(false);+ });++ test('DISABLED when the key is absent — consent was never granted', () => {+ // bin/gstack-config's DEFAULTS table reports 'off' for an unset telemetry+ // key; the daemon must agree or direct-$B spawns emit while the user is+ // told telemetry is off (default-polarity split-brain).+ tmpHomeWith('pair_agent: on\n');+ expect(isTelemetryDisabled()).toBe(true);+ });++ test('DISABLED when config.yaml does not exist — fresh installs emit nothing', () => {+ tmpHomeWith(null);+ expect(isTelemetryDisabled()).toBe(true);+ });++ test('DISABLED on an unrecognized tier value (fail-closed)', () => {+ tmpHomeWith('telemetry: banana\n');+ expect(isTelemetryDisabled()).toBe(true);+ });++ test('a commented-out consent line does not enable: `# telemetry: community`', () => {+ tmpHomeWith('# telemetry: community\n');+ expect(isTelemetryDisabled()).toBe(true);+ });+});++describe('telemetry env tier + cache semantics', () => {+ test('GSTACK_TELEMETRY_OFF=1 disables even when config says anonymous', () => {+ tmpHomeWith('telemetry: anonymous\n');+ process.env.GSTACK_TELEMETRY_OFF = '1';+ _resetTelemetryCache();+ expect(isTelemetryDisabled()).toBe(true);+ });++ test('GSTACK_TELEMETRY_OFF=0 never overrides an explicit `telemetry: off`', () => {+ // The =0 hint is a harness-side consent assertion for scratch homes with+ // no config store; a user's written opt-out always wins over it.+ tmpHomeWith('telemetry: off\n');+ process.env.GSTACK_TELEMETRY_OFF = '0';+ _resetTelemetryCache();+ expect(isTelemetryDisabled()).toBe(true);+ });++ test('GSTACK_TELEMETRY_OFF=0 enables when no config store exists (harness seam)', () => {+ tmpHomeWith(null);+ process.env.GSTACK_TELEMETRY_OFF = '0';+ _resetTelemetryCache();+ expect(isTelemetryDisabled()).toBe(false);+ });++ test('verdict is cached per process; _resetTelemetryCache re-reads config', () => {+ const dir = tmpHomeWith('telemetry: anonymous\n');+ expect(isTelemetryDisabled()).toBe(false);+ // Opt out on disk mid-process: the cached verdict holds until reset.+ fs.writeFileSync(path.join(dir, 'config.yaml'), 'telemetry: off\n');+ expect(isTelemetryDisabled()).toBe(false);+ _resetTelemetryCache();+ expect(isTelemetryDisabled()).toBe(true);+ });+});++describe('enforcement: logTelemetry writes only with granted consent', () => {+ test('config-tier opt-out suppresses the JSONL append', async () => {+ const dir = tmpHomeWith('telemetry: off\n');+ logTelemetry({ event: 'domain_skill_fired', host: 'example.com' });+ // Fire-and-forget path: give any (incorrect) async append time to land.+ await new Promise((r) => setTimeout(r, 30));+ expect(fs.existsSync(path.join(dir, 'analytics', 'browse-telemetry.jsonl'))).toBe(false);+ });++ test('no consent ever recorded (absent key) suppresses the JSONL append', async () => {+ const dir = tmpHomeWith('pair_agent: on\n');+ logTelemetry({ event: 'domain_skill_fired', host: 'example.com' });+ await new Promise((r) => setTimeout(r, 30));+ expect(fs.existsSync(path.join(dir, 'analytics', 'browse-telemetry.jsonl'))).toBe(false);+ });++ test('granted `community` tier appends the event', async () => {+ const dir = tmpHomeWith('telemetry: community\n');+ logTelemetry({ event: 'domain_skill_fired', host: 'example.com' });+ await new Promise((r) => setTimeout(r, 30));+ const file = path.join(dir, 'analytics', 'browse-telemetry.jsonl');+ expect(fs.existsSync(file)).toBe(true);+ expect(fs.readFileSync(file, 'utf-8')).toContain('domain_skill_fired');+ });+});diff --git a/browse/test/watchdog.test.ts b/browse/test/watchdog.test.tsindex 42faa262a..56201779e 100644--- a/browse/test/watchdog.test.ts+++ b/browse/test/watchdog.test.ts@@ -1,8 +1,12 @@-import { describe, test, expect, afterEach } from 'bun:test';+import { describe, test, expect, afterEach, beforeEach, mock } from 'bun:test';import { spawn, type Subprocess } from 'bun';import * as path from 'path';import * as fs from 'fs';import * as os from 'os';+import * as crypto from 'crypto';+import { buildFetchHandler, __testInternals__, type ServerConfig } from '../src/server';+import { __resetRegistry } from '../src/token-registry';+import { resolveConfig } from '../src/config';// End-to-end regression tests for the parent-process watchdog in server.ts.// The watchdog has layered behavior since v0.18.1.0 (#1025) and v0.18.2.0@@ -18,11 +22,9 @@ import * as os from 'os';// eventual cleanup.//// Tunnel mode coverage (parent dies → shutdown because idle timeout doesn't-// apply) is not covered by an automated test here — tunnelActive is a runtime-// variable set by /pair-agent's tunnel-create flow, not an env var, so faking-// it would require invasive test-only hooks. The mode check is documented-// inline at the watchdog and SIGTERM handlers, and would regress visibly for-// /pair-agent users (server lingers after disconnect).+// apply) is covered behaviorally in the in-process suite at the bottom of this+// file: the tick is exported via __testInternals__.parentWatchdogTick (same+// seam as idleCheckTick) and tunnelActive is simulated via setTunnelActive.//// Each test spawns the real server.ts. Tests 1 and 2 verify behavior via// stdout log line (fast). Test 3 waits for the watchdog poll cycle to confirm@@ -155,3 +157,163 @@ describe('parent-process watchdog (v0.18.1.0)', () => {expect(isProcessAlive(serverPid)).toBe(true);}, 45_000);});++// The three tests above all fix the mode via env at SPAWN time, so none of them+// reaches the headed branch of the watchdog. That branch is only reachable by a+// RUNTIME promotion, which `handoff` performs: it swaps in a headed context on a+// running daemon without a restart, moving a daemon that legitimately registered+// a watchdog onto the fatal side of the check. The parent is usually a+// short-lived shell (Claude Code's Bash tool kills one after every invocation),+// so the next poll shut the daemon down and discarded whatever the user had been+// handed off to do — observed as repeated session loss mid-login.+//+// The fix must NOT clear the interval, though: the same tick is the+// tunnel-orphan reaper (idle timeout is disabled in tunnel mode, so parent+// death is the ONLY thing that reaps an internet-exposed daemon). Promotion+// sets a suppress flag the tick re-reads each pass — "being headed" no longer+// kills the daemon on parent death, but an active tunnel still does.+//+// Driving a real `handoff` needs a headed Chromium, which does not belong in the+// free tier, so this pins the WIRING instead — the same static-tripwire approach+// used by cdp-session-cleanup.test.ts and server-auth.test.ts. If either half of+// the contract is dropped, the crash returns silently and these fail. The+// behavioral halves (suppression + tunnel reaping) run in-process below.+describe('headed parent-death shutdown is suppressed on runtime promotion', () => {+ const read = (rel: string) => fs.readFileSync(path.join(ROOT, rel), 'utf-8');++ test('handoff() notifies the server that it promoted the daemon', () => {+ const src = read('src/browser-manager.ts');+ const promote = src.indexOf("this.connectionMode = 'headed';", src.indexOf('async handoff('));+ expect(promote).toBeGreaterThan(-1);+ // The notification must follow the promotion closely; a call left far away+ // (or removed) is the regression this guards.+ expect(src.slice(promote, promote + 800)).toContain('this.onHeadedPromotion?.()');+ });++ test('the server binds that callback to the suppress-flag setter', () => {+ const src = read('src/server.ts');+ expect(src).toContain('function suppressHeadedParentShutdown()');+ // Bound on BOTH the module-level manager and any embedder-supplied one; the+ // watchdog reads activeBrowserManager, so binding only the default instance+ // leaves embedders (e.g. gbrowser) promoting silently.+ expect(src).toContain('browserManager.onHeadedPromotion = suppressHeadedParentShutdown');+ expect(src).toContain('cfgBrowserManager.onHeadedPromotion = suppressHeadedParentShutdown');+ });++ test('promotion must NOT clear the interval — the tick doubles as the tunnel-orphan reaper', () => {+ const src = read('src/server.ts');+ // The original #2565 absorption cleared the ENTIRE interval on promotion.+ // Sequence handoff → resume → /pair-agent tunnel then left an+ // internet-exposed daemon that nothing reaps. The tick must stay+ // registered and re-check the suppress flag + tunnelActive every pass.+ expect(src).not.toContain('clearInterval(parentWatchdogTimer)');+ expect(src).toContain('setInterval(parentWatchdogTick');+ const tickStart = src.indexOf('function parentWatchdogTick(');+ expect(tickStart).toBeGreaterThan(-1);+ const tick = src.slice(tickStart, src.indexOf('\n}', tickStart));+ expect(tick).toContain('headedParentShutdownSuppressed');+ expect(tick).toContain('tunnelActive');+ });+});++// ─── Behavioral: suppressed watchdog still reaps tunnel orphans ────────────+//+// In-process, via the same __testInternals__ seam server-factory.test.ts uses+// for idleCheckTick. parentWatchdogTick(deadPid) simulates the 15s poll+// discovering a dead parent; setTunnelActive simulates /pair-agent's+// tunnel-create flow; suppressHeadedParentShutdown is exactly what the+// handoff promotion callback invokes.+function makeMinimalConfig(mode: 'launched' | 'headed', tmpDir: string): ServerConfig {+ const base = resolveConfig();+ return {+ authToken: 'watchdog-test-' + crypto.randomBytes(16).toString('hex'),+ browsePort: 34567,+ idleTimeoutMs: 1_800_000,+ // State paths pointed at a scratch dir so shutdown()'s cleanup can never+ // touch a real daemon's files on the machine running the tests.+ config: { ...base, stateFile: path.join(tmpDir, 'browse-state.json'), stateDir: tmpDir },+ browserManager: {+ getConnectionMode: () => mode,+ isWatching: () => false,+ stopWatch: () => {},+ close: async () => {},+ onDisconnect: null,+ } as any,+ startTime: Date.now(),+ // Skip terminal-agent teardown: identity files live under the REAL state+ // dir conventions and this suite must stay hermetic.+ ownsTerminalAgent: false,+ };+}++describe('suppressed watchdog still reaps tunnel orphans (behavioral)', () => {+ // A PID above darwin/linux default pid_max: process.kill(pid, 0) throws+ // ESRCH, which the tick reads as "parent exited".+ const DEAD_PID = 999_999;+ let scratch: string;+ const savedChromiumProfile = process.env.CHROMIUM_PROFILE;++ beforeEach(() => {+ scratch = fs.mkdtempSync(path.join(os.tmpdir(), 'watchdog-tick-'));+ // shutdown() runs cleanSingletonLocks(resolveChromiumProfile()); point it+ // at scratch so the operator's real profile is never inspected.+ process.env.CHROMIUM_PROFILE = path.join(scratch, 'chromium-profile');+ __resetRegistry();+ __testInternals__.setTunnelActive(false);+ __testInternals__.setLastActivity(Date.now());+ __testInternals__.resetShutdownState();+ __testInternals__.resetParentWatchdogState();+ });++ afterEach(() => {+ if (savedChromiumProfile === undefined) delete process.env.CHROMIUM_PROFILE;+ else process.env.CHROMIUM_PROFILE = savedChromiumProfile;+ __testInternals__.setTunnelActive(false);+ __testInternals__.resetShutdownState();+ __testInternals__.resetParentWatchdogState();+ try { fs.rmSync(scratch, { recursive: true, force: true }); } catch {}+ });++ // Drain the fire-and-forget shutdown promise chain (flushBuffers + close)+ // the same way server-factory.test.ts does before asserting on exit.+ async function drainShutdown(): Promise<void> {+ await Promise.resolve();+ await Promise.resolve();+ await new Promise<void>((r) => setImmediate(r));+ await new Promise<void>((r) => setImmediate(r));+ }++ test('after promotion suppression, parent death does NOT shut down a headed daemon (#2565)', async () => {+ const exitMock = mock((_code?: number) => {});+ const originalExit = process.exit;+ (process as any).exit = exitMock;+ try {+ buildFetchHandler(makeMinimalConfig('headed', scratch));+ __testInternals__.suppressHeadedParentShutdown(); // what handoff promotion triggers+ __testInternals__.parentWatchdogTick(DEAD_PID);+ await drainShutdown();+ expect(exitMock).not.toHaveBeenCalled();+ } finally {+ (process as any).exit = originalExit;+ }+ });++ test('CRITICAL: suppression active + tunnel live — parent death still shuts down', async () => {+ const exitMock = mock((_code?: number) => {});+ const originalExit = process.exit;+ (process as any).exit = exitMock;+ try {+ buildFetchHandler(makeMinimalConfig('headed', scratch));+ __testInternals__.suppressHeadedParentShutdown();+ __testInternals__.setTunnelActive(true); // handoff → resume → /pair-agent tunnel+ __testInternals__.parentWatchdogTick(DEAD_PID);+ await drainShutdown();+ // The tick is the ONLY reaper for tunnel orphans (idle timeout is+ // disabled in tunnel mode). If this fails, an internet-exposed daemon+ // outlives its parent forever.+ expect(exitMock).toHaveBeenCalled();+ } finally {+ (process as any).exit = originalExit;+ }+ });+});diff --git a/browse/test/windows-spawn-hide.test.ts b/browse/test/windows-spawn-hide.test.tsnew file mode 100644index 000000000..086a28657--- /dev/null+++ b/browse/test/windows-spawn-hide.test.ts@@ -0,0 +1,64 @@+/**+ * Static tripwire for #1835: child spawns reachable on Windows must pass+ * windowsHide, or every daemon relaunch / taskkill / icacls / powershell+ * invocation flashes a black console window (and can steal focus).+ *+ * Source-level, same style as server-auth.test.ts / cdp-session-cleanup.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` in `src` must have `windowsHide` within the+ * next `window` chars (the spawn's options object). */+function expectHideNearEvery(src: string, needle: string, window = 400): void {+ let idx = src.indexOf(needle);+ expect(idx).toBeGreaterThanOrEqual(0);+ while (idx !== -1) {+ const slice = src.slice(idx, idx + window);+ expect(slice).toMatch(/windowsHide:\s*true/);+ idx = src.indexOf(needle, idx + needle.length);+ }+}++describe('windowsHide on Windows-reachable spawns (#1835)', () => {+ test('daemon launch paths in cli.ts pass windowsHide', () => {+ const cli = SRC('cli.ts');+ // Installed path: node -e launcher — both the outer spawnSync and the+ // inner detached daemon spawn (inside the launcher code string).+ expect(cli).toContain('detached:true,windowsHide:true');+ expectHideNearEvery(cli, "'-e', launcherCode]");+ // Dev fallback: detached bun spawn.+ expectHideNearEvery(cli, "nodeSpawn('bun'");+ // taskkill (killServer).+ expectHideNearEvery(cli, "'taskkill'");+ });++ test('Windows-only process probes pass windowsHide', () => {+ // tasklist in isProcessAlive — runs in polling loops.+ expectHideNearEvery(SRC('error-handling.ts'), "'tasklist'");+ // powershell DPAPI + tasklist in cookie import.+ const cookie = SRC('cookie-import-browser.ts');+ expectHideNearEvery(cookie, "'powershell'");+ expectHideNearEvery(cookie, "'tasklist'");+ });++ test('icacls calls in file-permissions.ts pass windowsHide', () => {+ const perms = SRC('file-permissions.ts');+ expect((perms.match(/'icacls'/g) || []).length).toBeGreaterThanOrEqual(3);+ expectHideNearEvery(perms, "'icacls'");+ });++ test('terminal-agent respawn in terminal-agent-control.ts passes windowsHide', () => {+ // The CLI cold-start + v1.44 watchdog respawn path. On Windows it runs+ // through the Node polyfill (dist/bun-polyfill.cjs) whose host default is+ // the opposite of Bun's — a visible console window on every watchdog+ // respawn is the symptom when the flag is dropped. Wider window: the+ // spawn's options object carries the full env wiring before the flag.+ expectHideNearEvery(SRC('terminal-agent-control.ts'), '(Bun as any).spawn(', 700);+ });+});diff --git a/canary/SKILL.md b/canary/SKILL.mdindex 02091fced..8b28c47e6 100644--- a/canary/SKILL.md+++ b/canary/SKILL.md@@ -674,6 +674,10 @@ When options differ in coverage, include `Completeness: X/10` (10 = all edge casFor high-stakes ambiguity (architecture, data model, destructive scope, missing context), STOP. Name it in one sentence, present 2-3 options with tradeoffs, and ask. Do not use for routine coding or obvious changes.+## Claimed Limitations Need Evidence++A claimed limitation or requirement ("the API can't do this", "X requires a credential", "that's impossible on this platform") is a material claim. State one only with the verbatim error, the documented statement, or a live probe in hand — pattern-matching a failure to a familiar story is not evidence. When a cheap probe settles the question, run it BEFORE asking the user anything or declaring a step blocked.+## Continuous Checkpoint ModeIf `CHECKPOINT_MODE` is `"continuous"`: auto-commit completed logical units with `WIP:` prefix.diff --git a/codex/SKILL.md b/codex/SKILL.mdindex a7d26539f..ff14f92c8 100644--- a/codex/SKILL.md+++ b/codex/SKILL.md@@ -677,6 +677,10 @@ When options differ in coverage, include `Completeness: X/10` (10 = all edge casFor high-stakes ambiguity (architecture, data model, destructive scope, missing context), STOP. Name it in one sentence, present 2-3 options with tradeoffs, and ask. Do not use for routine coding or obvious changes.+## Claimed Limitations Need Evidence++A claimed limitation or requirement ("the API can't do this", "X requires a credential", "that's impossible on this platform") is a material claim. State one only with the verbatim error, the documented statement, or a live probe in hand — pattern-matching a failure to a familiar story is not evidence. When a cheap probe settles the question, run it BEFORE asking the user anything or declaring a step blocked.+## Continuous Checkpoint ModeIf `CHECKPOINT_MODE` is `"continuous"`: auto-commit completed logical units with `WIP:` prefix.diff --git a/context-restore/SKILL.md b/context-restore/SKILL.mdindex c17f48d8c..e3dc24782 100644--- a/context-restore/SKILL.md+++ b/context-restore/SKILL.md@@ -678,6 +678,10 @@ When options differ in coverage, include `Completeness: X/10` (10 = all edge casFor high-stakes ambiguity (architecture, data model, destructive scope, missing context), STOP. Name it in one sentence, present 2-3 options with tradeoffs, and ask. Do not use for routine coding or obvious changes.+## Claimed Limitations Need Evidence++A claimed limitation or requirement ("the API can't do this", "X requires a credential", "that's impossible on this platform") is a material claim. State one only with the verbatim error, the documented statement, or a live probe in hand — pattern-matching a failure to a familiar story is not evidence. When a cheap probe settles the question, run it BEFORE asking the user anything or declaring a step blocked.+## Continuous Checkpoint ModeIf `CHECKPOINT_MODE` is `"continuous"`: auto-commit completed logical units with `WIP:` prefix.diff --git a/context-save/SKILL.md b/context-save/SKILL.mdindex 9a08d1c53..775b0de48 100644--- a/context-save/SKILL.md+++ b/context-save/SKILL.md@@ -677,6 +677,10 @@ When options differ in coverage, include `Completeness: X/10` (10 = all edge casFor high-stakes ambiguity (architecture, data model, destructive scope, missing context), STOP. Name it in one sentence, present 2-3 options with tradeoffs, and ask. Do not use for routine coding or obvious changes.+## Claimed Limitations Need Evidence++A claimed limitation or requirement ("the API can't do this", "X requires a credential", "that's impossible on this platform") is a material claim. State one only with the verbatim error, the documented statement, or a live probe in hand — pattern-matching a failure to a familiar story is not evidence. When a cheap probe settles the question, run it BEFORE asking the user anything or declaring a step blocked.+## Continuous Checkpoint ModeIf `CHECKPOINT_MODE` is `"continuous"`: auto-commit completed logical units with `WIP:` prefix.diff --git a/cso/SKILL.md b/cso/SKILL.mdindex 58c795f51..18f7321b0 100644--- a/cso/SKILL.md+++ b/cso/SKILL.md@@ -680,6 +680,10 @@ When options differ in coverage, include `Completeness: X/10` (10 = all edge casFor high-stakes ambiguity (architecture, data model, destructive scope, missing context), STOP. Name it in one sentence, present 2-3 options with tradeoffs, and ask. Do not use for routine coding or obvious changes.+## Claimed Limitations Need Evidence++A claimed limitation or requirement ("the API can't do this", "X requires a credential", "that's impossible on this platform") is a material claim. State one only with the verbatim error, the documented statement, or a live probe in hand — pattern-matching a failure to a familiar story is not evidence. When a cheap probe settles the question, run it BEFORE asking the user anything or declaring a step blocked.+## Continuous Checkpoint ModeIf `CHECKPOINT_MODE` is `"continuous"`: auto-commit completed logical units with `WIP:` prefix.diff --git a/design-consultation/SKILL.md b/design-consultation/SKILL.mdindex fb487eb5c..241b5c3d8 100644--- a/design-consultation/SKILL.md+++ b/design-consultation/SKILL.md@@ -700,6 +700,10 @@ When options differ in coverage, include `Completeness: X/10` (10 = all edge casFor high-stakes ambiguity (architecture, data model, destructive scope, missing context), STOP. Name it in one sentence, present 2-3 options with tradeoffs, and ask. Do not use for routine coding or obvious changes.+## Claimed Limitations Need Evidence++A claimed limitation or requirement ("the API can't do this", "X requires a credential", "that's impossible on this platform") is a material claim. State one only with the verbatim error, the documented statement, or a live probe in hand — pattern-matching a failure to a familiar story is not evidence. When a cheap probe settles the question, run it BEFORE asking the user anything or declaring a step blocked.+## Continuous Checkpoint ModeIf `CHECKPOINT_MODE` is `"continuous"`: auto-commit completed logical units with `WIP:` prefix.diff --git a/design-html/SKILL.md b/design-html/SKILL.mdindex 23c5a5ec2..59178c131 100644--- a/design-html/SKILL.md+++ b/design-html/SKILL.md@@ -681,6 +681,10 @@ When options differ in coverage, include `Completeness: X/10` (10 = all edge casFor high-stakes ambiguity (architecture, data model, destructive scope, missing context), STOP. Name it in one sentence, present 2-3 options with tradeoffs, and ask. Do not use for routine coding or obvious changes.+## Claimed Limitations Need Evidence++A claimed limitation or requirement ("the API can't do this", "X requires a credential", "that's impossible on this platform") is a material claim. State one only with the verbatim error, the documented statement, or a live probe in hand — pattern-matching a failure to a familiar story is not evidence. When a cheap probe settles the question, run it BEFORE asking the user anything or declaring a step blocked.+## Continuous Checkpoint ModeIf `CHECKPOINT_MODE` is `"continuous"`: auto-commit completed logical units with `WIP:` prefix.diff --git a/design-review/SKILL.md b/design-review/SKILL.mdindex a0f1cc526..8e177dfe7 100644--- a/design-review/SKILL.md+++ b/design-review/SKILL.md@@ -678,6 +678,10 @@ When options differ in coverage, include `Completeness: X/10` (10 = all edge casFor high-stakes ambiguity (architecture, data model, destructive scope, missing context), STOP. Name it in one sentence, present 2-3 options with tradeoffs, and ask. Do not use for routine coding or obvious changes.+## Claimed Limitations Need Evidence++A claimed limitation or requirement ("the API can't do this", "X requires a credential", "that's impossible on this platform") is a material claim. State one only with the verbatim error, the documented statement, or a live probe in hand — pattern-matching a failure to a familiar story is not evidence. When a cheap probe settles the question, run it BEFORE asking the user anything or declaring a step blocked.+## Continuous Checkpoint ModeIf `CHECKPOINT_MODE` is `"continuous"`: auto-commit completed logical units with `WIP:` prefix.@@ -899,41 +903,70 @@ If `NEEDS_SETUP`:## Test Framework Bootstrap-**Detect existing test framework and project runtime:**+**Read the project's CLAUDE.md (and TESTING.md if present) FIRST.** If it documents a test command, the project already told you: no detection, no bootstrap. Skip the rest of bootstrap and use that command in Step 5.++**Otherwise gather markers. Every marker below is EVIDENCE for the question you ask — never a command to run blind.** A marker tells you which ecosystem you're in and which command to OFFER. It does not tell you the command works. Do not execute a candidate test command to "check" it: a probe on a project that never had that runner fails loudly and teaches you nothing, and installing a second framework over a working one is worse.```bashsetopt +o nomatch 2>/dev/null || true # zsh compat-# Detect project runtime-[ -f Gemfile ] && echo "RUNTIME:ruby"+# Definitive ecosystem markers (presence = ecosystem, NOT a command to run)+[ -f manage.py ] && echo "RUNTIME:python FRAMEWORK:django MARKER:manage.py"+{ [ -f pyproject.toml ] || [ -f pytest.ini ] || [ -f tox.ini ] || [ -f setup.cfg ] || [ -f requirements.txt ]; } && echo "RUNTIME:python"+[ -f Gemfile ] || [ -f Rakefile ] || [ -f .rspec ] && echo "RUNTIME:ruby"[ -f package.json ] && echo "RUNTIME:node"-[ -f requirements.txt ] || [ -f pyproject.toml ] && echo "RUNTIME:python"[ -f go.mod ] && echo "RUNTIME:go"[ -f Cargo.toml ] && echo "RUNTIME:rust"[ -f composer.json ] && echo "RUNTIME:php"[ -f mix.exs ] && echo "RUNTIME:elixir"+[ -f pom.xml ] && echo "RUNTIME:jvm BUILD:maven"+{ [ -f build.gradle ] || [ -f build.gradle.kts ]; } && echo "RUNTIME:jvm BUILD:gradle"# Detect sub-frameworks[ -f Gemfile ] && grep -q "rails" Gemfile 2>/dev/null && echo "FRAMEWORK:rails"[ -f package.json ] && grep -q '"next"' package.json 2>/dev/null && echo "FRAMEWORK:nextjs"-# Check for existing test infrastructure-ls jest.config.* vitest.config.* playwright.config.* .rspec pytest.ini pyproject.toml phpunit.xml 2>/dev/null-ls -d test/ tests/ spec/ __tests__/ cypress/ e2e/ 2>/dev/null+# Existing test path — config files, declared scripts, AND test FILES.+# A project with real tests and no config file is the common miss.+ls jest.config.* vitest.config.* playwright.config.* .rspec pytest.ini tox.ini phpunit.xml* 2>/dev/null+[ -f package.json ] && grep -q '"test"[[:space:]]*:' package.json && echo "SCRIPT:package.json test"+[ -f Makefile ] && grep -qE '^(test|check):' Makefile && echo "TARGET:make test"+[ -f pyproject.toml ] && grep -q "pytest" pyproject.toml && echo "CONFIG:pyproject pytest"+git ls-files | grep -cE '(^|/)(tests?|spec|__tests__)/|(^|/)tests?\.py$|(^|/)test_[^/]+\.py$|_test\.(go|py|rb|ts|js|exs)$|\.(test|spec)\.[jt]sx?$|_spec\.rb$|Test\.(java|kt)$' | sed 's/^/TESTFILES:/'+# Rust keeps unit tests inside src/, so file names alone miss them+[ -f Cargo.toml ] && git grep -lF '#[test]' -- 'src' >/dev/null 2>&1 && echo "TESTS:rust in-source"# Check opt-out marker[ -f .gstack/no-test-bootstrap ] && echo "BOOTSTRAP_DECLINED"```-**If test framework detected** (config files or test directories found):-Print "Test framework detected: {name} ({N} existing tests). Skipping bootstrap."+Map the markers to the command you will OFFER — never to one you run on a guess:++| Marker | Ecosystem | Candidate command to offer |+|--------|-----------|----------------------------|+| `manage.py` | Django | `python manage.py test` (or `pytest` when pytest-django is in the deps) |+| `pytest.ini` / `tox.ini` / pytest in `pyproject.toml` / `test_*.py` | Python | `pytest` |+| `go.mod` (+ any `*_test.go`) | Go | `go test ./...` |+| `Cargo.toml` | Rust | `cargo test` |+| `pom.xml` | JVM (Maven) | `mvn test` |+| `build.gradle` / `build.gradle.kts` | JVM (Gradle) | `./gradlew test` |+| `Gemfile` / `Rakefile` / `.rspec` | Ruby | `bundle exec rspec`, `bin/rails test`, or `rake test` |+| `mix.exs` | Elixir | `mix test` |+| `composer.json` | PHP | `composer test` or `./vendor/bin/phpunit` |+| `package.json` with a `test` script | Node | that script, run with the package manager the lockfile names |+| `Makefile` with a `test:` target | any | `make test` |++**If ANY existing-test evidence appears** (a config file, a declared test script or make target, a nonzero `TESTFILES:` count, or `TESTS:rust in-source`): the project has tests. **Do NOT bootstrap.** Print "Existing tests detected: {the evidence}." Then get the command the same way Step 5 does — CLAUDE.md/TESTING.md if documented, otherwise AskUserQuestion offering the candidates from the table above plus "Other", and persist the answer to CLAUDE.md's `## Testing` section so it is never asked again. When the ecosystem ships a runner (Django, Go, Rust, Elixir, Maven/Gradle), that runner is the candidate — never install a second framework beside a working one.Read 2-3 existing test files to learn conventions (naming, imports, assertion style, setup patterns).Store conventions as prose context for use in Phase 8e.5 or Step 7. **Skip the rest of bootstrap.**+Absent config files and absent `tests/` directories are NOT evidence of "no tests": Django keeps tests in `<app>/tests.py`, Go in `*_test.go` beside the source, Rust in `#[test]` blocks inside `src/`. A green `python manage.py test` with no `pytest.ini` is a tested project, not a bootstrap candidate.+**If BOOTSTRAP_DECLINED** appears: Print "Test bootstrap previously declined — skipping." **Skip the rest of bootstrap.**-**If NO runtime detected** (no config files found): Use AskUserQuestion:+**If NO ecosystem marker matched:** Use AskUserQuestion:"I couldn't detect your project's language. What runtime are you using?"Options: A) Node.js/TypeScript B) Ruby/Rails C) Python D) Go E) Rust F) PHP G) Elixir H) This project doesn't need tests.+If the runtime you need isn't listed, offer "Other" and take the runtime plus the test command as free text.If user picks H → write `.gstack/no-test-bootstrap` and continue without tests.-**If runtime detected but no test framework — bootstrap:**+**If an ecosystem matched but there is no existing-test evidence at all — bootstrap:**### B2. Research best practices@@ -949,7 +982,9 @@ If WebSearch is unavailable, use this built-in knowledge table:| Node.js | vitest + @testing-library | jest + @testing-library || Next.js | vitest + @testing-library/react + playwright | jest + cypress || Python | pytest + pytest-cov | unittest |+| Django | pytest + pytest-django | Django's built-in `manage.py test` (unittest) || Go | stdlib testing + testify | stdlib only |+| JVM (Maven/Gradle) | JUnit 5 + AssertJ | JUnit 5 only || Rust | cargo test (built-in) + mockall | — || PHP | phpunit + mockery | pest || Elixir | ExUnit (built-in) + ex_machina | — |diff --git a/design-shotgun/SKILL.md b/design-shotgun/SKILL.mdindex 3671e10e5..2ba5556ea 100644--- a/design-shotgun/SKILL.md+++ b/design-shotgun/SKILL.md@@ -695,6 +695,10 @@ When options differ in coverage, include `Completeness: X/10` (10 = all edge casFor high-stakes ambiguity (architecture, data model, destructive scope, missing context), STOP. Name it in one sentence, present 2-3 options with tradeoffs, and ask. Do not use for routine coding or obvious changes.+## Claimed Limitations Need Evidence++A claimed limitation or requirement ("the API can't do this", "X requires a credential", "that's impossible on this platform") is a material claim. State one only with the verbatim error, the documented statement, or a live probe in hand — pattern-matching a failure to a familiar story is not evidence. When a cheap probe settles the question, run it BEFORE asking the user anything or declaring a step blocked.+## Continuous Checkpoint ModeIf `CHECKPOINT_MODE` is `"continuous"`: auto-commit completed logical units with `WIP:` prefix.diff --git a/devex-review/SKILL.md b/devex-review/SKILL.mdindex 7ed2fead6..1fe9f52d5 100644--- a/devex-review/SKILL.md+++ b/devex-review/SKILL.md@@ -680,6 +680,10 @@ When options differ in coverage, include `Completeness: X/10` (10 = all edge casFor high-stakes ambiguity (architecture, data model, destructive scope, missing context), STOP. Name it in one sentence, present 2-3 options with tradeoffs, and ask. Do not use for routine coding or obvious changes.+## Claimed Limitations Need Evidence++A claimed limitation or requirement ("the API can't do this", "X requires a credential", "that's impossible on this platform") is a material claim. State one only with the verbatim error, the documented statement, or a live probe in hand — pattern-matching a failure to a familiar story is not evidence. When a cheap probe settles the question, run it BEFORE asking the user anything or declaring a step blocked.+## Continuous Checkpoint ModeIf `CHECKPOINT_MODE` is `"continuous"`: auto-commit completed logical units with `WIP:` prefix.diff --git a/docs/designs/CODE_INTELLIGENCE_PROVIDER_CONTRACT.md b/docs/designs/CODE_INTELLIGENCE_PROVIDER_CONTRACT.mdnew file mode 100644index 000000000..575a87591--- /dev/null+++ b/docs/designs/CODE_INTELLIGENCE_PROVIDER_CONTRACT.md@@ -0,0 +1,305 @@+# Code-Intelligence Provider Contract++Status: design + first implementation slice+Owner: maintainer-directed internal work+Related: `runtime/context.js` (Context.dev provider pattern),+`scripts/gstack2/browser-provider-contract.ts` (the existing provider-contract idiom),+`lib/gstack-decision-semantic.ts` (degrade-to-null reliability contract)++## Problem++gstack carries ~17k LOC of home-grown code-intelligence glue: transcript+ingestion (`bin/gstack-memory-ingest.ts`, ~1.9k), a unified sync verb+(`bin/gstack-gbrain-sync.ts`, ~1.6k), context loading+(`bin/gstack-brain-context-load.ts`), a three-tier planning cache+(`bin/gstack-brain-cache`), source reconciliation, engine-status classification,+destructive-op guards, plus ~15 `bin/gstack-gbrain-*` and `bin/gstack-brain-*`+entrypoints and ~40 tests. All of it is bespoke wiring around one external tool+(GBrain) reached by direct CLI shell-out.++We do not want to keep maintaining a home-grown indexer. We want gstack to+define a **small optional contract** that external providers implement, so the+indexing/search/graph work lives in the provider, not in gstack.++Hard requirement, non-negotiable: **gstack must remain fully functional with the+provider OFF.** File-only paths (the decision store, Context Recovery, grep) stay+reliable and never depend on a provider being present. This is the existing+decision-store philosophy (`lib/gstack-decision.ts` has zero gbrain imports;+`lib/gstack-decision-semantic.ts` degrades to `null`). The contract is an+enhancement, never a dependency.++## Design decision: repo-oriented, not document-store++Settled (do not relitigate). The contract is **repo-oriented**:++```+register_source(repo) — required+refresh(source) — required+search(query) — required+status(source) — required+```++`add` / `delete` / `export` are **optional capabilities** a provider MAY+advertise. GBrain advertises them (its native primitive is document-by-slug:+put/delete/get/export); code-search and code-graph tools decline them.++A document-store contract (add / delete-by-id / export as *required* ops) was+rejected: it misrepresents code-search and code-graph tools. Sourcebot indexes a+whole repo and exposes search; it has no concept of "delete document id X".+Forcing every provider to implement a document CRUD surface would either exclude+the exact tools we most want (whole-repo indexers, graph tools) or force them to+stub required ops with lies. Repo-in / query-out is the honest common+denominator. GBrain's document axis survives as an *optional* capability, not as+the contract's shape.++## The contract++TypeScript in `lib/code-intelligence/contract.ts`. Shape (abridged):++```ts+type CodeProviderCapability =+ | "register_source" | "refresh" | "search" | "status" // required+ | "add" | "delete" | "export"; // optional++interface CodeProvider {+ readonly id: "gbrain" | "sourcebot" | "graphify";+ readonly label: string;+ readonly capabilities: ReadonlySet<CodeProviderCapability>;+ readonly local: boolean; // true = no repo content leaves the machine++ registerSource(repo: RepoRef, opts?: OpOptions): Promise<SourceStatus>;+ refresh(source: SourceRef, opts?: OpOptions): Promise<SourceStatus>;+ search(query: string, opts?: SearchOptions): Promise<CodeSearchHit[]>;+ status(source?: SourceRef, opts?: OpOptions): Promise<SourceStatus>;++ add?(doc: { slug: string; body: string }, opts?: OpOptions): Promise<SourceStatus>;+ delete?(slug: string, opts?: OpOptions): Promise<SourceStatus>;+ export?(source: SourceRef, opts?: OpOptions): Promise<string>;+}+```++Every provider MUST implement the four required methods and MUST advertise+exactly the capabilities it backs (`assertRequiredCapabilities` enforces the+required four at construction; a test pins it). Optional methods are present iff+the matching capability is advertised. Calling an unadvertised optional op throws+`CAPABILITY_UNSUPPORTED` — never a silent no-op.++### Typed failures++Mirrors `runtime/context.js`'s `ContextError` discipline (a closed code set,+constructor throws on an unknown code):++| Code | Meaning |+|------|---------|+| `PROVIDER_UNAVAILABLE` | CLI/MCP transport absent — degrade to file-only |+| `PROVIDER_NOT_CONSENTED` | repo indexing not consented and content would leave the machine |+| `CAPABILITY_UNSUPPORTED` | provider declines this op |+| `SOURCE_NOT_REGISTERED` | op needs a source that isn't registered |+| `PROVIDER_TIMEOUT` | provider exceeded the op timeout |+| `PROVIDER_ERROR` | provider ran and failed |++`PROVIDER_UNAVAILABLE` is the load-bearing one: callers catch it (or use the+picker's null resolution) and fall back to grep / file-only. It is never fatal.++### Consent++Two orthogonal consent axes, both explicit, neither auto-granted:++1. **Network / content-egress consent (repo-scoped).** Before any repo content+ leaves the machine, indexing must be consented *per repo*. The contract+ enforces this in `registerSource`/`refresh`/`add`: when+ `provider.local === false` and `opts.consented !== true`, it throws+ `PROVIDER_NOT_CONSENTED`. Local providers (Graphify) skip this axis — nothing+ leaves the machine.+2. **Install consent (Graphify only).** Graphify is never auto-installed. The+ `options`/`status` display marks it available only when its CLI is present,+ and nothing in gstack runs a Graphify installer. Install is a user action+ (`pip install graphifyy && graphify install`).++This matches the Context.dev model: selection persists without granting egress+consent; egress requires a separate explicit step.++## Per-provider capability matrix++| Op | GBrain (recommend first) | Sourcebot | Graphify |+|----|--------------------------|-----------|----------|+| `register_source` | ✓ `sources add --federated` | ✓ local `git` connection in config.json | ✓ `graphify update <dir>` (local, no LLM) |+| `refresh` | ✓ `sync` + `sync --strategy code --full` | ✓ auto (config change + reindexIntervalMs) | ✓ `graphify update <dir>` |+| `search` | ✓ `gbrain search` (federated corpora) | ✓ `POST /api/search` (keyless w/ anonymous access; Bearer key optional) | ✓ `graphify query "<q>" --graph <graph.json>` |+| `status` | ✓ `sources list` + page_count | ~ partial (server liveness) | ~ partial (graph.json present + node count) |+| `add` | ✓ `put <slug>` | ✗ declines | ✗ declines |+| `delete` | ✓ `delete <slug>` | ✗ declines | ✗ declines |+| `export` | ✓ `export` | ✗ declines | ✓ read `graphify-out/graph.json` |+| `local` (no egress) | no (federated DB) | loopback → **yes**; remote host → no | **yes** (local only) |++All three are driven directly from the runtime — no MCP client:++- **GBrain** (`garrytan/gbrain`, the gstack-ecosystem tool): full contract fit,+ driven via the existing `gbrain` CLI chokepoint (`lib/gbrain-exec.ts`). Native+ primitive is document-by-slug (put/delete/get/export) PLUS a repo axis+ (`sources add`/`sync`). Advertises all seven capabilities. **Recommended+ first.**+- **Sourcebot** (`github.com/sourcebot-dev/sourcebot`, YC Fall 2025): self-hosted+ whole-repo regex search, deployed via Docker Compose (bundled server + Postgres+ + Redis; no supported non-Docker path). `register_source` adds a local `{ "type":+ "git", "url": "file:///path" }` connection to the server's `config.json` (it+ re-indexes on config change; a local repo needs a `remote.origin.url` or it is+ skipped); `search` is `POST {baseUrl}/api/search`; `status` probes that endpoint.+ Declines `add`/`delete`/`export`. It is a **local** tool — indexed code stays on+ your machine — and an **API key is optional**: a local instance with anonymous+ access (`FORCE_ENABLE_ANONYMOUS_ACCESS=true`) serves `/api/search` keyless. The+ adapter sends `Authorization: Bearer <SOURCEBOT_API_KEY>` only when a key is set.+ A loopback `baseUrl` keeps content on the machine (local=true); a remote one+ requires egress consent.+- **Graphify** (`github.com/Graphify-Labs/graphify`, YC-backed): local+ tree-sitter code graph via the `graphify` CLI. The adapter uses **`graphify+ update <dir>`** — the local, no-LLM build (writes `graphify-out/graph.json`);+ it deliberately avoids the bare `graphify <dir>` build, which runs an LLM+ extraction backend needing an API key + network. `graphify query "<q>" --graph+ <graph.json>` searches it (its `NODE ...`/`EDGE ...` output carries the file at+ `src=`/`at=`); `export` reads the graph JSON. Fully local — nothing leaves the+ machine. Optional, **install only with explicit user action** (`pip install+ graphifyy && graphify install`, needs Python >= 3.10); never auto-installed.++**No local-index option is offered** (deliberately excluded — a naive local+index degrades result quality; we route to a real provider or to file-only grep,+not to a half-baked in-house index).++### Integration surfaces (no MCP needed)++Each provider exposes a runtime-drivable surface, so gstack drives them with a+CLI shell-out or plain HTTP — it never speaks MCP:++- **GBrain / Graphify: CLI.** Shell out (`spawnSync`), same shape and the same+ ENOENT→`PROVIDER_UNAVAILABLE` degrade as the existing gbrain glue.+- **Sourcebot: HTTP + a config-file edit.** `POST /api/search` for queries and a+ JSON edit of the server's `config.json` to register a repo. `fetch` is+ injectable so tests run against a stub, no live server.++Sourcebot and Graphify also ship MCP servers for in-agent use; the contract does+not depend on them, because their CLI/HTTP surfaces are enough to index and+search from the runtime.++## Picker: recommend GBrain first++`lib/code-intelligence/picker.ts` + `selection.ts`. The user picks a provider+with `gstack-code-intelligence select <provider>`, persisted to+`$GSTACK_HOME/code-intelligence.json`. `resolveSelectedProvider()` constructs the+selected provider, or returns `null` when nothing is selected — the provider-OFF+path, where callers degrade to grep / the file-only decision store. Availability+is proven at call time: a selected provider whose CLI/server is absent throws+`PROVIDER_UNAVAILABLE`, which callers catch and degrade on.++`RECOMMENDED_ORDER` is the static **GBrain → Sourcebot → Graphify** fact — GBrain+is always recommended first. `detectAvailable()` probes each provider for the+`options`/`status` display (GBrain via the real `localEngineStatus()`; Graphify+via its CLI/graph presence; Sourcebot via an HTTP liveness probe). The picker+never silently prefers a non-recommended tool.++## How this replaces the current GBrain glue++The contract is the seam; the bespoke glue collapses onto it. Mapping:++| Today (bespoke) | Under the contract |+|-----------------|--------------------|+| `bin/gstack-gbrain-sync.ts` (`sync`/`reindex-code`/`sources`) | `provider.registerSource` / `provider.refresh` |+| `lib/gstack-decision-semantic.ts` `semanticRecall` | `provider.search` (scoped) → same degrade-to-null |+| `bin/gstack-brain-context-load.ts` (`query`/`list_pages`) | `provider.search` / `provider.status` |+| `bin/gstack-memory-ingest.ts` (`import`, put) | `provider.add` (optional cap; GBrain-only) |+| `lib/gbrain-sources.ts` (`ensureSourceRegistered`, `probeSource`) | GBrain adapter internals |+| `lib/gbrain-local-status.ts` | GBrain adapter availability probe (kept, reused) |+| `bin/gstack-gbrain-detect` / `-install` / `-source-wireup` / `-repo-policy` | provider setup + picker + consent (thinner) |++The point is not to delete 17k LOC in one commit — it is to make every consumer+call the contract, then retire the bespoke paths provider-by-provider behind it.+Consumers that only need "search my code, or degrade" stop importing gbrain+specifics entirely.++## Rollout++Phased, each phase independently revertable. Skill-template edits are deferred to+a later phase precisely so the first slices do not trigger the+`gen:gstack2` / parity re-baseline cycle.++- **Phase 1 (this slice): the contract, three real adapters, and a usable CLI.**+ `contract.ts` + fully-drivable GBrain (CLI), Graphify (CLI), and Sourcebot+ (HTTP + config) adapters + the selection store + the `gstack-code-intelligence`+ CLI (`options`/`status`/`select`/`consent`/`index`/`search`) + tests. A user+ can select a provider and index/search their repo today. No skill-template or+ generated-file changes yet, so no `gen:gstack2` / parity re-baseline.+- **Phase 2: route internal consumers through the contract.** Point+ `gstack-decision-semantic` and `gstack-brain-context-load` at+ `resolveSelectedProvider()`, preserving degrade-to-null exactly. Behavior-neutral+ for the file-only paths.+- **Phase 3: surface selection in the skills.** Offer the picker at the moments a+ skill would benefit from indexed search, mirroring the `context` command's+ just-in-time consent prompt. Regenerate skills (`bun run gen:gstack2`), re-run+ `bun run test:gstack2`, re-baseline parity intentionally.+- **Phase 4: retire bespoke glue.** Once every consumer is on the contract,+ delete the sync/ingest/cache entrypoints and their tests provider-by-provider.++## Verified against real environments++All three adapters were driven against the real tools in isolated environments+(parallel agents, one worktree each), and all three now index + search a real repo+end-to-end. Two rounds ran, because the first round's fixes included a mistake that+only real execution caught — recorded here honestly.++- **GBrain — real Postgres+pgvector (Docker), gbrain 0.42.56 — PROVEN.** The+ default pglite/WASM engine is broken on macOS (upstream garrytan/gbrain#223), so+ the working recipe points gbrain at a real Postgres via `DATABASE_URL`. Real+ end-to-end search returned the actual code definition+ (`[0.88] src-checksum-ts … export statement computeChecksum`). Real execution+ caught a **regression I had introduced**: I removed `--strategy code` from+ `refresh` based on a `--help` misread, which silently stopped code from ever+ being indexed (only docs were). Restored to the verified two-pass+ (`sync`, then `sync --strategy code --full`); `--federated` registration is+ load-bearing for global search. Also fixed earlier: engine-down now degrades to+ `PROVIDER_UNAVAILABLE` (one-line message) instead of `PROVIDER_ERROR` + a WASM+ stack dump.+- **Sourcebot — live v6.5.0 (Docker) — PROVEN keyless.** Endpoint, body, and+ response parsing were correct against the real server. Correcting an earlier+ wrong conclusion: Sourcebot does **not** require an API key for local use —+ enabling anonymous access (`FORCE_ENABLE_ANONYMOUS_ACCESS=true`) serves+ `/api/search` keyless, verified with a real hit through the CLI with no key set.+ The key stays optional; the only fix was messaging (point users to anonymous+ access first, key as fallback) plus a note that a local repo needs a+ `remote.origin.url` to be indexed. It is a local tool (code stays on the+ machine; a boot telemetry ping unless `SOURCEBOT_TELEMETRY_DISABLED=true`).+- **Graphify — real install, graphify 0.9.23 — PROVEN.** Correcting an earlier+ wrong claim of mine: for **code**, `graphify <dir>` and `graphify update <dir>`+ produce the identical AST graph with **no LLM call**; the LLM only renames+ community clusters and ingests non-code docs, adding zero nodes/edges, and our+ parser discards the field it touches. So there is deliberately no LLM mode, and+ `local=true` is correct. The adapter uses `graphify update`; real `index`+search+ returned correct `file:line` refs. Also fixed: `search` now reads the indexed+ repo's graph (persisted root), and `options` reports an installed provider as+ available.++The larger lesson, kept on the record: a `--help` reading or a single agent's+conclusion is not proof — running the real tool is. It reversed two of my+first-round calls (the gbrain flag removal and the graphify LLM claim).++## What this does NOT change++Per the GStack 2 canonical contract and CLAUDE.md boundaries: no cloud browsers,+no alternate iOS drivers, no local image models, no provider marketplaces, no+workflow engines, **no new state database**. Context.dev remains the only+newly-authorized external service for web context; this contract governs code+intelligence, a separate axis. The existing decision store and Context Recovery+stay file-only and provider-independent.++## Testing++`test/code-intelligence.test.ts` (19 tests, no live tools): capability-matrix+invariants (all providers advertise the four required; only GBrain advertises the+document ops; `local` flags, including loopback-vs-remote Sourcebot); the result+parsers; the selection store + per-repo consent + provider-OFF (`null`); consent+gating (GBrain non-local without consent throws `PROVIDER_NOT_CONSENTED`; local+Graphify is exempt); the GBrain adapter against a fake `gbrain` shim; the Graphify+adapter against a fake `graphify` shim (index builds a graph, search returns hits,+status counts nodes); the Sourcebot adapter against an injected `fetch` + a temp+`config.json` (register writes a local git connection, search maps `files[]` to+hits); and every adapter degrading to `PROVIDER_UNAVAILABLE` when its tool/server+is absent. The `gstack-code-intelligence` CLI was smoke-tested end-to-end:+select → consent gate → local Graphify index (5-node graph) → search.diff --git a/docs/designs/PACING_UPDATES_V0.md b/docs/designs/PACING_UPDATES_V0.mdindex f8a49480a..7cffa3baf 100644--- a/docs/designs/PACING_UPDATES_V0.md+++ b/docs/designs/PACING_UPDATES_V0.md@@ -93,3 +93,17 @@ V2 items remain deferred:- Per-skill or per-topic explain levels- Team profiles- AST-based "delivered features" metric++## Fold-in from fork port wave 2 (2026-08-14)++The time-attack/gstack fork attacked the same question fatigue from a+complementary axis: build-scale classification (session/hobby/project/+product/venture) sizing the machinery, plus CHAIN-WIDE question budgets.+Approved decision (CEO review 2026-08-14): fold the fork's ACCOUNTING+judgment into this design round — the budget is chain-scoped (a chained+review deducts from what's left, never resets), handoffs carry+questions-already-spent, approval/mutation gates never count against it, and+the budget is spent on the hardest-to-reverse decisions first. Do NOT adopt+the fork's 5/8/12 numeric constants — the fork itself later replaced them+with a zero-default autonomy dial. Scale sizes the machinery and sets the+budget; pacing (this doc) ranks what the budget is spent on.diff --git a/docs/designs/SLATE_HOST.md b/docs/designs/SLATE_HOST.mdindex 8e5bb154d..f704e43d2 100644--- a/docs/designs/SLATE_HOST.md+++ b/docs/designs/SLATE_HOST.md@@ -241,7 +241,9 @@ Codex, Factory) is "host explosion for a path alias." The current architecture h- Per-host branches in `transformFrontmatter()` with near-duplicate logic- Per-host config in `EXTERNAL_HOST_CONFIG` with similar patterns- Per-host functions in the setup script (`create_codex_runtime_root`, `link_codex_skill_dirs`)-- Host names duplicated in `bin/gstack-platform-detect`, `bin/gstack-uninstall`, `bin/dev-setup`+- Host names duplicated in `bin/gstack-platform-detect` (since deleted — host+ detection now lives in the `hosts/` registry, exported to shell via+ `scripts/host-config-export.ts`), `bin/gstack-uninstall`, `bin/dev-setup`Adding Slate means copying all of these patterns again. A refactor to make hostsdata-driven (config objects instead of if/else branches) would make Slate integration@@ -253,7 +255,9 @@ trivial AND make future hosts (any new OpenCode fork, any new agent) zero-efforthave Slate skills- `bin/gstack-uninstall` doesn't know about `.slate/`- `bin/dev-setup` doesn't wire `.slate/` for contributor dev mode-- `bin/gstack-platform-detect` doesn't detect Slate+- `bin/gstack-platform-detect` doesn't detect Slate (obsolete: the bin was+ deleted; host detection is now the `hosts/` registry via+ `scripts/host-config-export.ts` — `hosts/slate.ts` is where Slate lives)- E2E tests should set `SLATE_DISABLE_CLAUDE_CODE_SKILLS=1` to prove `.slate/` pathactually works (not just falling back to `.claude/`)diff --git a/document-generate/SKILL.md b/document-generate/SKILL.mdindex 773b2ab2b..9eb9e9278 100644--- a/document-generate/SKILL.md+++ b/document-generate/SKILL.md@@ -680,6 +680,10 @@ When options differ in coverage, include `Completeness: X/10` (10 = all edge casFor high-stakes ambiguity (architecture, data model, destructive scope, missing context), STOP. Name it in one sentence, present 2-3 options with tradeoffs, and ask. Do not use for routine coding or obvious changes.+## Claimed Limitations Need Evidence++A claimed limitation or requirement ("the API can't do this", "X requires a credential", "that's impossible on this platform") is a material claim. State one only with the verbatim error, the documented statement, or a live probe in hand — pattern-matching a failure to a familiar story is not evidence. When a cheap probe settles the question, run it BEFORE asking the user anything or declaring a step blocked.+## Continuous Checkpoint ModeIf `CHECKPOINT_MODE` is `"continuous"`: auto-commit completed logical units with `WIP:` prefix.diff --git a/document-release/SKILL.md b/document-release/SKILL.mdindex ff728c667..de8b965c1 100644--- a/document-release/SKILL.md+++ b/document-release/SKILL.md@@ -678,6 +678,10 @@ When options differ in coverage, include `Completeness: X/10` (10 = all edge casFor high-stakes ambiguity (architecture, data model, destructive scope, missing context), STOP. Name it in one sentence, present 2-3 options with tradeoffs, and ask. Do not use for routine coding or obvious changes.+## Claimed Limitations Need Evidence++A claimed limitation or requirement ("the API can't do this", "X requires a credential", "that's impossible on this platform") is a material claim. State one only with the verbatim error, the documented statement, or a live probe in hand — pattern-matching a failure to a familiar story is not evidence. When a cheap probe settles the question, run it BEFORE asking the user anything or declaring a step blocked.+## Continuous Checkpoint ModeIf `CHECKPOINT_MODE` is `"continuous"`: auto-commit completed logical units with `WIP:` prefix.diff --git a/gstack-upgrade/migrations/v1.27.0.0.sh b/gstack-upgrade/migrations/v1.27.0.0.shindex fb1ce73ce..021c6a566 100755--- a/gstack-upgrade/migrations/v1.27.0.0.sh+++ b/gstack-upgrade/migrations/v1.27.0.0.sh@@ -45,6 +45,13 @@ JOURNAL="${MIGRATION_DIR}/v1.27.0.0.journal"DONE="${MIGRATION_DIR}/v1.27.0.0.done"SKIPPED="${MIGRATION_DIR}/v1.27.0.0.skipped-by-user"+# Real, copy-pasteable re-run command for every remediation message below.+# There is no runner re-ask: the upgrade runners' version windows never+# re-select an already-passed migration, so the only honest remediation is+# a direct invocation of this script ($0-derived so it survives any cwd).+SELF_PATH="$(cd "$(dirname "$0")" && pwd)/$(basename "$0")"+RERUN_CMD="GSTACK_MIGRATE_ASSUME_YES=1 bash ${SELF_PATH}"+USER_NAME="${USER:-$(whoami 2>/dev/null || echo unknown)}"OLD_REPO_NAME="gstack-brain-${USER_NAME}"NEW_REPO_NAME="gstack-artifacts-${USER_NAME}"@@ -61,8 +68,8 @@ mkdir -p "$MIGRATION_DIR"# Already done? exit silently.[ -f "$DONE" ] && exit 0-# User opted out previously? exit silently. (Re-invoke via-# `/setup-gbrain --rerun-migration` removes this marker.)+# User opted out previously? exit silently. (To re-run after an opt-out:+# rm the skipped-by-user marker, then invoke this script directly.)[ -f "$SKIPPED" ] && exit 0journal_done() {@@ -119,19 +126,33 @@ EOFread -r REPLY || REPLY=""case "$REPLY" inn|N|no|No|NO)- echo " Skipping migration. Re-run via /setup-gbrain --rerun-migration." >&2+ echo " Skipping migration. To re-run later:" >&2+ echo " rm ${SKIPPED} && ${RERUN_CMD}" >&2touch "$SKIPPED"exit 0;;skip|skip-for-now|s)- echo " Skipping for now. Will ask again next upgrade." >&2- # Don't write SKIPPED — leave both old + new state untouched, ask again next time.+ echo " Skipping for now. Re-run manually with: ${RERUN_CMD}" >&2+ # Don't write SKIPPED — leave both old + new state untouched. The+ # upgrade runner will NOT re-select this migration, so re-running is+ # manual via the command above.exit 0;;esacelse- # Non-interactive (CI, scripted upgrade): proceed automatically.- echo " (non-interactive: proceeding automatically)" >&2+ # Non-interactive (CI, Claude Code Bash tool, scripted upgrade). Step 1+ # renames a REMOTE repo — consent-shaped, and blanket auto-proceed once+ # left an install half-migrated when that step failed mid-run (#1383).+ # Skip for now by default (asked again next upgrade); explicit opt-in+ # proceeds unattended.+ if [ "${GSTACK_MIGRATE_ASSUME_YES:-0}" = "1" ]; then+ echo " (non-interactive: proceeding — GSTACK_MIGRATE_ASSUME_YES=1)" >&2+ else+ echo " Non-interactive session: skipping for now." >&2+ echo " Re-run manually with: ${RERUN_CMD}" >&2+ echo " To run interactively: bash ${SELF_PATH}" >&2+ exit 0+ fififi@@ -195,8 +216,8 @@ if ! journal_done "gh_repo_renamed"; thenmark_done "gh_repo_renamed"elseecho " WARNING: gh rename failed (repo may not exist or permission denied)" >&2- echo " skipping step 1; subsequent steps still run" >&2- mark_done "gh_repo_renamed"+ echo " step 1 stays PENDING and will retry on re-run; later steps still run (#1383)" >&2+ echo " manual: gh repo rename $NEW_REPO_NAME --repo $OLD_REPO_NAME --yes" >&2fifielse@@ -335,8 +356,20 @@ EOFfi# ----------------------------------------------------------------------------# Step 6: finalize (touchfile + clear journal)+# Step 6: finalize (touchfile + clear journal) — only when EVERY step is+# journaled. A failed step must leave the migration visibly incomplete and+# retryable, never silently recorded as done (#1383).# ---------------------------------------------------------------------------+INCOMPLETE=""+for _step in gh_repo_renamed remote_txt_renamed config_key_renamed claude_md_block_rewritten sources_swapped; do+ journal_done "$_step" || INCOMPLETE="$INCOMPLETE $_step"+done+if [ -n "$INCOMPLETE" ]; then+ echo " [v1.27.0.0] migration INCOMPLETE — pending step(s):$INCOMPLETE" >&2+ echo " Completed steps are journaled and will be skipped on re-run." >&2+ echo " Re-run manually with: ${RERUN_CMD}" >&2+ exit 1+fitouch "$DONE"rm -f "$JOURNAL"diff --git a/gstack-upgrade/migrations/v1.65.0.0.sh b/gstack-upgrade/migrations/v1.65.0.0.shnew file mode 100755index 000000000..56181d648--- /dev/null+++ b/gstack-upgrade/migrations/v1.65.0.0.sh@@ -0,0 +1,150 @@+#!/usr/bin/env bash+# Migration: v1.65.0.0 — repair Chrome-for-Testing bundles poisoned by the+# old in-place rebrand (#2242).+#+# Why a migration: pre-v1.64 launchHeaded() rewrote the Chromium .app's+# Info.plist ("Google Chrome for Testing" → "GStack Browser") and overwrote+# its Resources/*.icns — inside the SHARED Playwright cache. That broke the+# codesign seal (GPU process exit_code=5; headed mode dead on macOS 26) and+# poisoned the cache for the user's OTHER Playwright projects too. Deleting+# the rebrand code fixes fresh installs only; every existing macOS install+# still has the mutated bundle on disk. This migration removes poisoned+# bundles and re-fetches a clean one so the upgrade doesn't leave the user+# with zero working browser (the browse launch path also self-heals, as the+# belt to this suspenders, for installs that never run migrations).+#+# Removal scope: `playwright install chromium` treats the revision dir's+# INSTALLATION_COMPLETE marker as "is already downloaded" — removing only+# the .app strands the user with a marker, no browser, and a re-fetch that+# no-ops. So when the poisoned .app sits in the standard cache layout+# (chromium-<rev>/chrome-mac/<name>.app) the WHOLE revision dir goes;+# otherwise the .app plus its sibling INSTALLATION_COMPLETE /+# DEPENDENCIES_VALIDATED markers go. A revision dir already stranded in+# exactly that state (markers present, .app missing) is detected and+# removed too, so the re-fetch actually downloads.+#+# Affected: macOS installs that ever ran headed mode before v1.64.+#+# Idempotent: detection is content-based (plist contains "GStack Browser");+# a clean cache is a no-op, and the .done touchfile gates re-runs. After a+# removal, .done is only written once the end state is VERIFIED (a real+# Chromium executable exists in the cache) — a removal followed by a failed+# re-fetch (e.g. offline) leaves the migration pending, with a needs-refetch+# sentinel so the next run retries the download.++set -u++GSTACK_HOME="${GSTACK_HOME:-${HOME}/.gstack}"+MIGRATION_DIR="${GSTACK_HOME}/.migrations"+DONE="${MIGRATION_DIR}/v1.65.0.0.done"+# Written when a removal happened but the verified end state (a Chromium+# executable in the cache) wasn't reached — e.g. the re-fetch failed+# offline. Its presence re-triggers the re-fetch on the next run even when+# the scans below find nothing left to remove.+NEEDS_REFETCH="${MIGRATION_DIR}/v1.65.0.0.needs-refetch"+mkdir -p "${MIGRATION_DIR}" 2>/dev/null || true+[ -f "${DONE}" ] && exit 0++# macOS only: the mutation targeted .app bundle plists.+if [ "$(uname -s 2>/dev/null)" != "Darwin" ]; then+ touch "${DONE}"+ exit 0+fi++PW_CACHE="${PLAYWRIGHT_BROWSERS_PATH:-${HOME}/Library/Caches/ms-playwright}"+REMOVED=0+[ -f "${NEEDS_REFETCH}" ] && REMOVED=1++is_revision_dir() {+ # Standard Playwright cache revision dir name: chromium-<digits>.+ printf '%s' "$(basename "$1")" | grep -Eq '^chromium-[0-9]+$'+}++if [ -d "${PW_CACHE}" ]; then+ # 1. Content-based poison scan: every Chrome-for-Testing bundle in the+ # cache (one per pinned chromium build) whose plist carries the rebrand.+ while IFS= read -r plist; do+ if grep -q "GStack Browser" "${plist}" 2>/dev/null; then+ app_dir="$(dirname "$(dirname "${plist}")")"+ case "${app_dir}" in+ "${PW_CACHE}"/*.app|"${PW_CACHE}"/*/*.app|"${PW_CACHE}"/*/*/*.app)+ rev_dir="$(dirname "$(dirname "${app_dir}")")"+ if is_revision_dir "${rev_dir}"; then+ # Remove the WHOLE revision dir: Playwright's+ # INSTALLATION_COMPLETE marker lives beside chrome-mac/, and+ # `playwright install chromium` treats its presence as "already+ # downloaded" — removing only the .app would make the re-fetch+ # below a no-op and leave the user with NO browser.+ echo " [v1.65.0.0] removing rebrand-poisoned revision dir (incl. install markers): ${rev_dir}" >&2+ rm -rf "${rev_dir}"+ else+ echo " [v1.65.0.0] removing rebrand-poisoned bundle: ${app_dir}" >&2+ rm -rf "${app_dir}"+ rm -f "$(dirname "${app_dir}")/INSTALLATION_COMPLETE" \+ "$(dirname "${app_dir}")/DEPENDENCIES_VALIDATED" 2>/dev/null || true+ fi+ REMOVED=1+ ;;+ *)+ echo " [v1.65.0.0] WARNING: poisoned plist outside the Playwright cache shape, skipping: ${plist}" >&2+ ;;+ esac+ fi+ done < <(find "${PW_CACHE}" -maxdepth 5 -name "Info.plist" -path "*.app/Contents/Info.plist" 2>/dev/null)++ # 2. Stranded-state scan: an earlier version of this migration removed+ # only the poisoned .app, leaving the revision dir with its+ # INSTALLATION_COMPLETE marker — the exact state that makes+ # `playwright install chromium` no-op while the user has NO browser.+ # A chromium revision dir without any .app inside is that strand;+ # remove it whole so the re-fetch actually downloads.+ for rev_dir in "${PW_CACHE}"/chromium-*; do+ [ -d "${rev_dir}" ] || continue+ is_revision_dir "${rev_dir}" || continue+ if [ -z "$(find "${rev_dir}" -maxdepth 2 -name '*.app' -print 2>/dev/null | head -1)" ]; then+ echo " [v1.65.0.0] removing stranded revision dir (install markers without a browser): ${rev_dir}" >&2+ rm -rf "${rev_dir}"+ REMOVED=1+ fi+ done+fi++if [ "${REMOVED}" = "1" ]; then+ # Re-fetch immediately: migrations run AFTER ./setup, so without this the+ # user finishes the upgrade with no working browser at all (headless AND+ # headed use the same bundle). Run from the gstack install root so bunx+ # resolves the repo-pinned playwright version — an arbitrary migration-+ # runner cwd could resolve a different playwright and populate a revision+ # the pinned one never launches (same subshell-cd pattern as ./setup's+ # Chromium install block).+ SCRIPT_DIR="$(cd "$(dirname "$0")/../.." && pwd)"+ echo " [v1.65.0.0] re-fetching a clean Chromium (bunx playwright install chromium)..." >&2+ if command -v bunx >/dev/null 2>&1 && (cd "${SCRIPT_DIR}" && bunx playwright install chromium >&2); then+ echo " [v1.65.0.0] playwright install finished." >&2+ else+ echo " [v1.65.0.0] WARNING: automatic re-fetch failed." >&2+ fi++ # Gate .done on the VERIFIED end state, not the installer's exit code:+ # `playwright install` exits 0 even when it skips the download, and a+ # successful removal followed by a failed/offline fetch must not be+ # recorded as done — that would strand the user with no browser and a+ # success message.+ CHROME_EXE="$(find "${PW_CACHE}" -maxdepth 6 -type f -perm -u+x -path "*/chromium-*/*.app/Contents/MacOS/*" 2>/dev/null | head -1)"+ if [ -n "${CHROME_EXE}" ]; then+ echo " [v1.65.0.0] verified working Chromium at: ${CHROME_EXE}" >&2+ rm -f "${NEEDS_REFETCH}" 2>/dev/null || true+ else+ touch "${NEEDS_REFETCH}" 2>/dev/null || true+ echo " [v1.65.0.0] WARNING: no Chromium executable present after removing the poisoned bundle." >&2+ echo " [v1.65.0.0] Headless AND headed browsing are unavailable until it is re-fetched. Run:" >&2+ echo " [v1.65.0.0] cd ${SCRIPT_DIR} && bunx playwright install chromium" >&2+ echo " [v1.65.0.0] Leaving this migration pending — it retries on the next run." >&2+ exit 0+ fi+else+ echo " [v1.65.0.0] no rebrand-poisoned bundles found — no-op." >&2+fi++touch "${DONE}"+exit 0diff --git a/health/SKILL.md b/health/SKILL.mdindex bb4041718..cf1c3177c 100644--- a/health/SKILL.md+++ b/health/SKILL.md@@ -676,6 +676,10 @@ When options differ in coverage, include `Completeness: X/10` (10 = all edge casFor high-stakes ambiguity (architecture, data model, destructive scope, missing context), STOP. Name it in one sentence, present 2-3 options with tradeoffs, and ask. Do not use for routine coding or obvious changes.+## Claimed Limitations Need Evidence++A claimed limitation or requirement ("the API can't do this", "X requires a credential", "that's impossible on this platform") is a material claim. State one only with the verbatim error, the documented statement, or a live probe in hand — pattern-matching a failure to a familiar story is not evidence. When a cheap probe settles the question, run it BEFORE asking the user anything or declaring a step blocked.+## Continuous Checkpoint ModeIf `CHECKPOINT_MODE` is `"continuous"`: auto-commit completed logical units with `WIP:` prefix.diff --git a/investigate/SKILL.md b/investigate/SKILL.mdindex bee148085..2a7d241c9 100644--- a/investigate/SKILL.md+++ b/investigate/SKILL.md@@ -715,6 +715,10 @@ When options differ in coverage, include `Completeness: X/10` (10 = all edge casFor high-stakes ambiguity (architecture, data model, destructive scope, missing context), STOP. Name it in one sentence, present 2-3 options with tradeoffs, and ask. Do not use for routine coding or obvious changes.+## Claimed Limitations Need Evidence++A claimed limitation or requirement ("the API can't do this", "X requires a credential", "that's impossible on this platform") is a material claim. State one only with the verbatim error, the documented statement, or a live probe in hand — pattern-matching a failure to a familiar story is not evidence. When a cheap probe settles the question, run it BEFORE asking the user anything or declaring a step blocked.+## Continuous Checkpoint ModeIf `CHECKPOINT_MODE` is `"continuous"`: auto-commit completed logical units with `WIP:` prefix.diff --git a/ios-clean/SKILL.md b/ios-clean/SKILL.mdindex fddb3b51b..1d73d8f7b 100644--- a/ios-clean/SKILL.md+++ b/ios-clean/SKILL.md@@ -678,6 +678,10 @@ When options differ in coverage, include `Completeness: X/10` (10 = all edge casFor high-stakes ambiguity (architecture, data model, destructive scope, missing context), STOP. Name it in one sentence, present 2-3 options with tradeoffs, and ask. Do not use for routine coding or obvious changes.+## Claimed Limitations Need Evidence++A claimed limitation or requirement ("the API can't do this", "X requires a credential", "that's impossible on this platform") is a material claim. State one only with the verbatim error, the documented statement, or a live probe in hand — pattern-matching a failure to a familiar story is not evidence. When a cheap probe settles the question, run it BEFORE asking the user anything or declaring a step blocked.+## Continuous Checkpoint ModeIf `CHECKPOINT_MODE` is `"continuous"`: auto-commit completed logical units with `WIP:` prefix.diff --git a/ios-design-review/SKILL.md b/ios-design-review/SKILL.mdindex e90723398..8cdc8a024 100644--- a/ios-design-review/SKILL.md+++ b/ios-design-review/SKILL.md@@ -680,6 +680,10 @@ When options differ in coverage, include `Completeness: X/10` (10 = all edge casFor high-stakes ambiguity (architecture, data model, destructive scope, missing context), STOP. Name it in one sentence, present 2-3 options with tradeoffs, and ask. Do not use for routine coding or obvious changes.+## Claimed Limitations Need Evidence++A claimed limitation or requirement ("the API can't do this", "X requires a credential", "that's impossible on this platform") is a material claim. State one only with the verbatim error, the documented statement, or a live probe in hand — pattern-matching a failure to a familiar story is not evidence. When a cheap probe settles the question, run it BEFORE asking the user anything or declaring a step blocked.+## Continuous Checkpoint ModeIf `CHECKPOINT_MODE` is `"continuous"`: auto-commit completed logical units with `WIP:` prefix.diff --git a/ios-fix/SKILL.md b/ios-fix/SKILL.mdindex 59899778d..6857d49af 100644--- a/ios-fix/SKILL.md+++ b/ios-fix/SKILL.md@@ -681,6 +681,10 @@ When options differ in coverage, include `Completeness: X/10` (10 = all edge casFor high-stakes ambiguity (architecture, data model, destructive scope, missing context), STOP. Name it in one sentence, present 2-3 options with tradeoffs, and ask. Do not use for routine coding or obvious changes.+## Claimed Limitations Need Evidence++A claimed limitation or requirement ("the API can't do this", "X requires a credential", "that's impossible on this platform") is a material claim. State one only with the verbatim error, the documented statement, or a live probe in hand — pattern-matching a failure to a familiar story is not evidence. When a cheap probe settles the question, run it BEFORE asking the user anything or declaring a step blocked.+## Continuous Checkpoint ModeIf `CHECKPOINT_MODE` is `"continuous"`: auto-commit completed logical units with `WIP:` prefix.diff --git a/ios-qa/SKILL.md b/ios-qa/SKILL.mdindex 9b1756bce..5540914be 100644--- a/ios-qa/SKILL.md+++ b/ios-qa/SKILL.md@@ -684,6 +684,10 @@ When options differ in coverage, include `Completeness: X/10` (10 = all edge casFor high-stakes ambiguity (architecture, data model, destructive scope, missing context), STOP. Name it in one sentence, present 2-3 options with tradeoffs, and ask. Do not use for routine coding or obvious changes.+## Claimed Limitations Need Evidence++A claimed limitation or requirement ("the API can't do this", "X requires a credential", "that's impossible on this platform") is a material claim. State one only with the verbatim error, the documented statement, or a live probe in hand — pattern-matching a failure to a familiar story is not evidence. When a cheap probe settles the question, run it BEFORE asking the user anything or declaring a step blocked.+## Continuous Checkpoint ModeIf `CHECKPOINT_MODE` is `"continuous"`: auto-commit completed logical units with `WIP:` prefix.diff --git a/ios-qa/daemon/src/audit.ts b/ios-qa/daemon/src/audit.tsindex 9ee4cf739..7b328ca39 100644--- a/ios-qa/daemon/src/audit.ts+++ b/ios-qa/daemon/src/audit.ts@@ -60,14 +60,20 @@ export async function writeAudit(row: AuditRow, path: string = defaultAuditPath(await appendFile(path, JSON.stringify(row) + '\n', { mode: 0o600 });}+// Non-reversible identifier for tokens/identities in logs and API responses.+// Same device salt as the attempts log, so ids correlate across both.+export async function saltedHash(raw: string): Promise<string> {+ const salt = await loadDeviceSalt();+ return createHash('sha256').update(salt + ':' + raw).digest('hex').slice(0, 16);+}+export async function writeAttempt(opts: {rawIdentity: string;endpoint: string;reason: AttemptRow['reason'];path?: string;}): Promise<void> {- const salt = await loadDeviceSalt();- const hash = createHash('sha256').update(salt + ':' + opts.rawIdentity).digest('hex').slice(0, 16);+ const hash = await saltedHash(opts.rawIdentity);const row: AttemptRow = {ts: new Date().toISOString(),identity_canon: hash,diff --git a/ios-qa/daemon/src/index.ts b/ios-qa/daemon/src/index.tsindex f3a70c89f..9ae177ca7 100644--- a/ios-qa/daemon/src/index.ts+++ b/ios-qa/daemon/src/index.ts@@ -19,7 +19,7 @@ import { probeTailscale, whoIs } from './tailscale-localapi';import { SessionTokenStore } from './session-tokens';import { mintForCaller } from './auth-mint';import { classifyRoute, proxyToDevice, type DeviceTunnel } from './proxy';-import { writeAudit, writeAttempt, sanitizeReplacer } from './audit';+import { writeAudit, writeAttempt, sanitizeReplacer, saltedHash } from './audit';import { bootstrapTunnel } from './tunnel-bootstrap';import { startTunnelKeepalive } from './devicectl';import type { Capability } from './types';@@ -362,20 +362,38 @@ async function handleLoopback(ctx: HandlerCtx): Promise<void> {return;}- // /auth/sessions — list active sessions (owner only).+ // /auth/sessions — list active sessions (owner only). Raw token values+ // never leave the store: any local process can hit this listener, so a+ // list that echoed live bearer tokens was a harvest-and-replay primitive.+ // Callers get a salted-hash id plus metadata; revoke by identity, by the+ // token they already hold from mint, or by token_id from this list.if (method === 'GET' && path === '/auth/sessions') {- sendJson(res, 200, { sessions: tokenStore.list() });+ const sessions = await Promise.all(tokenStore.list().map(async ({ token, ...meta }) => ({+ token_id: await saltedHash(token),+ ...meta,+ })));+ sendJson(res, 200, { sessions });return;}- // /auth/revoke — revoke a token.+ // /auth/revoke — revoke by raw token (the caller's own, from mint), by+ // token_id (from /auth/sessions — keeps the list→revoke workflow alive+ // now that the list is hash-only), or by identity.if (method === 'POST' && path === '/auth/revoke') {const body = await readBody(req);if ('error' in body) { sendJson(res, 413, body); return; }- const parsed = JSON.parse(body.toString('utf-8') || '{}') as { token?: string; identity?: string };+ const parsed = JSON.parse(body.toString('utf-8') || '{}') as {+ token?: string; token_id?: string; identity?: string;+ };let count = 0;if (parsed.token) {count = tokenStore.revoke(parsed.token) ? 1 : 0;+ } else if (parsed.token_id) {+ for (const s of tokenStore.list()) {+ if ((await saltedHash(s.token)) === parsed.token_id) {+ count += tokenStore.revoke(s.token) ? 1 : 0;+ }+ }} else if (parsed.identity) {count = tokenStore.revokeByIdentity(parsed.identity);}diff --git a/ios-qa/daemon/test/daemon-integration.test.ts b/ios-qa/daemon/test/daemon-integration.test.tsindex b41144ecd..9073b18d4 100644--- a/ios-qa/daemon/test/daemon-integration.test.ts+++ b/ios-qa/daemon/test/daemon-integration.test.ts@@ -107,6 +107,83 @@ describe('daemon — loopback listener', () => {rmSync(workDir, { recursive: true, force: true });});+ test('/auth/sessions returns salted-hash ids and metadata, never raw tokens', async () => {+ const minted = daemon.tokenStore.mint({+ identity: '[email protected]',+ capability: 'interact',+ deviceUdid: 'STUB-UDID',+ origin: 'owner_granted',+ });+ if ('error' in minted) throw new Error(minted.error);+ try {+ const r = await fetchWith('GET', `http://127.0.0.1:${daemon.loopbackPort}/auth/sessions`);+ expect(r.status).toBe(200);+ // The harvest-and-replay primitive: any local process could read live+ // bearer tokens off this endpoint. The raw token must never appear.+ expect(r.bodyText).not.toContain(minted.token);++ const { sessions } = JSON.parse(r.bodyText) as { sessions: Array<Record<string, unknown>> };+ const row = sessions.find(s => s.identity === '[email protected]');+ expect(row).toMatchObject({+ capability: 'interact',+ device_udid: 'STUB-UDID',+ origin: 'owner_granted',+ expires_at: minted.expires_at,+ });+ expect(row?.token_id).toMatch(/^[0-9a-f]{16}$/);+ expect(row?.token).toBeUndefined();+ } finally {+ daemon.tokenStore.revoke(minted.token);+ }+ });++ test('revoke by token_id from the hash-only list still works (list→revoke)', async () => {+ const minted = daemon.tokenStore.mint({+ identity: '[email protected]',+ capability: 'observe',+ origin: 'owner_granted',+ });+ if ('error' in minted) throw new Error(minted.error);++ const list = await fetchWith('GET', `http://127.0.0.1:${daemon.loopbackPort}/auth/sessions`);+ const { sessions } = JSON.parse(list.bodyText) as { sessions: Array<Record<string, unknown>> };+ const row = sessions.find(s => s.identity === '[email protected]');+ expect(row?.token_id).toBeDefined();++ const revoke = await fetchWith('POST', `http://127.0.0.1:${daemon.loopbackPort}/auth/revoke`, {+ body: JSON.stringify({ token_id: row!.token_id }),+ });+ expect(revoke.status).toBe(200);+ expect(JSON.parse(revoke.bodyText).revoked).toBe(1);+ expect(daemon.tokenStore.list().some(s => s.identity === '[email protected]')).toBe(false);+ });++ test('revoke with an unknown token_id revokes nothing and leaves live sessions untouched', async () => {+ const minted = daemon.tokenStore.mint({+ identity: '[email protected]',+ capability: 'observe',+ origin: 'owner_granted',+ });+ if ('error' in minted) throw new Error(minted.error);+ try {+ // Well-formed (16 hex chars) but matches no session's salted hash.+ const revoke = await fetchWith('POST', `http://127.0.0.1:${daemon.loopbackPort}/auth/revoke`, {+ body: JSON.stringify({ token_id: '0'.repeat(16) }),+ });+ expect(revoke.status).toBe(200);+ expect(JSON.parse(revoke.bodyText).revoked).toBe(0);++ // The minted session must survive: still in the token store...+ expect(daemon.tokenStore.list().some(s => s.identity === '[email protected]')).toBe(true);+ // ...and still visible on the list endpoint.+ const list = await fetchWith('GET', `http://127.0.0.1:${daemon.loopbackPort}/auth/sessions`);+ const { sessions } = JSON.parse(list.bodyText) as { sessions: Array<Record<string, unknown>> };+ expect(sessions.some(s => s.identity === '[email protected]')).toBe(true);+ } finally {+ daemon.tokenStore.revoke(minted.token);+ }+ });+test('healthz returns 200 with mode=loopback', async () => {const r = await fetchWith('GET', `http://127.0.0.1:${daemon.loopbackPort}/healthz`);expect(r.status).toBe(200);diff --git a/ios-qa/templates/StateServer.swift.template b/ios-qa/templates/StateServer.swift.templateindex b8441df16..9696ff372 100644--- a/ios-qa/templates/StateServer.swift.template+++ b/ios-qa/templates/StateServer.swift.template@@ -97,10 +97,12 @@ public final class StateServer {try? bootToken.write(toFile: bootTokenPath, atomically: true, encoding: .utf8)try? FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: bootTokenPath)- // 2. Log the boot token EXACTLY ONCE so the daemon can scrape it.- // The daemon will rotate immediately; this log line is dead within- // seconds.- logger.notice("gstack-ios-qa-bootstrap token=\(self.bootToken, privacy: .public) port=\(self.port, privacy: .public) build=\(self.appBuildId, privacy: .public)")+ // 2. Announce bootstrap WITHOUT the token. The daemon reads the boot+ // token from the 0600 file above (copyFileFromAppContainer); the+ // os_log line that used to carry it had no consumer and handed a+ // live credential to anything reading the unified log during the+ // launch window. Port/build stay for diagnostics.+ logger.notice("gstack-ios-qa-bootstrap port=\(self.port, privacy: .public) build=\(self.appBuildId, privacy: .public)")// 3. Bind both IPv6 and IPv4 loopback. CoreDevice tunnel uses IPv6;// local tooling may use IPv4. Never bind 0.0.0.0 or ::.@@ -149,7 +151,19 @@ public final class StateServer {let params = NWParameters.tcpparams.allowLocalEndpointReuse = true- let listener = try NWListener(using: params, on: NWEndpoint.Port(rawValue: port)!)+ // IPv4 has no CoreDevice tunnel path, so it binds strictly to+ // loopback at the socket level; IPv6 keeps the wildcard bind and+ // relies on the per-connection peer check below for tunnel peers.+ let listener: NWListener+ switch family {+ case .ipv4:+ params.requiredLocalEndpoint = NWEndpoint.hostPort(+ host: NWEndpoint.Host("127.0.0.1"),+ port: NWEndpoint.Port(rawValue: port)!)+ listener = try NWListener(using: params)+ case .ipv6:+ listener = try NWListener(using: params, on: NWEndpoint.Port(rawValue: port)!)+ }listener.stateUpdateHandler = { [weak self] state inTask { @MainActor inif case .ready = state {diff --git a/ios-sync/SKILL.md b/ios-sync/SKILL.mdindex 5f20212aa..0b1390c1c 100644--- a/ios-sync/SKILL.md+++ b/ios-sync/SKILL.md@@ -678,6 +678,10 @@ When options differ in coverage, include `Completeness: X/10` (10 = all edge casFor high-stakes ambiguity (architecture, data model, destructive scope, missing context), STOP. Name it in one sentence, present 2-3 options with tradeoffs, and ask. Do not use for routine coding or obvious changes.+## Claimed Limitations Need Evidence++A claimed limitation or requirement ("the API can't do this", "X requires a credential", "that's impossible on this platform") is a material claim. State one only with the verbatim error, the documented statement, or a live probe in hand — pattern-matching a failure to a familiar story is not evidence. When a cheap probe settles the question, run it BEFORE asking the user anything or declaring a step blocked.+## Continuous Checkpoint ModeIf `CHECKPOINT_MODE` is `"continuous"`: auto-commit completed logical units with `WIP:` prefix.diff --git a/land-and-deploy/SKILL.md b/land-and-deploy/SKILL.mdindex c005ee82b..0e3d23509 100644--- a/land-and-deploy/SKILL.md+++ b/land-and-deploy/SKILL.md@@ -673,6 +673,10 @@ When options differ in coverage, include `Completeness: X/10` (10 = all edge casFor high-stakes ambiguity (architecture, data model, destructive scope, missing context), STOP. Name it in one sentence, present 2-3 options with tradeoffs, and ask. Do not use for routine coding or obvious changes.+## Claimed Limitations Need Evidence++A claimed limitation or requirement ("the API can't do this", "X requires a credential", "that's impossible on this platform") is a material claim. State one only with the verbatim error, the documented statement, or a live probe in hand — pattern-matching a failure to a familiar story is not evidence. When a cheap probe settles the question, run it BEFORE asking the user anything or declaring a step blocked.+## Continuous Checkpoint ModeIf `CHECKPOINT_MODE` is `"continuous"`: auto-commit completed logical units with `WIP:` prefix.@@ -803,6 +807,20 @@ the failure occurred (if outcome is error, otherwise use empty string "").Skills that run plan reviews (`/plan-*-review`, `/codex review`) include the EXIT PLAN MODE GATE blocking checklist at the end of the skill, which verifies the plan file ends with `## GSTACK REVIEW REPORT` before ExitPlanMode is called. Skills that don't run plan reviews (operational skills like `/ship`, `/qa`, `/review`) typically don't operate in plan mode and have no review report to verify; this footer is a no-op for them. Writing the plan file is the one edit allowed in plan mode.+## Third-Party Web Actions++A step sometimes requires action on an external website the user controls: registering an API key, creating a vendor or developer account, configuring a dashboard, webhook, OAuth app, billing plan, or domain verification. This contract governs that moment. It grants no new browsing authority — the AskUserQuestion format and one-way-door rules remain binding, including approval before anything that spends money.++1. **Never hand the user a manual step list for a third-party site without first offering to drive it.** The driver is gstack's own browser stack: `$B` headed mode with handoff/resume for the human-only moments (see the /browse skill), or GStack Browser when installed. Never install new tooling to close the gap, and never treat tooling presence as consent to browse.++2. **One explicit question before any browsing.** STOP and name the exact site and the exact actions (for example "create a test-mode API token in the Duffel dashboard"), then offer: A) I drive it now in a visible browser — you take over for sign-in and approvals, B) manual instructions, C) defer. The selection is per-task consent; never persist it as standing permission and never infer it from an earlier task.++3. **When driving, touch only the named site and actions.** Password entry, new-account credential choice, payment, CAPTCHA, and identity verification are user-performed: hand off (`$B handoff`) and wait instead of acting. Prefer credential flows that never expose the secret to the agent, such as password-manager autofill or the dashboard's own copy button used by the human.++4. **A captured secret never appears in chat output, logs, or shell history.** Write it to a user-approved local file with owner-only permissions (0600) or the user's secret store, and keep generated destinations out of version control. Dashboard fields are often masked placeholders — verify the captured credential with ONE non-mutating API call before claiming success; a 401 here has caught a placeholder masquerading as a key.++5. **If the user declines or defers, or no browser is usable,** provide the manual steps and mark the step blocked on the user. Do not recommend or install new products to close the gap.+## SETUP (run this check BEFORE any browse command)```bashdiff --git a/land-and-deploy/SKILL.md.tmpl b/land-and-deploy/SKILL.md.tmplindex 433129b39..0c8e17261 100644--- a/land-and-deploy/SKILL.md.tmpl+++ b/land-and-deploy/SKILL.md.tmpl@@ -22,6 +22,8 @@ triggers:{{PREAMBLE}}+{{THIRD_PARTY_ACTIONS}}+{{BROWSE_SETUP}}{{BASE_BRANCH_DETECT}}diff --git a/landing-report/SKILL.md b/landing-report/SKILL.mdindex d67c39415..4995332ac 100644--- a/landing-report/SKILL.md+++ b/landing-report/SKILL.md@@ -675,6 +675,10 @@ When options differ in coverage, include `Completeness: X/10` (10 = all edge casFor high-stakes ambiguity (architecture, data model, destructive scope, missing context), STOP. Name it in one sentence, present 2-3 options with tradeoffs, and ask. Do not use for routine coding or obvious changes.+## Claimed Limitations Need Evidence++A claimed limitation or requirement ("the API can't do this", "X requires a credential", "that's impossible on this platform") is a material claim. State one only with the verbatim error, the documented statement, or a live probe in hand — pattern-matching a failure to a familiar story is not evidence. When a cheap probe settles the question, run it BEFORE asking the user anything or declaring a step blocked.+## Continuous Checkpoint ModeIf `CHECKPOINT_MODE` is `"continuous"`: auto-commit completed logical units with `WIP:` prefix.diff --git a/learn/SKILL.md b/learn/SKILL.mdindex 58cf050b3..85c094c82 100644--- a/learn/SKILL.md+++ b/learn/SKILL.md@@ -676,6 +676,10 @@ When options differ in coverage, include `Completeness: X/10` (10 = all edge casFor high-stakes ambiguity (architecture, data model, destructive scope, missing context), STOP. Name it in one sentence, present 2-3 options with tradeoffs, and ask. Do not use for routine coding or obvious changes.+## Claimed Limitations Need Evidence++A claimed limitation or requirement ("the API can't do this", "X requires a credential", "that's impossible on this platform") is a material claim. State one only with the verbatim error, the documented statement, or a live probe in hand — pattern-matching a failure to a familiar story is not evidence. When a cheap probe settles the question, run it BEFORE asking the user anything or declaring a step blocked.+## Continuous Checkpoint ModeIf `CHECKPOINT_MODE` is `"continuous"`: auto-commit completed logical units with `WIP:` prefix.diff --git a/lib/code-intelligence/contract.ts b/lib/code-intelligence/contract.tsnew file mode 100644index 000000000..24619d714--- /dev/null+++ b/lib/code-intelligence/contract.ts@@ -0,0 +1,201 @@+/**+ * code-intelligence/contract — the OPTIONAL, repo-oriented provider contract.+ *+ * Portions copyright (c) 2026 Sina Matian, time-attack/gstack (GStack 2), MIT.+ *+ * gstack does not maintain a home-grown indexer. It defines this small contract+ * and external providers (GBrain, Sourcebot, Graphify) implement it. The whole+ * contract is OPTIONAL: when no provider is available/consented,+ * `resolveCodeProvider()` returns null and callers degrade to grep / the+ * file-only decision store. Never a dependency, always an enhancement — the same+ * reliability contract as lib/gstack-decision-semantic.ts.+ *+ * Repo-oriented, not document-store (settled): register_source / refresh /+ * search / status are required; add / delete / export are optional capabilities+ * a provider MAY advertise. A document-CRUD-required contract would misrepresent+ * whole-repo code-search and code-graph tools. See+ * docs/designs/CODE_INTELLIGENCE_PROVIDER_CONTRACT.md.+ */++export type CodeProviderId = "gbrain" | "sourcebot" | "graphify";++/**+ * Policy op classification for the per-remote trust-tier veto (selection.ts).+ * Write-class ops (register_source / index / refresh / add / delete) cause+ * pages to be written, so BOTH `deny` and `read-only` tiers veto them — the+ * same semantics as runCodeImport in bin/gstack-gbrain-sync.ts ("code ingest+ * writes pages"). Read-class ops (search / export / status) write nothing, so+ * only `deny` vetoes them. Callers that don't say get "write" — fail-closed.+ */+export type OpClass = "read" | "write";++export type CodeProviderCapability =+ | "register_source"+ | "refresh"+ | "search"+ | "status"+ | "add"+ | "delete"+ | "export";++export const REQUIRED_CAPABILITIES: readonly CodeProviderCapability[] = [+ "register_source",+ "refresh",+ "search",+ "status",+] as const;++export const OPTIONAL_CAPABILITIES: readonly CodeProviderCapability[] = [+ "add",+ "delete",+ "export",+] as const;++export interface RepoRef {+ /** Source id the provider registers this repo under. */+ id: string;+ /** Local worktree path. */+ path: string;+ /** Remote URL, when the provider clones/manages it. */+ remoteUrl?: string;+}++export interface SourceRef {+ id: string;+}++export interface SourceStatus {+ id: string;+ state: "registered" | "indexing" | "ready" | "absent" | "unknown";+ /** Pages / files / graph nodes, when the provider reports a count. */+ itemCount?: number;+ detail?: string;+ /** True when the provider only implements a partial status probe. */+ partial?: boolean;+}++export interface CodeSearchHit {+ /** Slug, file path, or symbol id — whatever the provider keys results on. */+ ref: string;+ score?: number;+ snippet?: string;+ kind?: "document" | "file" | "symbol" | "graph-node";+}++export interface OpOptions {+ /**+ * Env override for spawned processes and egress-receipt home resolution.+ * Production callers leave this unset; tests inject a synthetic env (fake+ * CLI on PATH, temp GSTACK_HOME). Matches the existing gbrain helpers.+ */+ env?: NodeJS.ProcessEnv;+ /** Timeout in ms for the underlying op. */+ timeout?: number;+ /**+ * Explicit per-repo consent that repo content may leave the machine. Required+ * for non-local providers on register_source / refresh / add / search (the+ * search query text is repo-derived content). The recorded value also feeds+ * the egress receipt, which attests the ACTUAL consent state — never assumed.+ */+ consented?: boolean;+}++export interface SearchOptions extends OpOptions {+ /** Restrict to a registered source. */+ source?: string;+ limit?: number;+ minScore?: number;+}++export interface CodeProvider {+ readonly id: CodeProviderId;+ readonly label: string;+ readonly capabilities: ReadonlySet<CodeProviderCapability>;+ /** True when no repo content leaves the machine (Graphify). */+ readonly local: boolean;++ has(capability: CodeProviderCapability): boolean;++ registerSource(repo: RepoRef, opts?: OpOptions): Promise<SourceStatus>;+ refresh(source: SourceRef, opts?: OpOptions): Promise<SourceStatus>;+ search(query: string, opts?: SearchOptions): Promise<CodeSearchHit[]>;+ status(source?: SourceRef, opts?: OpOptions): Promise<SourceStatus>;++ add?(doc: { slug: string; body: string }, opts?: OpOptions): Promise<SourceStatus>;+ delete?(slug: string, opts?: OpOptions): Promise<SourceStatus>;+ export?(source: SourceRef, opts?: OpOptions): Promise<string>;+}++export const CODE_PROVIDER_FAILURES = Object.freeze([+ "PROVIDER_UNAVAILABLE",+ "PROVIDER_NOT_CONSENTED",+ "CAPABILITY_UNSUPPORTED",+ "SOURCE_NOT_REGISTERED",+ "PROVIDER_TIMEOUT",+ "PROVIDER_ERROR",+] as const);++export type CodeProviderFailure = (typeof CODE_PROVIDER_FAILURES)[number];++const FAILURE_SET = new Set<string>(CODE_PROVIDER_FAILURES);++/**+ * Typed provider failure. Mirrors runtime/context.js ContextError discipline:+ * the code set is closed and the constructor throws on an unknown code, so a+ * typo can never mint an untyped failure.+ */+export class CodeProviderError extends Error {+ readonly code: CodeProviderFailure;+ readonly providerId?: CodeProviderId;++ constructor(code: CodeProviderFailure, message: string, providerId?: CodeProviderId) {+ if (!FAILURE_SET.has(code)) throw new TypeError(`Unknown code-provider failure code: ${code}`);+ super(message);+ this.name = "CodeProviderError";+ this.code = code;+ this.providerId = providerId;+ }+}++/**+ * Enforce that a provider advertises every required capability. Called by each+ * adapter constructor so an incomplete provider fails fast, not at first search.+ */+export function assertRequiredCapabilities(+ id: CodeProviderId,+ capabilities: ReadonlySet<CodeProviderCapability>,+): void {+ const missing = REQUIRED_CAPABILITIES.filter((cap) => !capabilities.has(cap));+ if (missing.length) {+ throw new TypeError(`Code provider ${id} is missing required capabilities: ${missing.join(", ")}`);+ }+}++/**+ * Guard for optional ops: throw CAPABILITY_UNSUPPORTED (never a silent no-op)+ * when a provider is asked for a capability it does not advertise.+ */+export function assertCapability(provider: CodeProvider, capability: CodeProviderCapability): void {+ if (!provider.has(capability)) {+ throw new CodeProviderError(+ "CAPABILITY_UNSUPPORTED",+ `${provider.label} does not support "${capability}"`,+ provider.id,+ );+ }+}++/**+ * Repo-scoped egress consent gate. Non-local providers must not move repo+ * content off the machine without explicit per-repo consent. Local providers+ * (nothing leaves the machine) are exempt.+ */+export function assertEgressConsent(provider: CodeProvider, opts?: OpOptions): void {+ if (provider.local) return;+ if (opts?.consented === true) return;+ throw new CodeProviderError(+ "PROVIDER_NOT_CONSENTED",+ `${provider.label} would send repo content off this machine; per-repo indexing consent is required`,+ provider.id,+ );+}diff --git a/lib/code-intelligence/gbrain-adapter.ts b/lib/code-intelligence/gbrain-adapter.tsnew file mode 100644index 000000000..4515ab296--- /dev/null+++ b/lib/code-intelligence/gbrain-adapter.ts@@ -0,0 +1,283 @@+/**+ * GBrain adapter — full contract fit over the existing gbrain CLI chokepoint.+ *+ * Portions copyright (c) 2026 Sina Matian, time-attack/gstack (GStack 2), MIT.+ *+ * Reuses lib/gbrain-exec.ts (spawnGbrain, seeded DATABASE_URL) and+ * lib/gbrain-sources.ts (ensureSourceRegistered, probeSource, sourcePageCount)+ * rather than re-issuing raw commands, so the DATABASE_URL / GBRAIN_HOME /+ * Windows-shim guarantees carry over unchanged. GBrain's native primitive is+ * document-by-slug (put/delete/get/export) PLUS a repo axis (sources add/sync),+ * so it advertises all seven capabilities.+ */++import { spawnSync } from "child_process";+import { sha256Hex, writeReceipt } from "../egress-receipt.js";+import { spawnGbrain, buildGbrainEnv, NEEDS_SHELL_ON_WINDOWS } from "../gbrain-exec";+import { ensureSourceRegistered, probeSource, sourcePageCount } from "../gbrain-sources";+import {+ assertCapability,+ assertEgressConsent,+ assertRequiredCapabilities,+ CodeProviderError,+ type CodeProvider,+ type CodeProviderCapability,+ type CodeSearchHit,+ type OpOptions,+ type RepoRef,+ type SearchOptions,+ type SourceRef,+ type SourceStatus,+} from "./contract";++const CAPABILITIES: CodeProviderCapability[] = [+ "register_source",+ "refresh",+ "search",+ "status",+ "add",+ "delete",+ "export",+];++const DEFAULT_TIMEOUT_MS = 30_000;+/**+ * refresh() default. Full code indexing on the 1000+-tracked-file repos this+ * feature targets routinely outruns the 30s op default; GraphifyProvider uses+ * the same 120s ceiling for the same indexing work. Query/status stay at 30s.+ */+const REFRESH_TIMEOUT_MS = 120_000;++/**+ * Environmental (engine / DB / config) failure shapes, shared by #assertOk and+ * #wrap so the two paths can never drift. These degrade to+ * PROVIDER_UNAVAILABLE (caller falls back to grep / file-only), not a hard+ * PROVIDER_ERROR with a raw dump. Covers the real case where gbrain's pglite+ * engine fails to init its WASM runtime (garrytan/gbrain#223) as well as+ * unreachable/unconfigured databases and a missing CLI.+ */+const ENVIRONMENTAL_ERROR_RE =+ /not on PATH|command not found|PGLite|WASM|failed to initialize|Aborted|Cannot connect to database|not configured|config\.json|database (is )?un(reachable|available)/i;++/**+ * Parse `gbrain search` text output (`[score] slug -- snippet`) into hits.+ * gbrain's search prints text, not JSON (verified in+ * lib/gstack-decision-semantic.ts). Exported for deterministic unit testing.+ */+export function parseGbrainSearch(stdout: string, minScore: number, limit: number): CodeSearchHit[] {+ const hits: CodeSearchHit[] = [];+ for (const line of stdout.split("\n")) {+ const m = line.match(/^\[([\d.]+)\]\s+(\S+)\s+--\s+(.*)$/);+ if (!m) continue;+ const score = parseFloat(m[1]);+ if (!Number.isFinite(score) || score < minScore) continue;+ hits.push({ ref: m[2], score, snippet: m[3].trim(), kind: "document" });+ }+ return hits.slice(0, limit);+}++export class GbrainProvider implements CodeProvider {+ readonly id = "gbrain" as const;+ readonly label = "GBrain";+ readonly capabilities = new Set<CodeProviderCapability>(CAPABILITIES);+ /** GBrain federates into a (possibly remote) DB, so content can leave the machine. */+ readonly local = false;++ constructor() {+ assertRequiredCapabilities(this.id, this.capabilities);+ }++ has(capability: CodeProviderCapability): boolean {+ return this.capabilities.has(capability);+ }++ /**+ * Fail-closed egress receipt, written BEFORE every content-bearing send+ * (register/refresh/add AND search/export). The gbrain subprocess owns the+ * wire bytes, so the receipt records destination + payload class; sha256 is+ * known when the exact payload text is (the `add` document body, the+ * `search` query). The consent field records the ACTUAL consent state from+ * opts — the tamper-evident ledger must never attest consented=true for a+ * send where nothing checked consent (every current caller asserts consent+ * first, so the unchecked branch is defense-in-depth, not a live path).+ */+ #receipt(payloadClass: string, opts: OpOptions, body?: string): void {+ writeReceipt({+ env: opts.env,+ sink: "gbrain",+ host: "gbrain-db (user-configured DATABASE_URL)",+ payloadClass,+ bytes: body == null ? 0 : Buffer.byteLength(body),+ sha256: body == null ? null : sha256Hex(body),+ consent: opts.consented === true+ ? "code-intelligence provider=gbrain + per-repo consented=true"+ : "code-intelligence provider=gbrain + consent=unchecked (content-bearing ops assert consent before sending)",+ });+ }++ async registerSource(repo: RepoRef, opts: OpOptions = {}): Promise<SourceStatus> {+ assertEgressConsent(this, opts);+ this.#receipt("repo-source-registration (sent by gbrain subprocess)", opts);+ try {+ const result = await ensureSourceRegistered(repo.id, repo.path, {+ federated: true,+ env: opts.env,+ });+ return {+ id: repo.id,+ state: result.state.status === "match" ? "registered" : "unknown",+ detail: result.changed ? "registered" : "already registered",+ };+ } catch (err) {+ throw this.#wrap(err);+ }+ }++ async refresh(source: SourceRef, opts: OpOptions = {}): Promise<SourceStatus> {+ assertEgressConsent(this, opts);+ this.#receipt("repo-code-index (sent by gbrain subprocess)", opts);+ const timeout = opts.timeout ?? REFRESH_TIMEOUT_MS;+ // Two passes, verified end-to-end against real Postgres-backed gbrain 0.42.56:+ // 1. default sync (markdown strategy) — indexes docs.+ // 2. `sync --strategy code` — the ACTUAL code-indexing pass. Without it code+ // is never indexed (the whole point of a code provider); `code-def` stays+ // "not_built" and search only finds incidental doc mentions. `--full`+ // forces it past the per-source checkpoint the markdown pass advanced.+ this.#assertOk(spawnGbrain(["sync", "--source", source.id], { baseEnv: opts.env, timeout }));+ this.#assertOk(spawnGbrain(["sync", "--source", source.id, "--strategy", "code", "--full"], { baseEnv: opts.env, timeout }));+ return this.status(source, opts);+ }++ async search(query: string, opts: SearchOptions = {}): Promise<CodeSearchHit[]> {+ if (!query.trim()) return [];+ // The query text is repo-derived content and DATABASE_URL may point at a+ // remote DB. Unlike Sourcebot there is no cheap loopback check here — the+ // URL is resolved inside the gbrain CLI's own config, not by this adapter+ // — so EVERY send is treated as consent-requiring (fail closed, matching+ // the contract's OpOptions doc). The throw happens before any bytes (or+ // any receipt) exist; the receipt lands before the subprocess spawns.+ assertEgressConsent(this, opts);+ this.#receipt("code-search-query (sent by gbrain subprocess)", opts, query);+ // `gbrain search` is global and has no `--source` flag; `--limit` is real+ // (verified against gbrain 0.42.x --help).+ const args = ["search", query];+ if (opts.limit) args.push("--limit", String(opts.limit));+ const r = spawnGbrain(args, { baseEnv: opts.env, timeout: opts.timeout ?? DEFAULT_TIMEOUT_MS });+ this.#assertOk(r);+ return parseGbrainSearch(r.stdout || "", opts.minScore ?? 0.1, opts.limit ?? 10);+ }++ async status(source?: SourceRef, opts: OpOptions = {}): Promise<SourceStatus> {+ if (!source) {+ // No source given: liveness probe. `sources list` reachable = ready.+ this.#assertOk(spawnGbrain(["sources", "list", "--json"], {+ baseEnv: opts.env,+ timeout: opts.timeout ?? DEFAULT_TIMEOUT_MS,+ }));+ return { id: "*", state: "ready" };+ }+ try {+ const probed = probeSource(source.id, opts.env);+ if (probed.status === "absent") return { id: source.id, state: "absent" };+ const count = sourcePageCount(source.id, opts.env);+ return {+ id: source.id,+ state: "ready",+ itemCount: count ?? undefined,+ detail: probed.registered_path,+ };+ } catch (err) {+ throw this.#wrap(err);+ }+ }++ // Document ops (add/delete/export) are GBrain-only and secondary; they match+ // gbrain's documented CLI surface (`put <slug>` reads stdin; `delete <slug>`;+ // `export`) but could not be exercised against a live engine on the test host+ // (pglite WASM broken, garrytan/gbrain#223), so treat them as best-effort.+ async add(doc: { slug: string; body: string }, opts: OpOptions = {}): Promise<SourceStatus> {+ assertCapability(this, "add");+ assertEgressConsent(this, opts);+ this.#receipt("document-body (sent by gbrain subprocess)", opts, doc.body);+ // `gbrain put <slug>` reads the document body from stdin.+ this.#assertOk(this.#runInput(["put", doc.slug], doc.body, opts));+ return { id: doc.slug, state: "ready" };+ }++ async delete(slug: string, opts: OpOptions = {}): Promise<SourceStatus> {+ assertCapability(this, "delete");+ // stdin closed ("") so any confirmation prompt gets EOF rather than hanging.+ this.#assertOk(this.#runInput(["delete", slug], "", opts));+ return { id: slug, state: "absent" };+ }++ async export(_source: SourceRef, opts: OpOptions = {}): Promise<string> {+ assertCapability(this, "export");+ // The export request federates into the same possibly-remote DB as+ // search — same fail-closed consent gate + receipt (no loopback+ // exemption exists for gbrain; see search()).+ assertEgressConsent(this, opts);+ this.#receipt("brain-export-request (sent by gbrain subprocess)", opts);+ // `gbrain export` is brain-wide (no per-source flag); returns whatever it prints.+ const r = spawnGbrain(["export"], {+ baseEnv: opts.env,+ timeout: opts.timeout ?? DEFAULT_TIMEOUT_MS,+ });+ this.#assertOk(r);+ return r.stdout || "";+ }++ /** spawn gbrain with `input` on stdin, seeded env, Windows-shim aware. */+ #runInput(args: string[], input: string, opts: OpOptions) {+ return spawnSync("gbrain", args, {+ input,+ encoding: "utf-8",+ timeout: opts.timeout ?? DEFAULT_TIMEOUT_MS,+ env: buildGbrainEnv({ baseEnv: opts.env }),+ shell: NEEDS_SHELL_ON_WINDOWS,+ });+ }++ /**+ * Throw a typed failure unless the spawn succeeded. Distinguishes a missing+ * CLI (ENOENT → PROVIDER_UNAVAILABLE, the degrade signal) from a timeout+ * (ETIMEDOUT/SIGTERM, status=null) and a real non-zero exit.+ */+ #assertOk(r: {+ status: number | null;+ stderr?: string;+ error?: Error & { code?: string };+ signal?: NodeJS.Signals | null;+ }): void {+ if (r.status === 0) return;+ const stderr = (r.stderr || "").trim();+ if (r.error?.code === "ENOENT" || /command not found/.test(stderr)) {+ throw new CodeProviderError("PROVIDER_UNAVAILABLE", "gbrain CLI not on PATH", this.id);+ }+ if (r.error?.code === "ETIMEDOUT" || r.signal === "SIGTERM") {+ throw new CodeProviderError("PROVIDER_TIMEOUT", "gbrain timed out", this.id);+ }+ // Engine / DB / config problems are ENVIRONMENTAL — degrade to UNAVAILABLE+ // (caller falls back to file-only). Shapes hoisted to ENVIRONMENTAL_ERROR_RE.+ if (ENVIRONMENTAL_ERROR_RE.test(stderr)) {+ throw new CodeProviderError("PROVIDER_UNAVAILABLE", firstLine(stderr) || "gbrain engine unavailable", this.id);+ }+ throw new CodeProviderError("PROVIDER_ERROR", firstLine(stderr) || `gbrain exited ${r.status}`, this.id);+ }++ #wrap(err: unknown): CodeProviderError {+ if (err instanceof CodeProviderError) return err;+ const message = err instanceof Error ? err.message : String(err);+ // Same environmental-vs-real split as #assertOk — literally the same+ // regex (ENVIRONMENTAL_ERROR_RE), so the two paths can never drift.+ if (ENVIRONMENTAL_ERROR_RE.test(message)) {+ return new CodeProviderError("PROVIDER_UNAVAILABLE", firstLine(message), this.id);+ }+ return new CodeProviderError("PROVIDER_ERROR", firstLine(message), this.id);+ }+}++/** First non-empty line, so a multi-line WASM/stack dump never reaches the user. */+function firstLine(text: string): string {+ return (text || "").split("\n").map((l) => l.trim()).find(Boolean) ?? "";+}diff --git a/lib/code-intelligence/graphify-adapter.ts b/lib/code-intelligence/graphify-adapter.tsnew file mode 100644index 000000000..b0cd85ca6--- /dev/null+++ b/lib/code-intelligence/graphify-adapter.ts@@ -0,0 +1,201 @@+/**+ * Graphify adapter — real CLI integration (github.com/Graphify-Labs/graphify).+ *+ * Portions copyright (c) 2026 Sina Matian, time-attack/gstack (GStack 2), MIT.+ *+ * Graphify is a LOCAL tree-sitter knowledge graph. For CODE, `graphify <dir>`+ * and `graphify update <dir>` produce the SAME AST graph with NO LLM and NO+ * network (verified against graphify 0.9.23 — both emit `AST extraction on N+ * code files`, all node origins `ast`). The LLM backend (openai/gemini) is only+ * used to RENAME community clusters (`graphify label` / `cluster-only`) and to+ * ingest non-code docs (`graphify add`); it adds zero nodes/edges, and our parser+ * discards the `community=` field it touches — so an LLM mode would send code+ * off-machine for no change in search output, and is intentionally not offered.+ *+ * This adapter uses `graphify update <dir>` (writes `<dir>/graphify-out/graph.json`+ * and does clustering in one shot) and stays fully local — nothing leaves the+ * machine, so `local = true` and no egress consent is needed.+ *+ * Query is `graphify query "<q>" --graph <dir>/graphify-out/graph.json`; the+ * `--graph` flag points at the built graph so search never depends on cwd.+ *+ * Never auto-installed: install is `pip install graphifyy && graphify install`+ * (needs Python >= 3.10), a user action the picker surfaces. When the CLI is+ * absent every op throws PROVIDER_UNAVAILABLE and callers degrade to file-only.+ *+ * Path-based, not id-based: for Graphify a source "id" IS the absolute repo path+ * (that is where `graphify-out/` lives), unlike GBrain's short source ids.+ */++import { spawnSync } from "child_process";+import { existsSync, readFileSync, statSync } from "fs";+import { join } from "path";+import {+ assertCapability,+ assertRequiredCapabilities,+ CodeProviderError,+ type CodeProvider,+ type CodeProviderCapability,+ type CodeSearchHit,+ type OpOptions,+ type RepoRef,+ type SearchOptions,+ type SourceRef,+ type SourceStatus,+} from "./contract";++const CAPABILITIES: CodeProviderCapability[] = ["register_source", "refresh", "search", "status", "export"];+const OUT_DIR = "graphify-out";+const GRAPH_JSON = "graph.json";+const DEFAULT_TIMEOUT_MS = 120_000; // indexing a repo can take a while+const NEEDS_SHELL_ON_WINDOWS = process.platform === "win32"; // graphify is a shim on Windows+/**+ * status() only parses graph.json for a node count when the file is at most+ * this big. On the 1000+-file repos this feature targets, graph.json can run+ * to hundreds of MB — JSON.parsing that for a cosmetic count is a heap spike.+ * Above the threshold the display reports the file size instead.+ */+const STATUS_PARSE_MAX_BYTES = 5 * 1024 * 1024;++export interface GraphifyOptions {+ /** Directory whose `graphify-out/` search/status/export read. Defaults to cwd. */+ root?: string;+ env?: NodeJS.ProcessEnv;+}++export class GraphifyProvider implements CodeProvider {+ readonly id = "graphify" as const;+ readonly label = "Graphify";+ readonly capabilities = new Set<CodeProviderCapability>(CAPABILITIES);+ /** Fully local — no repo content leaves the machine. */+ readonly local = true;+ readonly #root: string;+ readonly #env?: NodeJS.ProcessEnv;++ constructor(opts: GraphifyOptions = {}) {+ this.#root = opts.root ?? process.cwd();+ this.#env = opts.env;+ assertRequiredCapabilities(this.id, this.capabilities);+ }++ has(capability: CodeProviderCapability): boolean {+ return this.capabilities.has(capability);+ }++ #run(args: string[], cwd: string, timeout: number) {+ return spawnSync("graphify", args, {+ cwd,+ encoding: "utf-8",+ timeout,+ stdio: ["ignore", "pipe", "pipe"],+ env: this.#env,+ shell: NEEDS_SHELL_ON_WINDOWS,+ });+ }++ #assertOk(r: { status: number | null; stderr?: string; error?: Error & { code?: string }; signal?: NodeJS.Signals | null }): void {+ if (r.status === 0) return;+ const stderr = (r.stderr || "").trim();+ if (r.error?.code === "ENOENT" || /command not found/.test(stderr)) {+ throw new CodeProviderError("PROVIDER_UNAVAILABLE", "graphify CLI not on PATH (install: pip install graphifyy && graphify install)", this.id);+ }+ if (r.error?.code === "ETIMEDOUT" || r.signal === "SIGTERM") {+ throw new CodeProviderError("PROVIDER_TIMEOUT", "graphify timed out", this.id);+ }+ throw new CodeProviderError("PROVIDER_ERROR", stderr || `graphify exited ${r.status}`, this.id);+ }++ /** Build the graph over repo.path locally (no LLM, no egress consent needed). */+ async registerSource(repo: RepoRef, opts: OpOptions = {}): Promise<SourceStatus> {+ this.#assertOk(this.#run(["update", repo.path], repo.path, opts.timeout ?? DEFAULT_TIMEOUT_MS));+ return this.status({ id: repo.path }, opts);+ }++ /** Re-parse and rebuild the graph (same local `graphify update` path). */+ async refresh(source: SourceRef, opts: OpOptions = {}): Promise<SourceStatus> {+ this.#assertOk(this.#run(["update", source.id], source.id, opts.timeout ?? DEFAULT_TIMEOUT_MS));+ return this.status(source, opts);+ }++ /**+ * `graphify query "<q>" --graph <graph.json>` traces the graph and prints+ * `NODE ...` / `EDGE ...` lines (plus a `Traversal:` header). We pass `--graph`+ * explicitly so the query reads the indexed repo's graph regardless of cwd.+ */+ async search(query: string, opts: SearchOptions = {}): Promise<CodeSearchHit[]> {+ if (!query.trim()) return [];+ const root = opts.source ?? this.#root;+ const graphPath = join(root, OUT_DIR, GRAPH_JSON);+ const r = this.#run(["query", query, "--graph", graphPath], root, opts.timeout ?? DEFAULT_TIMEOUT_MS);+ this.#assertOk(r);+ return parseGraphifyQuery(r.stdout || "", opts.limit ?? 10);+ }++ async status(source?: SourceRef, _opts: OpOptions = {}): Promise<SourceStatus> {+ const dir = source?.id ?? this.#root;+ const graphPath = join(dir, OUT_DIR, GRAPH_JSON);+ if (!existsSync(graphPath)) return { id: dir, state: "absent" };+ let itemCount: number | undefined;+ let detail = graphPath;+ try {+ // stat first: parse the whole graph only when it's small (the node count+ // is display-only, never worth a hundreds-of-MB JSON.parse heap spike).+ const size = statSync(graphPath).size;+ if (size <= STATUS_PARSE_MAX_BYTES) {+ const graph = JSON.parse(readFileSync(graphPath, "utf-8")) as { nodes?: unknown[] };+ if (Array.isArray(graph.nodes)) itemCount = graph.nodes.length;+ } else {+ detail = `${graphPath} (${(size / (1024 * 1024)).toFixed(1)} MB graph; node count skipped)`;+ }+ } catch {+ // graph.json present but unstatable/unparseable — still ready, just no count.+ }+ return { id: dir, state: "ready", itemCount, detail };+ }++ async export(source: SourceRef, _opts: OpOptions = {}): Promise<string> {+ assertCapability(this, "export");+ const graphPath = join(source.id, OUT_DIR, GRAPH_JSON);+ if (!existsSync(graphPath)) {+ throw new CodeProviderError("SOURCE_NOT_REGISTERED", `no graph at ${graphPath}; index it first`, this.id);+ }+ return readFileSync(graphPath, "utf-8");+ }+}++/**+ * Parse real `graphify query` output into hits. The format (graphify 0.9.23):+ * Traversal: BFS depth=2 | Start: ['query()'] | ... | 4 nodes found+ * NODE query() [src=db.py loc=L4 community=login]+ * EDGE query() --calls [EXTRACTED context=call]--> login() at=auth.py:L8+ * The file lives mid-line (`src=<file> loc=L<n>` on NODE, `at=<file>:L<n>` on+ * EDGE), so the ref is `<file>:L<n>`. The `Traversal:` header and any other line+ * are skipped. Exported for deterministic unit testing against the real format.+ */+export function parseGraphifyQuery(stdout: string, limit: number): CodeSearchHit[] {+ const hits: CodeSearchHit[] = [];+ for (const raw of stdout.split("\n")) {+ const line = raw.trim();+ let ref: string | undefined;+ const node = line.match(/^NODE\b.*?\[src=(\S+)\s+loc=(L\d+)/);+ const edge = line.match(/^EDGE\b.*?\bat=(\S+?):(L\d+)\b/);+ if (node) ref = `${node[1]}:${node[2]}`;+ else if (edge) ref = `${edge[1]}:${edge[2]}`;+ else continue; // skip the Traversal header and anything non-NODE/EDGE+ hits.push({ ref, snippet: line, kind: "graph-node" });+ if (hits.length >= limit) break;+ }+ return hits;+}++/** Whether the `graphify` CLI is installed (for the picker's availability probe). */+export function graphifyInstalled(env?: NodeJS.ProcessEnv): boolean {+ const r = spawnSync("graphify", ["--version"], {+ encoding: "utf-8",+ timeout: 5_000,+ stdio: ["ignore", "ignore", "ignore"],+ env,+ shell: NEEDS_SHELL_ON_WINDOWS,+ });+ return r.status === 0;+}diff --git a/lib/code-intelligence/index.ts b/lib/code-intelligence/index.tsnew file mode 100644index 000000000..7db360259--- /dev/null+++ b/lib/code-intelligence/index.ts@@ -0,0 +1,36 @@+/**+ * code-intelligence — the OPTIONAL, repo-oriented provider contract.+ *+ * Portions copyright (c) 2026 Sina Matian, time-attack/gstack (GStack 2), MIT.+ *+ * See docs/designs/CODE_INTELLIGENCE_PROVIDER_CONTRACT.md.+ */++export * from "./contract";+export { GbrainProvider, parseGbrainSearch } from "./gbrain-adapter";+export { GraphifyProvider, parseGraphifyQuery, type GraphifyOptions } from "./graphify-adapter";+export { SourcebotProvider, parseSourcebotSearch, type SourcebotOptions } from "./sourcebot-adapter";+export {+ readSelection,+ setProvider,+ setConsent,+ hasConsent,+ setRoot,+ getRoot,+ type Selection,+} from "./selection";+export {+ LARGE_REPO_FILE_THRESHOLD,+ shouldOfferIndexing,+ trackedFileCount,+ type Suggestion,+ type SuggestReason,+} from "./suggest";+export {+ RECOMMENDED_ORDER,+ providerById,+ resolveSelectedProvider,+ detectAvailable,+ type PickerOptions,+ type Availability,+} from "./picker";diff --git a/lib/code-intelligence/picker.ts b/lib/code-intelligence/picker.tsnew file mode 100644index 000000000..9c21adaca--- /dev/null+++ b/lib/code-intelligence/picker.ts@@ -0,0 +1,110 @@+/**+ * Picker — constructs the code-intelligence provider the user selected, and+ * offers the recommendation order (GBrain first) for the selection UX.+ *+ * Portions copyright (c) 2026 Sina Matian, time-attack/gstack (GStack 2), MIT.+ *+ * `resolveSelectedProvider()` reads the persisted selection and constructs that+ * provider, or returns null when nothing is selected — the provider-OFF path,+ * where callers degrade to grep / the file-only decision store. Availability is+ * proven at call time: a selected provider whose tool/server is absent throws+ * PROVIDER_UNAVAILABLE from its ops, which callers catch and degrade on. The+ * `detectAvailable()` probe drives the `options`/`status` display.+ *+ * GBrain is recommended first. Graphify is NEVER auto-installed — it appears in+ * the options only once its CLI is present (a user install).+ */++import { localEngineStatus } from "../gbrain-local-status";+import { GbrainProvider } from "./gbrain-adapter";+import { GraphifyProvider, graphifyInstalled, type GraphifyOptions } from "./graphify-adapter";+import { SourcebotProvider, type SourcebotOptions } from "./sourcebot-adapter";+import { readSelection, getRoot } from "./selection";+import type { CodeProvider, CodeProviderId } from "./contract";++/** Recommendation order — GBrain first. */+export const RECOMMENDED_ORDER: readonly CodeProviderId[] = ["gbrain", "sourcebot", "graphify"];++export interface PickerOptions {+ env?: NodeJS.ProcessEnv;+ graphify?: GraphifyOptions;+ sourcebot?: SourcebotOptions;+}++/** Construct a provider by id (no availability check — ops degrade at call time). */+export function providerById(id: CodeProviderId, opts: PickerOptions = {}): CodeProvider {+ switch (id) {+ case "gbrain":+ return new GbrainProvider();+ case "graphify": {+ // Default the graph root to the repo Graphify last indexed, so `search`+ // reads the same graph `index` built (not whatever cwd happens to be).+ const root = opts.graphify?.root ?? getRoot("graphify", opts.env);+ return new GraphifyProvider({ env: opts.env, ...opts.graphify, ...(root ? { root } : {}) });+ }+ case "sourcebot":+ return new SourcebotProvider({ env: opts.env, ...opts.sourcebot });+ }+}++/**+ * The provider the user selected, constructed, or null when none is selected.+ * Null is the provider-OFF path: callers MUST degrade to grep / file-only.+ */+export function resolveSelectedProvider(opts: PickerOptions = {}): CodeProvider | null {+ const { provider } = readSelection(opts.env);+ return provider ? providerById(provider, opts) : null;+}++export interface Availability {+ id: CodeProviderId;+ available: boolean;+ detail: string;+}++/**+ * Availability probes are DISPLAY probes — they must never stall the CLI. A+ * dead non-loopback SOURCEBOT_URL at the adapters' 30s op default meant a 30s+ * hang just to print the options table; 3s is plenty for a liveness check.+ */+const PROBE_TIMEOUT_MS = 3_000;++/**+ * Probe which providers are usable right now, in recommendation order. Used by+ * the `options`/`status` display. GBrain via the real localEngineStatus();+ * Graphify via its CLI status; Sourcebot via an HTTP liveness probe. The three+ * probes are independent, so they run concurrently, each capped at+ * PROBE_TIMEOUT_MS (localEngineStatus owns its own probe timeout + cache).+ */+export async function detectAvailable(opts: PickerOptions = {}): Promise<Availability[]> {+ const [gbrain, sourcebot, graphify] = await Promise.all([+ (async (): Promise<Availability> => {+ const status = localEngineStatus({ env: opts.env });+ return { id: "gbrain", available: status === "ok" || status === "timeout", detail: `gbrain engine: ${status}` };+ })(),+ (async (): Promise<Availability> => {+ try {+ const s = await new SourcebotProvider({ env: opts.env, ...opts.sourcebot }).status(undefined, { timeout: PROBE_TIMEOUT_MS });+ return { id: "sourcebot", available: s.state === "ready", detail: s.detail ?? "" };+ } catch {+ return { id: "sourcebot", available: false, detail: "server unreachable" };+ }+ })(),+ (async (): Promise<Availability> => {+ // Available = the CLI is installed and selectable (NOT "a graph already exists+ // here"). A freshly installed Graphify with no graph yet is still available.+ const installed = graphifyInstalled(opts.env);+ let detail = "graphify CLI not installed (pip install graphifyy, Python >= 3.10)";+ if (installed) {+ try {+ const s = await new GraphifyProvider({ env: opts.env, ...opts.graphify }).status(undefined, { timeout: PROBE_TIMEOUT_MS });+ detail = s.state === "ready" ? "installed; graph built in this repo" : "installed; run `index` to build a graph";+ } catch {+ detail = "installed";+ }+ }+ return { id: "graphify", available: installed, detail };+ })(),+ ]);+ return [gbrain, sourcebot, graphify];+}diff --git a/lib/code-intelligence/selection.ts b/lib/code-intelligence/selection.tsnew file mode 100644index 000000000..b4fe58baf--- /dev/null+++ b/lib/code-intelligence/selection.ts@@ -0,0 +1,132 @@+/**+ * selection — persists the user's chosen code-intelligence provider and their+ * per-repo indexing consent. Stored at `$GSTACK_HOME/code-intelligence.json`+ * (default `~/.gstack/`), the same home the rest of gstack uses.+ *+ * Portions copyright (c) 2026 Sina Matian, time-attack/gstack (GStack 2), MIT.+ *+ * Consent is per-repo (keyed by absolute repo path), because indexing consent+ * is "may THIS repo's content be indexed by the selected provider" — a decision+ * a user makes per project, not once for the machine. No selection at all is the+ * provider-OFF default: callers degrade to grep / the file-only decision store.+ */++import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "fs";+import { homedir } from "os";+import { dirname, join, resolve } from "path";+import { execFileSync } from "child_process";+import { hasRepoPolicyStore, repoPolicyTier } from "../gbrain-repo-policy-client";+import type { CodeProviderId, OpClass } from "./contract";++export interface Selection {+ provider: CodeProviderId | null;+ /** Absolute repo path → consented. */+ consents: Record<string, boolean>;+ /** Provider id → the absolute repo path it last indexed (so search finds it). */+ roots: Record<string, string>;+ /** User explicitly chose no indexing — never offer again. */+ declined: boolean;+}++const EMPTY: Selection = { provider: null, consents: {}, roots: {}, declined: false };++function storePath(env: NodeJS.ProcessEnv = process.env): string {+ const home = env.GSTACK_HOME || join(env.HOME || homedir(), ".gstack");+ return join(home, "code-intelligence.json");+}++export function readSelection(env: NodeJS.ProcessEnv = process.env): Selection {+ const p = storePath(env);+ if (!existsSync(p)) return { ...EMPTY };+ try {+ const raw = JSON.parse(readFileSync(p, "utf-8")) as Partial<Selection>;+ return {+ provider: raw.provider ?? null,+ consents: raw.consents && typeof raw.consents === "object" ? raw.consents : {},+ roots: raw.roots && typeof raw.roots === "object" ? raw.roots : {},+ declined: raw.declined === true,+ };+ } catch {+ return { ...EMPTY };+ }+}++function write(selection: Selection, env: NodeJS.ProcessEnv = process.env): void {+ const p = storePath(env);+ mkdirSync(dirname(p), { recursive: true });+ const tmp = `${p}.tmp.${process.pid}`;+ writeFileSync(tmp, JSON.stringify(selection, null, 2), "utf-8");+ renameSync(tmp, p);+}++export function setProvider(provider: CodeProviderId | null, env: NodeJS.ProcessEnv = process.env): Selection {+ // Choosing a provider clears a prior decline; clearing to null records one,+ // so the session-start offer is never repeated after an explicit "none".+ const next = { ...readSelection(env), provider, declined: provider === null };+ write(next, env);+ return next;+}++/** Record per-repo indexing consent (repo path resolved to absolute). */+export function setConsent(repoPath: string, consented: boolean, env: NodeJS.ProcessEnv = process.env): Selection {+ const current = readSelection(env);+ const next: Selection = { ...current, consents: { ...current.consents, [resolve(repoPath)]: consented } };+ write(next, env);+ return next;+}++/**+ * The per-remote trust store (gstack-gbrain-repo-policy) is the SINGLE+ * authority for consent-to-send: a `deny` tier vetoes any recorded+ * code-intelligence consent, so two stores can never disagree about whether+ * code may leave this repo (R1, fork port wave 2 review). The veto is+ * op-class-aware (R2): `read-only` means "search allowed, page writes never"+ * (the exact semantics runCodeImport in bin/gstack-gbrain-sync.ts enforces —+ * code ingest writes pages), so it vetoes write-class ops (register / index /+ * refresh / add / delete) while read-class ops (search / export / status)+ * pass; `deny` vetoes both classes. Mirrors the gbrain-sync chokepoint's+ * polarity: no policy store → no veto (nothing was ever set); unreadable+ * store OR unspawnable policy helper → veto for every op class (fail-closed —+ * a policy the user set must not be bypassed by a broken store or a helper+ * that can't run). Reads through the shared lib/gbrain-repo-policy-client.ts+ * so this site and the gbrain-sync gate can never drift.+ */+function repoPolicyVeto(repoPath: string, opClass: OpClass, env: NodeJS.ProcessEnv = process.env): boolean {+ if (!hasRepoPolicyStore(env)) return false; // fast path: nothing was ever set — skip the git spawn too+ let url = "";+ try {+ url = execFileSync("git", ["-C", resolve(repoPath), "remote", "get-url", "origin"], {+ encoding: "utf-8", timeout: 5000,+ }).trim();+ } catch {+ return false; // no remote → policy (keyed by remote) has nothing set for this repo+ }+ if (!url) return false;+ const res = repoPolicyTier(url, env);+ if (res.error) return true; // fail-closed (unreadable store or spawn failure alike)+ if (res.tier === "deny") return true; // deny beats consent for every op class+ return res.tier === "read-only" && opClass === "write"; // read-only: writes never, reads pass+}++/**+ * Recorded per-repo consent, filtered through the repo-policy veto. `opClass`+ * defaults to "write" so a caller that doesn't classify its op gets the+ * fail-closed answer; pass "read" only for ops that write no pages (search /+ * export / status).+ */+export function hasConsent(repoPath: string, env: NodeJS.ProcessEnv = process.env, opClass: OpClass = "write"): boolean {+ if (readSelection(env).consents[resolve(repoPath)] !== true) return false;+ return !repoPolicyVeto(repoPath, opClass, env);+}++/** Record the repo path a provider last indexed, so search reads the same graph. */+export function setRoot(provider: CodeProviderId, repoPath: string, env: NodeJS.ProcessEnv = process.env): Selection {+ const current = readSelection(env);+ const next: Selection = { ...current, roots: { ...current.roots, [provider]: resolve(repoPath) } };+ write(next, env);+ return next;+}++export function getRoot(provider: CodeProviderId, env: NodeJS.ProcessEnv = process.env): string | undefined {+ return readSelection(env).roots[provider];+}diff --git a/lib/code-intelligence/sourcebot-adapter.ts b/lib/code-intelligence/sourcebot-adapter.tsnew file mode 100644index 000000000..f274cb09e--- /dev/null+++ b/lib/code-intelligence/sourcebot-adapter.ts@@ -0,0 +1,277 @@+/**+ * Sourcebot adapter — real HTTP + config integration+ * (github.com/sourcebot-dev/sourcebot, YC F2025).+ *+ * Portions copyright (c) 2026 Sina Matian, time-attack/gstack (GStack 2), MIT.+ *+ * Sourcebot is a self-hosted server that indexes repos declared in its+ * config.json and serves regex code search over `POST /api/search` (zoekt). So+ * the runtime drives it with plain HTTP + a config-file edit — no MCP:+ * - register_source: add `{ "type": "git", "url": "file:///abs/path" }` to the+ * server's config.json (it re-indexes automatically on config change).+ * - refresh: Sourcebot re-indexes on config change and on reindexIntervalMs;+ * there is no per-source trigger endpoint, so refresh reports current status.+ * - search: POST /api/search with a regex query, map files[] to hits.+ * - status: liveness GET against the base URL.+ * Declines the document ops (add/delete/export) — it is a whole-repo search index.+ *+ * Egress: a loopback base URL means the index runs on this machine, so no repo+ * content leaves it (local=true). A non-loopback base URL means content reaches+ * another host, so egress consent is required (local=false).+ */++import { existsSync, readFileSync, writeFileSync, renameSync } from "fs";+import { sha256Hex, writeReceipt } from "../egress-receipt.js";+import {+ assertCapability,+ assertEgressConsent,+ assertRequiredCapabilities,+ CodeProviderError,+ type CodeProvider,+ type CodeProviderCapability,+ type CodeSearchHit,+ type OpOptions,+ type RepoRef,+ type SearchOptions,+ type SourceRef,+ type SourceStatus,+} from "./contract";++const CAPABILITIES: CodeProviderCapability[] = ["register_source", "refresh", "search", "status"];+const DEFAULT_URL = "http://localhost:3000";+const DEFAULT_TIMEOUT_MS = 30_000;++type FetchLike = typeof globalThis.fetch;++export interface SourcebotOptions {+ /** Base URL of the Sourcebot server. Defaults to SOURCEBOT_URL or http://localhost:3000. */+ baseUrl?: string;+ /** Path to the server's config.json (for register_source). Defaults to SOURCEBOT_CONFIG. */+ configPath?: string;+ /**+ * OPTIONAL API key for the Sourcebot REST API. Defaults to SOURCEBOT_API_KEY.+ * A local instance with anonymous access enabled+ * (`FORCE_ENABLE_ANONYMOUS_ACCESS=true`) serves `/api/search` with NO key —+ * verified keyless against a real Sourcebot v6.5.0. Only set a key when your+ * instance is login-gated; it is sent as `Authorization: Bearer <key>`.+ */+ apiKey?: string;+ /** Injectable fetch for tests. */+ fetch?: FetchLike;+ env?: NodeJS.ProcessEnv;+}++function isLoopback(url: string): boolean {+ try {+ const h = new URL(url).hostname.toLowerCase();+ return h === "localhost" || h === "127.0.0.1" || h === "::1" || h.endsWith(".localhost");+ } catch {+ return false;+ }+}++export class SourcebotProvider implements CodeProvider {+ readonly id = "sourcebot" as const;+ readonly label = "Sourcebot";+ readonly capabilities = new Set<CodeProviderCapability>(CAPABILITIES);+ readonly local: boolean;+ readonly #baseUrl: string;+ readonly #configPath?: string;+ readonly #apiKey?: string;+ readonly #fetch: FetchLike;++ constructor(opts: SourcebotOptions = {}) {+ const env = opts.env ?? process.env;+ this.#baseUrl = (opts.baseUrl ?? env.SOURCEBOT_URL ?? DEFAULT_URL).replace(/\/$/, "");+ this.#configPath = opts.configPath ?? env.SOURCEBOT_CONFIG;+ this.#apiKey = opts.apiKey ?? env.SOURCEBOT_API_KEY;+ this.#fetch = opts.fetch ?? globalThis.fetch;+ this.local = isLoopback(this.#baseUrl);+ assertRequiredCapabilities(this.id, this.capabilities);+ }++ #authHeaders(): Record<string, string> {+ return this.#apiKey ? { Authorization: `Bearer ${this.#apiKey}` } : {};+ }++ has(capability: CodeProviderCapability): boolean {+ return this.capabilities.has(capability);+ }++ /**+ * Add the repo as a local `git` connection in Sourcebot's config.json.+ * NOTE: Sourcebot silently SKIPS a local repo that has no `remote.origin.url`+ * (logs "Skipping <path> - remote.origin.url not found"); a freshly `git init`'d+ * repo must set an origin before it will index.+ */+ async registerSource(repo: RepoRef, opts: OpOptions = {}): Promise<SourceStatus> {+ assertEgressConsent(this, opts); // no-op when the server is loopback (local)+ if (!this.#configPath) {+ throw new CodeProviderError(+ "PROVIDER_UNAVAILABLE",+ "set SOURCEBOT_CONFIG to the server's config.json path to register sources",+ this.id,+ );+ }+ let config: { connections?: Record<string, unknown> };+ try {+ config = existsSync(this.#configPath)+ ? (JSON.parse(readFileSync(this.#configPath, "utf-8")) as typeof config)+ : {};+ } catch (err) {+ throw new CodeProviderError("PROVIDER_ERROR", `unreadable Sourcebot config: ${(err as Error).message}`, this.id);+ }+ config.connections = config.connections ?? {};+ config.connections[repo.id] = { type: "git", url: `file://${repo.path}` };+ // Atomic write so a running Sourcebot never reads a half-written config.+ const tmp = `${this.#configPath}.tmp.${process.pid}`;+ writeFileSync(tmp, JSON.stringify(config, null, 2), "utf-8");+ renameSync(tmp, this.#configPath);+ return { id: repo.id, state: "registered", detail: "Sourcebot re-indexes on config change" };+ }++ /**+ * Sourcebot re-indexes automatically; report current liveness. Refresh is a+ * write-class op (it represents indexing repo content into the server), so a+ * non-loopback server requires per-repo consent even though the HTTP call+ * below is only the liveness probe.+ */+ async refresh(source: SourceRef, opts: OpOptions = {}): Promise<SourceStatus> {+ assertEgressConsent(this, opts); // no-op when the server is loopback (local)+ const live = await this.status(source, opts);+ return { ...live, detail: "Sourcebot re-indexes automatically (config change + reindexIntervalMs)" };+ }++ async search(query: string, opts: SearchOptions = {}): Promise<CodeSearchHit[]> {+ if (!query.trim()) return [];+ // Query text is repo-derived content (sensitive class): a non-loopback+ // server needs per-repo consent BEFORE the query is sent. Fail-closed —+ // the throw happens before any bytes (or any receipt) exist.+ assertEgressConsent(this, opts); // no-op when the server is loopback (local)+ const body = {+ query: opts.source ? `repo:${opts.source} ${query}` : query,+ matches: opts.limit ?? 20,+ isRegexEnabled: true,+ isCaseSensitivityEnabled: false,+ };+ const payload = await this.#post("/api/search", body, opts);+ return parseSourcebotSearch(payload, opts.limit ?? 20);+ }++ async status(_source?: SourceRef, opts: OpOptions = {}): Promise<SourceStatus> {+ // `redirect: manual` so an auth-gated server (307 -> /login) reads as+ // not-usable instead of following to a 200 and falsely reporting "ready".+ // The probe body is a FIXED literal (query "sourcebot") — no repo-derived+ // content — so it is allowed without consent; the receipt records that+ // consent was unchecked instead of pretending it was verified.+ try {+ const res = await this.#fetchWithTimeout(+ `${this.#baseUrl}/api/search`,+ { method: "POST", headers: { "Content-Type": "application/json", ...this.#authHeaders() }, body: JSON.stringify({ query: "sourcebot", matches: 1, isRegexEnabled: false }), redirect: "manual" },+ opts.timeout ?? DEFAULT_TIMEOUT_MS,+ { payloadClass: "liveness-probe (fixed query, no repo-derived content)", consented: opts.consented === true, env: opts.env },+ );+ if (res.status === 401 || res.status === 403) {+ return { id: "*", state: "unknown", partial: true, detail: "reachable but login-gated (enable anonymous access with FORCE_ENABLE_ANONYMOUS_ACCESS=true for local use, or set SOURCEBOT_API_KEY)" };+ }+ return { id: "*", state: res.ok ? "ready" : "unknown", partial: true, detail: `HTTP ${res.status}` };+ } catch {+ return { id: "*", state: "unknown", partial: true, detail: `unreachable at ${this.#baseUrl}` };+ }+ }++ async #post(path: string, body: unknown, opts: OpOptions): Promise<unknown> {+ let res: Response;+ try {+ res = await this.#fetchWithTimeout(`${this.#baseUrl}${path}`, {+ method: "POST",+ headers: { "Content-Type": "application/json", Accept: "application/json", ...this.#authHeaders() },+ body: JSON.stringify(body),+ }, opts.timeout ?? DEFAULT_TIMEOUT_MS, {+ payloadClass: "code-search-request",+ consented: opts.consented === true,+ env: opts.env,+ });+ } catch (err) {+ if (err instanceof CodeProviderError) throw err;+ throw new CodeProviderError("PROVIDER_UNAVAILABLE", `Sourcebot unreachable at ${this.#baseUrl}: ${(err as Error).message}`, this.id);+ }+ if (res.status === 401 || res.status === 403) {+ throw new CodeProviderError("PROVIDER_UNAVAILABLE", `Sourcebot is login-gated (HTTP ${res.status}); enable anonymous access (FORCE_ENABLE_ANONYMOUS_ACCESS=true) for local use, or set SOURCEBOT_API_KEY`, this.id);+ }+ if (!res.ok) throw new CodeProviderError("PROVIDER_ERROR", `Sourcebot ${path} returned HTTP ${res.status}`, this.id);+ try {+ return await res.json();+ } catch (err) {+ throw new CodeProviderError("PROVIDER_ERROR", `Sourcebot returned non-JSON: ${(err as Error).message}`, this.id);+ }+ }++ async #fetchWithTimeout(+ url: string,+ init: RequestInit,+ timeout: number,+ receipt: { payloadClass: string; consented: boolean; env?: NodeJS.ProcessEnv },+ ): Promise<Response> {+ // Every Sourcebot HTTP call routes through here. A loopback server keeps+ // content on this machine (no egress, no receipt); a non-loopback server+ // is an off-machine send and gets a fail-closed receipt BEFORE the fetch.+ // The receipt's consent field records the ACTUAL consent state passed by+ // the op (opts.consented) — the tamper-evident ledger must never attest+ // "consented=true" for a send where nothing checked consent. Content-+ // bearing ops (search/refresh) assert consent before reaching here; the+ // status liveness probe is allowed unconsented and its receipt says so.+ if (!this.local) {+ const body = typeof init.body === "string" ? init.body : "";+ writeReceipt({+ env: receipt.env,+ sink: "sourcebot",+ host: new URL(url).host,+ payloadClass: receipt.payloadClass,+ bytes: Buffer.byteLength(body),+ sha256: sha256Hex(body),+ consent: receipt.consented+ ? "code-intelligence provider=sourcebot (non-loopback SOURCEBOT_URL) + per-repo consented=true"+ : "code-intelligence provider=sourcebot (non-loopback SOURCEBOT_URL) + consent=unchecked (liveness probe only; content-bearing ops assert consent before sending)",+ });+ }+ const controller = new AbortController();+ const timer = setTimeout(() => controller.abort(), timeout);+ try {+ return await this.#fetch(url, { ...init, signal: controller.signal });+ } catch (err) {+ if ((err as Error)?.name === "AbortError") throw new CodeProviderError("PROVIDER_TIMEOUT", "Sourcebot request timed out", this.id);+ throw err;+ } finally {+ clearTimeout(timer);+ }+ }+}++interface SourcebotMatchRange { start?: { lineNumber?: number } }+interface SourcebotChunk { content?: string; matchRanges?: SourcebotMatchRange[] }+interface SourcebotFile { fileName?: { text?: string }; repository?: string; chunks?: SourcebotChunk[] }++/**+ * Map a `POST /api/search` response `{ files: [...] }` to hits: one hit per file,+ * ref = file path, snippet = first matching chunk, kind = "file". Tolerant of a+ * missing/garbage payload (returns []). Exported for deterministic testing.+ */+export function parseSourcebotSearch(payload: unknown, limit: number): CodeSearchHit[] {+ const files = (payload as { files?: unknown })?.files;+ if (!Array.isArray(files)) return [];+ const hits: CodeSearchHit[] = [];+ for (const f of files as SourcebotFile[]) {+ const ref = f?.fileName?.text;+ if (typeof ref !== "string") continue;+ const chunk = f.chunks?.[0];+ const line = chunk?.matchRanges?.[0]?.start?.lineNumber;+ hits.push({+ ref: typeof line === "number" ? `${ref}:${line}` : ref,+ snippet: typeof chunk?.content === "string" ? chunk.content.trim() : undefined,+ kind: "file",+ });+ if (hits.length >= limit) break;+ }+ return hits;+}diff --git a/lib/code-intelligence/suggest.ts b/lib/code-intelligence/suggest.tsnew file mode 100644index 000000000..283d5e076--- /dev/null+++ b/lib/code-intelligence/suggest.ts@@ -0,0 +1,57 @@+/**+ * suggest — should the session-start indexing offer be made for this repo?+ *+ * Portions copyright (c) 2026 Sina Matian, time-attack/gstack (GStack 2), MIT.+ *+ * The offer fires at most once per machine: never when a provider is already+ * selected, never after an explicit decline (`select none`), and never for+ * small repos where grep is already fast. Detection is cheap and local+ * (`git ls-files` count); a non-repo directory never triggers the offer.+ */++import { spawnSync } from "child_process";+import { resolve } from "path";+import { readSelection } from "./selection";++// Single tracked-file-count knob for "large"; add a LOC signal if it misfires.+/** Tracked-file count at which indexing starts paying for itself. */+export const LARGE_REPO_FILE_THRESHOLD = 1000;++export type SuggestReason =+ | "provider-selected"+ | "declined"+ | "not-a-repo"+ | "small-repo"+ | "large-repo";++export interface Suggestion {+ offer: boolean;+ reason: SuggestReason;+ fileCount: number | null;+ threshold: number;+}++/** Count of git-tracked files, or null when the path is not a git repo. */+export function trackedFileCount(repoPath: string): number | null {+ const result = spawnSync("git", ["-C", resolve(repoPath), "ls-files"], {+ encoding: "utf-8",+ maxBuffer: 64 * 1024 * 1024,+ });+ if (result.status !== 0 || typeof result.stdout !== "string") return null;+ const out = result.stdout.trim();+ return out ? out.split("\n").length : 0;+}++export function shouldOfferIndexing(+ repoPath: string,+ opts: { env?: NodeJS.ProcessEnv; threshold?: number } = {},+): Suggestion {+ const threshold = opts.threshold ?? LARGE_REPO_FILE_THRESHOLD;+ const selection = readSelection(opts.env);+ if (selection.provider) return { offer: false, reason: "provider-selected", fileCount: null, threshold };+ if (selection.declined) return { offer: false, reason: "declined", fileCount: null, threshold };+ const fileCount = trackedFileCount(repoPath);+ if (fileCount === null) return { offer: false, reason: "not-a-repo", fileCount, threshold };+ if (fileCount < threshold) return { offer: false, reason: "small-repo", fileCount, threshold };+ return { offer: true, reason: "large-repo", fileCount, threshold };+}diff --git a/lib/context-bill.ts b/lib/context-bill.tsindex bd191004a..b264e72c9 100644--- a/lib/context-bill.ts+++ b/lib/context-bill.ts@@ -222,6 +222,20 @@ function totalMd(dir: string, tokensOf: TokensOf): { bytes: number; tokens: numblet bytes = 0;let tokens = 0;for (const p of walkMd(dir)) {+ // A skill dir that CONTAINS other skill dirs (the gstack root skill wraps+ // the whole tree) must not swallow its children's files: each nested+ // skill reports its own totalMd, and the grand total sums per-skill+ // figures — counting them here again double-counted every nested skill+ // in the TOTAL line (v1.63 deferred polish, fixed in fork port wave 2).+ const rel = path.relative(dir, p);+ const topSeg = rel.split(path.sep)[0];+ if (+ topSeg &&+ topSeg !== rel && // p is inside a subdirectory+ fs.existsSync(path.join(dir, topSeg, "SKILL.md"))+ ) {+ continue;+ }const b = bytesOf(p) ?? 0;bytes += b;tokens += tokensOf(p, b);diff --git a/lib/eval-model.ts b/lib/eval-model.tsnew file mode 100644index 000000000..00e2723ca--- /dev/null+++ b/lib/eval-model.ts@@ -0,0 +1,43 @@+/**+ * Host-neutral eval/harness model resolution (fork port wave 2, G cluster).+ *+ * Model IDs were hardcoded at six call sites across the eval helpers and the+ * distill bin, so an environment that pins a different model (CI cost+ * control, a model migration, an air-gapped proxy alias) had to patch source.+ * One resolution point, env-overridable:+ *+ * GSTACK_EVAL_MODEL_<KIND> (e.g. GSTACK_EVAL_MODEL_WARMUP) — per-kind+ * GSTACK_EVAL_MODEL — global+ * explicit argument — caller wins+ * per-kind default — last resort+ *+ * Kinds and their defaults:+ * capture — AskUserQuestion SDK capture runs (quality matters): opus+ * warmup — PTY warm-up ping (cheapest thing that answers): haiku+ * distill — free-text distillation (cheap, structured): haiku (pinned)+ */++// `as const satisfies` keeps EvalModelKind the literal union+// 'capture' | 'warmup' | 'distill' — a `Record<string, string>` annotation+// would widen it to string and let any typo through the type gate.+const DEFAULTS = {+ capture: "claude-opus-4-7",+ warmup: "claude-haiku-4-5",+ distill: "claude-haiku-4-5-20251001",+} as const satisfies Record<string, string>;++export type EvalModelKind = keyof typeof DEFAULTS;++export function resolveEvalModel(+ kind: EvalModelKind,+ explicit?: string | null,+ env: NodeJS.ProcessEnv = process.env,+): string {+ if (explicit) return explicit;+ const perKind = env[`GSTACK_EVAL_MODEL_${kind.toUpperCase()}`];+ if (perKind) return perKind;+ if (env.GSTACK_EVAL_MODEL) return env.GSTACK_EVAL_MODEL;+ const fallback = DEFAULTS[kind];+ if (!fallback) throw new Error(`resolveEvalModel: unknown kind "${kind}"`);+ return fallback;+}diff --git a/lib/gbrain-repo-policy-client.ts b/lib/gbrain-repo-policy-client.tsnew file mode 100644index 000000000..dc5a368ad--- /dev/null+++ b/lib/gbrain-repo-policy-client.ts@@ -0,0 +1,84 @@+/**+ * gbrain-repo-policy-client — the ONE TypeScript client for the per-remote+ * trust store (bin/gstack-gbrain-repo-policy, a bash CLI that owns URL+ * normalization and schema migration — do not reimplement either here).+ *+ * Extracted because two call sites (lib/code-intelligence/selection.ts consent+ * veto; bin/gstack-gbrain-sync.ts code-import gate) each spawnSync'd the script+ * themselves and had started to drift. On win32, spawning a+ * `#!/usr/bin/env bash` script directly fails ENOENT, which both sites'+ * fail-closed paths then reported as "store could not be read" for EVERY repo+ * — so this client invokes the script through `bash` there (an ENOENT then+ * genuinely means "no bash on PATH") and reports a spawn failure distinctly+ * from a policy-read failure, so callers can say what actually broke.+ *+ * POLARITY IS THE CALLER'S. This client only reads and classifies; each call+ * site keeps its own fail-open / fail-closed decision on `error`.+ */++import { spawnSync } from "child_process";+import { existsSync } from "fs";+import { homedir } from "os";+import { join } from "path";++export type RepoPolicyTierValue = "deny" | "read-only" | "read-write" | "none";++export interface RepoPolicyResult {+ /** `none` = no policy store, no remote URL, or no entry for this remote. */+ tier: RepoPolicyTierValue;+ /**+ * Set when the tier could not be determined (tier is `none` then):+ * - `spawn-failed`: the policy script could not be executed at all+ * (script missing, or no bash on PATH on win32) — the store itself may+ * be perfectly fine.+ * - `unreadable`: the script ran but could not read the store+ * (permissions, corruption, unexpected output).+ */+ error?: "unreadable" | "spawn-failed";+}++/** Absolute path of the policy store for this env (GSTACK_HOME-aware). */+export function repoPolicyStorePath(env: NodeJS.ProcessEnv = process.env): string {+ const home = env.GSTACK_HOME || join(env.HOME || homedir(), ".gstack");+ return join(home, "gbrain-repo-policy.json");+}++/** No store on disk = no policy was ever set (the fast path — no subprocess). */+export function hasRepoPolicyStore(env: NodeJS.ProcessEnv = process.env): boolean {+ return existsSync(repoPolicyStorePath(env));+}++/** The bash script that owns the store — resolved relative to this file (lib/ → bin/), never cwd. */+const POLICY_SCRIPT = join(import.meta.dir, "..", "bin", "gstack-gbrain-repo-policy");++/**+ * Trust tier for a remote URL, via `gstack-gbrain-repo-policy get <url>`.+ *+ * Fast paths (no subprocess): no store on disk → `none`; no remote URL →+ * `none` (policy is keyed by origin remote, so nothing can be set for the+ * repo). Everything else shells to the script, which owns normalization.+ */+export function repoPolicyTier(url: string | null, env: NodeJS.ProcessEnv = process.env): RepoPolicyResult {+ if (!hasRepoPolicyStore(env)) return { tier: "none" };+ if (!url) return { tier: "none" };+ // The script is `#!/usr/bin/env bash`; win32 can't exec a shebang file, so+ // invoke through bash there. An ENOENT then means bash is not on PATH.+ const [cmd, args]: [string, string[]] =+ process.platform === "win32" ? ["bash", [POLICY_SCRIPT, "get", url]] : [POLICY_SCRIPT, ["get", url]];+ const res = spawnSync(cmd, args, {+ encoding: "utf-8",+ timeout: 10_000,+ // Explicit env: Bun's spawnSync default env snapshot misses runtime+ // process.env mutations (e.g. tests redirecting GSTACK_HOME).+ env: { ...env } as NodeJS.ProcessEnv,+ });+ if (res.error) {+ const code = (res.error as NodeJS.ErrnoException).code;+ return { tier: "none", error: code === "ENOENT" ? "spawn-failed" : "unreadable" };+ }+ if (res.status !== 0) return { tier: "none", error: "unreadable" };+ const tier = (res.stdout || "").trim();+ if (tier === "deny" || tier === "read-only" || tier === "read-write") return { tier };+ if (tier === "unset") return { tier: "none" };+ return { tier: "none", error: "unreadable" }; // unexpected output — a read failure, not a tier+}diff --git a/make-pdf/src/render.ts b/make-pdf/src/render.tsindex fa03c9eb3..609c63e0a 100644--- a/make-pdf/src/render.ts+++ b/make-pdf/src/render.ts@@ -208,6 +208,10 @@ function decodeTypographicEntities(html: string): string {* - on* event handler attributes (onclick, ONCLICK, etc.).* - href/src with javascript: scheme.* - <svg> tags with <script> inside them.+ * - remote href/xlink:href inside <svg> (and on svg-only elements anywhere)+ * → "#" (offline posture: no fetch at print time).+ * - remote CSS fetch vectors in <style> blocks and style attributes+ * (@import, url(), image-set() with remote string candidates).*/export function sanitizeUntrustedHtml(html: string): string {let s = html;@@ -249,6 +253,139 @@ export function sanitizeUntrustedHtml(html: string): string {// style="url(javascript:..)" — strip javascript: inside style attrs.s = s.replace(/url\(\s*javascript:[^)]*\)/gi, "url(#)");+ // ── Offline-posture fetch vectors (no --allow-network must mean no network+ // at print time; the image inliner covers <img src> only, and must keep+ // seeing remote <img src> so its blocked-remote placeholder still fires) ──++ // Untrusted CSS neutralization. Scoped to <style> blocks and style+ // attributes below so prose/code samples that mention URLs stay untouched.+ //+ // Chromium decodes CSS ident/string escapes (\69 → i, \68 → h) before+ // fetching, so literal patterns alone are bypassable: @\69mport dodges+ // /@import\b/, url("\68ttps://…") dodges the https?://-shaped remote-url+ // pattern, and u\72l(…) dodges the url( prefix itself. Untrusted styling+ // has no legitimate need for escaped url schemes or at-rule names, so any+ // construct carrying a backslash escape is dropped/defanged (fail closed).+ // In style ATTRIBUTES the HTML parser also entity-decodes before the CSS+ // parser runs, so \ / \ / \ spellings of the backslash count+ // as escapes too. (<style> content is raw text — no entity layer there.)+ const CSS_ESCAPE_MARKER = /\\|�*92(?![0-9])|�*5c(?![0-9a-f])|\/i;+ const neutralizeUntrustedCss = (css: string): string => {+ // (a) At-rules whose keyword carries a backslash escape (@\69mport …):+ // drop the whole statement through `;`, `{`, or end-of-value.+ let out = css.replace(+ /@[-\w\\&#;]*?(?:\\|�*92(?![0-9]);?|�*5c(?![0-9a-f]);?|\)[-\w\\&#;]*[^;{}]*(?:;|\{|$)/gi,+ "");+ // (b) Literal @import is always a fetch (relative ones can't resolve+ // under load-html either) — drop outright.+ out = out.replace(/@import\b[^;]*(;|$)/gi, "");+ // (c) Any function-like token whose name or arguments carry a backslash+ // escape → url(#). Covers escaped schemes (url("\68ttps://…")) and+ // escaped function names (u\72l(…)) in one fail-closed pass. The+ // end-of-value alternative closes the unterminated-url() dodge:+ // Chromium's CSS parser closes an open function token at EOF.+ out = out.replace(/[-\w\\&#;][-\w \t\\&#;]*\(\s*[^)]*(?:\)|$)/g, (m) =>+ CSS_ESCAPE_MARKER.test(m) ? "url(#)" : m);+ // (d) Remote url(...) → url(#).+ out = out.replace(+ /url\(\s*(?:"|�?39;|'|["'])?\s*(?:https?:)?\/\/[^)]*(?:\)|$)/gi,+ "url(#)");+ // (e) image-set() / -webkit-image-set() accept BARE quoted URL strings —+ // no url() token, no backslash — so passes (c)/(d) never fire on+ // `image-set("https://…" 1x)`. Any image-set whose arguments carry a+ // remote-scheme quoted string → url(#) (fail closed). Local string+ // candidates stay; url()-form arguments are already covered by (c)/(d).+ out = out.replace(/(?:-webkit-)?image-set\(\s*[^)]*(?:\)|$)/gi, (m) =>+ /(?:"|�?39;|'|["'])\s*(?:https?:)?\/\//i.test(m) ? "url(#)" : m);+ return out;+ };++ // Raw-HTML <style> blocks. Element content is RAW TEXT — the HTML parser+ // never entity-decodes it — so unlike style attributes below, no entity+ // decode step is needed (or correct) here.+ s = s.replace(/(<style\b[^>]*>)([\s\S]*?)(<\/style>)/gi, (_m, open, css, close) =>+ open + neutralizeUntrustedCss(css) + close);++ // Style ATTRIBUTE values are entity-decoded by the HTML parser before the+ // CSS parser ever runs, so https://… reaches Chromium as https://… and+ // // as // — dodging every literal pattern above. Decode the value+ // the way the parser will (numeric dec/hex refs with the spec's optional+ // semicolon; the syntax-significant named refs; the legacy semicolonless+ // four), in ONE left-to-right pass so the sanitizer performs exactly the+ // browser's single decode round — decoding recursively would turn a+ // double-encoded &#104; into a live scheme the browser never sees.+ const NAMED_REFS: Record<string, string> = {+ amp: "&", lt: "<", gt: ">", quot: '"', apos: "'",+ sol: "/", bsol: "\\", colon: ":", semi: ";", num: "#",+ lpar: "(", rpar: ")", commat: "@", grave: "`",+ Tab: "\t", NewLine: "\n",+ };+ const refCodePoint = (n: number): string =>+ (!Number.isFinite(n) || n <= 0 || n > 0x10ffff || (n >= 0xd800 && n <= 0xdfff))+ ? "�" : String.fromCodePoint(n);+ const decodeStyleAttrEntities = (v: string): string => v.replace(+ /&(?:#[xX]([0-9a-fA-F]+);?|#(\d+);?|([a-zA-Z]+);|(amp|lt|gt|quot)(?![a-zA-Z0-9=;]))/g,+ (m, hex, dec, named, legacy) => {+ if (hex !== undefined) return refCodePoint(parseInt(hex, 16));+ if (dec !== undefined) return refCodePoint(parseInt(dec, 10));+ if (named !== undefined) return NAMED_REFS[named] ?? m;+ return NAMED_REFS[legacy];+ });++ // Inline style attributes — quoted AND unquoted. HTML spec: an unquoted+ // attribute value runs until whitespace or `>`, so+ // <div style=background:url(https://…)> is live markup Chromium honors;+ // a quoted-only pattern misses it. The value is unquoted, entity-decoded+ // (see above), neutralized in decoded form, then RE-ENCODED and emitted+ // double-quoted — never emit decoded text raw (a decoded `"` would break+ // out of the attribute) and the re-encode also keeps once-decoded text like+ // h inert instead of granting it a second decode round.+ s = s.replace(/(\s+style\s*=\s*)(?:"([^"]*)"|'([^']*)'|([^\s"'>][^\s>]*))/gi,+ (_m, pre, dq, sq, uq) => {+ const raw = dq ?? sq ?? uq;+ const cleaned = neutralizeUntrustedCss(decodeStyleAttrEntities(raw));+ return `${pre}"${escapeHtml(cleaned)}"`;+ });++ // SVG remote-fetch vectors: <image href>, <use href>, <feImage href> (and+ // their xlink:href spellings) fetch at print time — the svg handling above+ // only strips <script>, and the javascript:-scheme rewrite doesn't touch a+ // plain https:// href. Fail closed: inside an <svg> block, ANY href /+ // xlink:href whose entity-decoded value is remote (https?:// or //) is+ // rewritten to "#"; local fragment refs (href="#id") and local files stay+ // intact. The tag-scoped second pass catches svg-only elements smuggled+ // through an UNCLOSED <svg> (Chromium auto-closes at EOF and still+ // fetches); outside foreign content those tags are inert or parser-mapped+ // to <img> (href ignored), so the extra pass can't break plain HTML —+ // regular <a href> hyperlinks are untouched (links don't fetch at print).+ const neutralizeRemoteSvgHref = (fragment: string): string =>+ fragment.replace(+ /(\s(?:xlink:)?href\s*=\s*)("([^"]*)"|'([^']*)'|[^\s>]+)/gi,+ (m, pre, val, dq, sq) => {+ // Decode the value the way the HTML parser will (same single-round+ // decode as style attributes above), then drop the tab/newline/CR+ // characters URL parsing ignores, so https and h\nttps count.+ const raw = dq ?? sq ?? String(val);+ const decoded = decodeStyleAttrEntities(raw).replace(/[\t\n\r]/g, "");+ return /^\s*(?:https?:)?\/\//i.test(decoded) ? `${pre}"#"` : m;+ });+ s = s.replace(/<svg\b[\s\S]*?<\/svg>/gi, neutralizeRemoteSvgHref);+ s = s.replace(/<(?:image|use|feimage)\b[^>]*>/gi, neutralizeRemoteSvgHref);++ // srcset with a remote candidate: Chromium prefers srcset over the inlined+ // src, so a remote candidate fetches at print time. Strip the attribute;+ // local/data: srcset values are left alone.+ const remoteSrcsetCandidate = /(?:^|[,\s])\s*(?:https?:)?\/\//i;+ s = s.replace(/\s+srcset\s*=\s*("[^"]*"|'[^']*'|[^\s>]+)/gi, (m, val) =>+ remoteSrcsetCandidate.test(String(val).replace(/^["']|["']$/g, "")) ? "" : m);++ // Remote src/poster on media elements (<video poster>, <source src>, …).+ s = s.replace(/<(?:video|audio|source|track)\b[^>]*>/gi, (tag) =>+ tag.replace(+ /(\s(?:src|poster)\s*=\s*)(?:"(?:https?:)?\/\/[^"]*"|'(?:https?:)?\/\/[^']*'|(?:https?:)?\/\/[^\s>]+)/gi,+ '$1"#"',+ ));+return s;}diff --git a/make-pdf/test/render-offline-sanitize.test.ts b/make-pdf/test/render-offline-sanitize.test.tsnew file mode 100644index 000000000..609ac02a7--- /dev/null+++ b/make-pdf/test/render-offline-sanitize.test.ts@@ -0,0 +1,268 @@+/**+ * Offline-posture sanitizer tests — raw-HTML fetch vectors beyond <img src>+ * (which the image inliner owns). No Playwright, no PDF generation.+ *+ * Regression for: <style>@import, inline style="…url(https://…)…", and+ * <img srcset> surviving sanitizeUntrustedHtml, letting Chromium fetch+ * remote resources at print time with no --allow-network.+ */++import { describe, expect, test } from "bun:test";++import { render, sanitizeUntrustedHtml } from "../src/render";++describe("sanitizeUntrustedHtml (offline fetch vectors)", () => {+ test("strips @import url(...) from raw <style> blocks, keeps legit rules", () => {+ const input = `<style>@import url("https://evil.example/track.css");\nh1 { color: red; }</style>`;+ const out = sanitizeUntrustedHtml(input);+ expect(out).not.toContain("@import");+ expect(out).not.toContain("evil.example");+ expect(out).toContain("color: red");+ });++ test("strips string-form @import (no url())", () => {+ const out = sanitizeUntrustedHtml(`<style>@import "https://evil.example/a.css";</style>`);+ expect(out).not.toContain("@import");+ expect(out).not.toContain("evil.example");+ });++ test("neutralizes remote url() inside <style> blocks", () => {+ const input = `<style>body { background: url(https://evil.example/px.gif); color: blue; }</style>`;+ const out = sanitizeUntrustedHtml(input);+ expect(out).not.toContain("evil.example");+ expect(out).toContain("url(#)");+ expect(out).toContain("color: blue");+ });++ test("neutralizes remote url() in inline style attributes", () => {+ const input = `<div style="background:url(https://evil.example/px.gif);padding:4px">x</div>`;+ const out = sanitizeUntrustedHtml(input);+ expect(out).not.toContain("evil.example");+ expect(out).toContain("url(#)");+ expect(out).toContain("padding:4px");+ });++ test("neutralizes protocol-relative url(//…) in style attributes", () => {+ const out = sanitizeUntrustedHtml(`<div style="background:url(//evil.example/px.gif)">x</div>`);+ expect(out).not.toContain("evil.example");+ });++ // ── Bypass regressions: unquoted style attributes ──+ // HTML spec: an unquoted attribute value runs until whitespace or `>`, so+ // <div style=background:url(https://…)> is live markup Chromium honors.+ // The original neutralizer only rewrote quoted values.++ test("neutralizes remote url() in UNQUOTED style attributes", () => {+ const out = sanitizeUntrustedHtml(`<div style=background:url(https://evil.example/px.gif)>x</div>`);+ expect(out).not.toContain("evil.example");+ expect(out).toContain("url(#)");+ });++ test("keeps local url() in unquoted style attributes functional", () => {+ const out = sanitizeUntrustedHtml(`<div style=background:url(local.png)>x</div>`);+ expect(out).toContain("url(local.png)");+ });++ // ── Bypass regressions: CSS-escape obfuscation ──+ // Chromium decodes CSS ident/string escapes before fetching, so \69 → i and+ // \68 → h defeat literal-pattern matching. Untrusted styling has no+ // legitimate need for escaped url schemes or at-rule names — fail closed.++ test("drops CSS-escaped @import (@\\69mport url(...)) in <style> blocks", () => {+ const out = sanitizeUntrustedHtml(`<style>@\\69mport url("https://evil.example/a.css");</style>`);+ expect(out).not.toContain("evil.example");+ expect(out).not.toMatch(/@\\/); // no escaped at-rule survives for Chromium to decode+ });++ test("drops CSS-escaped string-form @import (@\\69mport \"https://…\")", () => {+ const out = sanitizeUntrustedHtml(`<style>@\\69mport "https://evil.example/a.css";</style>`);+ expect(out).not.toContain("evil.example");+ expect(out).not.toMatch(/@\\/);+ });++ test("neutralizes CSS-escaped scheme inside url() (\\68ttps://…)", () => {+ const out = sanitizeUntrustedHtml(`<style>body{background:url("\\68ttps://evil.example/px.gif")}</style>`);+ expect(out).not.toContain("evil.example");+ });++ test("neutralizes CSS-escaped function names (u\\72l(https://…))", () => {+ const out = sanitizeUntrustedHtml(`<style>body{background:u\\72l(https://evil.example/px.gif)}</style>`);+ expect(out).not.toContain("evil.example");+ });++ test("neutralizes HTML-entity-encoded backslash escapes in style attributes", () => {+ // Attribute values are entity-decoded by the HTML parser before the CSS+ // parser runs, so \68ttps reaches Chromium as \68ttps → https.+ const out = sanitizeUntrustedHtml(`<div style="background:url('\68ttps://evil.example/px.gif')">x</div>`);+ expect(out).not.toContain("evil.example");+ });++ // ── Bypass regressions: non-backslash entity obfuscation in style attrs ──+ // The same attribute entity layer can hide ANY character of a fetch vector,+ // not just backslashes: h → h, / → /. <style> BLOCKS don't need+ // this handling — element content is raw text, never attribute-decoded.++ test("neutralizes numeric-entity-obfuscated scheme in style attributes (https)", () => {+ const out = sanitizeUntrustedHtml(`<div style="background:url(https://evil.example/px.gif)">x</div>`);+ expect(out).not.toContain("evil.example");+ });++ test("neutralizes entity-obfuscated slashes in style attributes (// for //)", () => {+ const out = sanitizeUntrustedHtml(`<div style="background:url(https://evil.example/px.gif)">x</div>`);+ expect(out).not.toContain("evil.example");+ });++ test("neutralizes entity-obfuscated url( name in style attributes (url)", () => {+ const out = sanitizeUntrustedHtml(`<div style="background:url(https://evil.example/px.gif)">x</div>`);+ expect(out).not.toContain("evil.example");+ });++ test("entity-decoded local styles stay functional and safely re-encoded", () => {+ const out = sanitizeUntrustedHtml(`<div style="content:"hi";background:url(local.png)">x</div>`);+ expect(out).toContain("url(local.png)");+ expect(out).toContain(""hi"");+ });++ test("double-encoded entities are not double-decoded into a live scheme", () => {+ // Browser decodes &#104; exactly once → literal https://… text,+ // which is not a scheme. The sanitizer must mirror that single decode:+ // decoding twice would CREATE url(https://…) where the browser sees none.+ const out = sanitizeUntrustedHtml(`<div style="background:url(&#104;ttps://evil.example/px.gif)">x</div>`);+ expect(out).not.toMatch(/url\(\s*https:/);+ });++ test("strips srcset with a remote candidate, leaves src for the inliner", () => {+ const input = `<img src="local.png" srcset="local.png 1x, https://evil.example/x.png 2x">`;+ const out = sanitizeUntrustedHtml(input);+ expect(out).not.toContain("srcset");+ expect(out).not.toContain("evil.example");+ expect(out).toContain(`src="local.png"`);+ });++ test("strips unquoted remote srcset", () => {+ const out = sanitizeUntrustedHtml(`<img src="a.png" srcset=https://evil.example/x.png>`);+ expect(out).not.toContain("evil.example");+ });++ test("keeps local-only srcset (no network vector)", () => {+ const input = `<img src="a.png" srcset="a.png 1x, [email protected] 2x">`;+ expect(sanitizeUntrustedHtml(input)).toContain(`srcset="a.png 1x, [email protected] 2x"`);+ });++ // ── Bypass regressions: SVG remote-fetch vectors ──+ // The svg handling only stripped <script> and the javascript: scheme, so a+ // plain https:// href on <image>/<use>/<feImage> survived and Chromium+ // fetched it at print time.++ test("neutralizes remote <image href> inside <svg> blocks", () => {+ const out = sanitizeUntrustedHtml(`<svg><image href="https://evil.example/x.png"/></svg>`);+ expect(out).not.toContain("evil.example");+ expect(out).toContain(`href="#"`);+ });++ test("neutralizes remote <use xlink:href> inside <svg> blocks", () => {+ const out = sanitizeUntrustedHtml(`<svg><use xlink:href="https://evil.example/defs.svg#icon"/></svg>`);+ expect(out).not.toContain("evil.example");+ });++ test("neutralizes protocol-relative and unquoted svg hrefs", () => {+ const out = sanitizeUntrustedHtml(`<svg><image href=//evil.example/x.png /><use href='//evil.example/d.svg#i'/></svg>`);+ expect(out).not.toContain("evil.example");+ });++ test("neutralizes remote svg-element href even when the <svg> is never closed", () => {+ // Chromium auto-closes an unclosed <svg> at EOF and still fetches.+ const out = sanitizeUntrustedHtml(`<svg><image href="https://evil.example/x.png">`);+ expect(out).not.toContain("evil.example");+ });++ test("neutralizes entity-obfuscated remote svg href (https)", () => {+ const out = sanitizeUntrustedHtml(`<svg><image href="https://evil.example/x.png"/></svg>`);+ expect(out).not.toContain("evil.example");+ });++ test("keeps local fragment href (#id) inside svg intact", () => {+ const input = `<svg><defs><circle id="dot" r="2"/></defs><use href="#dot"/><use xlink:href="#dot"/></svg>`;+ const out = sanitizeUntrustedHtml(input);+ expect(out).toContain(`href="#dot"`);+ expect(out).toContain(`xlink:href="#dot"`);+ });++ test("keeps local-file svg <image href> intact", () => {+ expect(sanitizeUntrustedHtml(`<svg><image href="local.png"/></svg>`)).toContain(`href="local.png"`);+ });++ test("leaves regular <a href=\"https://…\"> hyperlinks alone (links don't fetch at print)", () => {+ const input = `<a href="https://example.com/docs">docs</a>`;+ expect(sanitizeUntrustedHtml(input)).toContain(`href="https://example.com/docs"`);+ });++ // ── Bypass regressions: image-set() with bare quoted URL strings ──+ // `image-set("https://…" 1x)` carries no url() token and no backslash, so+ // the url()/escape passes never fired on it.++ test("neutralizes remote image-set(...) in <style> blocks", () => {+ const input = `<style>body { background: image-set("https://evil.example/a.png" 1x); color: blue; }</style>`;+ const out = sanitizeUntrustedHtml(input);+ expect(out).not.toContain("evil.example");+ expect(out).toContain("url(#)");+ expect(out).toContain("color: blue");+ });++ test("neutralizes remote image-set(...) in style attributes", () => {+ const out = sanitizeUntrustedHtml(`<div style="background: image-set('https://evil.example/a.png' 1x)">x</div>`);+ expect(out).not.toContain("evil.example");+ });++ test("neutralizes -webkit-image-set with a remote string argument", () => {+ const out = sanitizeUntrustedHtml(`<style>body{background:-webkit-image-set("//evil.example/a.png" 1x)}</style>`);+ expect(out).not.toContain("evil.example");+ });++ test("keeps local image-set(...) functional", () => {+ const input = `<style>body { background: image-set("local.png" 1x, "[email protected]" 2x); }</style>`;+ expect(sanitizeUntrustedHtml(input)).toContain(`image-set("local.png" 1x, "[email protected]" 2x)`);+ });++ test("neutralizes remote <video poster> and <source src>", () => {+ const input = `<video poster="https://evil.example/p.jpg"><source src="https://evil.example/v.mp4"></video>`;+ const out = sanitizeUntrustedHtml(input);+ expect(out).not.toContain("evil.example");+ });++ test("leaves remote <img src> alone — the image inliner owns its blocked-remote placeholder", () => {+ const input = `<img src="https://evil.example/px.gif">`;+ expect(sanitizeUntrustedHtml(input)).toContain(`src="https://evil.example/px.gif"`);+ });++ test("does NOT rewrite url(https://…) mentioned in code/prose text", () => {+ // marked entity-encodes quotes in code spans, so this is plain text+ // outside any <style> block or style attribute — must stay intact.+ const input = `<code>background: url(https://example.com/a.png)</code>`;+ expect(sanitizeUntrustedHtml(input)).toContain("url(https://example.com/a.png)");+ });++ test("end-to-end: rendered document carries no remote fetch vector from raw HTML", () => {+ const md = [+ "# Doc",+ `<style>@import url("https://evil.example/t.css"); h1{color:red}</style>`,+ `<div style="background:url('https://evil.example/px.gif')">hi</div>`,+ `<img src="a.png" srcset="https://evil.example/a.png 2x">`,+ `<svg><image href="https://evil.example/s.png"/><use xlink:href="https://evil.example/d.svg#i"/></svg>`,+ `<div style="background:image-set('https://evil.example/is.png' 1x)">x</div>`,+ ].join("\n\n");+ const { bodyHtml } = render({ markdown: md });+ expect(bodyHtml).not.toContain("evil.example");+ });++ test("end-to-end: unquoted and CSS-escaped vectors don't survive render()", () => {+ const md = [+ "# Doc",+ `<style>@\\69mport "https://evil.example/b.css"; body{background:url("\\68ttps://evil.example/px.gif")}</style>`,+ `<div style=background:url(https://evil.example/px.gif)>hi</div>`,+ ].join("\n\n");+ const { bodyHtml } = render({ markdown: md });+ expect(bodyHtml).not.toContain("evil.example");+ expect(bodyHtml).not.toMatch(/@\\/);+ });+});diff --git a/office-hours/SKILL.md b/office-hours/SKILL.mdindex 6dbaa455f..9c7dc5cad 100644--- a/office-hours/SKILL.md+++ b/office-hours/SKILL.md@@ -711,6 +711,10 @@ When options differ in coverage, include `Completeness: X/10` (10 = all edge casFor high-stakes ambiguity (architecture, data model, destructive scope, missing context), STOP. Name it in one sentence, present 2-3 options with tradeoffs, and ask. Do not use for routine coding or obvious changes.+## Claimed Limitations Need Evidence++A claimed limitation or requirement ("the API can't do this", "X requires a credential", "that's impossible on this platform") is a material claim. State one only with the verbatim error, the documented statement, or a live probe in hand — pattern-matching a failure to a familiar story is not evidence. When a cheap probe settles the question, run it BEFORE asking the user anything or declaring a step blocked.+## Continuous Checkpoint ModeIf `CHECKPOINT_MODE` is `"continuous"`: auto-commit completed logical units with `WIP:` prefix.@@ -841,6 +845,20 @@ the failure occurred (if outcome is error, otherwise use empty string "").Skills that run plan reviews (`/plan-*-review`, `/codex review`) include the EXIT PLAN MODE GATE blocking checklist at the end of the skill, which verifies the plan file ends with `## GSTACK REVIEW REPORT` before ExitPlanMode is called. Skills that don't run plan reviews (operational skills like `/ship`, `/qa`, `/review`) typically don't operate in plan mode and have no review report to verify; this footer is a no-op for them. Writing the plan file is the one edit allowed in plan mode.+## Third-Party Web Actions++A step sometimes requires action on an external website the user controls: registering an API key, creating a vendor or developer account, configuring a dashboard, webhook, OAuth app, billing plan, or domain verification. This contract governs that moment. It grants no new browsing authority — the AskUserQuestion format and one-way-door rules remain binding, including approval before anything that spends money.++1. **Never hand the user a manual step list for a third-party site without first offering to drive it.** The driver is gstack's own browser stack: `$B` headed mode with handoff/resume for the human-only moments (see the /browse skill), or GStack Browser when installed. Never install new tooling to close the gap, and never treat tooling presence as consent to browse.++2. **One explicit question before any browsing.** STOP and name the exact site and the exact actions (for example "create a test-mode API token in the Duffel dashboard"), then offer: A) I drive it now in a visible browser — you take over for sign-in and approvals, B) manual instructions, C) defer. The selection is per-task consent; never persist it as standing permission and never infer it from an earlier task.++3. **When driving, touch only the named site and actions.** Password entry, new-account credential choice, payment, CAPTCHA, and identity verification are user-performed: hand off (`$B handoff`) and wait instead of acting. Prefer credential flows that never expose the secret to the agent, such as password-manager autofill or the dashboard's own copy button used by the human.++4. **A captured secret never appears in chat output, logs, or shell history.** Write it to a user-approved local file with owner-only permissions (0600) or the user's secret store, and keep generated destinations out of version control. Dashboard fields are often masked placeholders — verify the captured credential with ONE non-mutating API call before claiming success; a 401 here has caught a placeholder masquerading as a key.++5. **If the user declines or defers, or no browser is usable,** provide the manual steps and mark the step blocked on the user. Do not recommend or install new products to close the gap.+## SETUP (run this check BEFORE any browse command)```bashdiff --git a/office-hours/SKILL.md.tmpl b/office-hours/SKILL.md.tmplindex 8568fe73c..80deddab6 100644--- a/office-hours/SKILL.md.tmpl+++ b/office-hours/SKILL.md.tmpl@@ -59,6 +59,8 @@ gbrain:{{PREAMBLE}}+{{THIRD_PARTY_ACTIONS}}+{{BROWSE_SETUP}}# YC Office Hoursdiff --git a/office-hours/sections/design-and-handoff.md b/office-hours/sections/design-and-handoff.mdindex 4c253e96a..3bf507c9e 100644--- a/office-hours/sections/design-and-handoff.md+++ b/office-hours/sections/design-and-handoff.md@@ -19,8 +19,32 @@ If `$PRIOR` exists, the new doc gets a `Supersedes:` field referencing it. ThisWrite to `~/.gstack/projects/{slug}/{user}-{branch}-design-{datetime}.md`.-After writing the design doc, tell the user:-**"Design doc saved to: {full path}. Other skills (/plan-ceo-review, /plan-eng-review) will find it automatically."**+**Repo copy (dual-write, #703 + #2000).** When the session runs inside a git+repository, ALSO write the doc to `docs/designs/{topic-slug}.md` in the repo —+visible, committable, team-shareable. The `~/.gstack` copy is still written+(memory ingest and cross-session discovery depend on it); the repo copy is+what teammates and plan reviews read. Rules:++1. **Scan at sink first.** The repo copy leaves the private store, so scan the+ EXACT bytes before writing: write to a temp file, run+ `~/.claude/skills/gstack/bin/gstack-redact --from-file <tmp>`; exit 3+ (HIGH) blocks the repo copy (keep the ~/.gstack copy, tell the user why);+ exit 2 (MEDIUM) confirms per finding before writing.+2. **Fallback is never blocking.** Read-only checkout, non-git directory, a+ failed write, or an unconfirmed MEDIUM → keep the `~/.gstack` copy and say+ in one line why the repo copy was skipped. The handoff continues either way.+3. **Name the repo path** in the handoff line and any approval questions when+ the repo copy exists — that's the copy the user can open and commit.++**Decision-record concision (#2000).** The doc is a decision record, not a+transcript: one bullet per decision with its why; an approach the user ruled+out DURING the session gets one line (name + rejection reason), never a+resurrected full section that re-argues the case; omit template sections that+are empty or that restate what's already settled. No page cap — extra length+must come from genuinely open questions, not template completeness.++After writing, tell the user:+**"Design doc saved to: {repo path if written, else ~/.gstack path}{when both: ' (cross-session copy in ~/.gstack)'}. Other skills (/plan-ceo-review, /plan-eng-review) will find it automatically."**### Startup mode design doc template:@@ -427,9 +451,32 @@ Then proceed to Founder Resources below.### Founder Resources (all tiers)+**Standing opt-out check (#538) — run FIRST:**++```bash+~/.claude/skills/gstack/bin/gstack-config get founder_resources 2>/dev/null || echo "true"+```++If the value is `false`, **skip this entire section silently** — no resources,+no "skipped as requested" mention. The user said never; config outlives+session context and memory instructions, so never means never. (Re-enable:+`gstack-config set founder_resources true`.)+Share 2-3 resources from the pool below. For repeat users, resources compound by matchingto accumulated session context, not just this session's category.+**After sharing, close with the standing choice** (one line, not a ceremony):++> Want these? I can open any of them — or say "never show me these again" and+> this section disappears for good.++If the user opts out (any clear phrasing of never/stop showing these): run+`~/.claude/skills/gstack/bin/gstack-config set founder_resources false`, then+VERIFY the write (`gstack-config get founder_resources` must read back+`false`) before promising anything — if the write failed, say so and skip for+this session only. On success confirm in one line with the re-enable command+and continue the handoff.+**Dedup check:** Read `RESOURCES_SHOWN` from the builder profile output above.If `RESOURCES_SHOWN_COUNT` is 34 or more, skip this section entirely (all resources exhausted).Otherwise, avoid selecting any URL that appears in the RESOURCES_SHOWN list.diff --git a/office-hours/sections/design-and-handoff.md.tmpl b/office-hours/sections/design-and-handoff.md.tmplindex a8f8c5aac..5924dd706 100644--- a/office-hours/sections/design-and-handoff.md.tmpl+++ b/office-hours/sections/design-and-handoff.md.tmpl@@ -17,8 +17,32 @@ If `$PRIOR` exists, the new doc gets a `Supersedes:` field referencing it. ThisWrite to `~/.gstack/projects/{slug}/{user}-{branch}-design-{datetime}.md`.-After writing the design doc, tell the user:-**"Design doc saved to: {full path}. Other skills (/plan-ceo-review, /plan-eng-review) will find it automatically."**+**Repo copy (dual-write, #703 + #2000).** When the session runs inside a git+repository, ALSO write the doc to `docs/designs/{topic-slug}.md` in the repo —+visible, committable, team-shareable. The `~/.gstack` copy is still written+(memory ingest and cross-session discovery depend on it); the repo copy is+what teammates and plan reviews read. Rules:++1. **Scan at sink first.** The repo copy leaves the private store, so scan the+ EXACT bytes before writing: write to a temp file, run+ `~/.claude/skills/gstack/bin/gstack-redact --from-file <tmp>`; exit 3+ (HIGH) blocks the repo copy (keep the ~/.gstack copy, tell the user why);+ exit 2 (MEDIUM) confirms per finding before writing.+2. **Fallback is never blocking.** Read-only checkout, non-git directory, a+ failed write, or an unconfirmed MEDIUM → keep the `~/.gstack` copy and say+ in one line why the repo copy was skipped. The handoff continues either way.+3. **Name the repo path** in the handoff line and any approval questions when+ the repo copy exists — that's the copy the user can open and commit.++**Decision-record concision (#2000).** The doc is a decision record, not a+transcript: one bullet per decision with its why; an approach the user ruled+out DURING the session gets one line (name + rejection reason), never a+resurrected full section that re-argues the case; omit template sections that+are empty or that restate what's already settled. No page cap — extra length+must come from genuinely open questions, not template completeness.++After writing, tell the user:+**"Design doc saved to: {repo path if written, else ~/.gstack path}{when both: ' (cross-session copy in ~/.gstack)'}. Other skills (/plan-ceo-review, /plan-eng-review) will find it automatically."**### Startup mode design doc template:@@ -316,9 +340,32 @@ Then proceed to Founder Resources below.### Founder Resources (all tiers)+**Standing opt-out check (#538) — run FIRST:**++```bash+~/.claude/skills/gstack/bin/gstack-config get founder_resources 2>/dev/null || echo "true"+```++If the value is `false`, **skip this entire section silently** — no resources,+no "skipped as requested" mention. The user said never; config outlives+session context and memory instructions, so never means never. (Re-enable:+`gstack-config set founder_resources true`.)+Share 2-3 resources from the pool below. For repeat users, resources compound by matchingto accumulated session context, not just this session's category.+**After sharing, close with the standing choice** (one line, not a ceremony):++> Want these? I can open any of them — or say "never show me these again" and+> this section disappears for good.++If the user opts out (any clear phrasing of never/stop showing these): run+`~/.claude/skills/gstack/bin/gstack-config set founder_resources false`, then+VERIFY the write (`gstack-config get founder_resources` must read back+`false`) before promising anything — if the write failed, say so and skip for+this session only. On success confirm in one line with the re-enable command+and continue the handoff.+**Dedup check:** Read `RESOURCES_SHOWN` from the builder profile output above.If `RESOURCES_SHOWN_COUNT` is 34 or more, skip this section entirely (all resources exhausted).Otherwise, avoid selecting any URL that appears in the RESOURCES_SHOWN list.diff --git a/package.json b/package.jsonindex f09019bef..12c0b7a2a 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "gstack",- "version": "1.64.1.0",+ "version": "1.65.0.0","description": "Garry's Stack — Claude Code skills + fast headless browser. One repo, one install, entire AI engineering workflow.","license": "MIT","type": "module",@@ -18,7 +18,7 @@"gen:skill-docs:user": "bun run scripts/gen-skill-docs.ts --respect-detection","dev": "bun run browse/src/cli.ts","server": "bun run browse/src/server.ts",- "test": "bun test browse/test/ test/ make-pdf/test/ design/test/ --timeout 30000 --ignore 'test/skill-e2e-*.test.ts' --ignore test/skill-llm-eval.test.ts --ignore test/skill-routing-e2e.test.ts --ignore test/codex-e2e.test.ts --ignore test/gemini-e2e.test.ts && (bun run slop:diff 2>/dev/null || true)",+ "test": "bun test browse/test/ test/ make-pdf/test/ design/test/ ios-qa/daemon/test/ --timeout 30000 --ignore 'test/skill-e2e-*.test.ts' --ignore test/skill-llm-eval.test.ts --ignore test/skill-routing-e2e.test.ts --ignore test/codex-e2e.test.ts --ignore test/gemini-e2e.test.ts && (bun run slop:diff 2>/dev/null || true)","test:free": "bun run scripts/test-free-shards.ts","test:windows": "bun run scripts/test-free-shards.ts --windows-only","test:evals": "EVALS=1 bun test --retry 2 --concurrent --max-concurrency ${EVALS_CONCURRENCY:-15} test/skill-llm-eval.test.ts test/skill-e2e-*.test.ts test/skill-routing-e2e.test.ts test/codex-e2e.test.ts test/gemini-e2e.test.ts",diff --git a/pair-agent/SKILL.md b/pair-agent/SKILL.mdindex 790647614..63f301c72 100644--- a/pair-agent/SKILL.md+++ b/pair-agent/SKILL.md@@ -676,6 +676,10 @@ When options differ in coverage, include `Completeness: X/10` (10 = all edge casFor high-stakes ambiguity (architecture, data model, destructive scope, missing context), STOP. Name it in one sentence, present 2-3 options with tradeoffs, and ask. Do not use for routine coding or obvious changes.+## Claimed Limitations Need Evidence++A claimed limitation or requirement ("the API can't do this", "X requires a credential", "that's impossible on this platform") is a material claim. State one only with the verbatim error, the documented statement, or a live probe in hand — pattern-matching a failure to a familiar story is not evidence. When a cheap probe settles the question, run it BEFORE asking the user anything or declaring a step blocked.+## Continuous Checkpoint ModeIf `CHECKPOINT_MODE` is `"continuous"`: auto-commit completed logical units with `WIP:` prefix.@@ -921,7 +925,27 @@ using the generic remote flow instead.### If different machine (option B):-First, detect ngrok status:+**Consent gate (once per machine).** The tunnel exposes this browser beyond+the machine, so it is OFF until the user opts in — the daemon refuses+`/tunnel/start` and `BROWSE_TUNNEL=1` otherwise. Check the standing consent:++```bash+~/.claude/skills/gstack/bin/gstack-config get pair_agent 2>/dev/null || echo "unset"+```++If the value is not `on`, ask via AskUserQuestion (one-way-door posture —+this opens a path from the internet to the local browser):++> "Remote pairing runs an ngrok tunnel from the internet to this machine's+> browser (locked to a 26-command allowlist + scoped token, but still an+> exposure). Enable pair-agent on this machine?"++Options: A) Enable — run `~/.claude/skills/gstack/bin/gstack-config set pair_agent on`, confirm it reads back `on`, and continue. B) No — stop here; local pairing (option A above) still works.++If the value is already `on`, say nothing and continue — consent stands until+`gstack-config set pair_agent off`.++Then detect ngrok status:```bashwhich ngrok 2>/dev/null && echo "NGROK_INSTALLED" || echo "NGROK_NOT_INSTALLED"diff --git a/pair-agent/SKILL.md.tmpl b/pair-agent/SKILL.md.tmplindex 54d0cfece..3b18af56c 100644--- a/pair-agent/SKILL.md.tmpl+++ b/pair-agent/SKILL.md.tmpl@@ -126,7 +126,27 @@ using the generic remote flow instead.### If different machine (option B):-First, detect ngrok status:+**Consent gate (once per machine).** The tunnel exposes this browser beyond+the machine, so it is OFF until the user opts in — the daemon refuses+`/tunnel/start` and `BROWSE_TUNNEL=1` otherwise. Check the standing consent:++```bash+~/.claude/skills/gstack/bin/gstack-config get pair_agent 2>/dev/null || echo "unset"+```++If the value is not `on`, ask via AskUserQuestion (one-way-door posture —+this opens a path from the internet to the local browser):++> "Remote pairing runs an ngrok tunnel from the internet to this machine's+> browser (locked to a 26-command allowlist + scoped token, but still an+> exposure). Enable pair-agent on this machine?"++Options: A) Enable — run `~/.claude/skills/gstack/bin/gstack-config set pair_agent on`, confirm it reads back `on`, and continue. B) No — stop here; local pairing (option A above) still works.++If the value is already `on`, say nothing and continue — consent stands until+`gstack-config set pair_agent off`.++Then detect ngrok status:```bashwhich ngrok 2>/dev/null && echo "NGROK_INSTALLED" || echo "NGROK_NOT_INSTALLED"diff --git a/plan-ceo-review/SKILL.md b/plan-ceo-review/SKILL.mdindex b79c9b02e..65dd790e1 100644--- a/plan-ceo-review/SKILL.md+++ b/plan-ceo-review/SKILL.md@@ -705,6 +705,10 @@ When options differ in coverage, include `Completeness: X/10` (10 = all edge casFor high-stakes ambiguity (architecture, data model, destructive scope, missing context), STOP. Name it in one sentence, present 2-3 options with tradeoffs, and ask. Do not use for routine coding or obvious changes.+## Claimed Limitations Need Evidence++A claimed limitation or requirement ("the API can't do this", "X requires a credential", "that's impossible on this platform") is a material claim. State one only with the verbatim error, the documented statement, or a live probe in hand — pattern-matching a failure to a familiar story is not evidence. When a cheap probe settles the question, run it BEFORE asking the user anything or declaring a step blocked.+## Continuous Checkpoint ModeIf `CHECKPOINT_MODE` is `"continuous"`: auto-commit completed logical units with `WIP:` prefix.@@ -957,8 +961,21 @@ Then read CLAUDE.md, TODOS.md, and any existing architecture docs.setopt +o nomatch 2>/dev/null || true # zsh compatSLUG=$(~/.claude/skills/gstack/browse/bin/remote-slug 2>/dev/null || basename "$(git rev-parse --show-toplevel 2>/dev/null || pwd)")BRANCH=$(git rev-parse --abbrev-ref HEAD 2>/dev/null | tr '/' '-' || echo 'no-branch')-DESIGN=$(ls -t ~/.gstack/projects/$SLUG/*-$BRANCH-design-*.md 2>/dev/null | head -1)-[ -z "$DESIGN" ] && DESIGN=$(ls -t ~/.gstack/projects/$SLUG/*-design-*.md 2>/dev/null | head -1)+_LOCALDOC=$(ls -t ~/.gstack/projects/$SLUG/*-$BRANCH-design-*.md 2>/dev/null | head -1)+[ -z "$_LOCALDOC" ] && _LOCALDOC=$(ls -t ~/.gstack/projects/$SLUG/*-design-*.md 2>/dev/null | head -1)+# Repo-local docs win when at least as fresh (#703): office-hours dual-writes+# docs/designs/ alongside ~/.gstack, and the committed copy is what teammates+# see. A stale old repo doc never shadows a newer private session.+_REPOTOP=$(git rev-parse --show-toplevel 2>/dev/null || echo "")+_REPODOC=""+if [ -n "$_REPOTOP" ]; then+ [ -f "$_REPOTOP/DESIGN.md" ] && _REPODOC="$_REPOTOP/DESIGN.md"+ [ -z "$_REPODOC" ] && _REPODOC=$(ls -t "$_REPOTOP"/docs/designs/*.md 2>/dev/null | head -1)+fi+DESIGN="$_LOCALDOC"+if [ -n "$_REPODOC" ] && { [ -z "$_LOCALDOC" ] || [ "$_REPODOC" -nt "$_LOCALDOC" ]; }; then+ DESIGN="$_REPODOC"+fi[ -n "$DESIGN" ] && echo "Design doc found: $DESIGN" || echo "No design doc found"```If a design doc exists (from `/office-hours`), read it. Use it as the source of truth for the problem statement, constraints, and chosen approach. If it has a `Supersedes:` field, note that this is a revised design.@@ -1028,8 +1045,21 @@ After /office-hours completes, re-run the design doc check:setopt +o nomatch 2>/dev/null || true # zsh compatSLUG=$(~/.claude/skills/gstack/browse/bin/remote-slug 2>/dev/null || basename "$(git rev-parse --show-toplevel 2>/dev/null || pwd)")BRANCH=$(git rev-parse --abbrev-ref HEAD 2>/dev/null | tr '/' '-' || echo 'no-branch')-DESIGN=$(ls -t ~/.gstack/projects/$SLUG/*-$BRANCH-design-*.md 2>/dev/null | head -1)-[ -z "$DESIGN" ] && DESIGN=$(ls -t ~/.gstack/projects/$SLUG/*-design-*.md 2>/dev/null | head -1)+_LOCALDOC=$(ls -t ~/.gstack/projects/$SLUG/*-$BRANCH-design-*.md 2>/dev/null | head -1)+[ -z "$_LOCALDOC" ] && _LOCALDOC=$(ls -t ~/.gstack/projects/$SLUG/*-design-*.md 2>/dev/null | head -1)+# Repo-local docs win when at least as fresh (#703): office-hours dual-writes+# docs/designs/ alongside ~/.gstack, and the committed copy is what teammates+# see. A stale old repo doc never shadows a newer private session.+_REPOTOP=$(git rev-parse --show-toplevel 2>/dev/null || echo "")+_REPODOC=""+if [ -n "$_REPOTOP" ]; then+ [ -f "$_REPOTOP/DESIGN.md" ] && _REPODOC="$_REPOTOP/DESIGN.md"+ [ -z "$_REPODOC" ] && _REPODOC=$(ls -t "$_REPOTOP"/docs/designs/*.md 2>/dev/null | head -1)+fi+DESIGN="$_LOCALDOC"+if [ -n "$_REPODOC" ] && { [ -z "$_LOCALDOC" ] || [ "$_REPODOC" -nt "$_LOCALDOC" ]; }; then+ DESIGN="$_REPODOC"+fi[ -n "$DESIGN" ] && echo "Design doc found: $DESIGN" || echo "No design doc found"```diff --git a/plan-ceo-review/SKILL.md.tmpl b/plan-ceo-review/SKILL.md.tmplindex c43cfe641..1b1affe16 100644--- a/plan-ceo-review/SKILL.md.tmpl+++ b/plan-ceo-review/SKILL.md.tmpl@@ -138,9 +138,7 @@ Then read CLAUDE.md, TODOS.md, and any existing architecture docs.setopt +o nomatch 2>/dev/null || true # zsh compatSLUG=$(~/.claude/skills/gstack/browse/bin/remote-slug 2>/dev/null || basename "$(git rev-parse --show-toplevel 2>/dev/null || pwd)")BRANCH=$(git rev-parse --abbrev-ref HEAD 2>/dev/null | tr '/' '-' || echo 'no-branch')-DESIGN=$(ls -t ~/.gstack/projects/$SLUG/*-$BRANCH-design-*.md 2>/dev/null | head -1)-[ -z "$DESIGN" ] && DESIGN=$(ls -t ~/.gstack/projects/$SLUG/*-design-*.md 2>/dev/null | head -1)-[ -n "$DESIGN" ] && echo "Design doc found: $DESIGN" || echo "No design doc found"+{{DESIGN_DOC_DISCOVERY}}```If a design doc exists (from `/office-hours`), read it. Use it as the source of truth for the problem statement, constraints, and chosen approach. If it has a `Supersedes:` field, note that this is a revised design.diff --git a/plan-design-review/SKILL.md b/plan-design-review/SKILL.mdindex 2663778c1..853609247 100644--- a/plan-design-review/SKILL.md+++ b/plan-design-review/SKILL.md@@ -677,6 +677,10 @@ When options differ in coverage, include `Completeness: X/10` (10 = all edge casFor high-stakes ambiguity (architecture, data model, destructive scope, missing context), STOP. Name it in one sentence, present 2-3 options with tradeoffs, and ask. Do not use for routine coding or obvious changes.+## Claimed Limitations Need Evidence++A claimed limitation or requirement ("the API can't do this", "X requires a credential", "that's impossible on this platform") is a material claim. State one only with the verbatim error, the documented statement, or a live probe in hand — pattern-matching a failure to a familiar story is not evidence. When a cheap probe settles the question, run it BEFORE asking the user anything or declaring a step blocked.+## Continuous Checkpoint ModeIf `CHECKPOINT_MODE` is `"continuous"`: auto-commit completed logical units with `WIP:` prefix.diff --git a/plan-devex-review/SKILL.md b/plan-devex-review/SKILL.mdindex e66550e93..9dc9d8b05 100644--- a/plan-devex-review/SKILL.md+++ b/plan-devex-review/SKILL.md@@ -683,6 +683,10 @@ When options differ in coverage, include `Completeness: X/10` (10 = all edge casFor high-stakes ambiguity (architecture, data model, destructive scope, missing context), STOP. Name it in one sentence, present 2-3 options with tradeoffs, and ask. Do not use for routine coding or obvious changes.+## Claimed Limitations Need Evidence++A claimed limitation or requirement ("the API can't do this", "X requires a credential", "that's impossible on this platform") is a material claim. State one only with the verbatim error, the documented statement, or a live probe in hand — pattern-matching a failure to a familiar story is not evidence. When a cheap probe settles the question, run it BEFORE asking the user anything or declaring a step blocked.+## Continuous Checkpoint ModeIf `CHECKPOINT_MODE` is `"continuous"`: auto-commit completed logical units with `WIP:` prefix.@@ -981,8 +985,21 @@ Then read:setopt +o nomatch 2>/dev/null || trueSLUG=$(~/.claude/skills/gstack/browse/bin/remote-slug 2>/dev/null || basename "$(git rev-parse --show-toplevel 2>/dev/null || pwd)")BRANCH=$(git rev-parse --abbrev-ref HEAD 2>/dev/null | tr '/' '-' || echo 'no-branch')-DESIGN=$(ls -t ~/.gstack/projects/$SLUG/*-$BRANCH-design-*.md 2>/dev/null | head -1)-[ -z "$DESIGN" ] && DESIGN=$(ls -t ~/.gstack/projects/$SLUG/*-design-*.md 2>/dev/null | head -1)+_LOCALDOC=$(ls -t ~/.gstack/projects/$SLUG/*-$BRANCH-design-*.md 2>/dev/null | head -1)+[ -z "$_LOCALDOC" ] && _LOCALDOC=$(ls -t ~/.gstack/projects/$SLUG/*-design-*.md 2>/dev/null | head -1)+# Repo-local docs win when at least as fresh (#703): office-hours dual-writes+# docs/designs/ alongside ~/.gstack, and the committed copy is what teammates+# see. A stale old repo doc never shadows a newer private session.+_REPOTOP=$(git rev-parse --show-toplevel 2>/dev/null || echo "")+_REPODOC=""+if [ -n "$_REPOTOP" ]; then+ [ -f "$_REPOTOP/DESIGN.md" ] && _REPODOC="$_REPOTOP/DESIGN.md"+ [ -z "$_REPODOC" ] && _REPODOC=$(ls -t "$_REPOTOP"/docs/designs/*.md 2>/dev/null | head -1)+fi+DESIGN="$_LOCALDOC"+if [ -n "$_REPODOC" ] && { [ -z "$_LOCALDOC" ] || [ "$_REPODOC" -nt "$_LOCALDOC" ]; }; then+ DESIGN="$_REPODOC"+fi[ -n "$DESIGN" ] && echo "Design doc found: $DESIGN" || echo "No design doc found"```If a design doc exists, read it.@@ -1041,8 +1058,21 @@ After /office-hours completes, re-run the design doc check:setopt +o nomatch 2>/dev/null || true # zsh compatSLUG=$(~/.claude/skills/gstack/browse/bin/remote-slug 2>/dev/null || basename "$(git rev-parse --show-toplevel 2>/dev/null || pwd)")BRANCH=$(git rev-parse --abbrev-ref HEAD 2>/dev/null | tr '/' '-' || echo 'no-branch')-DESIGN=$(ls -t ~/.gstack/projects/$SLUG/*-$BRANCH-design-*.md 2>/dev/null | head -1)-[ -z "$DESIGN" ] && DESIGN=$(ls -t ~/.gstack/projects/$SLUG/*-design-*.md 2>/dev/null | head -1)+_LOCALDOC=$(ls -t ~/.gstack/projects/$SLUG/*-$BRANCH-design-*.md 2>/dev/null | head -1)+[ -z "$_LOCALDOC" ] && _LOCALDOC=$(ls -t ~/.gstack/projects/$SLUG/*-design-*.md 2>/dev/null | head -1)+# Repo-local docs win when at least as fresh (#703): office-hours dual-writes+# docs/designs/ alongside ~/.gstack, and the committed copy is what teammates+# see. A stale old repo doc never shadows a newer private session.+_REPOTOP=$(git rev-parse --show-toplevel 2>/dev/null || echo "")+_REPODOC=""+if [ -n "$_REPOTOP" ]; then+ [ -f "$_REPOTOP/DESIGN.md" ] && _REPODOC="$_REPOTOP/DESIGN.md"+ [ -z "$_REPODOC" ] && _REPODOC=$(ls -t "$_REPOTOP"/docs/designs/*.md 2>/dev/null | head -1)+fi+DESIGN="$_LOCALDOC"+if [ -n "$_REPODOC" ] && { [ -z "$_LOCALDOC" ] || [ "$_REPODOC" -nt "$_LOCALDOC" ]; }; then+ DESIGN="$_REPODOC"+fi[ -n "$DESIGN" ] && echo "Design doc found: $DESIGN" || echo "No design doc found"```diff --git a/plan-devex-review/SKILL.md.tmpl b/plan-devex-review/SKILL.md.tmplindex 1ef723c10..76871cafa 100644--- a/plan-devex-review/SKILL.md.tmpl+++ b/plan-devex-review/SKILL.md.tmpl@@ -99,9 +99,7 @@ Then read:setopt +o nomatch 2>/dev/null || trueSLUG=$(~/.claude/skills/gstack/browse/bin/remote-slug 2>/dev/null || basename "$(git rev-parse --show-toplevel 2>/dev/null || pwd)")BRANCH=$(git rev-parse --abbrev-ref HEAD 2>/dev/null | tr '/' '-' || echo 'no-branch')-DESIGN=$(ls -t ~/.gstack/projects/$SLUG/*-$BRANCH-design-*.md 2>/dev/null | head -1)-[ -z "$DESIGN" ] && DESIGN=$(ls -t ~/.gstack/projects/$SLUG/*-design-*.md 2>/dev/null | head -1)-[ -n "$DESIGN" ] && echo "Design doc found: $DESIGN" || echo "No design doc found"+{{DESIGN_DOC_DISCOVERY}}```If a design doc exists, read it.diff --git a/plan-eng-review/SKILL.md b/plan-eng-review/SKILL.mdindex 057f547fc..8672c9464 100644--- a/plan-eng-review/SKILL.md+++ b/plan-eng-review/SKILL.md@@ -681,6 +681,10 @@ When options differ in coverage, include `Completeness: X/10` (10 = all edge casFor high-stakes ambiguity (architecture, data model, destructive scope, missing context), STOP. Name it in one sentence, present 2-3 options with tradeoffs, and ask. Do not use for routine coding or obvious changes.+## Claimed Limitations Need Evidence++A claimed limitation or requirement ("the API can't do this", "X requires a credential", "that's impossible on this platform") is a material claim. State one only with the verbatim error, the documented statement, or a live probe in hand — pattern-matching a failure to a familiar story is not evidence. When a cheap probe settles the question, run it BEFORE asking the user anything or declaring a step blocked.+## Continuous Checkpoint ModeIf `CHECKPOINT_MODE` is `"continuous"`: auto-commit completed logical units with `WIP:` prefix.@@ -929,8 +933,21 @@ sections. Read a section in full before doing its step; do not work from memory.setopt +o nomatch 2>/dev/null || true # zsh compatSLUG=$(~/.claude/skills/gstack/browse/bin/remote-slug 2>/dev/null || basename "$(git rev-parse --show-toplevel 2>/dev/null || pwd)")BRANCH=$(git rev-parse --abbrev-ref HEAD 2>/dev/null | tr '/' '-' || echo 'no-branch')-DESIGN=$(ls -t ~/.gstack/projects/$SLUG/*-$BRANCH-design-*.md 2>/dev/null | head -1)-[ -z "$DESIGN" ] && DESIGN=$(ls -t ~/.gstack/projects/$SLUG/*-design-*.md 2>/dev/null | head -1)+_LOCALDOC=$(ls -t ~/.gstack/projects/$SLUG/*-$BRANCH-design-*.md 2>/dev/null | head -1)+[ -z "$_LOCALDOC" ] && _LOCALDOC=$(ls -t ~/.gstack/projects/$SLUG/*-design-*.md 2>/dev/null | head -1)+# Repo-local docs win when at least as fresh (#703): office-hours dual-writes+# docs/designs/ alongside ~/.gstack, and the committed copy is what teammates+# see. A stale old repo doc never shadows a newer private session.+_REPOTOP=$(git rev-parse --show-toplevel 2>/dev/null || echo "")+_REPODOC=""+if [ -n "$_REPOTOP" ]; then+ [ -f "$_REPOTOP/DESIGN.md" ] && _REPODOC="$_REPOTOP/DESIGN.md"+ [ -z "$_REPODOC" ] && _REPODOC=$(ls -t "$_REPOTOP"/docs/designs/*.md 2>/dev/null | head -1)+fi+DESIGN="$_LOCALDOC"+if [ -n "$_REPODOC" ] && { [ -z "$_LOCALDOC" ] || [ "$_REPODOC" -nt "$_LOCALDOC" ]; }; then+ DESIGN="$_REPODOC"+fi[ -n "$DESIGN" ] && echo "Design doc found: $DESIGN" || echo "No design doc found"```If a design doc exists, read it. Use it as the source of truth for the problem statement, constraints, and chosen approach. If it has a `Supersedes:` field, note that this is a revised design — check the prior version for context on what changed and why.@@ -984,8 +1001,21 @@ After /office-hours completes, re-run the design doc check:setopt +o nomatch 2>/dev/null || true # zsh compatSLUG=$(~/.claude/skills/gstack/browse/bin/remote-slug 2>/dev/null || basename "$(git rev-parse --show-toplevel 2>/dev/null || pwd)")BRANCH=$(git rev-parse --abbrev-ref HEAD 2>/dev/null | tr '/' '-' || echo 'no-branch')-DESIGN=$(ls -t ~/.gstack/projects/$SLUG/*-$BRANCH-design-*.md 2>/dev/null | head -1)-[ -z "$DESIGN" ] && DESIGN=$(ls -t ~/.gstack/projects/$SLUG/*-design-*.md 2>/dev/null | head -1)+_LOCALDOC=$(ls -t ~/.gstack/projects/$SLUG/*-$BRANCH-design-*.md 2>/dev/null | head -1)+[ -z "$_LOCALDOC" ] && _LOCALDOC=$(ls -t ~/.gstack/projects/$SLUG/*-design-*.md 2>/dev/null | head -1)+# Repo-local docs win when at least as fresh (#703): office-hours dual-writes+# docs/designs/ alongside ~/.gstack, and the committed copy is what teammates+# see. A stale old repo doc never shadows a newer private session.+_REPOTOP=$(git rev-parse --show-toplevel 2>/dev/null || echo "")+_REPODOC=""+if [ -n "$_REPOTOP" ]; then+ [ -f "$_REPOTOP/DESIGN.md" ] && _REPODOC="$_REPOTOP/DESIGN.md"+ [ -z "$_REPODOC" ] && _REPODOC=$(ls -t "$_REPOTOP"/docs/designs/*.md 2>/dev/null | head -1)+fi+DESIGN="$_LOCALDOC"+if [ -n "$_REPODOC" ] && { [ -z "$_LOCALDOC" ] || [ "$_REPODOC" -nt "$_LOCALDOC" ]; }; then+ DESIGN="$_REPODOC"+fi[ -n "$DESIGN" ] && echo "Design doc found: $DESIGN" || echo "No design doc found"```diff --git a/plan-eng-review/SKILL.md.tmpl b/plan-eng-review/SKILL.md.tmplindex c1125bfaa..e066e2c5f 100644--- a/plan-eng-review/SKILL.md.tmpl+++ b/plan-eng-review/SKILL.md.tmpl@@ -112,9 +112,7 @@ When evaluating architecture, think "boring by default." When reviewing tests, tsetopt +o nomatch 2>/dev/null || true # zsh compatSLUG=$(~/.claude/skills/gstack/browse/bin/remote-slug 2>/dev/null || basename "$(git rev-parse --show-toplevel 2>/dev/null || pwd)")BRANCH=$(git rev-parse --abbrev-ref HEAD 2>/dev/null | tr '/' '-' || echo 'no-branch')-DESIGN=$(ls -t ~/.gstack/projects/$SLUG/*-$BRANCH-design-*.md 2>/dev/null | head -1)-[ -z "$DESIGN" ] && DESIGN=$(ls -t ~/.gstack/projects/$SLUG/*-design-*.md 2>/dev/null | head -1)-[ -n "$DESIGN" ] && echo "Design doc found: $DESIGN" || echo "No design doc found"+{{DESIGN_DOC_DISCOVERY}}```If a design doc exists, read it. Use it as the source of truth for the problem statement, constraints, and chosen approach. If it has a `Supersedes:` field, note that this is a revised design — check the prior version for context on what changed and why.diff --git a/plan-eng-review/sections/review-sections.md b/plan-eng-review/sections/review-sections.mdindex 7592f0a70..caae69a7e 100644--- a/plan-eng-review/sections/review-sections.md+++ b/plan-eng-review/sections/review-sections.md@@ -147,15 +147,20 @@ Before analyzing coverage, detect the project's test framework:```bashsetopt +o nomatch 2>/dev/null || true # zsh compat-# Detect project runtime-[ -f Gemfile ] && echo "RUNTIME:ruby"+# Detect project runtime (markers are evidence, not commands to run blind)+[ -f manage.py ] && echo "RUNTIME:python FRAMEWORK:django"+{ [ -f pyproject.toml ] || [ -f pytest.ini ] || [ -f tox.ini ] || [ -f setup.cfg ] || [ -f requirements.txt ]; } && echo "RUNTIME:python"+[ -f Gemfile ] || [ -f Rakefile ] || [ -f .rspec ] && echo "RUNTIME:ruby"[ -f package.json ] && echo "RUNTIME:node"-[ -f requirements.txt ] || [ -f pyproject.toml ] && echo "RUNTIME:python"[ -f go.mod ] && echo "RUNTIME:go"[ -f Cargo.toml ] && echo "RUNTIME:rust"-# Check for existing test infrastructure-ls jest.config.* vitest.config.* playwright.config.* cypress.config.* .rspec pytest.ini phpunit.xml 2>/dev/null-ls -d test/ tests/ spec/ __tests__/ cypress/ e2e/ 2>/dev/null+[ -f pom.xml ] && echo "RUNTIME:jvm BUILD:maven"+{ [ -f build.gradle ] || [ -f build.gradle.kts ]; } && echo "RUNTIME:jvm BUILD:gradle"+# Check for existing test infrastructure — config files, scripts, AND test files+ls jest.config.* vitest.config.* playwright.config.* cypress.config.* .rspec pytest.ini tox.ini phpunit.xml 2>/dev/null+[ -f package.json ] && grep -q '"test"[[:space:]]*:' package.json && echo "SCRIPT:package.json test"+[ -f Makefile ] && grep -qE '^(test|check):' Makefile && echo "TARGET:make test"+git ls-files | grep -cE '(^|/)(tests?|spec|__tests__)/|(^|/)tests?\.py$|(^|/)test_[^/]+\.py$|_test\.(go|py|rb|ts|js|exs)$|\.(test|spec)\.[jt]sx?$|_spec\.rb$|Test\.(java|kt)$' | sed 's/^/TESTFILES:/'```3. **If no framework detected:** still produce the coverage diagram, but skip test generation.diff --git a/plan-tune/SKILL.md b/plan-tune/SKILL.mdindex 5f8d6a917..7f3656d1a 100644--- a/plan-tune/SKILL.md+++ b/plan-tune/SKILL.md@@ -686,6 +686,10 @@ When options differ in coverage, include `Completeness: X/10` (10 = all edge casFor high-stakes ambiguity (architecture, data model, destructive scope, missing context), STOP. Name it in one sentence, present 2-3 options with tradeoffs, and ask. Do not use for routine coding or obvious changes.+## Claimed Limitations Need Evidence++A claimed limitation or requirement ("the API can't do this", "X requires a credential", "that's impossible on this platform") is a material claim. State one only with the verbatim error, the documented statement, or a live probe in hand — pattern-matching a failure to a familiar story is not evidence. When a cheap probe settles the question, run it BEFORE asking the user anything or declaring a step blocked.+## Continuous Checkpoint ModeIf `CHECKPOINT_MODE` is `"continuous"`: auto-commit completed logical units with `WIP:` prefix.diff --git a/qa-only/SKILL.md b/qa-only/SKILL.mdindex d566dcff0..1d58adcc7 100644--- a/qa-only/SKILL.md+++ b/qa-only/SKILL.md@@ -676,6 +676,10 @@ When options differ in coverage, include `Completeness: X/10` (10 = all edge casFor high-stakes ambiguity (architecture, data model, destructive scope, missing context), STOP. Name it in one sentence, present 2-3 options with tradeoffs, and ask. Do not use for routine coding or obvious changes.+## Claimed Limitations Need Evidence++A claimed limitation or requirement ("the API can't do this", "X requires a credential", "that's impossible on this platform") is a material claim. State one only with the verbatim error, the documented statement, or a live probe in hand — pattern-matching a failure to a familiar story is not evidence. When a cheap probe settles the question, run it BEFORE asking the user anything or declaring a step blocked.+## Continuous Checkpoint ModeIf `CHECKPOINT_MODE` is `"continuous"`: auto-commit completed logical units with `WIP:` prefix.diff --git a/qa/SKILL.md b/qa/SKILL.mdindex c607c4ef9..ce3633067 100644--- a/qa/SKILL.md+++ b/qa/SKILL.md@@ -682,6 +682,10 @@ When options differ in coverage, include `Completeness: X/10` (10 = all edge casFor high-stakes ambiguity (architecture, data model, destructive scope, missing context), STOP. Name it in one sentence, present 2-3 options with tradeoffs, and ask. Do not use for routine coding or obvious changes.+## Claimed Limitations Need Evidence++A claimed limitation or requirement ("the API can't do this", "X requires a credential", "that's impossible on this platform") is a material claim. State one only with the verbatim error, the documented statement, or a live probe in hand — pattern-matching a failure to a familiar story is not evidence. When a cheap probe settles the question, run it BEFORE asking the user anything or declaring a step blocked.+## Continuous Checkpoint ModeIf `CHECKPOINT_MODE` is `"continuous"`: auto-commit completed logical units with `WIP:` prefix.@@ -943,41 +947,70 @@ If `NEEDS_SETUP`:## Test Framework Bootstrap-**Detect existing test framework and project runtime:**+**Read the project's CLAUDE.md (and TESTING.md if present) FIRST.** If it documents a test command, the project already told you: no detection, no bootstrap. Skip the rest of bootstrap and use that command in Step 5.++**Otherwise gather markers. Every marker below is EVIDENCE for the question you ask — never a command to run blind.** A marker tells you which ecosystem you're in and which command to OFFER. It does not tell you the command works. Do not execute a candidate test command to "check" it: a probe on a project that never had that runner fails loudly and teaches you nothing, and installing a second framework over a working one is worse.```bashsetopt +o nomatch 2>/dev/null || true # zsh compat-# Detect project runtime-[ -f Gemfile ] && echo "RUNTIME:ruby"+# Definitive ecosystem markers (presence = ecosystem, NOT a command to run)+[ -f manage.py ] && echo "RUNTIME:python FRAMEWORK:django MARKER:manage.py"+{ [ -f pyproject.toml ] || [ -f pytest.ini ] || [ -f tox.ini ] || [ -f setup.cfg ] || [ -f requirements.txt ]; } && echo "RUNTIME:python"+[ -f Gemfile ] || [ -f Rakefile ] || [ -f .rspec ] && echo "RUNTIME:ruby"[ -f package.json ] && echo "RUNTIME:node"-[ -f requirements.txt ] || [ -f pyproject.toml ] && echo "RUNTIME:python"[ -f go.mod ] && echo "RUNTIME:go"[ -f Cargo.toml ] && echo "RUNTIME:rust"[ -f composer.json ] && echo "RUNTIME:php"[ -f mix.exs ] && echo "RUNTIME:elixir"+[ -f pom.xml ] && echo "RUNTIME:jvm BUILD:maven"+{ [ -f build.gradle ] || [ -f build.gradle.kts ]; } && echo "RUNTIME:jvm BUILD:gradle"# Detect sub-frameworks[ -f Gemfile ] && grep -q "rails" Gemfile 2>/dev/null && echo "FRAMEWORK:rails"[ -f package.json ] && grep -q '"next"' package.json 2>/dev/null && echo "FRAMEWORK:nextjs"-# Check for existing test infrastructure-ls jest.config.* vitest.config.* playwright.config.* .rspec pytest.ini pyproject.toml phpunit.xml 2>/dev/null-ls -d test/ tests/ spec/ __tests__/ cypress/ e2e/ 2>/dev/null+# Existing test path — config files, declared scripts, AND test FILES.+# A project with real tests and no config file is the common miss.+ls jest.config.* vitest.config.* playwright.config.* .rspec pytest.ini tox.ini phpunit.xml* 2>/dev/null+[ -f package.json ] && grep -q '"test"[[:space:]]*:' package.json && echo "SCRIPT:package.json test"+[ -f Makefile ] && grep -qE '^(test|check):' Makefile && echo "TARGET:make test"+[ -f pyproject.toml ] && grep -q "pytest" pyproject.toml && echo "CONFIG:pyproject pytest"+git ls-files | grep -cE '(^|/)(tests?|spec|__tests__)/|(^|/)tests?\.py$|(^|/)test_[^/]+\.py$|_test\.(go|py|rb|ts|js|exs)$|\.(test|spec)\.[jt]sx?$|_spec\.rb$|Test\.(java|kt)$' | sed 's/^/TESTFILES:/'+# Rust keeps unit tests inside src/, so file names alone miss them+[ -f Cargo.toml ] && git grep -lF '#[test]' -- 'src' >/dev/null 2>&1 && echo "TESTS:rust in-source"# Check opt-out marker[ -f .gstack/no-test-bootstrap ] && echo "BOOTSTRAP_DECLINED"```-**If test framework detected** (config files or test directories found):-Print "Test framework detected: {name} ({N} existing tests). Skipping bootstrap."+Map the markers to the command you will OFFER — never to one you run on a guess:++| Marker | Ecosystem | Candidate command to offer |+|--------|-----------|----------------------------|+| `manage.py` | Django | `python manage.py test` (or `pytest` when pytest-django is in the deps) |+| `pytest.ini` / `tox.ini` / pytest in `pyproject.toml` / `test_*.py` | Python | `pytest` |+| `go.mod` (+ any `*_test.go`) | Go | `go test ./...` |+| `Cargo.toml` | Rust | `cargo test` |+| `pom.xml` | JVM (Maven) | `mvn test` |+| `build.gradle` / `build.gradle.kts` | JVM (Gradle) | `./gradlew test` |+| `Gemfile` / `Rakefile` / `.rspec` | Ruby | `bundle exec rspec`, `bin/rails test`, or `rake test` |+| `mix.exs` | Elixir | `mix test` |+| `composer.json` | PHP | `composer test` or `./vendor/bin/phpunit` |+| `package.json` with a `test` script | Node | that script, run with the package manager the lockfile names |+| `Makefile` with a `test:` target | any | `make test` |++**If ANY existing-test evidence appears** (a config file, a declared test script or make target, a nonzero `TESTFILES:` count, or `TESTS:rust in-source`): the project has tests. **Do NOT bootstrap.** Print "Existing tests detected: {the evidence}." Then get the command the same way Step 5 does — CLAUDE.md/TESTING.md if documented, otherwise AskUserQuestion offering the candidates from the table above plus "Other", and persist the answer to CLAUDE.md's `## Testing` section so it is never asked again. When the ecosystem ships a runner (Django, Go, Rust, Elixir, Maven/Gradle), that runner is the candidate — never install a second framework beside a working one.Read 2-3 existing test files to learn conventions (naming, imports, assertion style, setup patterns).Store conventions as prose context for use in Phase 8e.5 or Step 7. **Skip the rest of bootstrap.**+Absent config files and absent `tests/` directories are NOT evidence of "no tests": Django keeps tests in `<app>/tests.py`, Go in `*_test.go` beside the source, Rust in `#[test]` blocks inside `src/`. A green `python manage.py test` with no `pytest.ini` is a tested project, not a bootstrap candidate.+**If BOOTSTRAP_DECLINED** appears: Print "Test bootstrap previously declined — skipping." **Skip the rest of bootstrap.**-**If NO runtime detected** (no config files found): Use AskUserQuestion:+**If NO ecosystem marker matched:** Use AskUserQuestion:"I couldn't detect your project's language. What runtime are you using?"Options: A) Node.js/TypeScript B) Ruby/Rails C) Python D) Go E) Rust F) PHP G) Elixir H) This project doesn't need tests.+If the runtime you need isn't listed, offer "Other" and take the runtime plus the test command as free text.If user picks H → write `.gstack/no-test-bootstrap` and continue without tests.-**If runtime detected but no test framework — bootstrap:**+**If an ecosystem matched but there is no existing-test evidence at all — bootstrap:**### B2. Research best practices@@ -993,7 +1026,9 @@ If WebSearch is unavailable, use this built-in knowledge table:| Node.js | vitest + @testing-library | jest + @testing-library || Next.js | vitest + @testing-library/react + playwright | jest + cypress || Python | pytest + pytest-cov | unittest |+| Django | pytest + pytest-django | Django's built-in `manage.py test` (unittest) || Go | stdlib testing + testify | stdlib only |+| JVM (Maven/Gradle) | JUnit 5 + AssertJ | JUnit 5 only || Rust | cargo test (built-in) + mockall | — || PHP | phpunit + mockery | pest || Elixir | ExUnit (built-in) + ex_machina | — |diff --git a/retro/SKILL.md b/retro/SKILL.mdindex d469f1687..03f3898dd 100644--- a/retro/SKILL.md+++ b/retro/SKILL.md@@ -693,6 +693,10 @@ When options differ in coverage, include `Completeness: X/10` (10 = all edge casFor high-stakes ambiguity (architecture, data model, destructive scope, missing context), STOP. Name it in one sentence, present 2-3 options with tradeoffs, and ask. Do not use for routine coding or obvious changes.+## Claimed Limitations Need Evidence++A claimed limitation or requirement ("the API can't do this", "X requires a credential", "that's impossible on this platform") is a material claim. State one only with the verbatim error, the documented statement, or a live probe in hand — pattern-matching a failure to a familiar story is not evidence. When a cheap probe settles the question, run it BEFORE asking the user anything or declaring a step blocked.+## Continuous Checkpoint ModeIf `CHECKPOINT_MODE` is `"continuous"`: auto-commit completed logical units with `WIP:` prefix.diff --git a/review/SKILL.md b/review/SKILL.mdindex 0f97f8f73..2c6fd4b30 100644--- a/review/SKILL.md+++ b/review/SKILL.md@@ -678,6 +678,10 @@ When options differ in coverage, include `Completeness: X/10` (10 = all edge casFor high-stakes ambiguity (architecture, data model, destructive scope, missing context), STOP. Name it in one sentence, present 2-3 options with tradeoffs, and ask. Do not use for routine coding or obvious changes.+## Claimed Limitations Need Evidence++A claimed limitation or requirement ("the API can't do this", "X requires a credential", "that's impossible on this platform") is a material claim. State one only with the verbatim error, the documented statement, or a live probe in hand — pattern-matching a failure to a familiar story is not evidence. When a cheap probe settles the question, run it BEFORE asking the user anything or declaring a step blocked.+## Continuous Checkpoint ModeIf `CHECKPOINT_MODE` is `"continuous"`: auto-commit completed logical units with `WIP:` prefix.diff --git a/scripts/resolvers/design-doc-discovery.ts b/scripts/resolvers/design-doc-discovery.tsnew file mode 100644index 000000000..757d85efe--- /dev/null+++ b/scripts/resolvers/design-doc-discovery.ts@@ -0,0 +1,49 @@+/**+ * {{DESIGN_DOC_DISCOVERY}} — the canonical design-doc discovery block (#703).+ *+ * Finds the design doc a plan review should read: newest branch-scoped doc+ * under ~/.gstack/projects/<slug>/, falling back to newest project-scoped+ * doc, then lets a repo-local doc (DESIGN.md or docs/designs/*.md) win when+ * it is at least as fresh. office-hours dual-writes docs/designs/ alongside+ * ~/.gstack, and the committed copy is what teammates see — but a stale old+ * repo doc must never shadow a newer private session.+ *+ * Single source of truth for the freshness-preference logic that previously+ * lived verbatim in plan-ceo-review, plan-eng-review, plan-devex-review, and+ * the prerequisite-skill re-check in review.ts (GStack 2 fork-port wave,+ * time-attack/gstack). Drift between copies meant plan reviews could+ * disagree about which design doc wins.+ *+ * The fragment carries no code fences — the {{DESIGN_DOC_DISCOVERY}} token+ * sits inside each caller's ```bash block. Callers must set $SLUG and+ * $BRANCH first (and `setopt +o nomatch` for zsh); the block sets $DESIGN+ * and prints "Design doc found: ..." or "No design doc found".+ */++import type { TemplateContext } from './types';++/**+ * Raw canonical fragment, exported so TS resolvers (review.ts's prerequisite+ * re-check) can interpolate it into their own template strings instead of+ * embedding a drifting copy.+ */+export const DESIGN_DOC_DISCOVERY_BLOCK = `_LOCALDOC=$(ls -t ~/.gstack/projects/$SLUG/*-$BRANCH-design-*.md 2>/dev/null | head -1)+[ -z "$_LOCALDOC" ] && _LOCALDOC=$(ls -t ~/.gstack/projects/$SLUG/*-design-*.md 2>/dev/null | head -1)+# Repo-local docs win when at least as fresh (#703): office-hours dual-writes+# docs/designs/ alongside ~/.gstack, and the committed copy is what teammates+# see. A stale old repo doc never shadows a newer private session.+_REPOTOP=$(git rev-parse --show-toplevel 2>/dev/null || echo "")+_REPODOC=""+if [ -n "$_REPOTOP" ]; then+ [ -f "$_REPOTOP/DESIGN.md" ] && _REPODOC="$_REPOTOP/DESIGN.md"+ [ -z "$_REPODOC" ] && _REPODOC=$(ls -t "$_REPOTOP"/docs/designs/*.md 2>/dev/null | head -1)+fi+DESIGN="$_LOCALDOC"+if [ -n "$_REPODOC" ] && { [ -z "$_LOCALDOC" ] || [ "$_REPODOC" -nt "$_LOCALDOC" ]; }; then+ DESIGN="$_REPODOC"+fi+[ -n "$DESIGN" ] && echo "Design doc found: $DESIGN" || echo "No design doc found"`;++export function generateDesignDocDiscovery(_ctx: TemplateContext): string {+ return DESIGN_DOC_DISCOVERY_BLOCK;+}diff --git a/scripts/resolvers/index.ts b/scripts/resolvers/index.tsindex b7b7c5d92..fce4bc6b7 100644--- a/scripts/resolvers/index.ts+++ b/scripts/resolvers/index.ts@@ -33,11 +33,15 @@ import { generateGBrainContextLoad, generateGBrainSaveResults, generateBrainPrefimport { generateTasksSectionEmit, generateTasksSectionAggregate } from './tasks-section';import { SECTION, SECTION_INDEX } from './sections';import { generateRedactInvocationBlock } from './redact-doc';+import { generateThirdPartyActions } from './third-party-actions';+import { generateDesignDocDiscovery } from './design-doc-discovery';export const RESOLVERS: Record<string, ResolverFn> = {SLUG_EVAL: generateSlugEval,SLUG_SETUP: generateSlugSetup,REDACT_INVOCATION_BLOCK: generateRedactInvocationBlock,+ THIRD_PARTY_ACTIONS: generateThirdPartyActions,+ DESIGN_DOC_DISCOVERY: generateDesignDocDiscovery,COMMAND_REFERENCE: generateCommandReference,SNAPSHOT_FLAGS: generateSnapshotFlags,PREAMBLE: generatePreamble,diff --git a/scripts/resolvers/preamble.ts b/scripts/resolvers/preamble.tsindex 4a7cff4bc..2c6e1fceb 100644--- a/scripts/resolvers/preamble.ts+++ b/scripts/resolvers/preamble.ts@@ -53,6 +53,7 @@ import { generateAskUserFormat } from './preamble/generate-ask-user-format';import { generateWritingStyle } from './preamble/generate-writing-style';import { generateCompletenessSection } from './preamble/generate-completeness-section';import { generateConfusionProtocol } from './preamble/generate-confusion-protocol';+import { generateEvidenceDirective } from './preamble/generate-evidence-directive';import { generateContinuousCheckpoint } from './preamble/generate-continuous-checkpoint';import { generateContextHealth } from './preamble/generate-context-health';@@ -117,6 +118,7 @@ export function generatePreamble(ctx: TemplateContext): string {generateWritingStyle(ctx),generateCompletenessSection(ctx),generateConfusionProtocol(ctx),+ generateEvidenceDirective(ctx),generateContinuousCheckpoint(),generateContextHealth(ctx),generateQuestionTuning(ctx),diff --git a/scripts/resolvers/preamble/generate-evidence-directive.ts b/scripts/resolvers/preamble/generate-evidence-directive.tsnew file mode 100644index 000000000..f4fdaa67e--- /dev/null+++ b/scripts/resolvers/preamble/generate-evidence-directive.ts@@ -0,0 +1,18 @@+import type { TemplateContext } from '../types';++/**+ * Evidence-before-claimed-limitations (fork port wave 2, D1).+ *+ * The single highest-leverage judgment clause from the fork's live App Store+ * releases: nine release failures in two days shared one root — the agent+ * asserting folklore as fact ("the API can't do this", "X requires a+ * password") instead of running the ten-second check that would have+ * disproven it. Adapted as ONE directive into the shared preamble (the+ * fork's full SHARED-JUDGMENT contract is deliberately not imported).+ */+export function generateEvidenceDirective(ctx?: TemplateContext): string {+ if (ctx?.explainLevel === 'terse') return '';+ return `## Claimed Limitations Need Evidence++A claimed limitation or requirement ("the API can't do this", "X requires a credential", "that's impossible on this platform") is a material claim. State one only with the verbatim error, the documented statement, or a live probe in hand — pattern-matching a failure to a familiar story is not evidence. When a cheap probe settles the question, run it BEFORE asking the user anything or declaring a step blocked.`;+}diff --git a/scripts/resolvers/review.ts b/scripts/resolvers/review.tsindex d1823e522..aea233dbe 100644--- a/scripts/resolvers/review.ts+++ b/scripts/resolvers/review.ts@@ -15,6 +15,7 @@import type { TemplateContext } from './types';import { generateInvokeSkill } from './composition';import { codexPreflight, codexErrorHandling } from './constants';+import { DESIGN_DOC_DISCOVERY_BLOCK } from './design-doc-discovery';import { getHostConfig } from '../../hosts/index';const CODEX_BOUNDARY = 'IMPORTANT: Do NOT read or execute any files under ~/.claude/, ~/.agents/, .claude/skills/, or agents/. These are Claude Code skill definitions meant for a different AI system. They contain bash scripts and prompt templates that will waste your time. Ignore them completely. Do NOT modify agents/openai.yaml. Stay focused on the repository code only.\\n\\n';@@ -310,9 +311,7 @@ After /${first} completes, re-run the design doc check:setopt +o nomatch 2>/dev/null || true # zsh compatSLUG=$(~/.claude/skills/gstack/browse/bin/remote-slug 2>/dev/null || basename "$(git rev-parse --show-toplevel 2>/dev/null || pwd)")BRANCH=$(git rev-parse --abbrev-ref HEAD 2>/dev/null | tr '/' '-' || echo 'no-branch')-DESIGN=$(ls -t ~/.gstack/projects/$SLUG/*-$BRANCH-design-*.md 2>/dev/null | head -1)-[ -z "$DESIGN" ] && DESIGN=$(ls -t ~/.gstack/projects/$SLUG/*-design-*.md 2>/dev/null | head -1)-[ -n "$DESIGN" ] && echo "Design doc found: $DESIGN" || echo "No design doc found"+${DESIGN_DOC_DISCOVERY_BLOCK}\`\`\`If a design doc is now found, read it and continue the review.@@ -1145,16 +1144,23 @@ Using the plan file already discovered in Step 8, look for a verification sectio### 2. Check for running dev server-Before invoking browse-based verification, check if a dev server is reachable:+Before invoking browse-based verification, find the dev-server URL the way the+project declares it — never trust a hardcoded port list alone:++1. **CLAUDE.md first:** look for a documented dev URL or dev command (a+ \`## Development\`/\`## Testing\` section naming a port or URL). Use it.+2. **The plan file:** if the plan's verification section names a URL, use it.+3. **Fallback probe** (common ports, only when 1-2 found nothing):\`\`\`bash-curl -s -o /dev/null -w '%{http_code}' http://localhost:3000 2>/dev/null || \\-curl -s -o /dev/null -w '%{http_code}' http://localhost:8080 2>/dev/null || \\-curl -s -o /dev/null -w '%{http_code}' http://localhost:5173 2>/dev/null || \\-curl -s -o /dev/null -w '%{http_code}' http://localhost:4000 2>/dev/null || echo "NO_SERVER"+for _p in 3000 8080 5173 4000 4321 8000; do+ _code=$(curl -s -o /dev/null -w '%{http_code}' "http://localhost:$_p" 2>/dev/null)+ [ -n "$_code" ] && [ "$_code" != "000" ] && { echo "DEV_SERVER: http://localhost:$_p ($_code)"; break; }+done+[ -z "\${_code:-}" ] || [ "\${_code:-000}" = "000" ] && echo "NO_SERVER"\`\`\`-**If NO_SERVER:** Skip with "No dev server detected — skipping plan verification. Run /qa separately after deploying."+**If NO_SERVER:** Skip with "No dev server detected (checked CLAUDE.md, the plan, and common ports) — skipping plan verification. Run /qa separately after deploying, or document the dev URL in CLAUDE.md so this step finds it next time."### 3. Invoke /qa-only inlinediff --git a/scripts/resolvers/tasks-section.ts b/scripts/resolvers/tasks-section.tsindex f36dbc0fc..0aeba08da 100644--- a/scripts/resolvers/tasks-section.ts+++ b/scripts/resolvers/tasks-section.ts@@ -120,12 +120,12 @@ if command -v jq >/dev/null 2>&1; then# Filter to current branch + recent commits, then keep records for the# latest run_id only. (Single phase may have multiple files if the user# re-ran the review; aggregator takes the newest.)- # NOTE: bind .commit BEFORE the split pipe. Inside ($commits | split(...))- # the "." context is the resulting ARRAY, so a bare .commit there raises- # "Cannot index array with string" on every record — and the 2>/dev/null- # below swallows it, so the whole aggregation silently yields zero tasks.+ # .commit must be bound BEFORE piping to the split commit array: a+ # pipe rebinds jq's context, so a bare .commit after it indexes the+ # ARRAY with a string, every line errors into 2>/dev/null, and the+ # aggregate is empty forever — the #2018 zero-tasks bug.jq -c --arg branch "$BRANCH" --arg commits "$COMMITS_RECENT" \\- 'select(.branch == $branch and ((.commit) as $c | ($commits | split("|") | index($c)) != null))' \\+ '.commit as $c | select(.branch == $branch and ($commits | split("|") | index($c) != null))' \\"$f" 2>/dev/null >> "$ALL_JSONL" || truedone < <(find "$TASKS_DIR" -maxdepth 1 -name "tasks-$phase-*.jsonl" 2>/dev/null | sort)# Reduce to latest run_id per phasediff --git a/scripts/resolvers/testing.ts b/scripts/resolvers/testing.tsindex 7790d8472..6ae68cff0 100644--- a/scripts/resolvers/testing.ts+++ b/scripts/resolvers/testing.ts@@ -3,41 +3,70 @@ import type { TemplateContext } from './types';export function generateTestBootstrap(_ctx: TemplateContext): string {return `## Test Framework Bootstrap-**Detect existing test framework and project runtime:**+**Read the project's CLAUDE.md (and TESTING.md if present) FIRST.** If it documents a test command, the project already told you: no detection, no bootstrap. Skip the rest of bootstrap and use that command in Step 5.++**Otherwise gather markers. Every marker below is EVIDENCE for the question you ask — never a command to run blind.** A marker tells you which ecosystem you're in and which command to OFFER. It does not tell you the command works. Do not execute a candidate test command to "check" it: a probe on a project that never had that runner fails loudly and teaches you nothing, and installing a second framework over a working one is worse.\`\`\`bashsetopt +o nomatch 2>/dev/null || true # zsh compat-# Detect project runtime-[ -f Gemfile ] && echo "RUNTIME:ruby"+# Definitive ecosystem markers (presence = ecosystem, NOT a command to run)+[ -f manage.py ] && echo "RUNTIME:python FRAMEWORK:django MARKER:manage.py"+{ [ -f pyproject.toml ] || [ -f pytest.ini ] || [ -f tox.ini ] || [ -f setup.cfg ] || [ -f requirements.txt ]; } && echo "RUNTIME:python"+[ -f Gemfile ] || [ -f Rakefile ] || [ -f .rspec ] && echo "RUNTIME:ruby"[ -f package.json ] && echo "RUNTIME:node"-[ -f requirements.txt ] || [ -f pyproject.toml ] && echo "RUNTIME:python"[ -f go.mod ] && echo "RUNTIME:go"[ -f Cargo.toml ] && echo "RUNTIME:rust"[ -f composer.json ] && echo "RUNTIME:php"[ -f mix.exs ] && echo "RUNTIME:elixir"+[ -f pom.xml ] && echo "RUNTIME:jvm BUILD:maven"+{ [ -f build.gradle ] || [ -f build.gradle.kts ]; } && echo "RUNTIME:jvm BUILD:gradle"# Detect sub-frameworks[ -f Gemfile ] && grep -q "rails" Gemfile 2>/dev/null && echo "FRAMEWORK:rails"[ -f package.json ] && grep -q '"next"' package.json 2>/dev/null && echo "FRAMEWORK:nextjs"-# Check for existing test infrastructure-ls jest.config.* vitest.config.* playwright.config.* .rspec pytest.ini pyproject.toml phpunit.xml 2>/dev/null-ls -d test/ tests/ spec/ __tests__/ cypress/ e2e/ 2>/dev/null+# Existing test path — config files, declared scripts, AND test FILES.+# A project with real tests and no config file is the common miss.+ls jest.config.* vitest.config.* playwright.config.* .rspec pytest.ini tox.ini phpunit.xml* 2>/dev/null+[ -f package.json ] && grep -q '"test"[[:space:]]*:' package.json && echo "SCRIPT:package.json test"+[ -f Makefile ] && grep -qE '^(test|check):' Makefile && echo "TARGET:make test"+[ -f pyproject.toml ] && grep -q "pytest" pyproject.toml && echo "CONFIG:pyproject pytest"+git ls-files | grep -cE '(^|/)(tests?|spec|__tests__)/|(^|/)tests?\\.py$|(^|/)test_[^/]+\\.py$|_test\\.(go|py|rb|ts|js|exs)$|\\.(test|spec)\\.[jt]sx?$|_spec\\.rb$|Test\\.(java|kt)$' | sed 's/^/TESTFILES:/'+# Rust keeps unit tests inside src/, so file names alone miss them+[ -f Cargo.toml ] && git grep -lF '#[test]' -- 'src' >/dev/null 2>&1 && echo "TESTS:rust in-source"# Check opt-out marker[ -f .gstack/no-test-bootstrap ] && echo "BOOTSTRAP_DECLINED"\`\`\`-**If test framework detected** (config files or test directories found):-Print "Test framework detected: {name} ({N} existing tests). Skipping bootstrap."+Map the markers to the command you will OFFER — never to one you run on a guess:++| Marker | Ecosystem | Candidate command to offer |+|--------|-----------|----------------------------|+| \`manage.py\` | Django | \`python manage.py test\` (or \`pytest\` when pytest-django is in the deps) |+| \`pytest.ini\` / \`tox.ini\` / pytest in \`pyproject.toml\` / \`test_*.py\` | Python | \`pytest\` |+| \`go.mod\` (+ any \`*_test.go\`) | Go | \`go test ./...\` |+| \`Cargo.toml\` | Rust | \`cargo test\` |+| \`pom.xml\` | JVM (Maven) | \`mvn test\` |+| \`build.gradle\` / \`build.gradle.kts\` | JVM (Gradle) | \`./gradlew test\` |+| \`Gemfile\` / \`Rakefile\` / \`.rspec\` | Ruby | \`bundle exec rspec\`, \`bin/rails test\`, or \`rake test\` |+| \`mix.exs\` | Elixir | \`mix test\` |+| \`composer.json\` | PHP | \`composer test\` or \`./vendor/bin/phpunit\` |+| \`package.json\` with a \`test\` script | Node | that script, run with the package manager the lockfile names |+| \`Makefile\` with a \`test:\` target | any | \`make test\` |++**If ANY existing-test evidence appears** (a config file, a declared test script or make target, a nonzero \`TESTFILES:\` count, or \`TESTS:rust in-source\`): the project has tests. **Do NOT bootstrap.** Print "Existing tests detected: {the evidence}." Then get the command the same way Step 5 does — CLAUDE.md/TESTING.md if documented, otherwise AskUserQuestion offering the candidates from the table above plus "Other", and persist the answer to CLAUDE.md's \`## Testing\` section so it is never asked again. When the ecosystem ships a runner (Django, Go, Rust, Elixir, Maven/Gradle), that runner is the candidate — never install a second framework beside a working one.Read 2-3 existing test files to learn conventions (naming, imports, assertion style, setup patterns).Store conventions as prose context for use in Phase 8e.5 or Step 7. **Skip the rest of bootstrap.**+Absent config files and absent \`tests/\` directories are NOT evidence of "no tests": Django keeps tests in \`<app>/tests.py\`, Go in \`*_test.go\` beside the source, Rust in \`#[test]\` blocks inside \`src/\`. A green \`python manage.py test\` with no \`pytest.ini\` is a tested project, not a bootstrap candidate.+**If BOOTSTRAP_DECLINED** appears: Print "Test bootstrap previously declined — skipping." **Skip the rest of bootstrap.**-**If NO runtime detected** (no config files found): Use AskUserQuestion:+**If NO ecosystem marker matched:** Use AskUserQuestion:"I couldn't detect your project's language. What runtime are you using?"Options: A) Node.js/TypeScript B) Ruby/Rails C) Python D) Go E) Rust F) PHP G) Elixir H) This project doesn't need tests.+If the runtime you need isn't listed, offer "Other" and take the runtime plus the test command as free text.If user picks H → write \`.gstack/no-test-bootstrap\` and continue without tests.-**If runtime detected but no test framework — bootstrap:**+**If an ecosystem matched but there is no existing-test evidence at all — bootstrap:**### B2. Research best practices@@ -53,7 +82,9 @@ If WebSearch is unavailable, use this built-in knowledge table:| Node.js | vitest + @testing-library | jest + @testing-library || Next.js | vitest + @testing-library/react + playwright | jest + cypress || Python | pytest + pytest-cov | unittest |+| Django | pytest + pytest-django | Django's built-in \`manage.py test\` (unittest) || Go | stdlib testing + testify | stdlib only |+| JVM (Maven/Gradle) | JUnit 5 + AssertJ | JUnit 5 only || Rust | cargo test (built-in) + mockall | — || PHP | phpunit + mockery | pest || Elixir | ExUnit (built-in) + ex_machina | — |@@ -202,15 +233,20 @@ Before analyzing coverage, detect the project's test framework:\`\`\`bashsetopt +o nomatch 2>/dev/null || true # zsh compat-# Detect project runtime-[ -f Gemfile ] && echo "RUNTIME:ruby"+# Detect project runtime (markers are evidence, not commands to run blind)+[ -f manage.py ] && echo "RUNTIME:python FRAMEWORK:django"+{ [ -f pyproject.toml ] || [ -f pytest.ini ] || [ -f tox.ini ] || [ -f setup.cfg ] || [ -f requirements.txt ]; } && echo "RUNTIME:python"+[ -f Gemfile ] || [ -f Rakefile ] || [ -f .rspec ] && echo "RUNTIME:ruby"[ -f package.json ] && echo "RUNTIME:node"-[ -f requirements.txt ] || [ -f pyproject.toml ] && echo "RUNTIME:python"[ -f go.mod ] && echo "RUNTIME:go"[ -f Cargo.toml ] && echo "RUNTIME:rust"-# Check for existing test infrastructure-ls jest.config.* vitest.config.* playwright.config.* cypress.config.* .rspec pytest.ini phpunit.xml 2>/dev/null-ls -d test/ tests/ spec/ __tests__/ cypress/ e2e/ 2>/dev/null+[ -f pom.xml ] && echo "RUNTIME:jvm BUILD:maven"+{ [ -f build.gradle ] || [ -f build.gradle.kts ]; } && echo "RUNTIME:jvm BUILD:gradle"+# Check for existing test infrastructure — config files, scripts, AND test files+ls jest.config.* vitest.config.* playwright.config.* cypress.config.* .rspec pytest.ini tox.ini phpunit.xml 2>/dev/null+[ -f package.json ] && grep -q '"test"[[:space:]]*:' package.json && echo "SCRIPT:package.json test"+[ -f Makefile ] && grep -qE '^(test|check):' Makefile && echo "TARGET:make test"+git ls-files | grep -cE '(^|/)(tests?|spec|__tests__)/|(^|/)tests?\\.py$|(^|/)test_[^/]+\\.py$|_test\\.(go|py|rb|ts|js|exs)$|\\.(test|spec)\\.[jt]sx?$|_spec\\.rb$|Test\\.(java|kt)$' | sed 's/^/TESTFILES:/'\`\`\`3. **If no framework detected:**${mode === 'ship' ? ' falls through to the Test Framework Bootstrap step (Step 4) which handles full setup.' : ' still produce the coverage diagram, but skip test generation.'}`);diff --git a/scripts/resolvers/third-party-actions.ts b/scripts/resolvers/third-party-actions.tsnew file mode 100644index 000000000..f325ac6ec--- /dev/null+++ b/scripts/resolvers/third-party-actions.ts@@ -0,0 +1,33 @@+/**+ * {{THIRD_PARTY_ACTIONS}} — the third-party web actions contract.+ *+ * Governs the moment a workflow needs something done on an external website+ * the user controls: registering an API key, creating a vendor account,+ * configuring a dashboard, webhook, OAuth app, billing plan, or domain+ * verification. Instead of dumping a manual step list, the skill offers to+ * drive the browser (consent-gated, secrets never in chat) and verifies the+ * captured credential before claiming success.+ *+ * Adapted from time-attack/gstack's THIRD-PARTY-ACTIONS.md (GStack 2, MIT):+ * the fork detected the Aside AI browser; we drive our own stack — browse+ * headed mode + handoff/resume ($B), GStack Browser, and pair-agent.+ * Portions copyright (c) 2026 Sina Matian, time-attack/gstack, MIT.+ */++import type { TemplateContext } from './types';++export function generateThirdPartyActions(_ctx: TemplateContext): string {+ return `## Third-Party Web Actions++A step sometimes requires action on an external website the user controls: registering an API key, creating a vendor or developer account, configuring a dashboard, webhook, OAuth app, billing plan, or domain verification. This contract governs that moment. It grants no new browsing authority — the AskUserQuestion format and one-way-door rules remain binding, including approval before anything that spends money.++1. **Never hand the user a manual step list for a third-party site without first offering to drive it.** The driver is gstack's own browser stack: \`$B\` headed mode with handoff/resume for the human-only moments (see the /browse skill), or GStack Browser when installed. Never install new tooling to close the gap, and never treat tooling presence as consent to browse.++2. **One explicit question before any browsing.** STOP and name the exact site and the exact actions (for example "create a test-mode API token in the Duffel dashboard"), then offer: A) I drive it now in a visible browser — you take over for sign-in and approvals, B) manual instructions, C) defer. The selection is per-task consent; never persist it as standing permission and never infer it from an earlier task.++3. **When driving, touch only the named site and actions.** Password entry, new-account credential choice, payment, CAPTCHA, and identity verification are user-performed: hand off (\`$B handoff\`) and wait instead of acting. Prefer credential flows that never expose the secret to the agent, such as password-manager autofill or the dashboard's own copy button used by the human.++4. **A captured secret never appears in chat output, logs, or shell history.** Write it to a user-approved local file with owner-only permissions (0600) or the user's secret store, and keep generated destinations out of version control. Dashboard fields are often masked placeholders — verify the captured credential with ONE non-mutating API call before claiming success; a 401 here has caught a placeholder masquerading as a key.++5. **If the user declines or defers, or no browser is usable,** provide the manual steps and mark the step blocked on the user. Do not recommend or install new products to close the gap.`;+}diff --git a/scripts/test-free-shards.ts b/scripts/test-free-shards.tsindex df82e4df6..c5724a293 100755--- a/scripts/test-free-shards.ts+++ b/scripts/test-free-shards.ts@@ -30,10 +30,11 @@ import { spawnSync } from 'child_process';import { isPaidTestFile } from '../test/helpers/paid-test-set';const ROOT = path.resolve(import.meta.dir, '..');-// design/test was silently absent from BOTH the package.json test script and-// this list — design tests (including a teardown bomb) never ran in any CI-// or local free run. Keep the two lists in sync.-const TEST_ROOTS = ['browse/test', 'test', 'make-pdf/test', 'design/test'] as const;+// design/test and ios-qa/daemon/test were both silently absent from every+// runner (package.json glob + this list) — design tests (including a teardown+// bomb) and the 10 hermetic ios-qa daemon suites never ran in any CI or local+// free run. Keep the two lists in sync with package.json's test script.+const TEST_ROOTS = ['browse/test', 'test', 'make-pdf/test', 'design/test', 'ios-qa/daemon/test'] as const;const TEST_FILE_REGEX = /\.test\.(?:[cm]?[jt]s|tsx|jsx)$/;// POSIX-only patterns that indicate a test will fail on windows-latest nodiff --git a/setup b/setupindex ede9d4eae..51be8f13a 100755--- a/setup+++ b/setup@@ -293,20 +293,62 @@ if [ "$INSTALL_CODEX" -eq 1 ]; thenmigrate_direct_codex_install "$SOURCE_GSTACK_DIR" "$CODEX_GSTACK"fi+# Kill an entire process tree rooted at $1, leaves first. Killing only the+# backgrounded subshell orphans the wedged node/bun -> Chromium probe+# processes underneath it — re-creating the #2136 stuck-process pile-up and+# potentially leaving Playwright cache locks held. macOS ships no setsid+# binary, so a portable group-kill isn't available; walk `pgrep -P` children+# depth-first instead (pgrep exists on macOS and Linux). Falls back to a+# plain kill of the root pid when pgrep is unavailable.+_kill_tree() {+ local pid="$1" child+ if command -v pgrep >/dev/null 2>&1; then+ for child in $(pgrep -P "$pid" 2>/dev/null); do+ _kill_tree "$child"+ done+ fi+ kill -9 "$pid" 2>/dev/null || true+}++# Deadline-bounded wait for a background probe. macOS ships no GNU timeout;+# poll the PID and SIGKILL the whole probe tree past the deadline. Returns+# the probe's exit code, or 124 on timeout.+_wait_with_deadline() {+ local pid="$1" deadline_s="$2" waited=0+ while kill -0 "$pid" 2>/dev/null; do+ if [ "$waited" -ge "$deadline_s" ]; then+ _kill_tree "$pid"+ wait "$pid" 2>/dev/null || true+ return 124+ fi+ sleep 1+ waited=$((waited + 1))+ done+ wait "$pid"+}+ensure_playwright_browser() {- if [ "$IS_WINDOWS" -eq 1 ]; then- # On Windows, Bun can't launch Chromium due to broken pipe handling- # (oven-sh/bun#4253). Use Node.js to verify Chromium works instead.- (- cd "$SOURCE_GSTACK_DIR"- node -e "const { chromium } = require('playwright'); (async () => { const b = await chromium.launch(); await b.close(); })()" 2>/dev/null- )+ # #2136: fresh installs hung forever at this probe (macOS arm64) and+ # re-runs stacked stuck process trees, so skills never got linked. Two+ # fixes: prefer Node for the launch probe everywhere it exists (the+ # bun --eval launch is the same pipe-bug family already worked around on+ # Windows), and bound the probe with a 90s deadline — a wedged probe now+ # reports failure (which routes to the install path) instead of hanging+ # setup.+ local probe_cmd+ if command -v node >/dev/null 2>&1; then+ probe_cmd='node -e "const { chromium } = require((process.cwd()) + \"/node_modules/playwright\"); (async () => { const b = await chromium.launch(); await b.close(); })().then(() => process.exit(0), () => process.exit(1))"'+ elif [ "$IS_WINDOWS" -eq 1 ]; then+ echo "gstack setup failed: Node.js is required on Windows" >&2+ return 1else- (- cd "$SOURCE_GSTACK_DIR"- bun --eval 'import { chromium } from "playwright"; const browser = await chromium.launch(); await browser.close();'- ) >/dev/null 2>&1+ probe_cmd="bun --eval 'import { chromium } from \"playwright\"; const browser = await chromium.launch(); await browser.close();'"fi+ (+ cd "$SOURCE_GSTACK_DIR"+ eval "$probe_cmd"+ ) >/dev/null 2>&1 &+ _wait_with_deadline $! 90}# Ensure a color-emoji font is installed (Linux only).@@ -568,14 +610,41 @@ fiif ! ensure_playwright_browser; thenecho "Installing Playwright Chromium..."- (- cd "$SOURCE_GSTACK_DIR"- if [ -n "$_PLAYWRIGHT_PLATFORM_OVERRIDE" ]; then- PLAYWRIGHT_HOST_PLATFORM_OVERRIDE="$_PLAYWRIGHT_PLATFORM_OVERRIDE" bunx playwright install chromium- else- bunx playwright install chromium+ _PW_LOCK="${TMPDIR:-/tmp}/gstack-playwright-install.lock"+ # Stale-lock self-heal: a SIGKILL'd prior setup leaves the lock dir behind+ # forever (mkdir mutexes have no owner). If the recorded holder PID is dead,+ # reclaim instead of telling the user to rmdir by hand.+ if [ -d "$_PW_LOCK" ] && [ -f "$_PW_LOCK/pid" ]; then+ _PW_HOLDER=$(cat "$_PW_LOCK/pid" 2>/dev/null || true)+ if [ -n "$_PW_HOLDER" ] && ! kill -0 "$_PW_HOLDER" 2>/dev/null; then+ echo " reclaiming stale Chromium-install lock (holder pid $_PW_HOLDER is gone)" >&2+ rm -rf "$_PW_LOCK" 2>/dev/null || truefi- )+ fi+ if mkdir "$_PW_LOCK" 2>/dev/null; then+ echo "$$" > "$_PW_LOCK/pid" 2>/dev/null || true+ # Chain the earlier cleanup_copied_bun EXIT trap: `trap ... EXIT` REPLACES+ # the previous handler, so the lock trap must run both or any run taking+ # this path leaves .tmp-bun-bin behind.+ trap 'rm -rf "$_PW_LOCK" 2>/dev/null || true; cleanup_copied_bun' EXIT+ (+ cd "$SOURCE_GSTACK_DIR"+ if [ -n "$_PLAYWRIGHT_PLATFORM_OVERRIDE" ]; then+ PLAYWRIGHT_HOST_PLATFORM_OVERRIDE="$_PLAYWRIGHT_PLATFORM_OVERRIDE" bunx playwright install chromium+ else+ bunx playwright install chromium+ fi+ )+ rm -rf "$_PW_LOCK" 2>/dev/null || true+ # Restore the original handler (never `trap - EXIT`, which would clear+ # cleanup_copied_bun for the rest of the script).+ trap cleanup_copied_bun EXIT+ else+ echo " another gstack setup is already installing Chromium (lock: $_PW_LOCK)." >&2+ echo " Wait for it to finish, then re-run ./setup. If no other setup is running," >&2+ echo " remove the stale lock: rm -rf \"$_PW_LOCK\"" >&2+ exit 1+ fiif [ "$IS_WINDOWS" -eq 1 ]; then# On Windows, Node.js launches Chromium (not Bun — see oven-sh/bun#4253).diff --git a/setup-deploy/SKILL.md b/setup-deploy/SKILL.mdindex 0207b09a0..d4eb17044 100644--- a/setup-deploy/SKILL.md+++ b/setup-deploy/SKILL.md@@ -677,6 +677,10 @@ When options differ in coverage, include `Completeness: X/10` (10 = all edge casFor high-stakes ambiguity (architecture, data model, destructive scope, missing context), STOP. Name it in one sentence, present 2-3 options with tradeoffs, and ask. Do not use for routine coding or obvious changes.+## Claimed Limitations Need Evidence++A claimed limitation or requirement ("the API can't do this", "X requires a credential", "that's impossible on this platform") is a material claim. State one only with the verbatim error, the documented statement, or a live probe in hand — pattern-matching a failure to a familiar story is not evidence. When a cheap probe settles the question, run it BEFORE asking the user anything or declaring a step blocked.+## Continuous Checkpoint ModeIf `CHECKPOINT_MODE` is `"continuous"`: auto-commit completed logical units with `WIP:` prefix.@@ -789,6 +793,20 @@ the failure occurred (if outcome is error, otherwise use empty string "").Skills that run plan reviews (`/plan-*-review`, `/codex review`) include the EXIT PLAN MODE GATE blocking checklist at the end of the skill, which verifies the plan file ends with `## GSTACK REVIEW REPORT` before ExitPlanMode is called. Skills that don't run plan reviews (operational skills like `/ship`, `/qa`, `/review`) typically don't operate in plan mode and have no review report to verify; this footer is a no-op for them. Writing the plan file is the one edit allowed in plan mode.+## Third-Party Web Actions++A step sometimes requires action on an external website the user controls: registering an API key, creating a vendor or developer account, configuring a dashboard, webhook, OAuth app, billing plan, or domain verification. This contract governs that moment. It grants no new browsing authority — the AskUserQuestion format and one-way-door rules remain binding, including approval before anything that spends money.++1. **Never hand the user a manual step list for a third-party site without first offering to drive it.** The driver is gstack's own browser stack: `$B` headed mode with handoff/resume for the human-only moments (see the /browse skill), or GStack Browser when installed. Never install new tooling to close the gap, and never treat tooling presence as consent to browse.++2. **One explicit question before any browsing.** STOP and name the exact site and the exact actions (for example "create a test-mode API token in the Duffel dashboard"), then offer: A) I drive it now in a visible browser — you take over for sign-in and approvals, B) manual instructions, C) defer. The selection is per-task consent; never persist it as standing permission and never infer it from an earlier task.++3. **When driving, touch only the named site and actions.** Password entry, new-account credential choice, payment, CAPTCHA, and identity verification are user-performed: hand off (`$B handoff`) and wait instead of acting. Prefer credential flows that never expose the secret to the agent, such as password-manager autofill or the dashboard's own copy button used by the human.++4. **A captured secret never appears in chat output, logs, or shell history.** Write it to a user-approved local file with owner-only permissions (0600) or the user's secret store, and keep generated destinations out of version control. Dashboard fields are often masked placeholders — verify the captured credential with ONE non-mutating API call before claiming success; a 401 here has caught a placeholder masquerading as a key.++5. **If the user declines or defers, or no browser is usable,** provide the manual steps and mark the step blocked on the user. Do not recommend or install new products to close the gap.+# /setup-deploy — Configure Deployment for gstackYou are helping the user configure their deployment so `/land-and-deploy` worksdiff --git a/setup-deploy/SKILL.md.tmpl b/setup-deploy/SKILL.md.tmplindex 587a993c0..5630f294b 100644--- a/setup-deploy/SKILL.md.tmpl+++ b/setup-deploy/SKILL.md.tmpl@@ -25,6 +25,8 @@ allowed-tools:{{PREAMBLE}}+{{THIRD_PARTY_ACTIONS}}+# /setup-deploy — Configure Deployment for gstackYou are helping the user configure their deployment so `/land-and-deploy` worksdiff --git a/setup-gbrain/SKILL.md b/setup-gbrain/SKILL.mdindex f66f88fcb..0cc751fbc 100644--- a/setup-gbrain/SKILL.md+++ b/setup-gbrain/SKILL.md@@ -676,6 +676,10 @@ When options differ in coverage, include `Completeness: X/10` (10 = all edge casFor high-stakes ambiguity (architecture, data model, destructive scope, missing context), STOP. Name it in one sentence, present 2-3 options with tradeoffs, and ask. Do not use for routine coding or obvious changes.+## Claimed Limitations Need Evidence++A claimed limitation or requirement ("the API can't do this", "X requires a credential", "that's impossible on this platform") is a material claim. State one only with the verbatim error, the documented statement, or a live probe in hand — pattern-matching a failure to a familiar story is not evidence. When a cheap probe settles the question, run it BEFORE asking the user anything or declaring a step blocked.+## Continuous Checkpoint ModeIf `CHECKPOINT_MODE` is `"continuous"`: auto-commit completed logical units with `WIP:` prefix.@@ -896,22 +900,16 @@ mv "$HOME/.gbrain/config.json" "$BACKUP"# gstack default: voyage-code-3 (1024d) when VOYAGE_API_KEY is set — best for# code retrieval. Without the key, fall back to gbrain's own auto-selected# embedding provider chain (OpenAI 1536d when OPENAI_API_KEY is present, etc.).+set -- # flags ride the positional params — unquoted $VAR breaks under zsh word-splitting (#1798)if [ -n "${VOYAGE_API_KEY:-}" ]; then- if ! gbrain init --pglite --json --embedding-model voyage:voyage-code-3 --embedding-dimensions 1024; then- # Restore on failure- mv "$BACKUP" "$HOME/.gbrain/config.json"- echo "gbrain init failed. Your previous config was restored at $HOME/.gbrain/config.json." >&2- echo "PGLite directory at ~/.gbrain/pglite/ may be in a partial state — \`rm -rf ~/.gbrain/pglite\` if needed before retrying." >&2- exit 1- fi-else- if ! gbrain init --pglite --json; then- # Restore on failure- mv "$BACKUP" "$HOME/.gbrain/config.json"- echo "gbrain init failed. Your previous config was restored at $HOME/.gbrain/config.json." >&2- echo "PGLite directory at ~/.gbrain/pglite/ may be in a partial state — \`rm -rf ~/.gbrain/pglite\` if needed before retrying." >&2- exit 1- fi+ set -- --embedding-model voyage:voyage-code-3 --embedding-dimensions 1024+fi+if ! gbrain init --pglite --json "$@"; then+ # Restore on failure+ mv "$BACKUP" "$HOME/.gbrain/config.json"+ echo "gbrain init failed. Your previous config was restored at $HOME/.gbrain/config.json." >&2+ echo "PGLite directory at ~/.gbrain/pglite/ may be in a partial state — \`rm -rf ~/.gbrain/pglite\` if needed before retrying." >&2+ exit 1fiecho "Switched to local PGLite. Previous config saved at $BACKUP — review before deleting."```@@ -929,6 +927,51 @@ Step 1.5 — fall through to Step 2 (where `no-cli` triggers Step 3 install and---+## Step 1.7: Code-intelligence provider choice (Step 0 of indexing)++You are INSIDE /setup-gbrain: the user asked for gbrain by name, so the+provider question is already answered. NEVER ask it here, and never let this+step delay or derail the actual setup. Record the choice best-effort, then+continue immediately with Step 2:++```bash+[ -f ~/.claude/skills/gstack/bin/gstack-code-intelligence ] \+ && bun ~/.claude/skills/gstack/bin/gstack-code-intelligence select gbrain 2>/dev/null \+ || true+```++The offer ceremony below applies ONLY when this skill is reached from another+entry point where no provider was named (a routing skill exploring indexing+options). Even then:++- `"offer": false` with reason `bin-absent` → the installed gstack predates+ the code-intelligence CLI. Skip this step entirely and continue with the+ skill — the user asked for gbrain, so set up gbrain. Never block setup on+ a missing optional gate.++- `"offer": false` with reason `small-repo` → grep is already fast here; say+ so in one line and continue with this skill only if the user asked for+ gbrain by name.+- `"offer": false` with reason `provider-selected` or `declined` → the+ machine-wide question was already answered; apply it silently and continue.+- `"offer": true` → present the returned options ONCE via AskUserQuestion:+ **GBrain** (recommended — semantic memory + code, sends repo content to+ YOUR gbrain DB, per-repo consent), **Sourcebot** (self-hosted whole-repo+ search, local when on localhost), **Graphify** (local tree-sitter graph,+ nothing leaves the machine, user installs it), or **No indexing**. Record+ the choice: `gstack-code-intelligence select <provider|none>` — `none`+ persists the decline so NO skill ever asks again, on any repo+ (re-enable: `gstack-code-intelligence select <provider>`). Local-compute+ and remote-send providers are separate consents — never bundle them.+- Per-repo send consent (GBrain/Sourcebot) is recorded with+ `gstack-code-intelligence consent <repo> yes|no` and is ALWAYS vetoed by a+ `deny` tier in gstack-gbrain-repo-policy — the trust store is the single+ authority for whether code leaves a repo.++If the user picked GBrain (or asked for this skill directly), continue below.+If they picked Sourcebot/Graphify, run `gstack-code-intelligence index <repo>`+and stop — the rest of this skill is gbrain-specific.+## Step 2: Pick a path (AskUserQuestion)Only fire this if Step 1 shows no existing working config AND no shortcut@@ -1116,11 +1159,11 @@ Then follow the same secret-read + verify + init flow as Path 1.# gstack default: voyage-code-3 (1024d) when VOYAGE_API_KEY is set — code# retrieval beats general-purpose embeddings on real code queries (validated# A/B). Without the key, gbrain auto-selects (OpenAI 1536d when available).+set -- # flags ride the positional params — unquoted $VAR breaks under zsh word-splitting (#1798)if [ -n "${VOYAGE_API_KEY:-}" ]; then- gbrain init --pglite --json --embedding-model voyage:voyage-code-3 --embedding-dimensions 1024-else- gbrain init --pglite --json+ set -- --embedding-model voyage:voyage-code-3 --embedding-dimensions 1024fi+gbrain init --pglite --json "$@"```Done. No network, no secrets (beyond Voyage embedding API calls during sync, if@@ -1208,18 +1251,14 @@ fi# VOYAGE_API_KEY is set. It wins the A/B over voyage-4-large and OpenAI# text-embedding-3-large on this codebase's symbol queries. Falls back to# gbrain's auto-selected provider when the key isn't present.+set -- # flags ride the positional params — unquoted $VAR breaks under zsh word-splitting (#1798)if [ -n "${VOYAGE_API_KEY:-}" ]; then- if ! gbrain init --pglite --json --embedding-model voyage:voyage-code-3 --embedding-dimensions 1024; then- if [ -n "${BACKUP:-}" ] && [ -f "$BACKUP" ]; then mv "$BACKUP" "$HOME/.gbrain/config.json"; fi- echo "gbrain init failed. Existing config (if any) was restored. PGLite at ~/.gbrain/pglite/ may be in a partial state — \`rm -rf ~/.gbrain/pglite\` to reset." >&2- echo "Continuing setup without local code search; you can re-run /setup-gbrain to retry." >&2- fi-else- if ! gbrain init --pglite --json; then- if [ -n "${BACKUP:-}" ] && [ -f "$BACKUP" ]; then mv "$BACKUP" "$HOME/.gbrain/config.json"; fi- echo "gbrain init failed. Existing config (if any) was restored. PGLite at ~/.gbrain/pglite/ may be in a partial state — \`rm -rf ~/.gbrain/pglite\` to reset." >&2- echo "Continuing setup without local code search; you can re-run /setup-gbrain to retry." >&2- fi+ set -- --embedding-model voyage:voyage-code-3 --embedding-dimensions 1024+fi+if ! gbrain init --pglite --json "$@"; then+ if [ -n "${BACKUP:-}" ] && [ -f "$BACKUP" ]; then mv "$BACKUP" "$HOME/.gbrain/config.json"; fi+ echo "gbrain init failed. Existing config (if any) was restored. PGLite at ~/.gbrain/pglite/ may be in a partial state — \`rm -rf ~/.gbrain/pglite\` to reset." >&2+ echo "Continuing setup without local code search; you can re-run /setup-gbrain to retry." >&2fi```diff --git a/setup-gbrain/SKILL.md.tmpl b/setup-gbrain/SKILL.md.tmplindex f33b929d0..2eff76403 100644--- a/setup-gbrain/SKILL.md.tmpl+++ b/setup-gbrain/SKILL.md.tmpl@@ -134,22 +134,16 @@ mv "$HOME/.gbrain/config.json" "$BACKUP"# gstack default: voyage-code-3 (1024d) when VOYAGE_API_KEY is set — best for# code retrieval. Without the key, fall back to gbrain's own auto-selected# embedding provider chain (OpenAI 1536d when OPENAI_API_KEY is present, etc.).+set -- # flags ride the positional params — unquoted $VAR breaks under zsh word-splitting (#1798)if [ -n "${VOYAGE_API_KEY:-}" ]; then- if ! gbrain init --pglite --json --embedding-model voyage:voyage-code-3 --embedding-dimensions 1024; then- # Restore on failure- mv "$BACKUP" "$HOME/.gbrain/config.json"- echo "gbrain init failed. Your previous config was restored at $HOME/.gbrain/config.json." >&2- echo "PGLite directory at ~/.gbrain/pglite/ may be in a partial state — \`rm -rf ~/.gbrain/pglite\` if needed before retrying." >&2- exit 1- fi-else- if ! gbrain init --pglite --json; then- # Restore on failure- mv "$BACKUP" "$HOME/.gbrain/config.json"- echo "gbrain init failed. Your previous config was restored at $HOME/.gbrain/config.json." >&2- echo "PGLite directory at ~/.gbrain/pglite/ may be in a partial state — \`rm -rf ~/.gbrain/pglite\` if needed before retrying." >&2- exit 1- fi+ set -- --embedding-model voyage:voyage-code-3 --embedding-dimensions 1024+fi+if ! gbrain init --pglite --json "$@"; then+ # Restore on failure+ mv "$BACKUP" "$HOME/.gbrain/config.json"+ echo "gbrain init failed. Your previous config was restored at $HOME/.gbrain/config.json." >&2+ echo "PGLite directory at ~/.gbrain/pglite/ may be in a partial state — \`rm -rf ~/.gbrain/pglite\` if needed before retrying." >&2+ exit 1fiecho "Switched to local PGLite. Previous config saved at $BACKUP — review before deleting."```@@ -167,6 +161,51 @@ Step 1.5 — fall through to Step 2 (where `no-cli` triggers Step 3 install and---+## Step 1.7: Code-intelligence provider choice (Step 0 of indexing)++You are INSIDE /setup-gbrain: the user asked for gbrain by name, so the+provider question is already answered. NEVER ask it here, and never let this+step delay or derail the actual setup. Record the choice best-effort, then+continue immediately with Step 2:++```bash+[ -f ~/.claude/skills/gstack/bin/gstack-code-intelligence ] \+ && bun ~/.claude/skills/gstack/bin/gstack-code-intelligence select gbrain 2>/dev/null \+ || true+```++The offer ceremony below applies ONLY when this skill is reached from another+entry point where no provider was named (a routing skill exploring indexing+options). Even then:++- `"offer": false` with reason `bin-absent` → the installed gstack predates+ the code-intelligence CLI. Skip this step entirely and continue with the+ skill — the user asked for gbrain, so set up gbrain. Never block setup on+ a missing optional gate.++- `"offer": false` with reason `small-repo` → grep is already fast here; say+ so in one line and continue with this skill only if the user asked for+ gbrain by name.+- `"offer": false` with reason `provider-selected` or `declined` → the+ machine-wide question was already answered; apply it silently and continue.+- `"offer": true` → present the returned options ONCE via AskUserQuestion:+ **GBrain** (recommended — semantic memory + code, sends repo content to+ YOUR gbrain DB, per-repo consent), **Sourcebot** (self-hosted whole-repo+ search, local when on localhost), **Graphify** (local tree-sitter graph,+ nothing leaves the machine, user installs it), or **No indexing**. Record+ the choice: `gstack-code-intelligence select <provider|none>` — `none`+ persists the decline so NO skill ever asks again, on any repo+ (re-enable: `gstack-code-intelligence select <provider>`). Local-compute+ and remote-send providers are separate consents — never bundle them.+- Per-repo send consent (GBrain/Sourcebot) is recorded with+ `gstack-code-intelligence consent <repo> yes|no` and is ALWAYS vetoed by a+ `deny` tier in gstack-gbrain-repo-policy — the trust store is the single+ authority for whether code leaves a repo.++If the user picked GBrain (or asked for this skill directly), continue below.+If they picked Sourcebot/Graphify, run `gstack-code-intelligence index <repo>`+and stop — the rest of this skill is gbrain-specific.+## Step 2: Pick a path (AskUserQuestion)Only fire this if Step 1 shows no existing working config AND no shortcut@@ -354,11 +393,11 @@ Then follow the same secret-read + verify + init flow as Path 1.# gstack default: voyage-code-3 (1024d) when VOYAGE_API_KEY is set — code# retrieval beats general-purpose embeddings on real code queries (validated# A/B). Without the key, gbrain auto-selects (OpenAI 1536d when available).+set -- # flags ride the positional params — unquoted $VAR breaks under zsh word-splitting (#1798)if [ -n "${VOYAGE_API_KEY:-}" ]; then- gbrain init --pglite --json --embedding-model voyage:voyage-code-3 --embedding-dimensions 1024-else- gbrain init --pglite --json+ set -- --embedding-model voyage:voyage-code-3 --embedding-dimensions 1024fi+gbrain init --pglite --json "$@"```Done. No network, no secrets (beyond Voyage embedding API calls during sync, if@@ -446,18 +485,14 @@ fi# VOYAGE_API_KEY is set. It wins the A/B over voyage-4-large and OpenAI# text-embedding-3-large on this codebase's symbol queries. Falls back to# gbrain's auto-selected provider when the key isn't present.+set -- # flags ride the positional params — unquoted $VAR breaks under zsh word-splitting (#1798)if [ -n "${VOYAGE_API_KEY:-}" ]; then- if ! gbrain init --pglite --json --embedding-model voyage:voyage-code-3 --embedding-dimensions 1024; then- if [ -n "${BACKUP:-}" ] && [ -f "$BACKUP" ]; then mv "$BACKUP" "$HOME/.gbrain/config.json"; fi- echo "gbrain init failed. Existing config (if any) was restored. PGLite at ~/.gbrain/pglite/ may be in a partial state — \`rm -rf ~/.gbrain/pglite\` to reset." >&2- echo "Continuing setup without local code search; you can re-run /setup-gbrain to retry." >&2- fi-else- if ! gbrain init --pglite --json; then- if [ -n "${BACKUP:-}" ] && [ -f "$BACKUP" ]; then mv "$BACKUP" "$HOME/.gbrain/config.json"; fi- echo "gbrain init failed. Existing config (if any) was restored. PGLite at ~/.gbrain/pglite/ may be in a partial state — \`rm -rf ~/.gbrain/pglite\` to reset." >&2- echo "Continuing setup without local code search; you can re-run /setup-gbrain to retry." >&2- fi+ set -- --embedding-model voyage:voyage-code-3 --embedding-dimensions 1024+fi+if ! gbrain init --pglite --json "$@"; then+ if [ -n "${BACKUP:-}" ] && [ -f "$BACKUP" ]; then mv "$BACKUP" "$HOME/.gbrain/config.json"; fi+ echo "gbrain init failed. Existing config (if any) was restored. PGLite at ~/.gbrain/pglite/ may be in a partial state — \`rm -rf ~/.gbrain/pglite\` to reset." >&2+ echo "Continuing setup without local code search; you can re-run /setup-gbrain to retry." >&2fi```diff --git a/ship/SKILL.md b/ship/SKILL.mdindex 319dd43fc..1446dd74b 100644--- a/ship/SKILL.md+++ b/ship/SKILL.md@@ -678,6 +678,10 @@ When options differ in coverage, include `Completeness: X/10` (10 = all edge casFor high-stakes ambiguity (architecture, data model, destructive scope, missing context), STOP. Name it in one sentence, present 2-3 options with tradeoffs, and ask. Do not use for routine coding or obvious changes.+## Claimed Limitations Need Evidence++A claimed limitation or requirement ("the API can't do this", "X requires a credential", "that's impossible on this platform") is a material claim. State one only with the verbatim error, the documented statement, or a live probe in hand — pattern-matching a failure to a familiar story is not evidence. When a cheap probe settles the question, run it BEFORE asking the user anything or declaring a step blocked.+## Continuous Checkpoint ModeIf `CHECKPOINT_MODE` is `"continuous"`: auto-commit completed logical units with `WIP:` prefix.@@ -808,6 +812,20 @@ the failure occurred (if outcome is error, otherwise use empty string "").Skills that run plan reviews (`/plan-*-review`, `/codex review`) include the EXIT PLAN MODE GATE blocking checklist at the end of the skill, which verifies the plan file ends with `## GSTACK REVIEW REPORT` before ExitPlanMode is called. Skills that don't run plan reviews (operational skills like `/ship`, `/qa`, `/review`) typically don't operate in plan mode and have no review report to verify; this footer is a no-op for them. Writing the plan file is the one edit allowed in plan mode.+## Third-Party Web Actions++A step sometimes requires action on an external website the user controls: registering an API key, creating a vendor or developer account, configuring a dashboard, webhook, OAuth app, billing plan, or domain verification. This contract governs that moment. It grants no new browsing authority — the AskUserQuestion format and one-way-door rules remain binding, including approval before anything that spends money.++1. **Never hand the user a manual step list for a third-party site without first offering to drive it.** The driver is gstack's own browser stack: `$B` headed mode with handoff/resume for the human-only moments (see the /browse skill), or GStack Browser when installed. Never install new tooling to close the gap, and never treat tooling presence as consent to browse.++2. **One explicit question before any browsing.** STOP and name the exact site and the exact actions (for example "create a test-mode API token in the Duffel dashboard"), then offer: A) I drive it now in a visible browser — you take over for sign-in and approvals, B) manual instructions, C) defer. The selection is per-task consent; never persist it as standing permission and never infer it from an earlier task.++3. **When driving, touch only the named site and actions.** Password entry, new-account credential choice, payment, CAPTCHA, and identity verification are user-performed: hand off (`$B handoff`) and wait instead of acting. Prefer credential flows that never expose the secret to the agent, such as password-manager autofill or the dashboard's own copy button used by the human.++4. **A captured secret never appears in chat output, logs, or shell history.** Write it to a user-approved local file with owner-only permissions (0600) or the user's secret store, and keep generated destinations out of version control. Dashboard fields are often masked placeholders — verify the captured credential with ONE non-mutating API call before claiming success; a 401 here has caught a placeholder masquerading as a key.++5. **If the user declines or defers, or no browser is usable,** provide the manual steps and mark the step blocked on the user. Do not recommend or install new products to close the gap.+## Step 0: Detect platform and base branchFirst, detect the git hosting platform from the remote URL:@@ -895,6 +913,7 @@ sections. Read a section in full before doing its step; do not work from memory.| When | Read this section ||------|-------------------|+| the ship target is an Apple platform app (.xcodeproj, .xcworkspace, or an app-product Swift package) — read BEFORE Step 1's branch gate and any preflight; store distribution never routes through the branch/PR ceremony | `sections/apple-release.md` || running the test suites and (if prompt files changed) the eval suites (Steps 4-6) | `sections/tests.md` || auditing test coverage of the diff (Step 7) | `sections/test-coverage.md` || auditing plan completion, verification, and scope drift (Step 8) | `sections/plan-completion.md` |@@ -906,6 +925,18 @@ sections. Read a section in full before doing its step; do not work from memory.---+## Step 0.9: Apple target detection++Shipping to the App Store is not landing a PR. If the repository contains an+`.xcodeproj`, `.xcworkspace`, or a Swift package with an app product AND the+user's ask is store distribution (App Store, TestFlight, "release my app"),+**STOP and Read `~/.claude/skills/gstack/ship/sections/apple-release.md` FIRST**+— before the branch gate and any preflight below. Store distribution proceeds+from whatever branch the user is on (a clean tree on the base branch is the+solo developer's normal case, not an error) and follows the adapter end to+end. The branch gate and repository-landing pipeline below apply ONLY to+repository-landing asks, including on Apple repos.+## Step 1: Pre-flight1. Check the current branch. If on the base branch or the repo's default branch, **abort**: "You're on the base branch. Ship from a feature branch."diff --git a/ship/SKILL.md.tmpl b/ship/SKILL.md.tmplindex c867b020f..a01296688 100644--- a/ship/SKILL.md.tmpl+++ b/ship/SKILL.md.tmpl@@ -28,6 +28,8 @@ triggers:{{PREAMBLE}}+{{THIRD_PARTY_ACTIONS}}+{{BASE_BRANCH_DETECT}}{{GBRAIN_CONTEXT_LOAD}}@@ -75,6 +77,18 @@ Never skip a verification step because a prior `/ship` run already performed it.---+## Step 0.9: Apple target detection++Shipping to the App Store is not landing a PR. If the repository contains an+`.xcodeproj`, `.xcworkspace`, or a Swift package with an app product AND the+user's ask is store distribution (App Store, TestFlight, "release my app"),+**STOP and Read `~/.claude/skills/gstack/ship/sections/apple-release.md` FIRST**+— before the branch gate and any preflight below. Store distribution proceeds+from whatever branch the user is on (a clean tree on the base branch is the+solo developer's normal case, not an error) and follows the adapter end to+end. The branch gate and repository-landing pipeline below apply ONLY to+repository-landing asks, including on Apple repos.+## Step 1: Pre-flight1. Check the current branch. If on the base branch or the repo's default branch, **abort**: "You're on the base branch. Ship from a feature branch."diff --git a/ship/sections/apple-release.md b/ship/sections/apple-release.mdnew file mode 100644index 000000000..77afc79f4--- /dev/null+++ b/ship/sections/apple-release.md@@ -0,0 +1,58 @@+<!-- AUTO-GENERATED from apple-release.md.tmpl — do not edit directly -->+<!-- Regenerate: bun run gen:skill-docs -->+# Apple App Store release++<!-- Ported from time-attack/gstack (GStack 2) APPLE-RELEASE.md, refined+ across 21 live App Store releases. Portions copyright (c) 2026+ Sina Matian, time-attack/gstack, MIT. Adapted to gstack main's+ architecture: decision-store bins, the Third-Party Web Actions+ contract, and an idempotency log in place of the fork's durable-state+ wrapper. All credential examples are placeholders, never live formats. -->++Applies when the ship target is an Apple platform app: the repository contains an `.xcodeproj` or `.xcworkspace`, or a Swift package with an app product. Read this BEFORE Step 1's branch gate and any preflight. This adapter extends ship's judgment to the App Store journey end to end, and every upload or submission is treated as a durable external effect (idempotency contract below) — but store distribution is its own release path, not repository landing: ship's branch/PR ceremony (feature-branch gate, commit-review-PR pipeline, merge queue) applies only when the user asked to land repository changes. A user shipping to the App Store or TestFlight proceeds through this adapter from whatever branch they are on; a clean working tree on the base branch is a normal and valid state to archive and upload from. Never abort an App Store release over branch topology.++One tool runs the entire release: machine-level fastlane — `produce` (app record and bundle ID), `cert` and `sigh` (signing), `gym` (archive and signed export), `pilot` (TestFlight), `deliver` (metadata, screenshots, Submit for Review), `frameit` (device frames). Install it when missing (`brew install fastlane`) with a one-line announcement, not a question — the release authorization covers machine-tool installs. Never install additional App Store CLI tools, and never mention API keys, `.p8` files, sessions, or any credential format to the user; they paid US$99 and want to ship, and the release itself adds no new dependency to the user's project.++A Mac is required only for the build legs. Archiving, signing, and the binary upload ride Xcode's macOS-only toolchain — Apple ships it nowhere else, and no tool routes around that. On a non-macOS host, say so plainly, then route exactly those legs through a macOS CI runner (a GitHub Actions `macos` runner executing the same `gym` and `deliver`/`pilot` commands, with the minted upload key supplied as a CI secret — key auth is precisely what CI wants); sign-in, key minting, metadata, screenshots, pricing, and submission judgment are plain API work that stays on the user's machine. Never claim the whole release is impossible off a Mac, and never pretend the build leg is possible there.++## The one authorization moment++The whole journey permits exactly two interactions, and no others. FIRST, up front: confirm the user holds a paid Apple Developer Program membership (US$99/year — the App Store and TestFlight both require it) and authorize the release. Pricing belongs to this same breath, once per app EVER: ask free or paid (and the price if paid) inside the authorization question — never as a separate interruption — after checking the decision store (`bin/gstack-decision-search --scope repo --query "pricing"`); persist the answer (`~/.claude/skills/gstack/bin/gstack-decision-log`, scope `repo`) so no later release re-asks, and a paid answer names the one-time Paid Apps banking/tax agreement honestly right there, since nothing sells until it is signed. Price is a launch decision the agent never defaults silently: a free launch cannot be un-launched. Apple sign-in happens inside this same moment: run `fastlane spaceauth -u <apple-id>` through the host's interactive command path (in Claude Code, the user types `! fastlane spaceauth -u <email>` so their password and one two-factor code go directly to Apple in-session; a separate terminal window is the fallback only when the host has no interactive path). Keep the printed session token out of the transcript — the cached cookie in `~/.fastlane/spaceship/` is the credential fastlane actually uses; never store, echo, or log the password or token, and re-run the same one command when the session expires. Immediately after the first sign-in, mint the permanent upload key from the session (step 4 of Archive and upload) — when that key already sits at `~/.gstack/apple/api-key.json` and no new app record is needed, skip the sign-in entirely: repeat releases authorize and proceed with zero sign-in. SECOND, only when preflight finds the icon or screenshots missing: the store-assets question below. Everything else — tool installs, upload, storefront, submission — is covered by the authorization and proceeds without asking. Auth menus, tool-choice questions, plan confirmations, and step-by-step narration requests are contract violations.++No membership: STOP the App Store path. Offer to walk enrollment at developer.apple.com through the Third-Party Web Actions contract (earlier in this skill) (a purchase the user completes themselves; activation can take a day or two), and name the free-account ceiling honestly: personal-team installs on the user's own devices only, expiring after 7 days, no TestFlight, no App Store.++## Release preflight++Resolve and verify before archiving. Fix what the printed mutation boundary authorizes; report everything else as a blocking finding.++- Signing: development team on the app target; `cert` and `sigh` mint the distribution certificate and App Store profile when none exist.+- Versioning: a marketing version users should see and a build number strictly greater than any build already uploaded for that version.+- Dependencies: `xcodebuild -resolvePackageDependencies` succeeds; if a `Podfile` or `Cartfile` exists, its install step has been run and lockfiles are current.+- App Store validation blockers: complete app icon set including the 1024pt marketing icon, launch screen, a usage-description string for every privacy-gated API the app touches, required privacy manifests, an export-compliance answer (`ITSAppUsesNonExemptEncryption`), and a sane deployment target.++## Store assets++Only when preflight finds the icon or screenshots missing, ask once — the journey's second and final permitted question — then act on the choice without further prompts. Once per app, EVER: before asking, check the decision store (`bin/gstack-decision-search --scope repo --query "store assets"`); a settled choice (including "defer screenshots" or "TestFlight only") is applied silently, never re-asked. After the user answers, persist it (`~/.claude/skills/gstack/bin/gstack-decision-log` with scope `repo`) so no future run asks again; the user changes it by saying so, not by being re-prompted. Offer:++- **App icon**: SnapAI (`npx snapai`, the app-icon agent skill) generates the single 1024×1024 with the user's own image-generation key; Xcode 15+ derives every size from that one image.+- **Marketing screenshots, free and local, no API key**: the app-store-screenshots deck editor skill — scaffold it, prefill its deck JSON with simulator captures and benefit headlines, and export one bundle covering every required iPhone size (the export is headlessly automatable). Marketing-grade does NOT require an image backend; never claim screenshots need an API key while this skill is installed.+- **Plain frames, free and local**: capture the built app in the simulator and frame with fastlane `frameit` — the minimal option when no designed deck is wanted.+- **AI-enhanced marketing screenshots**: the aso-appstore-screenshots agent skill (benefit headlines, breakout panels, exact App Store dimensions) — the only option that needs the user's own image-generation key; when installed, follow its workflow rather than reimplementing it.+- **User-supplied files**: always a valid answer; validate dimensions and move on.++Build this question's options from a LIVE check of installed skills at ask time — never from memory or an earlier conversation turn. Whenever the app-store-screenshots deck editor skill is installed, its free no-key option MUST appear in the list; omitting it is a contract violation equal to claiming screenshots need an API key. Assets already present skip this entirely. Announce what was generated at exit.++## Archive and upload++1. Archive and export the signed Release build with `gym` (it drives xcodebuild and the signing minted in preflight). Projects with custom archive requirements may drop to `xcodebuild archive` directly; the output either way is an App Store-signed `.ipa`.+2. The upload is an external effect: run `pilot` (TestFlight) or `deliver` (App Store) under the durable-effect contract: before executing, append the key `appstore.upload.<bundle-id>.<build>` to `~/.gstack/projects/$SLUG/apple-effects.log`; if the key is already present from a prior run (crash, retry), treat the upload as possibly-done and do NOT re-run it. Never re-upload on ambiguity; inspect App Store Connect for the build first.+3. The cached session, the minted key, and every credential file are env- or file-level secrets: never argv, never echoed, never committed.+4. NEVER demand an app-specific password — the session MINTS the upload key instead. Per fastlane's documented authentication, Apple's binary-upload tool (iTMSTransporter, which `deliver`/`pilot` shell out to for the `.ipa`) does not accept the web session: it takes only an App Store Connect API key or an app-specific password, and Apple's error `-22938` ("Sign in with the app-specific password") is Transporter saying exactly this. That is not a gate and not a question, because the web session creates the key itself, silently: through fastlane's bundled spaceship (`Spaceship::Tunes.login(<apple-id>)` reuses the cached cookie, then raw client requests), `POST https://appstoreconnect.apple.com/iris/v1/apiKeys` with JSON:API body `{data:{type:"apiKeys",attributes:{nickname:"gstack-upload",allAppsVisible:true,roles:["APP_MANAGER"],keyType:"PUBLIC_API"}}}`, then `GET .../iris/v1/apiKeys/<id>?fields[apiKeys]=privateKey` — the `privateKey` attribute is base64 of the COMPLETE PEM file: decode it exactly once and write `~/.appstoreconnect/private_keys/AuthKey_<id>.p8` (0600) immediately, it is downloadable only at creation. The issuer ID is `provider.publicProviderId` from `GET https://appstoreconnect.apple.com/olympus/v1/session`. Record key id, issuer id, and key content as a fastlane api-key JSON at `~/.gstack/apple/api-key.json` (0600) and run `deliver`/`pilot` with `api_key_path` from then on. The key never expires, so every later release skips sign-in; the session stays necessary only for `produce` (Apple's public API cannot create app records) and for re-minting if the key is ever revoked. Stating that the user must generate any credential themselves while key minting is untried is a contract violation. CLASSIFY the error before touching credentials: an error is an authentication failure ONLY when it says so (401/403, session invalid or expired, "sign in", "app-specific password" in Apple's own words). A `Spaceship::UnexpectedResponse`, missing/invalid attribute, validation, or precheck error is a METADATA problem — fix the payload (for example, Apple's expanded age-rating attributes such as `lootBox`, `ageAssurance`, `parentalControls`, `messagingAndChat` in `app_rating_config.json`) and retry from the CLI. Treating a metadata error as a credential problem is a contract violation.+5. Within an Apple release, this adapter OVERRIDES the Third-Party Web Actions contract (earlier in this skill): the general agentic-browser offer never applies to App Store Connect, Apple ID, or credential work here. The entire release is CLI (fastlane) plus the two permitted interactions; the ONLY browser use this adapter allows, ever, is the paid-app agreements/banking/tax residue named at the end of this document. Opening a browser — driven or manual — for anything else in this journey is a contract violation. When a real error does force the fallback, QUOTE the error verbatim, then escalate in this order: FIRST mint (or re-mint) the upload key from the session per step 4 and retry the upload with `api_key_path` — an upload-auth error with no key on disk means the mint was skipped, not that the user owes a credential. SECOND, if the minting itself fails with a session error, ask the user to sign in again (the same `! fastlane spaceauth -u <apple-id>` moment as the original authorization), re-mint, and retry. Only when a FRESH session still cannot mint a key — a permissions refusal because the signed-in Apple ID is not Admin or Account Holder on its team — does the app-specific-password path open, and its only shape is self-service: the user generates the password on any device and enters it through the host's in-session masked prompt into the macOS keychain (`fastlane fastlane-credentials add --username <apple-id>`), then the upload is retried. NEVER offer or recommend a browser drive to create credentials — no agentic browser of any kind, for any password, key, or token, under any framing.+6. App Review contact details (name, email, phone) are required metadata for submission: infer name and email from the signed-in Apple ID and git config, collect the phone number once inside the authorization moment, persist it to the decision store, and never re-ask. Contact details are metadata, not a blocking gate to announce mid-run.++## Storefront completion++`produce` already created the app record and bundle ID during the run — never call the app record a manual gate. Apply the pricing settled in the authorization moment through the App Store Connect price-schedule endpoint (`POST /v1/appPriceSchedules` via the session or the minted key): fastlane's `price_tier` option is broken against the current API ("'prices' is not a relationship on 'apps'"), so never route pricing through it or call its failure an account problem. `deliver` owns everything else the store listing needs: description, keywords, localizations, screenshot upload per device size, attaching the uploaded build, and Submit for Review; `pilot` manages TestFlight groups and testers as an intermediate round when the user asked for one. Submission follows the same durable-effect contract with key `appstore.submit.<bundle-id>.<version>` — on ambiguity, inspect App Store Connect before re-running. Monitor review status from the CLI afterward.++What remains web-only, ever: the paid Apple Developer Program membership purchase itself (a precondition, not a release step) and, for PAID apps only, the one-time Paid Apps agreement with banking and tax — offer the agentic-browser drive per the Third-Party Web Actions contract (earlier in this skill) before any manual checklist for those. A free app needs no browser at any point. After submission, report that App Review typically answers within a day or two and close the run; review outcome is not a gate this workflow can hold open.diff --git a/ship/sections/apple-release.md.tmpl b/ship/sections/apple-release.md.tmplnew file mode 100644index 000000000..b65d2e112--- /dev/null+++ b/ship/sections/apple-release.md.tmpl@@ -0,0 +1,56 @@+# Apple App Store release++<!-- Ported from time-attack/gstack (GStack 2) APPLE-RELEASE.md, refined+ across 21 live App Store releases. Portions copyright (c) 2026+ Sina Matian, time-attack/gstack, MIT. Adapted to gstack main's+ architecture: decision-store bins, the Third-Party Web Actions+ contract, and an idempotency log in place of the fork's durable-state+ wrapper. All credential examples are placeholders, never live formats. -->++Applies when the ship target is an Apple platform app: the repository contains an `.xcodeproj` or `.xcworkspace`, or a Swift package with an app product. Read this BEFORE Step 1's branch gate and any preflight. This adapter extends ship's judgment to the App Store journey end to end, and every upload or submission is treated as a durable external effect (idempotency contract below) — but store distribution is its own release path, not repository landing: ship's branch/PR ceremony (feature-branch gate, commit-review-PR pipeline, merge queue) applies only when the user asked to land repository changes. A user shipping to the App Store or TestFlight proceeds through this adapter from whatever branch they are on; a clean working tree on the base branch is a normal and valid state to archive and upload from. Never abort an App Store release over branch topology.++One tool runs the entire release: machine-level fastlane — `produce` (app record and bundle ID), `cert` and `sigh` (signing), `gym` (archive and signed export), `pilot` (TestFlight), `deliver` (metadata, screenshots, Submit for Review), `frameit` (device frames). Install it when missing (`brew install fastlane`) with a one-line announcement, not a question — the release authorization covers machine-tool installs. Never install additional App Store CLI tools, and never mention API keys, `.p8` files, sessions, or any credential format to the user; they paid US$99 and want to ship, and the release itself adds no new dependency to the user's project.++A Mac is required only for the build legs. Archiving, signing, and the binary upload ride Xcode's macOS-only toolchain — Apple ships it nowhere else, and no tool routes around that. On a non-macOS host, say so plainly, then route exactly those legs through a macOS CI runner (a GitHub Actions `macos` runner executing the same `gym` and `deliver`/`pilot` commands, with the minted upload key supplied as a CI secret — key auth is precisely what CI wants); sign-in, key minting, metadata, screenshots, pricing, and submission judgment are plain API work that stays on the user's machine. Never claim the whole release is impossible off a Mac, and never pretend the build leg is possible there.++## The one authorization moment++The whole journey permits exactly two interactions, and no others. FIRST, up front: confirm the user holds a paid Apple Developer Program membership (US$99/year — the App Store and TestFlight both require it) and authorize the release. Pricing belongs to this same breath, once per app EVER: ask free or paid (and the price if paid) inside the authorization question — never as a separate interruption — after checking the decision store (`bin/gstack-decision-search --scope repo --query "pricing"`); persist the answer (`~/.claude/skills/gstack/bin/gstack-decision-log`, scope `repo`) so no later release re-asks, and a paid answer names the one-time Paid Apps banking/tax agreement honestly right there, since nothing sells until it is signed. Price is a launch decision the agent never defaults silently: a free launch cannot be un-launched. Apple sign-in happens inside this same moment: run `fastlane spaceauth -u <apple-id>` through the host's interactive command path (in Claude Code, the user types `! fastlane spaceauth -u <email>` so their password and one two-factor code go directly to Apple in-session; a separate terminal window is the fallback only when the host has no interactive path). Keep the printed session token out of the transcript — the cached cookie in `~/.fastlane/spaceship/` is the credential fastlane actually uses; never store, echo, or log the password or token, and re-run the same one command when the session expires. Immediately after the first sign-in, mint the permanent upload key from the session (step 4 of Archive and upload) — when that key already sits at `~/.gstack/apple/api-key.json` and no new app record is needed, skip the sign-in entirely: repeat releases authorize and proceed with zero sign-in. SECOND, only when preflight finds the icon or screenshots missing: the store-assets question below. Everything else — tool installs, upload, storefront, submission — is covered by the authorization and proceeds without asking. Auth menus, tool-choice questions, plan confirmations, and step-by-step narration requests are contract violations.++No membership: STOP the App Store path. Offer to walk enrollment at developer.apple.com through the Third-Party Web Actions contract (earlier in this skill) (a purchase the user completes themselves; activation can take a day or two), and name the free-account ceiling honestly: personal-team installs on the user's own devices only, expiring after 7 days, no TestFlight, no App Store.++## Release preflight++Resolve and verify before archiving. Fix what the printed mutation boundary authorizes; report everything else as a blocking finding.++- Signing: development team on the app target; `cert` and `sigh` mint the distribution certificate and App Store profile when none exist.+- Versioning: a marketing version users should see and a build number strictly greater than any build already uploaded for that version.+- Dependencies: `xcodebuild -resolvePackageDependencies` succeeds; if a `Podfile` or `Cartfile` exists, its install step has been run and lockfiles are current.+- App Store validation blockers: complete app icon set including the 1024pt marketing icon, launch screen, a usage-description string for every privacy-gated API the app touches, required privacy manifests, an export-compliance answer (`ITSAppUsesNonExemptEncryption`), and a sane deployment target.++## Store assets++Only when preflight finds the icon or screenshots missing, ask once — the journey's second and final permitted question — then act on the choice without further prompts. Once per app, EVER: before asking, check the decision store (`bin/gstack-decision-search --scope repo --query "store assets"`); a settled choice (including "defer screenshots" or "TestFlight only") is applied silently, never re-asked. After the user answers, persist it (`~/.claude/skills/gstack/bin/gstack-decision-log` with scope `repo`) so no future run asks again; the user changes it by saying so, not by being re-prompted. Offer:++- **App icon**: SnapAI (`npx snapai`, the app-icon agent skill) generates the single 1024×1024 with the user's own image-generation key; Xcode 15+ derives every size from that one image.+- **Marketing screenshots, free and local, no API key**: the app-store-screenshots deck editor skill — scaffold it, prefill its deck JSON with simulator captures and benefit headlines, and export one bundle covering every required iPhone size (the export is headlessly automatable). Marketing-grade does NOT require an image backend; never claim screenshots need an API key while this skill is installed.+- **Plain frames, free and local**: capture the built app in the simulator and frame with fastlane `frameit` — the minimal option when no designed deck is wanted.+- **AI-enhanced marketing screenshots**: the aso-appstore-screenshots agent skill (benefit headlines, breakout panels, exact App Store dimensions) — the only option that needs the user's own image-generation key; when installed, follow its workflow rather than reimplementing it.+- **User-supplied files**: always a valid answer; validate dimensions and move on.++Build this question's options from a LIVE check of installed skills at ask time — never from memory or an earlier conversation turn. Whenever the app-store-screenshots deck editor skill is installed, its free no-key option MUST appear in the list; omitting it is a contract violation equal to claiming screenshots need an API key. Assets already present skip this entirely. Announce what was generated at exit.++## Archive and upload++1. Archive and export the signed Release build with `gym` (it drives xcodebuild and the signing minted in preflight). Projects with custom archive requirements may drop to `xcodebuild archive` directly; the output either way is an App Store-signed `.ipa`.+2. The upload is an external effect: run `pilot` (TestFlight) or `deliver` (App Store) under the durable-effect contract: before executing, append the key `appstore.upload.<bundle-id>.<build>` to `~/.gstack/projects/$SLUG/apple-effects.log`; if the key is already present from a prior run (crash, retry), treat the upload as possibly-done and do NOT re-run it. Never re-upload on ambiguity; inspect App Store Connect for the build first.+3. The cached session, the minted key, and every credential file are env- or file-level secrets: never argv, never echoed, never committed.+4. NEVER demand an app-specific password — the session MINTS the upload key instead. Per fastlane's documented authentication, Apple's binary-upload tool (iTMSTransporter, which `deliver`/`pilot` shell out to for the `.ipa`) does not accept the web session: it takes only an App Store Connect API key or an app-specific password, and Apple's error `-22938` ("Sign in with the app-specific password") is Transporter saying exactly this. That is not a gate and not a question, because the web session creates the key itself, silently: through fastlane's bundled spaceship (`Spaceship::Tunes.login(<apple-id>)` reuses the cached cookie, then raw client requests), `POST https://appstoreconnect.apple.com/iris/v1/apiKeys` with JSON:API body `{data:{type:"apiKeys",attributes:{nickname:"gstack-upload",allAppsVisible:true,roles:["APP_MANAGER"],keyType:"PUBLIC_API"}}}`, then `GET .../iris/v1/apiKeys/<id>?fields[apiKeys]=privateKey` — the `privateKey` attribute is base64 of the COMPLETE PEM file: decode it exactly once and write `~/.appstoreconnect/private_keys/AuthKey_<id>.p8` (0600) immediately, it is downloadable only at creation. The issuer ID is `provider.publicProviderId` from `GET https://appstoreconnect.apple.com/olympus/v1/session`. Record key id, issuer id, and key content as a fastlane api-key JSON at `~/.gstack/apple/api-key.json` (0600) and run `deliver`/`pilot` with `api_key_path` from then on. The key never expires, so every later release skips sign-in; the session stays necessary only for `produce` (Apple's public API cannot create app records) and for re-minting if the key is ever revoked. Stating that the user must generate any credential themselves while key minting is untried is a contract violation. CLASSIFY the error before touching credentials: an error is an authentication failure ONLY when it says so (401/403, session invalid or expired, "sign in", "app-specific password" in Apple's own words). A `Spaceship::UnexpectedResponse`, missing/invalid attribute, validation, or precheck error is a METADATA problem — fix the payload (for example, Apple's expanded age-rating attributes such as `lootBox`, `ageAssurance`, `parentalControls`, `messagingAndChat` in `app_rating_config.json`) and retry from the CLI. Treating a metadata error as a credential problem is a contract violation.+5. Within an Apple release, this adapter OVERRIDES the Third-Party Web Actions contract (earlier in this skill): the general agentic-browser offer never applies to App Store Connect, Apple ID, or credential work here. The entire release is CLI (fastlane) plus the two permitted interactions; the ONLY browser use this adapter allows, ever, is the paid-app agreements/banking/tax residue named at the end of this document. Opening a browser — driven or manual — for anything else in this journey is a contract violation. When a real error does force the fallback, QUOTE the error verbatim, then escalate in this order: FIRST mint (or re-mint) the upload key from the session per step 4 and retry the upload with `api_key_path` — an upload-auth error with no key on disk means the mint was skipped, not that the user owes a credential. SECOND, if the minting itself fails with a session error, ask the user to sign in again (the same `! fastlane spaceauth -u <apple-id>` moment as the original authorization), re-mint, and retry. Only when a FRESH session still cannot mint a key — a permissions refusal because the signed-in Apple ID is not Admin or Account Holder on its team — does the app-specific-password path open, and its only shape is self-service: the user generates the password on any device and enters it through the host's in-session masked prompt into the macOS keychain (`fastlane fastlane-credentials add --username <apple-id>`), then the upload is retried. NEVER offer or recommend a browser drive to create credentials — no agentic browser of any kind, for any password, key, or token, under any framing.+6. App Review contact details (name, email, phone) are required metadata for submission: infer name and email from the signed-in Apple ID and git config, collect the phone number once inside the authorization moment, persist it to the decision store, and never re-ask. Contact details are metadata, not a blocking gate to announce mid-run.++## Storefront completion++`produce` already created the app record and bundle ID during the run — never call the app record a manual gate. Apply the pricing settled in the authorization moment through the App Store Connect price-schedule endpoint (`POST /v1/appPriceSchedules` via the session or the minted key): fastlane's `price_tier` option is broken against the current API ("'prices' is not a relationship on 'apps'"), so never route pricing through it or call its failure an account problem. `deliver` owns everything else the store listing needs: description, keywords, localizations, screenshot upload per device size, attaching the uploaded build, and Submit for Review; `pilot` manages TestFlight groups and testers as an intermediate round when the user asked for one. Submission follows the same durable-effect contract with key `appstore.submit.<bundle-id>.<version>` — on ambiguity, inspect App Store Connect before re-running. Monitor review status from the CLI afterward.++What remains web-only, ever: the paid Apple Developer Program membership purchase itself (a precondition, not a release step) and, for PAID apps only, the one-time Paid Apps agreement with banking and tax — offer the agentic-browser drive per the Third-Party Web Actions contract (earlier in this skill) before any manual checklist for those. A free app needs no browser at any point. After submission, report that App Review typically answers within a day or two and close the run; review outcome is not a gate this workflow can hold open.diff --git a/ship/sections/manifest.json b/ship/sections/manifest.jsonindex e003837cf..4ffc25023 100644--- a/ship/sections/manifest.json+++ b/ship/sections/manifest.json@@ -2,8 +2,14 @@"$schema": "https://gstack.dev/schemas/section-manifest.json","skill": "ship","version": 1,- "note": "PASSIVE registry (v2 plan T9 / CM2). Fields are IDs, file paths, human titles, and human-readable trigger text ONLY. The skeleton's decision-tree prose is the ONLY place that decides WHEN to read a section; required-reads live in the E2E fixtures. No machine predicate here — see docs/designs/v2_PLAN.md:663.",+ "note": "PASSIVE registry (v2 plan T9 / CM2). Fields are IDs, file paths, human titles, and human-readable trigger text ONLY. The skeleton's decision-tree prose is the ONLY place that decides WHEN to read a section; required-reads live in the E2E fixtures. No machine predicate here \u2014 see docs/designs/v2_PLAN.md:663.","sections": [+ {+ "id": "apple-release",+ "file": "apple-release.md",+ "title": "Apple App Store / TestFlight release adapter",+ "trigger": "the ship target is an Apple platform app (.xcodeproj, .xcworkspace, or an app-product Swift package) \u2014 read BEFORE Step 1's branch gate and any preflight; store distribution never routes through the branch/PR ceremony"+ },{"id": "tests","file": "tests.md",diff --git a/ship/sections/plan-completion.md b/ship/sections/plan-completion.mdindex b325d7a10..207d80d63 100644--- a/ship/sections/plan-completion.md+++ b/ship/sections/plan-completion.md@@ -201,16 +201,23 @@ Using the plan file already discovered in Step 8, look for a verification sectio### 2. Check for running dev server-Before invoking browse-based verification, check if a dev server is reachable:+Before invoking browse-based verification, find the dev-server URL the way the+project declares it — never trust a hardcoded port list alone:++1. **CLAUDE.md first:** look for a documented dev URL or dev command (a+ `## Development`/`## Testing` section naming a port or URL). Use it.+2. **The plan file:** if the plan's verification section names a URL, use it.+3. **Fallback probe** (common ports, only when 1-2 found nothing):```bash-curl -s -o /dev/null -w '%{http_code}' http://localhost:3000 2>/dev/null || \-curl -s -o /dev/null -w '%{http_code}' http://localhost:8080 2>/dev/null || \-curl -s -o /dev/null -w '%{http_code}' http://localhost:5173 2>/dev/null || \-curl -s -o /dev/null -w '%{http_code}' http://localhost:4000 2>/dev/null || echo "NO_SERVER"+for _p in 3000 8080 5173 4000 4321 8000; do+ _code=$(curl -s -o /dev/null -w '%{http_code}' "http://localhost:$_p" 2>/dev/null)+ [ -n "$_code" ] && [ "$_code" != "000" ] && { echo "DEV_SERVER: http://localhost:$_p ($_code)"; break; }+done+[ -z "${_code:-}" ] || [ "${_code:-000}" = "000" ] && echo "NO_SERVER"```-**If NO_SERVER:** Skip with "No dev server detected — skipping plan verification. Run /qa separately after deploying."+**If NO_SERVER:** Skip with "No dev server detected (checked CLAUDE.md, the plan, and common ports) — skipping plan verification. Run /qa separately after deploying, or document the dev URL in CLAUDE.md so this step finds it next time."### 3. Invoke /qa-only inlinediff --git a/ship/sections/pr-body.md b/ship/sections/pr-body.mdindex 90888b7a9..742ba0c57 100644--- a/ship/sections/pr-body.md+++ b/ship/sections/pr-body.md@@ -43,6 +43,8 @@ glab mr view -F json 2>/dev/null | jq -r 'if .state == "opened" then "MR_EXISTS"If an **open** PR/MR already exists: **update** the PR body using `gh pr edit --body-file "$PR_BODY_FILE"` (GitHub) or `glab mr update -d ...` (GitLab). Always regenerate the PR body from scratch using this run's fresh results (test output, coverage audit, review findings, adversarial review, TODOS summary, documentation_section from Step 18). Never reuse stale PR body content from a prior run. **Run the same redaction scan-at-sink (PR body + title) as the create path (Step 19) before editing — scan the temp file, then `gh pr edit --body-file` from it.**+**REST fallback (#1079):** on some repos `gh pr edit` hard-errors with a GraphQL deprecation mentioning `repository.pullRequest.projectCards` ("Projects (classic) is being deprecated..."). That is a `gh` GraphQL-path problem, not a permissions problem — do not re-ask for auth. Fall back to the REST endpoint, which never touches the deprecated field, using the SAME already-scanned temp file: `PR_NUMBER=$(gh pr view --json number -q .number)` then `gh api "repos/{owner}/{repo}/pulls/$PR_NUMBER" -X PATCH -F body=@"$PR_BODY_FILE"` for the body, and `gh api "repos/{owner}/{repo}/pulls/$PR_NUMBER" -X PATCH -f title="$NEW_TITLE"` when the title edit below hits the same error. Verify with the same self-checks as the primary path.+**Always update the PR title to start with `v$NEW_VERSION`.** PR titles use the workspace-aware format `v<NEW_VERSION> <type>: <summary>` — version ALWAYS first, no exceptions, no "custom title kept intentionally" escape hatch. The shared helper `bin/gstack-pr-title-rewrite.sh` is the single source of truth for the rule.1. Read the current title: `CURRENT=$(gh pr view --json title -q .title)` (or `glab mr view -F json | jq -r .title`).diff --git a/ship/sections/pr-body.md.tmpl b/ship/sections/pr-body.md.tmplindex 22ac0d668..dbc087e5b 100644--- a/ship/sections/pr-body.md.tmpl+++ b/ship/sections/pr-body.md.tmpl@@ -41,6 +41,8 @@ glab mr view -F json 2>/dev/null | jq -r 'if .state == "opened" then "MR_EXISTS"If an **open** PR/MR already exists: **update** the PR body using `gh pr edit --body-file "$PR_BODY_FILE"` (GitHub) or `glab mr update -d ...` (GitLab). Always regenerate the PR body from scratch using this run's fresh results (test output, coverage audit, review findings, adversarial review, TODOS summary, documentation_section from Step 18). Never reuse stale PR body content from a prior run. **Run the same redaction scan-at-sink (PR body + title) as the create path (Step 19) before editing — scan the temp file, then `gh pr edit --body-file` from it.**+**REST fallback (#1079):** on some repos `gh pr edit` hard-errors with a GraphQL deprecation mentioning `repository.pullRequest.projectCards` ("Projects (classic) is being deprecated..."). That is a `gh` GraphQL-path problem, not a permissions problem — do not re-ask for auth. Fall back to the REST endpoint, which never touches the deprecated field, using the SAME already-scanned temp file: `PR_NUMBER=$(gh pr view --json number -q .number)` then `gh api "repos/{owner}/{repo}/pulls/$PR_NUMBER" -X PATCH -F body=@"$PR_BODY_FILE"` for the body, and `gh api "repos/{owner}/{repo}/pulls/$PR_NUMBER" -X PATCH -f title="$NEW_TITLE"` when the title edit below hits the same error. Verify with the same self-checks as the primary path.+**Always update the PR title to start with `v$NEW_VERSION`.** PR titles use the workspace-aware format `v<NEW_VERSION> <type>: <summary>` — version ALWAYS first, no exceptions, no "custom title kept intentionally" escape hatch. The shared helper `bin/gstack-pr-title-rewrite.sh` is the single source of truth for the rule.1. Read the current title: `CURRENT=$(gh pr view --json title -q .title)` (or `glab mr view -F json | jq -r .title`).diff --git a/ship/sections/test-coverage.md b/ship/sections/test-coverage.mdindex 60fea89d5..578b97068 100644--- a/ship/sections/test-coverage.md+++ b/ship/sections/test-coverage.md@@ -19,15 +19,20 @@ Before analyzing coverage, detect the project's test framework:```bashsetopt +o nomatch 2>/dev/null || true # zsh compat-# Detect project runtime-[ -f Gemfile ] && echo "RUNTIME:ruby"+# Detect project runtime (markers are evidence, not commands to run blind)+[ -f manage.py ] && echo "RUNTIME:python FRAMEWORK:django"+{ [ -f pyproject.toml ] || [ -f pytest.ini ] || [ -f tox.ini ] || [ -f setup.cfg ] || [ -f requirements.txt ]; } && echo "RUNTIME:python"+[ -f Gemfile ] || [ -f Rakefile ] || [ -f .rspec ] && echo "RUNTIME:ruby"[ -f package.json ] && echo "RUNTIME:node"-[ -f requirements.txt ] || [ -f pyproject.toml ] && echo "RUNTIME:python"[ -f go.mod ] && echo "RUNTIME:go"[ -f Cargo.toml ] && echo "RUNTIME:rust"-# Check for existing test infrastructure-ls jest.config.* vitest.config.* playwright.config.* cypress.config.* .rspec pytest.ini phpunit.xml 2>/dev/null-ls -d test/ tests/ spec/ __tests__/ cypress/ e2e/ 2>/dev/null+[ -f pom.xml ] && echo "RUNTIME:jvm BUILD:maven"+{ [ -f build.gradle ] || [ -f build.gradle.kts ]; } && echo "RUNTIME:jvm BUILD:gradle"+# Check for existing test infrastructure — config files, scripts, AND test files+ls jest.config.* vitest.config.* playwright.config.* cypress.config.* .rspec pytest.ini tox.ini phpunit.xml 2>/dev/null+[ -f package.json ] && grep -q '"test"[[:space:]]*:' package.json && echo "SCRIPT:package.json test"+[ -f Makefile ] && grep -qE '^(test|check):' Makefile && echo "TARGET:make test"+git ls-files | grep -cE '(^|/)(tests?|spec|__tests__)/|(^|/)tests?\.py$|(^|/)test_[^/]+\.py$|_test\.(go|py|rb|ts|js|exs)$|\.(test|spec)\.[jt]sx?$|_spec\.rb$|Test\.(java|kt)$' | sed 's/^/TESTFILES:/'```3. **If no framework detected:** falls through to the Test Framework Bootstrap step (Step 4) which handles full setup.diff --git a/ship/sections/tests.md b/ship/sections/tests.mdindex e9d4dd819..2b93deab1 100644--- a/ship/sections/tests.md+++ b/ship/sections/tests.md@@ -4,41 +4,70 @@## Test Framework Bootstrap-**Detect existing test framework and project runtime:**+**Read the project's CLAUDE.md (and TESTING.md if present) FIRST.** If it documents a test command, the project already told you: no detection, no bootstrap. Skip the rest of bootstrap and use that command in Step 5.++**Otherwise gather markers. Every marker below is EVIDENCE for the question you ask — never a command to run blind.** A marker tells you which ecosystem you're in and which command to OFFER. It does not tell you the command works. Do not execute a candidate test command to "check" it: a probe on a project that never had that runner fails loudly and teaches you nothing, and installing a second framework over a working one is worse.```bashsetopt +o nomatch 2>/dev/null || true # zsh compat-# Detect project runtime-[ -f Gemfile ] && echo "RUNTIME:ruby"+# Definitive ecosystem markers (presence = ecosystem, NOT a command to run)+[ -f manage.py ] && echo "RUNTIME:python FRAMEWORK:django MARKER:manage.py"+{ [ -f pyproject.toml ] || [ -f pytest.ini ] || [ -f tox.ini ] || [ -f setup.cfg ] || [ -f requirements.txt ]; } && echo "RUNTIME:python"+[ -f Gemfile ] || [ -f Rakefile ] || [ -f .rspec ] && echo "RUNTIME:ruby"[ -f package.json ] && echo "RUNTIME:node"-[ -f requirements.txt ] || [ -f pyproject.toml ] && echo "RUNTIME:python"[ -f go.mod ] && echo "RUNTIME:go"[ -f Cargo.toml ] && echo "RUNTIME:rust"[ -f composer.json ] && echo "RUNTIME:php"[ -f mix.exs ] && echo "RUNTIME:elixir"+[ -f pom.xml ] && echo "RUNTIME:jvm BUILD:maven"+{ [ -f build.gradle ] || [ -f build.gradle.kts ]; } && echo "RUNTIME:jvm BUILD:gradle"# Detect sub-frameworks[ -f Gemfile ] && grep -q "rails" Gemfile 2>/dev/null && echo "FRAMEWORK:rails"[ -f package.json ] && grep -q '"next"' package.json 2>/dev/null && echo "FRAMEWORK:nextjs"-# Check for existing test infrastructure-ls jest.config.* vitest.config.* playwright.config.* .rspec pytest.ini pyproject.toml phpunit.xml 2>/dev/null-ls -d test/ tests/ spec/ __tests__/ cypress/ e2e/ 2>/dev/null+# Existing test path — config files, declared scripts, AND test FILES.+# A project with real tests and no config file is the common miss.+ls jest.config.* vitest.config.* playwright.config.* .rspec pytest.ini tox.ini phpunit.xml* 2>/dev/null+[ -f package.json ] && grep -q '"test"[[:space:]]*:' package.json && echo "SCRIPT:package.json test"+[ -f Makefile ] && grep -qE '^(test|check):' Makefile && echo "TARGET:make test"+[ -f pyproject.toml ] && grep -q "pytest" pyproject.toml && echo "CONFIG:pyproject pytest"+git ls-files | grep -cE '(^|/)(tests?|spec|__tests__)/|(^|/)tests?\.py$|(^|/)test_[^/]+\.py$|_test\.(go|py|rb|ts|js|exs)$|\.(test|spec)\.[jt]sx?$|_spec\.rb$|Test\.(java|kt)$' | sed 's/^/TESTFILES:/'+# Rust keeps unit tests inside src/, so file names alone miss them+[ -f Cargo.toml ] && git grep -lF '#[test]' -- 'src' >/dev/null 2>&1 && echo "TESTS:rust in-source"# Check opt-out marker[ -f .gstack/no-test-bootstrap ] && echo "BOOTSTRAP_DECLINED"```-**If test framework detected** (config files or test directories found):-Print "Test framework detected: {name} ({N} existing tests). Skipping bootstrap."+Map the markers to the command you will OFFER — never to one you run on a guess:++| Marker | Ecosystem | Candidate command to offer |+|--------|-----------|----------------------------|+| `manage.py` | Django | `python manage.py test` (or `pytest` when pytest-django is in the deps) |+| `pytest.ini` / `tox.ini` / pytest in `pyproject.toml` / `test_*.py` | Python | `pytest` |+| `go.mod` (+ any `*_test.go`) | Go | `go test ./...` |+| `Cargo.toml` | Rust | `cargo test` |+| `pom.xml` | JVM (Maven) | `mvn test` |+| `build.gradle` / `build.gradle.kts` | JVM (Gradle) | `./gradlew test` |+| `Gemfile` / `Rakefile` / `.rspec` | Ruby | `bundle exec rspec`, `bin/rails test`, or `rake test` |+| `mix.exs` | Elixir | `mix test` |+| `composer.json` | PHP | `composer test` or `./vendor/bin/phpunit` |+| `package.json` with a `test` script | Node | that script, run with the package manager the lockfile names |+| `Makefile` with a `test:` target | any | `make test` |++**If ANY existing-test evidence appears** (a config file, a declared test script or make target, a nonzero `TESTFILES:` count, or `TESTS:rust in-source`): the project has tests. **Do NOT bootstrap.** Print "Existing tests detected: {the evidence}." Then get the command the same way Step 5 does — CLAUDE.md/TESTING.md if documented, otherwise AskUserQuestion offering the candidates from the table above plus "Other", and persist the answer to CLAUDE.md's `## Testing` section so it is never asked again. When the ecosystem ships a runner (Django, Go, Rust, Elixir, Maven/Gradle), that runner is the candidate — never install a second framework beside a working one.Read 2-3 existing test files to learn conventions (naming, imports, assertion style, setup patterns).Store conventions as prose context for use in Phase 8e.5 or Step 7. **Skip the rest of bootstrap.**+Absent config files and absent `tests/` directories are NOT evidence of "no tests": Django keeps tests in `<app>/tests.py`, Go in `*_test.go` beside the source, Rust in `#[test]` blocks inside `src/`. A green `python manage.py test` with no `pytest.ini` is a tested project, not a bootstrap candidate.+**If BOOTSTRAP_DECLINED** appears: Print "Test bootstrap previously declined — skipping." **Skip the rest of bootstrap.**-**If NO runtime detected** (no config files found): Use AskUserQuestion:+**If NO ecosystem marker matched:** Use AskUserQuestion:"I couldn't detect your project's language. What runtime are you using?"Options: A) Node.js/TypeScript B) Ruby/Rails C) Python D) Go E) Rust F) PHP G) Elixir H) This project doesn't need tests.+If the runtime you need isn't listed, offer "Other" and take the runtime plus the test command as free text.If user picks H → write `.gstack/no-test-bootstrap` and continue without tests.-**If runtime detected but no test framework — bootstrap:**+**If an ecosystem matched but there is no existing-test evidence at all — bootstrap:**### B2. Research best practices@@ -54,7 +83,9 @@ If WebSearch is unavailable, use this built-in knowledge table:| Node.js | vitest + @testing-library | jest + @testing-library || Next.js | vitest + @testing-library/react + playwright | jest + cypress || Python | pytest + pytest-cov | unittest |+| Django | pytest + pytest-django | Django's built-in `manage.py test` (unittest) || Go | stdlib testing + testify | stdlib only |+| JVM (Maven/Gradle) | JUnit 5 + AssertJ | JUnit 5 only || Rust | cargo test (built-in) + mockall | — || PHP | phpunit + mockery | pest || Elixir | ExUnit (built-in) + ex_machina | — |diff --git a/skillify/SKILL.md b/skillify/SKILL.mdindex 99e0ac8e1..0bbacd857 100644--- a/skillify/SKILL.md+++ b/skillify/SKILL.md@@ -675,6 +675,10 @@ When options differ in coverage, include `Completeness: X/10` (10 = all edge casFor high-stakes ambiguity (architecture, data model, destructive scope, missing context), STOP. Name it in one sentence, present 2-3 options with tradeoffs, and ask. Do not use for routine coding or obvious changes.+## Claimed Limitations Need Evidence++A claimed limitation or requirement ("the API can't do this", "X requires a credential", "that's impossible on this platform") is a material claim. State one only with the verbatim error, the documented statement, or a live probe in hand — pattern-matching a failure to a familiar story is not evidence. When a cheap probe settles the question, run it BEFORE asking the user anything or declaring a step blocked.+## Continuous Checkpoint ModeIf `CHECKPOINT_MODE` is `"continuous"`: auto-commit completed logical units with `WIP:` prefix.diff --git a/spec/SKILL.md b/spec/SKILL.mdindex f25fa002e..0a9b1d17f 100644--- a/spec/SKILL.md+++ b/spec/SKILL.md@@ -676,6 +676,10 @@ When options differ in coverage, include `Completeness: X/10` (10 = all edge casFor high-stakes ambiguity (architecture, data model, destructive scope, missing context), STOP. Name it in one sentence, present 2-3 options with tradeoffs, and ask. Do not use for routine coding or obvious changes.+## Claimed Limitations Need Evidence++A claimed limitation or requirement ("the API can't do this", "X requires a credential", "that's impossible on this platform") is a material claim. State one only with the verbatim error, the documented statement, or a live probe in hand — pattern-matching a failure to a familiar story is not evidence. When a cheap probe settles the question, run it BEFORE asking the user anything or declaring a step blocked.+## Continuous Checkpoint ModeIf `CHECKPOINT_MODE` is `"continuous"`: auto-commit completed logical units with `WIP:` prefix.@@ -806,6 +810,20 @@ the failure occurred (if outcome is error, otherwise use empty string "").Skills that run plan reviews (`/plan-*-review`, `/codex review`) include the EXIT PLAN MODE GATE blocking checklist at the end of the skill, which verifies the plan file ends with `## GSTACK REVIEW REPORT` before ExitPlanMode is called. Skills that don't run plan reviews (operational skills like `/ship`, `/qa`, `/review`) typically don't operate in plan mode and have no review report to verify; this footer is a no-op for them. Writing the plan file is the one edit allowed in plan mode.+## Third-Party Web Actions++A step sometimes requires action on an external website the user controls: registering an API key, creating a vendor or developer account, configuring a dashboard, webhook, OAuth app, billing plan, or domain verification. This contract governs that moment. It grants no new browsing authority — the AskUserQuestion format and one-way-door rules remain binding, including approval before anything that spends money.++1. **Never hand the user a manual step list for a third-party site without first offering to drive it.** The driver is gstack's own browser stack: `$B` headed mode with handoff/resume for the human-only moments (see the /browse skill), or GStack Browser when installed. Never install new tooling to close the gap, and never treat tooling presence as consent to browse.++2. **One explicit question before any browsing.** STOP and name the exact site and the exact actions (for example "create a test-mode API token in the Duffel dashboard"), then offer: A) I drive it now in a visible browser — you take over for sign-in and approvals, B) manual instructions, C) defer. The selection is per-task consent; never persist it as standing permission and never infer it from an earlier task.++3. **When driving, touch only the named site and actions.** Password entry, new-account credential choice, payment, CAPTCHA, and identity verification are user-performed: hand off (`$B handoff`) and wait instead of acting. Prefer credential flows that never expose the secret to the agent, such as password-manager autofill or the dashboard's own copy button used by the human.++4. **A captured secret never appears in chat output, logs, or shell history.** Write it to a user-approved local file with owner-only permissions (0600) or the user's secret store, and keep generated destinations out of version control. Dashboard fields are often masked placeholders — verify the captured credential with ONE non-mutating API call before claiming success; a 401 here has caught a placeholder masquerading as a key.++5. **If the user declines or defers, or no browser is usable,** provide the manual steps and mark the step blocked on the user. Do not recommend or install new products to close the gap.+# /spec — Author a Backlog-Ready Spec (issue + optional agent spawn)You are a **principal engineer who refuses to let ambiguous work into the backlog**.diff --git a/spec/SKILL.md.tmpl b/spec/SKILL.md.tmplindex 1b56d440f..0694c2ddd 100644--- a/spec/SKILL.md.tmpl+++ b/spec/SKILL.md.tmpl@@ -25,6 +25,8 @@ triggers:{{PREAMBLE}}+{{THIRD_PARTY_ACTIONS}}+# /spec — Author a Backlog-Ready Spec (issue + optional agent spawn)You are a **principal engineer who refuses to let ambiguous work into the backlog**.diff --git a/sync-gbrain/SKILL.md b/sync-gbrain/SKILL.mdindex 985d0b808..4637351c7 100644--- a/sync-gbrain/SKILL.md+++ b/sync-gbrain/SKILL.md@@ -677,6 +677,10 @@ When options differ in coverage, include `Completeness: X/10` (10 = all edge casFor high-stakes ambiguity (architecture, data model, destructive scope, missing context), STOP. Name it in one sentence, present 2-3 options with tradeoffs, and ask. Do not use for routine coding or obvious changes.+## Claimed Limitations Need Evidence++A claimed limitation or requirement ("the API can't do this", "X requires a credential", "that's impossible on this platform") is a material claim. State one only with the verbatim error, the documented statement, or a live probe in hand — pattern-matching a failure to a familiar story is not evidence. When a cheap probe settles the question, run it BEFORE asking the user anything or declaring a step blocked.+## Continuous Checkpoint ModeIf `CHECKPOINT_MODE` is `"continuous"`: auto-commit completed logical units with `WIP:` prefix.diff --git a/test/audit-compliance.test.ts b/test/audit-compliance.test.tsindex 80ef6dced..6241b18bc 100644--- a/test/audit-compliance.test.ts+++ b/test/audit-compliance.test.ts@@ -109,12 +109,6 @@ describe('Audit compliance', () => {});// Round 2 Fix 4: Chrome CDP binds to localhost only- test('chrome-cdp binds to localhost only', () => {- const cdp = readFileSync(join(ROOT, 'bin/chrome-cdp'), 'utf-8');- expect(cdp).toContain('--remote-debugging-address=127.0.0.1');- expect(cdp).toContain('--remote-allow-origins=');- });-// Fix 2+6: All generated SKILL.md files with telemetry are conditionaltest('all generated SKILL.md files with telemetry calls use conditional pattern', () => {const skills = getAllSkillMds();diff --git a/test/claude-provider-keychain.test.ts b/test/claude-provider-keychain.test.tsnew file mode 100644index 000000000..9aff4be61--- /dev/null+++ b/test/claude-provider-keychain.test.ts@@ -0,0 +1,151 @@+/**+ * Free unit tests for the ClaudeAdapter auth sniff in+ * test/helpers/providers/claude.ts — specifically the macOS Keychain branch+ * (#1890): the default subscription install stores OAuth under the+ * generic-password service "Claude Code-credentials" and never writes+ * ~/.claude/.credentials.json, so availability must consult+ * `security find-generic-password -s "Claude Code-credentials"` when neither+ * the creds file nor ANTHROPIC_API_KEY exists.+ *+ * The `security` spawn is darwin-gated in the adapter (the probe only runs+ * when process.platform === 'darwin'), so the keychain-branch tests skip+ * elsewhere; the creds-file / env-key / no-auth verdicts run on every+ * platform.+ *+ * Harness note: available() spawns `security` without an explicit `env:`, and+ * Bun resolves such spawns against the PROCESS STARTUP env — mutating+ * process.env.PATH in-test cannot shadow the real /usr/bin/security (verified;+ * same Bun property lib/gbrain-exec.ts documents for DATABASE_URL). So each+ * case runs available() in a child `bun -e` whose env (and PATH shim) the test+ * fully controls; the fake `security` logs its argv, so the operator's real+ * Keychain is never consulted and a logged-in machine can't false-pass the+ * "no auth" cases. cwd is the fake home so Bun doesn't autoload the repo .env+ * (which defines ANTHROPIC_API_KEY).+ */++import { describe, test, expect, beforeEach, afterEach } from "bun:test";+import { spawnSync } from "child_process";+import * as fs from "fs";+import * as os from "os";+import * as path from "path";++const ADAPTER = path.join(import.meta.dir, "helpers", "providers", "claude.ts");++describe("ClaudeAdapter.available() — auth sniff incl. macOS Keychain branch (#1890)", () => {+ let fakeHome: string;+ let shimDir: string;+ let securityLog: string;++ beforeEach(() => {+ fakeHome = fs.mkdtempSync(path.join(os.tmpdir(), "claude-auth-home-"));+ shimDir = fs.mkdtempSync(path.join(os.tmpdir(), "claude-auth-bin-"));+ securityLog = path.join(shimDir, "security-argv.log");+ });++ afterEach(() => {+ fs.rmSync(fakeHome, { recursive: true, force: true });+ fs.rmSync(shimDir, { recursive: true, force: true });+ });++ /** Fake `security` that logs its argv and exits with `exitCode`. */+ function writeFakeSecurity(exitCode: number): void {+ fs.writeFileSync(+ path.join(shimDir, "security"),+ `#!/bin/sh+printf '%s\\n' "$*" >> "${securityLog}"+exit ${exitCode}+`,+ { mode: 0o755 },+ );+ }++ /** Run `new ClaudeAdapter().available()` in a child bun with a controlled env. */+ function runAvailable(opts: { anthropicKey?: string; bareShimPath?: boolean } = {}): { ok: boolean; reason?: string } {+ const env: Record<string, string | undefined> = {+ ...process.env,+ // Shim dir first so a fake `security` shadows /usr/bin/security; the+ // bare variant drops the inherited PATH entirely (no `claude` findable).+ PATH: opts.bareShimPath ? shimDir : `${shimDir}${path.delimiter}${process.env.PATH ?? ""}`,+ // os.homedir() honors $HOME (POSIX) / %USERPROFILE% (Windows), so the+ // adapter's ~/.claude/.credentials.json check reads the fake home.+ HOME: fakeHome,+ USERPROFILE: fakeHome,+ // Absolute-path override satisfies resolveClaudeCommand() without a real+ // claude install — available() never spawns it, only resolves it. The+ // bare-PATH case clears it to exercise the not-found branch.+ GSTACK_CLAUDE_BIN: opts.bareShimPath ? undefined : path.join(shimDir, "claude"),+ CLAUDE_BIN: undefined,+ GSTACK_CLAUDE_BIN_ARGS: undefined,+ CLAUDE_BIN_ARGS: undefined,+ ANTHROPIC_API_KEY: opts.anthropicKey,+ };+ for (const k of Object.keys(env)) if (env[k] === undefined) delete env[k];+ const driver = `const { ClaudeAdapter } = await import(${JSON.stringify(ADAPTER)});+const check = await new ClaudeAdapter().available();+console.log(JSON.stringify(check));`;+ // process.execPath (absolute bun binary): the bare-PATH case strips the+ // inherited PATH, so a name-based "bun" lookup would ENOENT.+ const res = spawnSync(process.execPath, ["-e", driver], {+ encoding: "utf-8",+ timeout: 30_000,+ cwd: fakeHome, // no .env here — the repo root's would inject ANTHROPIC_API_KEY+ env: env as Record<string, string>,+ });+ if (res.status !== 0) throw new Error(`driver failed (${res.status}): ${res.stderr}`);+ return JSON.parse(res.stdout.trim()) as { ok: boolean; reason?: string };+ }++ test("creds file present → available, and the Keychain is never consulted", () => {+ fs.mkdirSync(path.join(fakeHome, ".claude"), { recursive: true });+ fs.writeFileSync(path.join(fakeHome, ".claude", ".credentials.json"), "{}");+ // A fake security that would report NOT FOUND — if the probe ran anyway,+ // ok would still be true, so the no-spawn pin is the argv log staying empty.+ writeFakeSecurity(1);+ const check = runAvailable();+ expect(check.ok).toBe(true);+ expect(fs.existsSync(securityLog)).toBe(false);+ });++ test("ANTHROPIC_API_KEY set → available without creds file or Keychain probe", () => {+ writeFakeSecurity(1);+ const check = runAvailable({ anthropicKey: "sk-ant-test-not-a-real-key" });+ expect(check.ok).toBe(true);+ expect(fs.existsSync(securityLog)).toBe(false);+ });++ test("darwin: Keychain hit (security exit 0) → available, probed with the exact service name", () => {+ if (process.platform !== "darwin") return; // keychain branch is darwin-gated in the adapter+ writeFakeSecurity(0);+ const check = runAvailable();+ expect(check.ok).toBe(true);+ // Exactly one metadata-only probe, against the service subscription installs use.+ const argv = fs.readFileSync(securityLog, "utf-8").trim().split("\n");+ expect(argv).toEqual(["find-generic-password -s Claude Code-credentials"]);+ expect(argv[0]).not.toContain("-w"); // never reads the secret itself+ });++ test("darwin: Keychain miss (security exit 1) → not available with the no-auth reason", () => {+ if (process.platform !== "darwin") return;+ writeFakeSecurity(1);+ const check = runAvailable();+ expect(check.ok).toBe(false);+ expect(check.reason).toContain("No Claude auth found");+ // The probe DID run (this is the miss path, not a skipped probe).+ expect(fs.readFileSync(securityLog, "utf-8")).toContain("find-generic-password");+ });++ test("non-darwin: no creds file + no env key → not available (no Keychain to consult)", () => {+ if (process.platform === "darwin") return; // darwin covered by the shimmed miss case above+ const check = runAvailable();+ expect(check.ok).toBe(false);+ expect(check.reason).toContain("No Claude auth found");+ });++ test("claude CLI unresolvable → not-found reason, before any auth sniff", () => {+ writeFakeSecurity(0); // even a keychain HIT can't rescue a missing binary+ const check = runAvailable({ bareShimPath: true });+ expect(check.ok).toBe(false);+ expect(check.reason).toContain("claude CLI not found on PATH");+ expect(fs.existsSync(securityLog)).toBe(false); // returned before the auth sniff+ });+});diff --git a/test/code-intelligence.test.ts b/test/code-intelligence.test.tsnew file mode 100644index 000000000..aac388f71--- /dev/null+++ b/test/code-intelligence.test.ts@@ -0,0 +1,1120 @@+/**+ * Tests for lib/code-intelligence — the OPTIONAL, repo-oriented provider contract+ * with three REAL adapters (GBrain CLI, Graphify CLI, Sourcebot HTTP) and the+ * selection store the `gstack-code-intelligence` CLI drives.+ *+ * The Graphify and Sourcebot expectations here are pinned to the REAL formats+ * captured from live tools (graphify 0.9.23 NODE/EDGE query output; Sourcebot v5+ * `/api/search` response + Bearer auth), not invented shapes.+ */++import { describe, test, expect, beforeEach, afterEach } from "bun:test";+import * as fs from "fs";+import * as os from "os";+import * as path from "path";+import { execFileSync, spawnSync } from "child_process";+import { sha256Hex } from "../lib/egress-receipt.js";+import {+ REQUIRED_CAPABILITIES,+ detectAvailable,+ GbrainProvider,+ GraphifyProvider,+ SourcebotProvider,+ parseGbrainSearch,+ parseGraphifyQuery,+ parseSourcebotSearch,+ readSelection,+ setProvider,+ setConsent,+ hasConsent,+ setRoot,+ getRoot,+ resolveSelectedProvider,+ RECOMMENDED_ORDER,+ shouldOfferIndexing,+ trackedFileCount,+ LARGE_REPO_FILE_THRESHOLD,+} from "../lib/code-intelligence";++describe("capability matrix", () => {+ test("every provider advertises the four required capabilities", () => {+ for (const p of [new GbrainProvider(), new SourcebotProvider(), new GraphifyProvider()]) {+ for (const cap of REQUIRED_CAPABILITIES) expect(p.has(cap)).toBe(true);+ }+ });++ test("only GBrain advertises the document ops; local flags are right", () => {+ const g = new GbrainProvider();+ expect(g.local).toBe(false);+ for (const cap of ["add", "delete", "export"] as const) expect(g.has(cap)).toBe(true);++ const s = new SourcebotProvider({ baseUrl: "http://localhost:3000" });+ expect(s.local).toBe(true); // loopback → content stays on machine+ expect(s.has("add")).toBe(false);+ expect(new SourcebotProvider({ baseUrl: "https://sb.example.com" }).local).toBe(false);++ const gf = new GraphifyProvider();+ expect(gf.local).toBe(true);+ expect(gf.has("export")).toBe(true);+ expect(gf.has("add")).toBe(false);+ });++ test("RECOMMENDED_ORDER puts GBrain first", () => {+ expect([...RECOMMENDED_ORDER]).toEqual(["gbrain", "sourcebot", "graphify"]);+ });+});++describe("parsers (pinned to real tool output)", () => {+ test("parseGbrainSearch (text surface)", () => {+ const hits = parseGbrainSearch("[0.91] slug/a -- one\nbanner\n[0.05] slug/b -- low", 0.1, 10);+ expect(hits).toEqual([{ ref: "slug/a", score: 0.91, snippet: "one", kind: "document" }]);+ });++ test("parseGraphifyQuery reads file:line from real NODE/EDGE lines", () => {+ // Verbatim shape from graphify 0.9.23 `query ... --graph`.+ const real = [+ "Traversal: BFS depth=2 | Start: ['query()'] | Context: call (heuristic) | 4 nodes found",+ "",+ "NODE query() [src=db.py loc=L4 community=login]",+ "EDGE query() --calls [EXTRACTED context=call]--> login() at=auth.py:L8",+ ].join("\n");+ const hits = parseGraphifyQuery(real, 10);+ expect(hits.map((h) => h.ref)).toEqual(["db.py:L4", "auth.py:L8"]); // NOT "graphify"+ expect(hits.every((h) => h.kind === "graph-node")).toBe(true);+ // The Traversal header must NOT become a bogus hit.+ expect(hits.some((h) => h.snippet?.startsWith("Traversal:"))).toBe(false);+ });++ test("parseSourcebotSearch maps files to file:line hits (real v5 shape)", () => {+ const real = {+ files: [+ {+ fileName: { text: "src/checksum.ts", matchRanges: [] },+ repository: "github.com/example/sb-sample",+ chunks: [{ content: "export function computeChecksum(data: string): number {", matchRanges: [{ start: { byteOffset: 58, column: 17, lineNumber: 2 } }] }],+ },+ ],+ };+ expect(parseSourcebotSearch(real, 10)).toEqual([+ { ref: "src/checksum.ts:2", snippet: "export function computeChecksum(data: string): number {", kind: "file" },+ ]);+ expect(parseSourcebotSearch("nope", 10)).toEqual([]);+ });+});++describe("selection store + provider-OFF", () => {+ let home: string;+ let env: NodeJS.ProcessEnv;+ beforeEach(() => {+ home = fs.mkdtempSync(path.join(os.tmpdir(), "ci-home-"));+ env = { ...process.env, GSTACK_HOME: home };+ });+ afterEach(() => fs.rmSync(home, { recursive: true, force: true }));++ test("no selection = provider-OFF (null)", () => {+ expect(readSelection(env).provider).toBeNull();+ expect(resolveSelectedProvider({ env })).toBeNull();+ });++ test("select persists and resolves the provider", () => {+ setProvider("graphify", env);+ expect(readSelection(env).provider).toBe("graphify");+ expect(resolveSelectedProvider({ env })?.id).toBe("graphify");+ });++ test("consent is per-repo", () => {+ const repo = path.join(home, "repoA");+ expect(hasConsent(repo, env)).toBe(false);+ setConsent(repo, true, env);+ expect(hasConsent(repo, env)).toBe(true);+ expect(hasConsent(path.join(home, "repoB"), env)).toBe(false);+ });++ test("indexed root persists per provider (so search reads the same graph)", () => {+ expect(getRoot("graphify", env)).toBeUndefined();+ setRoot("graphify", "/tmp/some/repo", env);+ expect(getRoot("graphify", env)).toBe(path.resolve("/tmp/some/repo"));+ });++ test("select none records the decline; selecting a provider clears it", () => {+ setProvider(null, env);+ expect(readSelection(env).declined).toBe(true);+ setProvider("graphify", env);+ expect(readSelection(env).declined).toBe(false);+ });+});++describe("session-start indexing offer (suggest)", () => {+ let home: string;+ let repo: string;+ let env: NodeJS.ProcessEnv;+ beforeEach(() => {+ home = fs.mkdtempSync(path.join(os.tmpdir(), "ci-home-"));+ repo = fs.mkdtempSync(path.join(os.tmpdir(), "ci-repo-"));+ env = { ...process.env, GSTACK_HOME: home };+ Bun.spawnSync(["git", "init", "-q", repo]);+ for (const name of ["a.ts", "b.ts", "c.ts"]) fs.writeFileSync(path.join(repo, name), "x\n");+ Bun.spawnSync(["git", "-C", repo, "add", "-A"]);+ });+ afterEach(() => {+ fs.rmSync(home, { recursive: true, force: true });+ fs.rmSync(repo, { recursive: true, force: true });+ });++ test("offers exactly once: large repo with no prior decision", () => {+ const s = shouldOfferIndexing(repo, { env, threshold: 3 });+ expect(s).toEqual({ offer: true, reason: "large-repo", fileCount: 3, threshold: 3 });+ });++ test("small repo → no offer", () => {+ expect(shouldOfferIndexing(repo, { env, threshold: 4 }).reason).toBe("small-repo");+ });++ test("not a git repo → no offer", () => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ci-plain-"));+ try {+ expect(shouldOfferIndexing(dir, { env, threshold: 0 }).reason).toBe("not-a-repo");+ } finally {+ fs.rmSync(dir, { recursive: true, force: true });+ }+ });++ test("provider already selected → no offer", () => {+ setProvider("graphify", env);+ expect(shouldOfferIndexing(repo, { env, threshold: 3 }).reason).toBe("provider-selected");+ });++ test("explicit decline → never asked again", () => {+ setProvider(null, env);+ expect(shouldOfferIndexing(repo, { env, threshold: 3 }).reason).toBe("declined");+ });++ test("trackedFileCount counts git-tracked files only", () => {+ fs.writeFileSync(path.join(repo, "untracked.ts"), "x\n");+ expect(trackedFileCount(repo)).toBe(3);+ });+});++describe("egress consent gate", () => {+ test("GBrain (non-local) registerSource without consent → PROVIDER_NOT_CONSENTED", async () => {+ await expect(new GbrainProvider().registerSource({ id: "code", path: "/repo" })).rejects.toMatchObject({+ code: "PROVIDER_NOT_CONSENTED",+ });+ });++ test("Graphify (local) is exempt from the egress gate", async () => {+ await expect(+ new GraphifyProvider({ env: { PATH: "/nonexistent" } }).registerSource({ id: "r", path: os.tmpdir() }),+ ).rejects.toMatchObject({ code: "PROVIDER_UNAVAILABLE" });+ });+});++describe("Graphify adapter (fake graphify shim, real NODE/EDGE format)", () => {+ let binDir: string;+ let repo: string;+ function env(): NodeJS.ProcessEnv {+ return { PATH: `${binDir}:${process.env.PATH}` };+ }+ beforeEach(() => {+ binDir = fs.mkdtempSync(path.join(os.tmpdir(), "ci-gf-bin-"));+ repo = fs.mkdtempSync(path.join(os.tmpdir(), "ci-gf-repo-"));+ // Shim emulates real graphify 0.9.23: `update <path>` writes graph.json (no LLM);+ // `query <q> --graph <path>` prints NODE/EDGE lines.+ fs.writeFileSync(+ path.join(binDir, "graphify"),+ `#!/usr/bin/env bash+case "$1" in+ --version) echo "graphify 0.9.23"; exit 0;;+ update) mkdir -p "$2/graphify-out"; echo '{"nodes":[1,2,3,4,5],"edges":[]}' > "$2/graphify-out/graph.json"; echo "Rebuilt: 5 nodes, 8 edges"; exit 0;;+ query)+ echo "Traversal: BFS depth=2 | Start: ['query()'] | 4 nodes found"+ echo ""+ echo "NODE query() [src=db.py loc=L4 community=login]"+ echo "EDGE query() --calls [EXTRACTED context=call]--> login() at=auth.py:L8"+ exit 0;;+esac+exit 1+`,+ { mode: 0o755 },+ );+ });+ afterEach(() => {+ fs.rmSync(binDir, { recursive: true, force: true });+ fs.rmSync(repo, { recursive: true, force: true });+ });++ test("index builds a graph (via `graphify update`) and status counts nodes", async () => {+ const gf = new GraphifyProvider({ root: repo, env: env() });+ const reg = await gf.registerSource({ id: repo, path: repo });+ expect(reg.state).toBe("ready");+ expect(reg.itemCount).toBe(5);+ expect(fs.existsSync(path.join(repo, "graphify-out", "graph.json"))).toBe(true);+ });++ test("search reads file:line refs from real query output", async () => {+ const gf = new GraphifyProvider({ root: repo, env: env() });+ await gf.registerSource({ id: repo, path: repo });+ const hits = await gf.search("what calls db", { source: repo });+ expect(hits.map((h) => h.ref)).toEqual(["db.py:L4", "auth.py:L8"]);+ });++ test("missing graphify CLI degrades to PROVIDER_UNAVAILABLE", async () => {+ await expect(+ new GraphifyProvider({ root: repo, env: { PATH: os.tmpdir() } }).search("q"),+ ).rejects.toMatchObject({ code: "PROVIDER_UNAVAILABLE" });+ });++ test("status skips parsing a huge graph.json (heap guard): size in detail, no itemCount", async () => {+ const outDir = path.join(repo, "graphify-out");+ fs.mkdirSync(outDir, { recursive: true });+ // 6MB of spaces — over the 5MB parse threshold, so the content is never+ // parsed (on real target repos graph.json can run to hundreds of MB).+ fs.writeFileSync(path.join(outDir, "graph.json"), Buffer.alloc(6 * 1024 * 1024, 0x20));+ const s = await new GraphifyProvider({ root: repo, env: env() }).status();+ expect(s.state).toBe("ready");+ expect(s.itemCount).toBeUndefined();+ expect(s.detail).toContain("node count skipped");+ });+});++describe("Sourcebot adapter (injected fetch, real v5 auth + shape)", () => {+ test("registerSource writes a local git connection to config.json", async () => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ci-sb-"));+ const configPath = path.join(dir, "config.json");+ await new SourcebotProvider({ baseUrl: "http://localhost:3000", configPath }).registerSource({ id: "myrepo", path: "/abs/repo" });+ const written = JSON.parse(fs.readFileSync(configPath, "utf-8"));+ expect(written.connections.myrepo).toEqual({ type: "git", url: "file:///abs/repo" });+ fs.rmSync(dir, { recursive: true, force: true });+ });++ test("search sends Bearer auth and maps the real v5 response to hits", async () => {+ const seen: Array<{ url: string; auth: string | null }> = [];+ const fetchStub = (async (url: string, init: RequestInit) => {+ seen.push({ url: String(url), auth: (init.headers as Record<string, string>)?.Authorization ?? null });+ return new Response(+ JSON.stringify({ files: [{ fileName: { text: "a.ts" }, chunks: [{ content: "x", matchRanges: [{ start: { lineNumber: 3 } }] }] }] }),+ { status: 200, headers: { "Content-Type": "application/json" } },+ );+ }) as unknown as typeof fetch;+ const sb = new SourcebotProvider({ baseUrl: "http://localhost:3000", apiKey: "sbk_test", fetch: fetchStub });+ const hits = await sb.search("foo");+ expect(seen[0].url).toBe("http://localhost:3000/api/search");+ expect(seen[0].auth).toBe("Bearer sbk_test");+ expect(hits).toEqual([{ ref: "a.ts:3", snippet: "x", kind: "file" }]);+ });++ test("401 (no API key) degrades to PROVIDER_UNAVAILABLE, not PROVIDER_ERROR", async () => {+ const fetchStub = (async () =>+ new Response(JSON.stringify({ errorCode: "NOT_AUTHENTICATED" }), { status: 401 })) as unknown as typeof fetch;+ await expect(+ new SourcebotProvider({ baseUrl: "http://localhost:3000", fetch: fetchStub }).search("q"),+ ).rejects.toMatchObject({ code: "PROVIDER_UNAVAILABLE" });+ });++ test("unreachable server degrades to PROVIDER_UNAVAILABLE", async () => {+ const fetchStub = (async () => {+ throw new Error("ECONNREFUSED");+ }) as unknown as typeof fetch;+ await expect(+ new SourcebotProvider({ baseUrl: "http://localhost:3999", fetch: fetchStub }).search("q"),+ ).rejects.toMatchObject({ code: "PROVIDER_UNAVAILABLE" });+ });++ test("registerSource without SOURCEBOT_CONFIG → PROVIDER_UNAVAILABLE", async () => {+ await expect(+ new SourcebotProvider({ baseUrl: "http://localhost:3000", env: {} }).registerSource({ id: "r", path: "/x" }),+ ).rejects.toMatchObject({ code: "PROVIDER_UNAVAILABLE" });+ });+});++describe("GBrain adapter (fake gbrain shim)", () => {+ let binDir: string;+ let homeDir: string;+ function env(): NodeJS.ProcessEnv {+ return { PATH: `${binDir}:${process.env.PATH}`, HOME: homeDir };+ }+ function writeShim(body: string): void {+ fs.writeFileSync(path.join(binDir, "gbrain"), body, { mode: 0o755 });+ }+ beforeEach(() => {+ binDir = fs.mkdtempSync(path.join(os.tmpdir(), "ci-gb-bin-"));+ homeDir = fs.mkdtempSync(path.join(os.tmpdir(), "ci-gb-home-"));+ });+ afterEach(() => {+ fs.rmSync(binDir, { recursive: true, force: true });+ fs.rmSync(homeDir, { recursive: true, force: true });+ });++ test("search parses hits (and sends no --source: gbrain search is global)", async () => {+ writeShim(`#!/usr/bin/env bash+if [ "$1" = "search" ]; then+ if printf '%s ' "$@" | grep -q -- "--source"; then echo "[0.0] ERR -- adapter sent phantom --source"; exit 0; fi+ echo "[0.88] src/x.ts -- match"; exit 0+fi+exit 1+`);+ const hits = await new GbrainProvider().search("where", { env: env(), consented: true });+ expect(hits).toEqual([{ ref: "src/x.ts", score: 0.88, snippet: "match", kind: "document" }]);+ });++ test("refresh runs the code-indexing pass (`sync --strategy code --full`)", async () => {+ // Real gbrain only indexes code when `sync --strategy code` runs; without it+ // code-def stays not_built. Pin that the adapter issues that pass.+ const marker = path.join(homeDir, "sync-calls.log");+ writeShim(`#!/usr/bin/env bash+if [ "$1" = "sync" ]; then printf '%s\\n' "$*" >> "${marker}"; exit 0; fi+if [ "$1" = "sources" ]; then echo '{"sources":[{"id":"code","local_path":"/r","page_count":1}]}'; exit 0; fi+exit 1+`);+ await new GbrainProvider().refresh({ id: "code" }, { env: env(), consented: true });+ const log = fs.readFileSync(marker, "utf-8");+ expect(log).toContain("--strategy code");+ expect(log).toContain("--full");+ });++ test("engine-down (pglite WASM) degrades to PROVIDER_UNAVAILABLE, not PROVIDER_ERROR", async () => {+ // Reproduces garrytan/gbrain#223: engine fails to init; must degrade cleanly.+ writeShim(`#!/usr/bin/env bash+echo "PGLite failed to initialize its WASM runtime." >&2+echo " Original error: Aborted()." >&2+exit 1+`);+ await expect(new GbrainProvider().search("q", { env: env(), consented: true })).rejects.toMatchObject({+ code: "PROVIDER_UNAVAILABLE",+ });+ });++ test("missing CLI degrades to PROVIDER_UNAVAILABLE", async () => {+ await expect(+ new GbrainProvider().search("q", { env: { PATH: binDir, HOME: homeDir }, consented: true }),+ ).rejects.toMatchObject({ code: "PROVIDER_UNAVAILABLE" });+ });+});++// ── R1: the repo-policy deny tier vetoes recorded consent ───────────────────+// Two consent stores must never disagree about whether code may leave a repo:+// gstack-gbrain-repo-policy (per-remote trust tiers) is the single authority.+describe("consent unification — deny tier wins (R1)", () => {+ function makeRepo(dir: string, url: string): string {+ const repo = path.join(dir, "repo");+ fs.mkdirSync(repo, { recursive: true });+ const git = (...a: string[]) => execFileSync("git", a, { cwd: repo });+ git("init", "-q", ".");+ git("remote", "add", "origin", url);+ return repo;+ }+ const POLICY_BIN = path.join(import.meta.dir, "..", "bin", "gstack-gbrain-repo-policy");+ const URL = "https://github.com/acme/veto-widget.git";++ test("recorded consent survives when no policy store exists", () => {+ const home = fs.mkdtempSync(path.join(os.tmpdir(), "ci-veto-"));+ try {+ const env = { ...process.env, GSTACK_HOME: home };+ const repo = makeRepo(home, URL);+ setConsent(repo, true, env);+ expect(hasConsent(repo, env)).toBe(true);+ } finally { fs.rmSync(home, { recursive: true, force: true }); }+ });++ test("deny tier vetoes recorded consent", () => {+ const home = fs.mkdtempSync(path.join(os.tmpdir(), "ci-veto-"));+ try {+ const env = { ...process.env, GSTACK_HOME: home };+ const repo = makeRepo(home, URL);+ setConsent(repo, true, env);+ execFileSync(POLICY_BIN, ["set", URL, "deny"], { env, encoding: "utf-8" });+ expect(hasConsent(repo, env)).toBe(false);+ // Flipping the tier back restores the recorded consent — the veto is+ // live policy, not a destructive rewrite of the consent store.+ execFileSync(POLICY_BIN, ["set", URL, "read-write"], { env, encoding: "utf-8" });+ expect(hasConsent(repo, env)).toBe(true);+ } finally { fs.rmSync(home, { recursive: true, force: true }); }+ });++ test("unreadable policy store fails closed (consent vetoed) for BOTH op classes", () => {+ if (process.platform === "win32" || process.getuid?.() === 0) return; // chmod semantics differ+ const home = fs.mkdtempSync(path.join(os.tmpdir(), "ci-veto-"));+ try {+ const env = { ...process.env, GSTACK_HOME: home };+ const repo = makeRepo(home, URL);+ setConsent(repo, true, env);+ execFileSync(POLICY_BIN, ["set", URL, "read-write"], { env, encoding: "utf-8" });+ fs.chmodSync(path.join(home, "gbrain-repo-policy.json"), 0o000);+ try {+ expect(hasConsent(repo, env)).toBe(false);+ expect(hasConsent(repo, env, "read")).toBe(false);+ } finally {+ fs.chmodSync(path.join(home, "gbrain-repo-policy.json"), 0o600);+ }+ } finally { fs.rmSync(home, { recursive: true, force: true }); }+ });++ // ── R2: read-only is a WRITE veto, not a total one ─────────────────────────+ // gstack-gbrain-sync semantics: "search allowed, page writes never". The+ // code-intelligence veto must match: index/register/refresh (write-class)+ // are refused on read-only; search (read-class) still works.+ test("read-only tier vetoes write-class consent but allows read-class (R2)", () => {+ const home = fs.mkdtempSync(path.join(os.tmpdir(), "ci-veto-"));+ try {+ const env = { ...process.env, GSTACK_HOME: home };+ const repo = makeRepo(home, URL);+ setConsent(repo, true, env);+ execFileSync(POLICY_BIN, ["set", URL, "read-only"], { env, encoding: "utf-8" });+ // Default op class is write — a caller that doesn't say gets fail-closed.+ expect(hasConsent(repo, env)).toBe(false);+ expect(hasConsent(repo, env, "write")).toBe(false);+ // Read-class (search/export/status) survives read-only.+ expect(hasConsent(repo, env, "read")).toBe(true);+ } finally { fs.rmSync(home, { recursive: true, force: true }); }+ });++ test("deny beats consent for BOTH op classes", () => {+ const home = fs.mkdtempSync(path.join(os.tmpdir(), "ci-veto-"));+ try {+ const env = { ...process.env, GSTACK_HOME: home };+ const repo = makeRepo(home, URL);+ setConsent(repo, true, env);+ execFileSync(POLICY_BIN, ["set", URL, "deny"], { env, encoding: "utf-8" });+ expect(hasConsent(repo, env, "write")).toBe(false);+ expect(hasConsent(repo, env, "read")).toBe(false);+ } finally { fs.rmSync(home, { recursive: true, force: true }); }+ });+});++// ── R2 at the CLI: `index` is write-class, so read-only refuses it ──────────+describe("read-only repo policy blocks write-class CLI index (R2)", () => {+ const CLI = path.join(import.meta.dir, "..", "bin", "gstack-code-intelligence");+ const POLICY_BIN = path.join(import.meta.dir, "..", "bin", "gstack-gbrain-repo-policy");+ const URL = "https://github.com/acme/readonly-widget.git";++ test("index refuses on read-only even with recorded consent (gbrain provider)", () => {+ const home = fs.mkdtempSync(path.join(os.tmpdir(), "ci-ro-"));+ const shimDir = fs.mkdtempSync(path.join(os.tmpdir(), "ci-ro-bin-"));+ try {+ // Shim shadows any real gbrain on PATH: even if a regression lets the+ // index proceed, this test can never touch a real brain.+ fs.writeFileSync(path.join(shimDir, "gbrain"), "#!/usr/bin/env bash\nexit 1\n", { mode: 0o755 });+ const env = { ...process.env, GSTACK_HOME: home, PATH: `${shimDir}:${process.env.PATH}` };+ const repo = path.join(home, "repo");+ fs.mkdirSync(repo, { recursive: true });+ execFileSync("git", ["init", "-q", "."], { cwd: repo });+ execFileSync("git", ["remote", "add", "origin", URL], { cwd: repo });+ setProvider("gbrain", env);+ setConsent(repo, true, env);+ execFileSync(POLICY_BIN, ["set", URL, "read-only"], { env, encoding: "utf-8" });+ const res = spawnSync("bun", [CLI, "index", repo], {+ encoding: "utf-8",+ timeout: 30_000,+ env: env as Record<string, string>,+ });+ expect(res.status).not.toBe(0);+ expect(res.stderr).toContain("repo trust policy");+ } finally {+ fs.rmSync(home, { recursive: true, force: true });+ fs.rmSync(shimDir, { recursive: true, force: true });+ }+ });+});++// ── receipt truthfulness: the tamper-evident ledger must never claim a consent+// that was never checked (red-team finding 1). Non-loopback Sourcebot only —+// loopback sends nothing off-machine and writes no receipt at all.+describe("Sourcebot egress receipts record the TRUE consent state", () => {+ let home: string;+ beforeEach(() => {+ home = fs.mkdtempSync(path.join(os.tmpdir(), "ci-sb-egress-"));+ });+ afterEach(() => fs.rmSync(home, { recursive: true, force: true }));++ function ledgerLines(): Array<Record<string, unknown>> {+ const p = path.join(home, "security", "egress.jsonl");+ if (!fs.existsSync(p)) return [];+ return fs+ .readFileSync(p, "utf-8")+ .split("\n")+ .filter(Boolean)+ .map((l) => JSON.parse(l) as Record<string, unknown>);+ }++ const okFetch = (async () =>+ new Response(JSON.stringify({ files: [] }), {+ status: 200,+ headers: { "Content-Type": "application/json" },+ })) as unknown as typeof fetch;++ test("status probe: allowed without consent, receipt says consent=unchecked (never consented=true)", async () => {+ const sb = new SourcebotProvider({ baseUrl: "http://sb.example.com:3000", fetch: okFetch });+ const s = await sb.status(undefined, { env: { GSTACK_HOME: home } });+ expect(s.state).toBe("ready");+ const lines = ledgerLines();+ expect(lines.length).toBe(1);+ expect(lines[0].sink).toBe("sourcebot");+ expect(String(lines[0].consent)).toContain("consent=unchecked");+ expect(String(lines[0].consent)).not.toContain("consented=true");+ expect(String(lines[0].payload_class)).toContain("liveness-probe");+ });++ test("non-loopback search without consent is refused BEFORE any bytes leave (fail-closed)", async () => {+ let calls = 0;+ const spyFetch = (async () => {+ calls++;+ return new Response("{}", { status: 200 });+ }) as unknown as typeof fetch;+ const sb = new SourcebotProvider({ baseUrl: "http://sb.example.com:3000", fetch: spyFetch });+ await expect(sb.search("internalSecretFn", { env: { GSTACK_HOME: home } })).rejects.toMatchObject({+ code: "PROVIDER_NOT_CONSENTED",+ });+ expect(calls).toBe(0); // the query never left the machine+ expect(ledgerLines()).toEqual([]); // nothing sent → nothing receipted+ });++ test("non-loopback refresh without consent → PROVIDER_NOT_CONSENTED (write-class)", async () => {+ const sb = new SourcebotProvider({ baseUrl: "http://sb.example.com:3000", fetch: okFetch });+ await expect(sb.refresh({ id: "r" }, { env: { GSTACK_HOME: home } })).rejects.toMatchObject({+ code: "PROVIDER_NOT_CONSENTED",+ });+ expect(ledgerLines()).toEqual([]);+ });++ test("consented non-loopback search sends, and the receipt truthfully records consented=true", async () => {+ const sb = new SourcebotProvider({ baseUrl: "http://sb.example.com:3000", fetch: okFetch });+ const hits = await sb.search("foo", { consented: true, env: { GSTACK_HOME: home } });+ expect(hits).toEqual([]);+ const lines = ledgerLines();+ expect(lines.length).toBe(1);+ expect(String(lines[0].consent)).toContain("consented=true");+ expect(lines[0].payload_class).toBe("code-search-request");+ });++ test("loopback search stays consent-free and writes no receipt (no egress)", async () => {+ const sb = new SourcebotProvider({ baseUrl: "http://localhost:3000", fetch: okFetch });+ await sb.search("foo", { env: { GSTACK_HOME: home } });+ expect(ledgerLines()).toEqual([]);+ });+});++// ── GBrain consent + receipts: gbrain federates into a possibly-remote+// DATABASE_URL and (unlike Sourcebot) has no cheap loopback check — the URL is+// resolved inside the gbrain CLI's own config — so EVERY content-bearing send+// is consent-gated and receipted: search's query text and the export request+// included, not just register/refresh/add.+describe("GBrain search/export consent gate + egress receipts", () => {+ let binDir: string;+ let home: string;+ let marker: string;+ function env(): NodeJS.ProcessEnv {+ return { PATH: `${binDir}:${process.env.PATH}`, HOME: home, GSTACK_HOME: home };+ }+ function ledgerLines(): Array<Record<string, unknown>> {+ const p = path.join(home, "security", "egress.jsonl");+ if (!fs.existsSync(p)) return [];+ return fs+ .readFileSync(p, "utf-8")+ .split("\n")+ .filter(Boolean)+ .map((l) => JSON.parse(l) as Record<string, unknown>);+ }+ beforeEach(() => {+ binDir = fs.mkdtempSync(path.join(os.tmpdir(), "ci-gb-egress-bin-"));+ home = fs.mkdtempSync(path.join(os.tmpdir(), "ci-gb-egress-home-"));+ marker = path.join(home, "gbrain-invocations.log");+ // Shim logs every invocation, so "refused BEFORE the subprocess runs" is+ // provable: an unconsented op must leave the marker file nonexistent.+ fs.writeFileSync(+ path.join(binDir, "gbrain"),+ `#!/usr/bin/env bash+printf '%s\\n' "$*" >> "${marker}"+if [ "$1" = "search" ]; then echo "[0.88] src/x.ts -- match"; exit 0; fi+if [ "$1" = "export" ]; then echo "exported-brain-body"; exit 0; fi+exit 1+`,+ { mode: 0o755 },+ );+ });+ afterEach(() => {+ fs.rmSync(binDir, { recursive: true, force: true });+ fs.rmSync(home, { recursive: true, force: true });+ });++ test("unconsented search is refused BEFORE the subprocess runs (fail-closed) and writes no receipt", async () => {+ await expect(new GbrainProvider().search("internalSecretFn", { env: env() })).rejects.toMatchObject({+ code: "PROVIDER_NOT_CONSENTED",+ });+ expect(fs.existsSync(marker)).toBe(false); // the query never left the machine+ expect(ledgerLines()).toEqual([]); // nothing sent → nothing receipted+ });++ test("consented search sends, and the receipt truthfully records consented=true + the query hash", async () => {+ const hits = await new GbrainProvider().search("where is auth", { env: env(), consented: true });+ expect(hits).toEqual([{ ref: "src/x.ts", score: 0.88, snippet: "match", kind: "document" }]);+ const lines = ledgerLines();+ expect(lines.length).toBe(1);+ expect(lines[0].sink).toBe("gbrain");+ expect(String(lines[0].consent)).toContain("consented=true");+ expect(String(lines[0].payload_class)).toContain("code-search-query");+ expect(lines[0].sha256).toBe(sha256Hex("where is auth"));+ expect(lines[0].bytes).toBe(Buffer.byteLength("where is auth"));+ });++ test("unconsented export is refused (no loopback exemption exists for gbrain) and writes no receipt", async () => {+ await expect(new GbrainProvider().export({ id: "code" }, { env: env() })).rejects.toMatchObject({+ code: "PROVIDER_NOT_CONSENTED",+ });+ expect(fs.existsSync(marker)).toBe(false);+ expect(ledgerLines()).toEqual([]);+ });++ test("consented export sends and writes a truthful receipt", async () => {+ const body = await new GbrainProvider().export({ id: "code" }, { env: env(), consented: true });+ expect(body).toContain("exported-brain-body");+ const lines = ledgerLines();+ expect(lines.length).toBe(1);+ expect(lines[0].sink).toBe("gbrain");+ expect(String(lines[0].consent)).toContain("consented=true");+ expect(String(lines[0].payload_class)).toContain("brain-export-request");+ });+});++// ── the CLI names WHY a gbrain search is refused (missing consent vs a deny+// repo trust policy) instead of surfacing a generic provider error, and the+// refusal happens before any subprocess spawn or receipt.+describe("CLI search consent gate (gbrain provider, honest refusal message)", () => {+ const CLI = path.join(import.meta.dir, "..", "bin", "gstack-code-intelligence");+ const POLICY_BIN = path.join(import.meta.dir, "..", "bin", "gstack-gbrain-repo-policy");+ const URL = "https://github.com/acme/search-widget.git";+ let home: string;+ let shimDir: string;+ let marker: string;+ let repo: string;+ let env: NodeJS.ProcessEnv;++ beforeEach(() => {+ home = fs.mkdtempSync(path.join(os.tmpdir(), "ci-cli-search-"));+ shimDir = fs.mkdtempSync(path.join(os.tmpdir(), "ci-cli-search-bin-"));+ marker = path.join(home, "gbrain-invocations.log");+ fs.writeFileSync(+ path.join(shimDir, "gbrain"),+ `#!/usr/bin/env bash\nprintf '%s\\n' "$*" >> "${marker}"\necho "[0.90] slug -- hit"; exit 0\n`,+ { mode: 0o755 },+ );+ repo = path.join(home, "repo");+ fs.mkdirSync(repo, { recursive: true });+ execFileSync("git", ["init", "-q", "."], { cwd: repo });+ execFileSync("git", ["remote", "add", "origin", URL], { cwd: repo });+ env = { ...process.env, GSTACK_HOME: home, PATH: `${shimDir}:${process.env.PATH}` };+ setProvider("gbrain", env);+ setRoot("gbrain", repo, env);+ });+ afterEach(() => {+ fs.rmSync(home, { recursive: true, force: true });+ fs.rmSync(shimDir, { recursive: true, force: true });+ });++ function runSearch() {+ return spawnSync("bun", [CLI, "search", "internalSecretFn"], {+ encoding: "utf-8",+ timeout: 30_000,+ env: env as Record<string, string>,+ });+ }++ test("no recorded consent → refused with the consent instruction; nothing spawned, nothing receipted", () => {+ const res = runSearch();+ expect(res.status).not.toBe(0);+ expect(res.stderr).toContain("consent");+ expect(fs.existsSync(marker)).toBe(false);+ expect(fs.existsSync(path.join(home, "security", "egress.jsonl"))).toBe(false);+ });++ test("deny repo trust policy → refused with the trust-policy explanation even with recorded consent", () => {+ setConsent(repo, true, env);+ execFileSync(POLICY_BIN, ["set", URL, "deny"], { env, encoding: "utf-8" });+ const res = runSearch();+ expect(res.status).not.toBe(0);+ expect(res.stderr).toContain("repo trust policy");+ expect(fs.existsSync(marker)).toBe(false);+ });++ test("recorded consent + no deny → search runs against the provider", () => {+ setConsent(repo, true, env);+ const res = runSearch();+ expect(res.status).toBe(0);+ expect(res.stdout).toContain("slug");+ expect(fs.existsSync(marker)).toBe(true);+ });+});++// ── consent CLI polarity — a recorded "no" must persist DENIED, never granted ─+describe("consent CLI requires an explicit yes|no (never defaults to granted)", () => {+ const CLI = path.join(import.meta.dir, "..", "bin", "gstack-code-intelligence");+ let home: string;+ let repo: string;+ let env: NodeJS.ProcessEnv;++ function runConsent(...args: string[]) {+ const res = spawnSync("bun", [CLI, "consent", ...args], {+ encoding: "utf-8",+ timeout: 30_000,+ env: env as Record<string, string>,+ });+ return { status: res.status ?? -1, stdout: res.stdout || "", stderr: res.stderr || "" };+ }++ beforeEach(() => {+ home = fs.mkdtempSync(path.join(os.tmpdir(), "ci-consent-home-"));+ repo = fs.mkdtempSync(path.join(os.tmpdir(), "ci-consent-repo-"));+ env = { ...process.env, GSTACK_HOME: home };+ });+ afterEach(() => {+ fs.rmSync(home, { recursive: true, force: true });+ fs.rmSync(repo, { recursive: true, force: true });+ });++ test("consent <repo> no records FALSE, and the deny-check honors it", () => {+ const r = runConsent(repo, "no");+ expect(r.status).toBe(0);+ expect(readSelection(env).consents[path.resolve(repo)]).toBe(false);+ expect(hasConsent(repo, env)).toBe(false);+ });++ test("consent <repo> yes records true; a later no overrides it", () => {+ expect(runConsent(repo, "yes").status).toBe(0);+ expect(hasConsent(repo, env)).toBe(true);+ expect(runConsent(repo, "no").status).toBe(0);+ expect(readSelection(env).consents[path.resolve(repo)]).toBe(false);+ expect(hasConsent(repo, env)).toBe(false);+ });++ test("true/false are accepted as aliases", () => {+ expect(runConsent(repo, "false").status).toBe(0);+ expect(readSelection(env).consents[path.resolve(repo)]).toBe(false);+ expect(runConsent(repo, "true").status).toBe(0);+ expect(readSelection(env).consents[path.resolve(repo)]).toBe(true);+ });++ test("missing value exits nonzero and records NOTHING (never defaults to yes)", () => {+ const r = runConsent(repo);+ expect(r.status).not.toBe(0);+ expect(r.stderr).toContain("yes|no");+ expect(readSelection(env).consents).toEqual({});+ expect(hasConsent(repo, env)).toBe(false);+ });++ test("garbage value exits nonzero and records NOTHING", () => {+ const r = runConsent(repo, "maybe");+ expect(r.status).not.toBe(0);+ expect(r.stderr).toContain("yes|no");+ expect(readSelection(env).consents).toEqual({});+ });+});++// ── GBrain document ops (add/delete/export) — behavioral pins over the same+// fake-gbrain shim harness. add() must pipe the body to `put <slug>` on stdin+// and receipt the body's sha256 BEFORE the send; delete() must survive a+// confirmation prompt via the stdin-EOF guard; export() must return the CLI's+// stdout verbatim; and each must degrade to PROVIDER_UNAVAILABLE (not a hard+// error) when the CLI is absent.+describe("GBrain document ops (add/delete/export) via fake gbrain shim", () => {+ let binDir: string;+ let home: string;+ let argvLog: string;+ let stdinLog: string;+ function env(): NodeJS.ProcessEnv {+ return { PATH: `${binDir}:${process.env.PATH}`, HOME: home, GSTACK_HOME: home };+ }+ function ledgerLines(): Array<Record<string, unknown>> {+ const p = path.join(home, "security", "egress.jsonl");+ if (!fs.existsSync(p)) return [];+ return fs+ .readFileSync(p, "utf-8")+ .split("\n")+ .filter(Boolean)+ .map((l) => JSON.parse(l) as Record<string, unknown>);+ }+ beforeEach(() => {+ binDir = fs.mkdtempSync(path.join(os.tmpdir(), "ci-gb-docops-bin-"));+ home = fs.mkdtempSync(path.join(os.tmpdir(), "ci-gb-docops-home-"));+ argvLog = path.join(home, "gbrain-argv.log");+ stdinLog = path.join(home, "gbrain-stdin.log");+ // Shim logs every argv (so "refused BEFORE the subprocess" is provable),+ // captures put's stdin byte-for-byte, and blocks delete on a confirmation+ // read the way a real prompt would — the adapter's stdin-EOF guard is the+ // only thing keeping that from hanging until the op timeout.+ fs.writeFileSync(+ path.join(binDir, "gbrain"),+ `#!/usr/bin/env bash+printf '%s\\n' "$*" >> "${argvLog}"+case "$1" in+ put) cat > "${stdinLog}"; echo "stored $2"; exit 0;;+ delete) read -r _confirm; echo "deleted $2"; exit 0;;+ export) printf 'line-one\\nline-two\\n'; exit 0;;+esac+exit 1+`,+ { mode: 0o755 },+ );+ });+ afterEach(() => {+ fs.rmSync(binDir, { recursive: true, force: true });+ fs.rmSync(home, { recursive: true, force: true });+ });++ test("add() pipes the document body to `put <slug>` on stdin and receipts the body's sha256", async () => {+ const body = "# curated memory\nthe exact body bytes\n";+ const s = await new GbrainProvider().add({ slug: "my-doc", body }, { env: env(), consented: true });+ expect(s).toEqual({ id: "my-doc", state: "ready" });+ expect(fs.readFileSync(argvLog, "utf-8").trim()).toBe("put my-doc");+ // The body reached gbrain via stdin, byte-for-byte (not argv, not a temp file).+ expect(fs.readFileSync(stdinLog, "utf-8")).toBe(body);+ const lines = ledgerLines();+ expect(lines.length).toBe(1);+ expect(lines[0].sink).toBe("gbrain");+ expect(String(lines[0].payload_class)).toContain("document-body");+ expect(String(lines[0].consent)).toContain("consented=true");+ expect(lines[0].sha256).toBe(sha256Hex(body));+ expect(lines[0].bytes).toBe(Buffer.byteLength(body));+ });++ test("add() asserts consent: unconsented add is refused BEFORE the subprocess runs, no receipt", async () => {+ await expect(new GbrainProvider().add({ slug: "s", body: "secret body" }, { env: env() })).rejects.toMatchObject({+ code: "PROVIDER_NOT_CONSENTED",+ });+ expect(fs.existsSync(argvLog)).toBe(false); // the body never left the machine+ expect(ledgerLines()).toEqual([]);+ });++ test("delete() survives a confirmation prompt via the stdin-EOF guard (never hangs)", async () => {+ // Shim blocks on `read` — with the adapter's input:"" the read gets EOF+ // instantly. A regression to inherited/open stdin fails here at the 5s+ // op timeout (PROVIDER_TIMEOUT) instead of returning state=absent.+ const s = await new GbrainProvider().delete("stale-doc", { env: env(), timeout: 5_000 });+ expect(s).toEqual({ id: "stale-doc", state: "absent" });+ expect(fs.readFileSync(argvLog, "utf-8").trim()).toBe("delete stale-doc");+ });++ test("export() returns the CLI's stdout verbatim (multi-line, unparsed)", async () => {+ const body = await new GbrainProvider().export({ id: "code" }, { env: env(), consented: true });+ expect(body).toBe("line-one\nline-two\n");+ expect(fs.readFileSync(argvLog, "utf-8").trim()).toBe("export");+ });++ test("add/delete/export each degrade to PROVIDER_UNAVAILABLE when the CLI is absent", async () => {+ const missing = { PATH: os.tmpdir(), HOME: home, GSTACK_HOME: home };+ const g = new GbrainProvider();+ await expect(g.add({ slug: "s", body: "b" }, { env: missing, consented: true })).rejects.toMatchObject({+ code: "PROVIDER_UNAVAILABLE",+ });+ await expect(g.delete("s", { env: missing })).rejects.toMatchObject({ code: "PROVIDER_UNAVAILABLE" });+ await expect(g.export({ id: "code" }, { env: missing, consented: true })).rejects.toMatchObject({+ code: "PROVIDER_UNAVAILABLE",+ });+ });+});++// ── CLI rendering surfaces: options / status / suggest --json ───────────────+// The human/agent-facing renderers had zero reach: pin that `options` lists+// the three providers with availability rows (GBrain first), `status` renders+// the persisted selection + per-provider availability, and `suggest --json`+// emits the machine-readable offer/reason contract.+describe("CLI rendering (options / status / suggest --json)", () => {+ const CLI = path.join(import.meta.dir, "..", "bin", "gstack-code-intelligence");+ let home: string;+ let shimDir: string;+ let env: NodeJS.ProcessEnv;++ function runCli(...args: string[]) {+ return spawnSync("bun", [CLI, ...args], {+ encoding: "utf-8",+ timeout: 30_000,+ env: env as Record<string, string>,+ });+ }++ beforeEach(() => {+ home = fs.mkdtempSync(path.join(os.tmpdir(), "ci-cli-render-"));+ shimDir = fs.mkdtempSync(path.join(os.tmpdir(), "ci-cli-render-bin-"));+ // Fake gbrain satisfies the FULL localEngineStatus probe chain (--version+ // resolution + `sources list --json` liveness) so the GBrain row is+ // deterministically available; config.json lives in the temp GBRAIN_HOME+ // so the operator's real ~/.gbrain is never read.+ fs.writeFileSync(+ path.join(shimDir, "gbrain"),+ `#!/usr/bin/env bash+if [ "$1" = "--version" ]; then echo "gbrain 0.42.0"; exit 0; fi+if [ "$1" = "sources" ]; then echo '{"sources":[]}'; exit 0; fi+exit 1+`,+ { mode: 0o755 },+ );+ const gbrainHome = path.join(home, ".gbrain");+ fs.mkdirSync(gbrainHome, { recursive: true });+ fs.writeFileSync(path.join(gbrainHome, "config.json"), JSON.stringify({ engine: "pglite" }));+ env = {+ ...process.env,+ GSTACK_HOME: home,+ HOME: home,+ GBRAIN_HOME: gbrainHome,+ PATH: `${shimDir}:${process.env.PATH}`,+ // Dead loopback port → the Sourcebot probe fails fast + deterministically+ // (connection refused) instead of poking whatever operator dev server+ // happens to sit on localhost:3000.+ SOURCEBOT_URL: "http://127.0.0.1:1",+ };+ });+ afterEach(() => {+ fs.rmSync(home, { recursive: true, force: true });+ fs.rmSync(shimDir, { recursive: true, force: true });+ });++ function makeRepoWithFiles(count: number): string {+ const repo = fs.mkdtempSync(path.join(os.tmpdir(), "ci-cli-suggest-"));+ Bun.spawnSync(["git", "init", "-q", repo]);+ for (let i = 0; i < count; i++) fs.writeFileSync(path.join(repo, `f${i}.ts`), "x\n");+ Bun.spawnSync(["git", "-C", repo, "add", "-A"]);+ return repo;+ }++ test("options lists the three providers with availability rows, GBrain first", () => {+ const res = runCli("options");+ expect(res.status).toBe(0);+ expect(res.stdout).toContain("Code-intelligence providers");+ // GBrain row: recommended marker + deterministically available via the shim.+ expect(res.stdout).toMatch(/\* GBrain\s+\[available\]/);+ expect(res.stdout).toContain("gbrain engine: ok");+ // Sourcebot row: dead loopback port → not available, probe detail rendered.+ expect(res.stdout).toMatch(/Sourcebot\s+\[not available\]/);+ expect(res.stdout).toContain("unreachable at http://127.0.0.1:1");+ // Graphify row renders an availability mark either way (the operator+ // machine may or may not have graphify installed).+ expect(res.stdout).toMatch(/Graphify\s+\[(available|not available)\]/);+ // Rows come out in recommendation order (GBrain → Sourcebot → Graphify).+ const at = ["GBrain", "Sourcebot", "Graphify"].map((s) => res.stdout.indexOf(s));+ expect(at[0]).toBeGreaterThan(-1);+ expect(at[0]).toBeLessThan(at[1]);+ expect(at[1]).toBeLessThan(at[2]);+ expect(res.stdout).toContain("select <provider>");+ });++ test("status renders the provider-OFF selection and per-provider availability", () => {+ const res = runCli("status");+ expect(res.status).toBe(0);+ expect(res.stdout).toContain("selected: none (grep / file-only fallback)");+ expect(res.stdout).toContain("GBrain: available (gbrain engine: ok)");+ expect(res.stdout).toContain("Sourcebot: unavailable (unreachable at http://127.0.0.1:1)");+ expect(res.stdout).toMatch(/Graphify: (available|unavailable)/);+ });++ test("status renders a persisted selection", () => {+ setProvider("gbrain", env);+ const res = runCli("status");+ expect(res.status).toBe(0);+ expect(res.stdout).toContain("selected: gbrain");+ });++ test("suggest --json: small repo → machine-readable offer:false / reason:small-repo", () => {+ const repo = makeRepoWithFiles(3);+ try {+ const res = runCli("suggest", repo, "--json");+ expect(res.status).toBe(0);+ const parsed = JSON.parse(res.stdout) as Record<string, unknown>;+ expect(parsed).toEqual({+ offer: false,+ reason: "small-repo",+ fileCount: 3,+ threshold: LARGE_REPO_FILE_THRESHOLD,+ repoPath: repo,+ });+ } finally {+ fs.rmSync(repo, { recursive: true, force: true });+ }+ });++ test("suggest --json: large repo → offer:true with self-contained provider options", () => {+ const repo = makeRepoWithFiles(LARGE_REPO_FILE_THRESHOLD);+ try {+ const res = runCli("suggest", repo, "--json");+ expect(res.status).toBe(0);+ const parsed = JSON.parse(res.stdout) as {+ offer: boolean;+ reason: string;+ fileCount: number;+ options: Array<{ id: string; label: string; reason: string; local: boolean; available: boolean; detail: string }>;+ };+ expect(parsed.offer).toBe(true);+ expect(parsed.reason).toBe("large-repo");+ expect(parsed.fileCount).toBe(LARGE_REPO_FILE_THRESHOLD);+ // The offer is self-contained: every provider option carries the fields+ // an agent needs to render the question without a second CLI call.+ expect(parsed.options.map((o) => o.id)).toEqual(["gbrain", "sourcebot", "graphify"]);+ for (const o of parsed.options) {+ expect(typeof o.label).toBe("string");+ expect(typeof o.reason).toBe("string");+ expect(typeof o.local).toBe("boolean");+ expect(typeof o.available).toBe("boolean");+ expect(typeof o.detail).toBe("string");+ }+ const gbrain = parsed.options[0];+ expect(gbrain.label).toBe("GBrain");+ expect(gbrain.local).toBe(false);+ expect(gbrain.available).toBe(true);+ expect(gbrain.detail).toContain("gbrain engine:");+ const sourcebot = parsed.options[1];+ expect(sourcebot.local).toBe(true); // loopback SOURCEBOT_URL+ expect(sourcebot.available).toBe(false);+ } finally {+ fs.rmSync(repo, { recursive: true, force: true });+ }+ });+});++// ── picker probes: concurrent, short-timeout, never a 30s CLI stall ─────────+describe("detectAvailable probes fast even when Sourcebot is a dead non-loopback host", () => {+ test("rows come back in recommendation order, well under the old 30s stall", async () => {+ const binDir = fs.mkdtempSync(path.join(os.tmpdir(), "ci-pick-bin-"));+ const homeDir = fs.mkdtempSync(path.join(os.tmpdir(), "ci-pick-home-"));+ // localEngineStatus writes its probe cache via process.env.GSTACK_HOME —+ // point it at the temp home for the duration so nothing touches ~/.gstack.+ const prevGstackHome = process.env.GSTACK_HOME;+ process.env.GSTACK_HOME = homeDir;+ try {+ // PATH-scoped fake gbrain; graphify deliberately absent from that PATH.+ fs.writeFileSync(+ path.join(binDir, "gbrain"),+ `#!/usr/bin/env bash+if [ "$1" = "--version" ]; then echo "gbrain 0.42.0"; exit 0; fi+if [ "$1" = "sources" ]; then echo '{"sources":[]}'; exit 0; fi+exit 1+`,+ { mode: 0o755 },+ );+ const env: NodeJS.ProcessEnv = { PATH: binDir, HOME: homeDir, GSTACK_HOME: homeDir };+ // A hanging fetch that only settles on abort — the 3s probe cap must cut+ // it off; with the adapters' 30s default this test would blow its budget.+ const hangingFetch = ((_url: string, init: RequestInit) =>+ new Promise((_resolve, reject) => {+ init.signal?.addEventListener("abort", () =>+ reject(Object.assign(new Error("aborted"), { name: "AbortError" })),+ );+ })) as unknown as typeof fetch;+ const t0 = Date.now();+ const rows = await detectAvailable({+ env,+ sourcebot: { baseUrl: "http://sb.internal.example:3000", fetch: hangingFetch },+ });+ expect(Date.now() - t0).toBeLessThan(5_000);+ expect(rows.map((r) => r.id)).toEqual(["gbrain", "sourcebot", "graphify"]);+ const gbrain = rows.find((r) => r.id === "gbrain")!;+ expect(gbrain.detail).toContain("gbrain engine:");+ const sourcebot = rows.find((r) => r.id === "sourcebot")!;+ expect(sourcebot.available).toBe(false);+ const graphify = rows.find((r) => r.id === "graphify")!;+ expect(graphify.available).toBe(false); // not on the scoped PATH+ expect(graphify.detail).toContain("not installed");+ } finally {+ if (prevGstackHome === undefined) delete process.env.GSTACK_HOME;+ else process.env.GSTACK_HOME = prevGstackHome;+ fs.rmSync(binDir, { recursive: true, force: true });+ fs.rmSync(homeDir, { recursive: true, force: true });+ }+ }, 20_000);+});diff --git a/test/context-bill.test.ts b/test/context-bill.test.tsindex 79cf79aab..4c44279a3 100644--- a/test/context-bill.test.ts+++ b/test/context-bill.test.ts@@ -152,6 +152,40 @@ describe("upstream fix a: root-as-container + walkMd exclusions", () => {fs.rmSync(tmp, { recursive: true, force: true });});+ it("totalMd: a container skill excludes nested child skills' bytes; the grand total sums per-skill with no overlap", () => {+ // Regression pin for the v1.63 double-count: totalMd on a skill dir that+ // CONTAINS other skill dirs (the gstack root wraps the whole tree) used to+ // swallow the children's .md bytes too, so the TOTAL line billed every+ // nested skill twice. A revert of the topSeg/SKILL.md skip in totalMd+ // (lib/context-bill.ts) must fail here.+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "context-bill-nested-total-"));+ fs.writeFileSync(path.join(tmp, "SKILL.md"), "---\nname: parent\ndescription: p\n---\n# Parent\n");+ fs.writeFileSync(path.join(tmp, "NOTES.md"), "n".repeat(1_000));+ // A non-skill subdir (no SKILL.md) still belongs to the parent's total.+ fs.mkdirSync(path.join(tmp, "references"));+ fs.writeFileSync(path.join(tmp, "references", "GUIDE.md"), "g".repeat(2_000));+ // Nested child skill with a LARGE .md — the bytes a revert double-counts.+ fs.mkdirSync(path.join(tmp, "child"));+ fs.writeFileSync(path.join(tmp, "child", "SKILL.md"), "---\nname: child\ndescription: c\n---\n# Child\n");+ fs.writeFileSync(path.join(tmp, "child", "BIG.md"), "x".repeat(50_000));++ const bill = buildBill(tmp);+ const parent = bill.skills.find((s) => s.name !== "child")!;+ const child = bill.skills.find((s) => s.name === "child")!;+ expect(bill.skills).toHaveLength(2);++ const parentOwn =+ fileBytes(tmp, "SKILL.md") + fileBytes(tmp, "NOTES.md") + fileBytes(tmp, "references", "GUIDE.md");+ const childOwn = fileBytes(tmp, "child", "SKILL.md") + fileBytes(tmp, "child", "BIG.md");+ // Parent's total is its OWN files only — the child's 50KB is excluded.+ expect(parent.totalMdBytes).toBe(parentOwn);+ expect(child.totalMdBytes).toBe(childOwn);+ // Grand total = sum of per-skill figures, every byte billed exactly once.+ expect(bill.totals.totalMdBytes).toBe(parentOwn + childOwn);+ expect(bill.totals.totalMdBytes).toBe(parent.totalMdBytes + child.totalMdBytes);+ fs.rmSync(tmp, { recursive: true, force: true });+ });+it("walkMd skips node_modules and dot-directories", () => {const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "context-bill-walk-"));fs.writeFileSync(path.join(tmp, "real.md"), "x");diff --git a/test/egress-receipt-wiring.test.ts b/test/egress-receipt-wiring.test.tsindex 82dafa7de..b3ed8f419 100644--- a/test/egress-receipt-wiring.test.ts+++ b/test/egress-receipt-wiring.test.ts@@ -67,6 +67,13 @@ const MODULE_SINKS = ['bin/gstack-gbrain-sync.ts','bin/gstack-memory-ingest.ts','browse/src/server.ts',+ // Code-intelligence adapters (fork port wave 2): the gbrain adapter shells+ // repo content to the user's gbrain DB and the Sourcebot adapter POSTs+ // queries to a self-hosted HTTP endpoint — both sensitive-class+ // (repo-content) sinks, fail-closed. Registered so a refactor that drops+ // their writeReceipt calls fails CI, not just the tree-sweep scanner.+ 'lib/code-intelligence/gbrain-adapter.ts',+ 'lib/code-intelligence/sourcebot-adapter.ts',// Unconditional: context-bill ships in the same tree as this tripwire. A// missing file must fail loudly (a rename/move that drops its receipt wiring// is exactly what this pins), not silently soften the assertion.diff --git a/test/eval-model.test.ts b/test/eval-model.test.tsnew file mode 100644index 000000000..a4dfab878--- /dev/null+++ b/test/eval-model.test.ts@@ -0,0 +1,23 @@+/** OV11: the host-neutral eval-model resolver's contract. */+import { describe, test, expect } from "bun:test";+import { resolveEvalModel } from "../lib/eval-model";++describe("resolveEvalModel", () => {+ test("explicit argument wins over everything", () => {+ expect(resolveEvalModel("capture", "my-model", { GSTACK_EVAL_MODEL: "x" } as never)).toBe("my-model");+ });+ test("per-kind env beats the global env", () => {+ expect(resolveEvalModel("warmup", null, { GSTACK_EVAL_MODEL_WARMUP: "w", GSTACK_EVAL_MODEL: "g" } as never)).toBe("w");+ });+ test("global env beats the default", () => {+ expect(resolveEvalModel("distill", null, { GSTACK_EVAL_MODEL: "g" } as never)).toBe("g");+ });+ test("defaults per kind", () => {+ expect(resolveEvalModel("capture", null, {} as never)).toBe("claude-opus-4-7");+ expect(resolveEvalModel("warmup", null, {} as never)).toBe("claude-haiku-4-5");+ expect(resolveEvalModel("distill", null, {} as never)).toBe("claude-haiku-4-5-20251001");+ });+ test("unknown kind throws instead of silently defaulting", () => {+ expect(() => resolveEvalModel("banana" as never, null, {} as never)).toThrow();+ });+});diff --git a/test/fixtures/golden/claude-ship-SKILL.md b/test/fixtures/golden/claude-ship-SKILL.mdindex 319dd43fc..1446dd74b 100644--- a/test/fixtures/golden/claude-ship-SKILL.md+++ b/test/fixtures/golden/claude-ship-SKILL.md@@ -678,6 +678,10 @@ When options differ in coverage, include `Completeness: X/10` (10 = all edge casFor high-stakes ambiguity (architecture, data model, destructive scope, missing context), STOP. Name it in one sentence, present 2-3 options with tradeoffs, and ask. Do not use for routine coding or obvious changes.+## Claimed Limitations Need Evidence++A claimed limitation or requirement ("the API can't do this", "X requires a credential", "that's impossible on this platform") is a material claim. State one only with the verbatim error, the documented statement, or a live probe in hand — pattern-matching a failure to a familiar story is not evidence. When a cheap probe settles the question, run it BEFORE asking the user anything or declaring a step blocked.+## Continuous Checkpoint ModeIf `CHECKPOINT_MODE` is `"continuous"`: auto-commit completed logical units with `WIP:` prefix.@@ -808,6 +812,20 @@ the failure occurred (if outcome is error, otherwise use empty string "").Skills that run plan reviews (`/plan-*-review`, `/codex review`) include the EXIT PLAN MODE GATE blocking checklist at the end of the skill, which verifies the plan file ends with `## GSTACK REVIEW REPORT` before ExitPlanMode is called. Skills that don't run plan reviews (operational skills like `/ship`, `/qa`, `/review`) typically don't operate in plan mode and have no review report to verify; this footer is a no-op for them. Writing the plan file is the one edit allowed in plan mode.+## Third-Party Web Actions++A step sometimes requires action on an external website the user controls: registering an API key, creating a vendor or developer account, configuring a dashboard, webhook, OAuth app, billing plan, or domain verification. This contract governs that moment. It grants no new browsing authority — the AskUserQuestion format and one-way-door rules remain binding, including approval before anything that spends money.++1. **Never hand the user a manual step list for a third-party site without first offering to drive it.** The driver is gstack's own browser stack: `$B` headed mode with handoff/resume for the human-only moments (see the /browse skill), or GStack Browser when installed. Never install new tooling to close the gap, and never treat tooling presence as consent to browse.++2. **One explicit question before any browsing.** STOP and name the exact site and the exact actions (for example "create a test-mode API token in the Duffel dashboard"), then offer: A) I drive it now in a visible browser — you take over for sign-in and approvals, B) manual instructions, C) defer. The selection is per-task consent; never persist it as standing permission and never infer it from an earlier task.++3. **When driving, touch only the named site and actions.** Password entry, new-account credential choice, payment, CAPTCHA, and identity verification are user-performed: hand off (`$B handoff`) and wait instead of acting. Prefer credential flows that never expose the secret to the agent, such as password-manager autofill or the dashboard's own copy button used by the human.++4. **A captured secret never appears in chat output, logs, or shell history.** Write it to a user-approved local file with owner-only permissions (0600) or the user's secret store, and keep generated destinations out of version control. Dashboard fields are often masked placeholders — verify the captured credential with ONE non-mutating API call before claiming success; a 401 here has caught a placeholder masquerading as a key.++5. **If the user declines or defers, or no browser is usable,** provide the manual steps and mark the step blocked on the user. Do not recommend or install new products to close the gap.+## Step 0: Detect platform and base branchFirst, detect the git hosting platform from the remote URL:@@ -895,6 +913,7 @@ sections. Read a section in full before doing its step; do not work from memory.| When | Read this section ||------|-------------------|+| the ship target is an Apple platform app (.xcodeproj, .xcworkspace, or an app-product Swift package) — read BEFORE Step 1's branch gate and any preflight; store distribution never routes through the branch/PR ceremony | `sections/apple-release.md` || running the test suites and (if prompt files changed) the eval suites (Steps 4-6) | `sections/tests.md` || auditing test coverage of the diff (Step 7) | `sections/test-coverage.md` || auditing plan completion, verification, and scope drift (Step 8) | `sections/plan-completion.md` |@@ -906,6 +925,18 @@ sections. Read a section in full before doing its step; do not work from memory.---+## Step 0.9: Apple target detection++Shipping to the App Store is not landing a PR. If the repository contains an+`.xcodeproj`, `.xcworkspace`, or a Swift package with an app product AND the+user's ask is store distribution (App Store, TestFlight, "release my app"),+**STOP and Read `~/.claude/skills/gstack/ship/sections/apple-release.md` FIRST**+— before the branch gate and any preflight below. Store distribution proceeds+from whatever branch the user is on (a clean tree on the base branch is the+solo developer's normal case, not an error) and follows the adapter end to+end. The branch gate and repository-landing pipeline below apply ONLY to+repository-landing asks, including on Apple repos.+## Step 1: Pre-flight1. Check the current branch. If on the base branch or the repo's default branch, **abort**: "You're on the base branch. Ship from a feature branch."diff --git a/test/fixtures/golden/codex-ship-SKILL.md b/test/fixtures/golden/codex-ship-SKILL.mdindex 476eefb00..642e15bc9 100644--- a/test/fixtures/golden/codex-ship-SKILL.md+++ b/test/fixtures/golden/codex-ship-SKILL.md@@ -664,6 +664,10 @@ When options differ in coverage, include `Completeness: X/10` (10 = all edge casFor high-stakes ambiguity (architecture, data model, destructive scope, missing context), STOP. Name it in one sentence, present 2-3 options with tradeoffs, and ask. Do not use for routine coding or obvious changes.+## Claimed Limitations Need Evidence++A claimed limitation or requirement ("the API can't do this", "X requires a credential", "that's impossible on this platform") is a material claim. State one only with the verbatim error, the documented statement, or a live probe in hand — pattern-matching a failure to a familiar story is not evidence. When a cheap probe settles the question, run it BEFORE asking the user anything or declaring a step blocked.+## Continuous Checkpoint ModeIf `CHECKPOINT_MODE` is `"continuous"`: auto-commit completed logical units with `WIP:` prefix.@@ -794,6 +798,20 @@ the failure occurred (if outcome is error, otherwise use empty string "").Skills that run plan reviews (`/plan-*-review`, `/codex review`) include the EXIT PLAN MODE GATE blocking checklist at the end of the skill, which verifies the plan file ends with `## GSTACK REVIEW REPORT` before ExitPlanMode is called. Skills that don't run plan reviews (operational skills like `/ship`, `/qa`, `/review`) typically don't operate in plan mode and have no review report to verify; this footer is a no-op for them. Writing the plan file is the one edit allowed in plan mode.+## Third-Party Web Actions++A step sometimes requires action on an external website the user controls: registering an API key, creating a vendor or developer account, configuring a dashboard, webhook, OAuth app, billing plan, or domain verification. This contract governs that moment. It grants no new browsing authority — the AskUserQuestion format and one-way-door rules remain binding, including approval before anything that spends money.++1. **Never hand the user a manual step list for a third-party site without first offering to drive it.** The driver is gstack's own browser stack: `$B` headed mode with handoff/resume for the human-only moments (see the /browse skill), or GStack Browser when installed. Never install new tooling to close the gap, and never treat tooling presence as consent to browse.++2. **One explicit question before any browsing.** STOP and name the exact site and the exact actions (for example "create a test-mode API token in the Duffel dashboard"), then offer: A) I drive it now in a visible browser — you take over for sign-in and approvals, B) manual instructions, C) defer. The selection is per-task consent; never persist it as standing permission and never infer it from an earlier task.++3. **When driving, touch only the named site and actions.** Password entry, new-account credential choice, payment, CAPTCHA, and identity verification are user-performed: hand off (`$B handoff`) and wait instead of acting. Prefer credential flows that never expose the secret to the agent, such as password-manager autofill or the dashboard's own copy button used by the human.++4. **A captured secret never appears in chat output, logs, or shell history.** Write it to a user-approved local file with owner-only permissions (0600) or the user's secret store, and keep generated destinations out of version control. Dashboard fields are often masked placeholders — verify the captured credential with ONE non-mutating API call before claiming success; a 401 here has caught a placeholder masquerading as a key.++5. **If the user declines or defers, or no browser is usable,** provide the manual steps and mark the step blocked on the user. Do not recommend or install new products to close the gap.+## Step 0: Detect platform and base branchFirst, detect the git hosting platform from the remote URL:@@ -878,6 +896,18 @@ Never skip a verification step because a prior `/ship` run already performed it.---+## Step 0.9: Apple target detection++Shipping to the App Store is not landing a PR. If the repository contains an+`.xcodeproj`, `.xcworkspace`, or a Swift package with an app product AND the+user's ask is store distribution (App Store, TestFlight, "release my app"),+**STOP and Read `$GSTACK_ROOT/ship/sections/apple-release.md` FIRST**+— before the branch gate and any preflight below. Store distribution proceeds+from whatever branch the user is on (a clean tree on the base branch is the+solo developer's normal case, not an error) and follows the adapter end to+end. The branch gate and repository-landing pipeline below apply ONLY to+repository-landing asks, including on Apple repos.+## Step 1: Pre-flight1. Check the current branch. If on the base branch or the repo's default branch, **abort**: "You're on the base branch. Ship from a feature branch."@@ -999,41 +1029,70 @@ git fetch origin <base> && git merge origin/<base> --no-edit## Test Framework Bootstrap-**Detect existing test framework and project runtime:**+**Read the project's AGENTS.md (and TESTING.md if present) FIRST.** If it documents a test command, the project already told you: no detection, no bootstrap. Skip the rest of bootstrap and use that command in Step 5.++**Otherwise gather markers. Every marker below is EVIDENCE for the question you ask — never a command to run blind.** A marker tells you which ecosystem you're in and which command to OFFER. It does not tell you the command works. Do not execute a candidate test command to "check" it: a probe on a project that never had that runner fails loudly and teaches you nothing, and installing a second framework over a working one is worse.```bashsetopt +o nomatch 2>/dev/null || true # zsh compat-# Detect project runtime-[ -f Gemfile ] && echo "RUNTIME:ruby"+# Definitive ecosystem markers (presence = ecosystem, NOT a command to run)+[ -f manage.py ] && echo "RUNTIME:python FRAMEWORK:django MARKER:manage.py"+{ [ -f pyproject.toml ] || [ -f pytest.ini ] || [ -f tox.ini ] || [ -f setup.cfg ] || [ -f requirements.txt ]; } && echo "RUNTIME:python"+[ -f Gemfile ] || [ -f Rakefile ] || [ -f .rspec ] && echo "RUNTIME:ruby"[ -f package.json ] && echo "RUNTIME:node"-[ -f requirements.txt ] || [ -f pyproject.toml ] && echo "RUNTIME:python"[ -f go.mod ] && echo "RUNTIME:go"[ -f Cargo.toml ] && echo "RUNTIME:rust"[ -f composer.json ] && echo "RUNTIME:php"[ -f mix.exs ] && echo "RUNTIME:elixir"+[ -f pom.xml ] && echo "RUNTIME:jvm BUILD:maven"+{ [ -f build.gradle ] || [ -f build.gradle.kts ]; } && echo "RUNTIME:jvm BUILD:gradle"# Detect sub-frameworks[ -f Gemfile ] && grep -q "rails" Gemfile 2>/dev/null && echo "FRAMEWORK:rails"[ -f package.json ] && grep -q '"next"' package.json 2>/dev/null && echo "FRAMEWORK:nextjs"-# Check for existing test infrastructure-ls jest.config.* vitest.config.* playwright.config.* .rspec pytest.ini pyproject.toml phpunit.xml 2>/dev/null-ls -d test/ tests/ spec/ __tests__/ cypress/ e2e/ 2>/dev/null+# Existing test path — config files, declared scripts, AND test FILES.+# A project with real tests and no config file is the common miss.+ls jest.config.* vitest.config.* playwright.config.* .rspec pytest.ini tox.ini phpunit.xml* 2>/dev/null+[ -f package.json ] && grep -q '"test"[[:space:]]*:' package.json && echo "SCRIPT:package.json test"+[ -f Makefile ] && grep -qE '^(test|check):' Makefile && echo "TARGET:make test"+[ -f pyproject.toml ] && grep -q "pytest" pyproject.toml && echo "CONFIG:pyproject pytest"+git ls-files | grep -cE '(^|/)(tests?|spec|__tests__)/|(^|/)tests?\.py$|(^|/)test_[^/]+\.py$|_test\.(go|py|rb|ts|js|exs)$|\.(test|spec)\.[jt]sx?$|_spec\.rb$|Test\.(java|kt)$' | sed 's/^/TESTFILES:/'+# Rust keeps unit tests inside src/, so file names alone miss them+[ -f Cargo.toml ] && git grep -lF '#[test]' -- 'src' >/dev/null 2>&1 && echo "TESTS:rust in-source"# Check opt-out marker[ -f .gstack/no-test-bootstrap ] && echo "BOOTSTRAP_DECLINED"```-**If test framework detected** (config files or test directories found):-Print "Test framework detected: {name} ({N} existing tests). Skipping bootstrap."+Map the markers to the command you will OFFER — never to one you run on a guess:++| Marker | Ecosystem | Candidate command to offer |+|--------|-----------|----------------------------|+| `manage.py` | Django | `python manage.py test` (or `pytest` when pytest-django is in the deps) |+| `pytest.ini` / `tox.ini` / pytest in `pyproject.toml` / `test_*.py` | Python | `pytest` |+| `go.mod` (+ any `*_test.go`) | Go | `go test ./...` |+| `Cargo.toml` | Rust | `cargo test` |+| `pom.xml` | JVM (Maven) | `mvn test` |+| `build.gradle` / `build.gradle.kts` | JVM (Gradle) | `./gradlew test` |+| `Gemfile` / `Rakefile` / `.rspec` | Ruby | `bundle exec rspec`, `bin/rails test`, or `rake test` |+| `mix.exs` | Elixir | `mix test` |+| `composer.json` | PHP | `composer test` or `./vendor/bin/phpunit` |+| `package.json` with a `test` script | Node | that script, run with the package manager the lockfile names |+| `Makefile` with a `test:` target | any | `make test` |++**If ANY existing-test evidence appears** (a config file, a declared test script or make target, a nonzero `TESTFILES:` count, or `TESTS:rust in-source`): the project has tests. **Do NOT bootstrap.** Print "Existing tests detected: {the evidence}." Then get the command the same way Step 5 does — AGENTS.md/TESTING.md if documented, otherwise AskUserQuestion offering the candidates from the table above plus "Other", and persist the answer to AGENTS.md's `## Testing` section so it is never asked again. When the ecosystem ships a runner (Django, Go, Rust, Elixir, Maven/Gradle), that runner is the candidate — never install a second framework beside a working one.Read 2-3 existing test files to learn conventions (naming, imports, assertion style, setup patterns).Store conventions as prose context for use in Phase 8e.5 or Step 7. **Skip the rest of bootstrap.**+Absent config files and absent `tests/` directories are NOT evidence of "no tests": Django keeps tests in `<app>/tests.py`, Go in `*_test.go` beside the source, Rust in `#[test]` blocks inside `src/`. A green `python manage.py test` with no `pytest.ini` is a tested project, not a bootstrap candidate.+**If BOOTSTRAP_DECLINED** appears: Print "Test bootstrap previously declined — skipping." **Skip the rest of bootstrap.**-**If NO runtime detected** (no config files found): Use AskUserQuestion:+**If NO ecosystem marker matched:** Use AskUserQuestion:"I couldn't detect your project's language. What runtime are you using?"Options: A) Node.js/TypeScript B) Ruby/Rails C) Python D) Go E) Rust F) PHP G) Elixir H) This project doesn't need tests.+If the runtime you need isn't listed, offer "Other" and take the runtime plus the test command as free text.If user picks H → write `.gstack/no-test-bootstrap` and continue without tests.-**If runtime detected but no test framework — bootstrap:**+**If an ecosystem matched but there is no existing-test evidence at all — bootstrap:**### B2. Research best practices@@ -1049,7 +1108,9 @@ If WebSearch is unavailable, use this built-in knowledge table:| Node.js | vitest + @testing-library | jest + @testing-library || Next.js | vitest + @testing-library/react + playwright | jest + cypress || Python | pytest + pytest-cov | unittest |+| Django | pytest + pytest-django | Django's built-in `manage.py test` (unittest) || Go | stdlib testing + testify | stdlib only |+| JVM (Maven/Gradle) | JUnit 5 + AssertJ | JUnit 5 only || Rust | cargo test (built-in) + mockall | — || PHP | phpunit + mockery | pest || Elixir | ExUnit (built-in) + ex_machina | — |@@ -1378,15 +1439,20 @@ Before analyzing coverage, detect the project's test framework:```bashsetopt +o nomatch 2>/dev/null || true # zsh compat-# Detect project runtime-[ -f Gemfile ] && echo "RUNTIME:ruby"+# Detect project runtime (markers are evidence, not commands to run blind)+[ -f manage.py ] && echo "RUNTIME:python FRAMEWORK:django"+{ [ -f pyproject.toml ] || [ -f pytest.ini ] || [ -f tox.ini ] || [ -f setup.cfg ] || [ -f requirements.txt ]; } && echo "RUNTIME:python"+[ -f Gemfile ] || [ -f Rakefile ] || [ -f .rspec ] && echo "RUNTIME:ruby"[ -f package.json ] && echo "RUNTIME:node"-[ -f requirements.txt ] || [ -f pyproject.toml ] && echo "RUNTIME:python"[ -f go.mod ] && echo "RUNTIME:go"[ -f Cargo.toml ] && echo "RUNTIME:rust"-# Check for existing test infrastructure-ls jest.config.* vitest.config.* playwright.config.* cypress.config.* .rspec pytest.ini phpunit.xml 2>/dev/null-ls -d test/ tests/ spec/ __tests__/ cypress/ e2e/ 2>/dev/null+[ -f pom.xml ] && echo "RUNTIME:jvm BUILD:maven"+{ [ -f build.gradle ] || [ -f build.gradle.kts ]; } && echo "RUNTIME:jvm BUILD:gradle"+# Check for existing test infrastructure — config files, scripts, AND test files+ls jest.config.* vitest.config.* playwright.config.* cypress.config.* .rspec pytest.ini tox.ini phpunit.xml 2>/dev/null+[ -f package.json ] && grep -q '"test"[[:space:]]*:' package.json && echo "SCRIPT:package.json test"+[ -f Makefile ] && grep -qE '^(test|check):' Makefile && echo "TARGET:make test"+git ls-files | grep -cE '(^|/)(tests?|spec|__tests__)/|(^|/)tests?\.py$|(^|/)test_[^/]+\.py$|_test\.(go|py|rb|ts|js|exs)$|\.(test|spec)\.[jt]sx?$|_spec\.rb$|Test\.(java|kt)$' | sed 's/^/TESTFILES:/'```3. **If no framework detected:** falls through to the Test Framework Bootstrap step (Step 4) which handles full setup.@@ -1818,16 +1884,23 @@ Using the plan file already discovered in Step 8, look for a verification sectio### 2. Check for running dev server-Before invoking browse-based verification, check if a dev server is reachable:+Before invoking browse-based verification, find the dev-server URL the way the+project declares it — never trust a hardcoded port list alone:++1. **AGENTS.md first:** look for a documented dev URL or dev command (a+ `## Development`/`## Testing` section naming a port or URL). Use it.+2. **The plan file:** if the plan's verification section names a URL, use it.+3. **Fallback probe** (common ports, only when 1-2 found nothing):```bash-curl -s -o /dev/null -w '%{http_code}' http://localhost:3000 2>/dev/null || \-curl -s -o /dev/null -w '%{http_code}' http://localhost:8080 2>/dev/null || \-curl -s -o /dev/null -w '%{http_code}' http://localhost:5173 2>/dev/null || \-curl -s -o /dev/null -w '%{http_code}' http://localhost:4000 2>/dev/null || echo "NO_SERVER"+for _p in 3000 8080 5173 4000 4321 8000; do+ _code=$(curl -s -o /dev/null -w '%{http_code}' "http://localhost:$_p" 2>/dev/null)+ [ -n "$_code" ] && [ "$_code" != "000" ] && { echo "DEV_SERVER: http://localhost:$_p ($_code)"; break; }+done+[ -z "${_code:-}" ] || [ "${_code:-000}" = "000" ] && echo "NO_SERVER"```-**If NO_SERVER:** Skip with "No dev server detected — skipping plan verification. Run /qa separately after deploying."+**If NO_SERVER:** Skip with "No dev server detected (checked AGENTS.md, the plan, and common ports) — skipping plan verification. Run /qa separately after deploying, or document the dev URL in AGENTS.md so this step finds it next time."### 3. Invoke /qa-only inline@@ -2579,6 +2652,8 @@ glab mr view -F json 2>/dev/null | jq -r 'if .state == "opened" then "MR_EXISTS"If an **open** PR/MR already exists: **update** the PR body using `gh pr edit --body-file "$PR_BODY_FILE"` (GitHub) or `glab mr update -d ...` (GitLab). Always regenerate the PR body from scratch using this run's fresh results (test output, coverage audit, review findings, adversarial review, TODOS summary, documentation_section from Step 18). Never reuse stale PR body content from a prior run. **Run the same redaction scan-at-sink (PR body + title) as the create path (Step 19) before editing — scan the temp file, then `gh pr edit --body-file` from it.**+**REST fallback (#1079):** on some repos `gh pr edit` hard-errors with a GraphQL deprecation mentioning `repository.pullRequest.projectCards` ("Projects (classic) is being deprecated..."). That is a `gh` GraphQL-path problem, not a permissions problem — do not re-ask for auth. Fall back to the REST endpoint, which never touches the deprecated field, using the SAME already-scanned temp file: `PR_NUMBER=$(gh pr view --json number -q .number)` then `gh api "repos/{owner}/{repo}/pulls/$PR_NUMBER" -X PATCH -F body=@"$PR_BODY_FILE"` for the body, and `gh api "repos/{owner}/{repo}/pulls/$PR_NUMBER" -X PATCH -f title="$NEW_TITLE"` when the title edit below hits the same error. Verify with the same self-checks as the primary path.+**Always update the PR title to start with `v$NEW_VERSION`.** PR titles use the workspace-aware format `v<NEW_VERSION> <type>: <summary>` — version ALWAYS first, no exceptions, no "custom title kept intentionally" escape hatch. The shared helper `bin/gstack-pr-title-rewrite.sh` is the single source of truth for the rule.1. Read the current title: `CURRENT=$(gh pr view --json title -q .title)` (or `glab mr view -F json | jq -r .title`).diff --git a/test/fixtures/golden/factory-ship-SKILL.md b/test/fixtures/golden/factory-ship-SKILL.mdindex 1045168b2..14d070b52 100644--- a/test/fixtures/golden/factory-ship-SKILL.md+++ b/test/fixtures/golden/factory-ship-SKILL.md@@ -666,6 +666,10 @@ When options differ in coverage, include `Completeness: X/10` (10 = all edge casFor high-stakes ambiguity (architecture, data model, destructive scope, missing context), STOP. Name it in one sentence, present 2-3 options with tradeoffs, and ask. Do not use for routine coding or obvious changes.+## Claimed Limitations Need Evidence++A claimed limitation or requirement ("the API can't do this", "X requires a credential", "that's impossible on this platform") is a material claim. State one only with the verbatim error, the documented statement, or a live probe in hand — pattern-matching a failure to a familiar story is not evidence. When a cheap probe settles the question, run it BEFORE asking the user anything or declaring a step blocked.+## Continuous Checkpoint ModeIf `CHECKPOINT_MODE` is `"continuous"`: auto-commit completed logical units with `WIP:` prefix.@@ -796,6 +800,20 @@ the failure occurred (if outcome is error, otherwise use empty string "").Skills that run plan reviews (`/plan-*-review`, `/codex review`) include the EXIT PLAN MODE GATE blocking checklist at the end of the skill, which verifies the plan file ends with `## GSTACK REVIEW REPORT` before ExitPlanMode is called. Skills that don't run plan reviews (operational skills like `/ship`, `/qa`, `/review`) typically don't operate in plan mode and have no review report to verify; this footer is a no-op for them. Writing the plan file is the one edit allowed in plan mode.+## Third-Party Web Actions++A step sometimes requires action on an external website the user controls: registering an API key, creating a vendor or developer account, configuring a dashboard, webhook, OAuth app, billing plan, or domain verification. This contract governs that moment. It grants no new browsing authority — the AskUserQuestion format and one-way-door rules remain binding, including approval before anything that spends money.++1. **Never hand the user a manual step list for a third-party site without first offering to drive it.** The driver is gstack's own browser stack: `$B` headed mode with handoff/resume for the human-only moments (see the /browse skill), or GStack Browser when installed. Never install new tooling to close the gap, and never treat tooling presence as consent to browse.++2. **One explicit question before any browsing.** STOP and name the exact site and the exact actions (for example "create a test-mode API token in the Duffel dashboard"), then offer: A) I drive it now in a visible browser — you take over for sign-in and approvals, B) manual instructions, C) defer. The selection is per-task consent; never persist it as standing permission and never infer it from an earlier task.++3. **When driving, touch only the named site and actions.** Password entry, new-account credential choice, payment, CAPTCHA, and identity verification are user-performed: hand off (`$B handoff`) and wait instead of acting. Prefer credential flows that never expose the secret to the agent, such as password-manager autofill or the dashboard's own copy button used by the human.++4. **A captured secret never appears in chat output, logs, or shell history.** Write it to a user-approved local file with owner-only permissions (0600) or the user's secret store, and keep generated destinations out of version control. Dashboard fields are often masked placeholders — verify the captured credential with ONE non-mutating API call before claiming success; a 401 here has caught a placeholder masquerading as a key.++5. **If the user declines or defers, or no browser is usable,** provide the manual steps and mark the step blocked on the user. Do not recommend or install new products to close the gap.+## Step 0: Detect platform and base branchFirst, detect the git hosting platform from the remote URL:@@ -880,6 +898,18 @@ Never skip a verification step because a prior `/ship` run already performed it.---+## Step 0.9: Apple target detection++Shipping to the App Store is not landing a PR. If the repository contains an+`.xcodeproj`, `.xcworkspace`, or a Swift package with an app product AND the+user's ask is store distribution (App Store, TestFlight, "release my app"),+**STOP and Read `$GSTACK_ROOT/ship/sections/apple-release.md` FIRST**+— before the branch gate and any preflight below. Store distribution proceeds+from whatever branch the user is on (a clean tree on the base branch is the+solo developer's normal case, not an error) and follows the adapter end to+end. The branch gate and repository-landing pipeline below apply ONLY to+repository-landing asks, including on Apple repos.+## Step 1: Pre-flight1. Check the current branch. If on the base branch or the repo's default branch, **abort**: "You're on the base branch. Ship from a feature branch."@@ -1001,41 +1031,70 @@ git fetch origin <base> && git merge origin/<base> --no-edit## Test Framework Bootstrap-**Detect existing test framework and project runtime:**+**Read the project's CLAUDE.md (and TESTING.md if present) FIRST.** If it documents a test command, the project already told you: no detection, no bootstrap. Skip the rest of bootstrap and use that command in Step 5.++**Otherwise gather markers. Every marker below is EVIDENCE for the question you ask — never a command to run blind.** A marker tells you which ecosystem you're in and which command to OFFER. It does not tell you the command works. Do not execute a candidate test command to "check" it: a probe on a project that never had that runner fails loudly and teaches you nothing, and installing a second framework over a working one is worse.```bashsetopt +o nomatch 2>/dev/null || true # zsh compat-# Detect project runtime-[ -f Gemfile ] && echo "RUNTIME:ruby"+# Definitive ecosystem markers (presence = ecosystem, NOT a command to run)+[ -f manage.py ] && echo "RUNTIME:python FRAMEWORK:django MARKER:manage.py"+{ [ -f pyproject.toml ] || [ -f pytest.ini ] || [ -f tox.ini ] || [ -f setup.cfg ] || [ -f requirements.txt ]; } && echo "RUNTIME:python"+[ -f Gemfile ] || [ -f Rakefile ] || [ -f .rspec ] && echo "RUNTIME:ruby"[ -f package.json ] && echo "RUNTIME:node"-[ -f requirements.txt ] || [ -f pyproject.toml ] && echo "RUNTIME:python"[ -f go.mod ] && echo "RUNTIME:go"[ -f Cargo.toml ] && echo "RUNTIME:rust"[ -f composer.json ] && echo "RUNTIME:php"[ -f mix.exs ] && echo "RUNTIME:elixir"+[ -f pom.xml ] && echo "RUNTIME:jvm BUILD:maven"+{ [ -f build.gradle ] || [ -f build.gradle.kts ]; } && echo "RUNTIME:jvm BUILD:gradle"# Detect sub-frameworks[ -f Gemfile ] && grep -q "rails" Gemfile 2>/dev/null && echo "FRAMEWORK:rails"[ -f package.json ] && grep -q '"next"' package.json 2>/dev/null && echo "FRAMEWORK:nextjs"-# Check for existing test infrastructure-ls jest.config.* vitest.config.* playwright.config.* .rspec pytest.ini pyproject.toml phpunit.xml 2>/dev/null-ls -d test/ tests/ spec/ __tests__/ cypress/ e2e/ 2>/dev/null+# Existing test path — config files, declared scripts, AND test FILES.+# A project with real tests and no config file is the common miss.+ls jest.config.* vitest.config.* playwright.config.* .rspec pytest.ini tox.ini phpunit.xml* 2>/dev/null+[ -f package.json ] && grep -q '"test"[[:space:]]*:' package.json && echo "SCRIPT:package.json test"+[ -f Makefile ] && grep -qE '^(test|check):' Makefile && echo "TARGET:make test"+[ -f pyproject.toml ] && grep -q "pytest" pyproject.toml && echo "CONFIG:pyproject pytest"+git ls-files | grep -cE '(^|/)(tests?|spec|__tests__)/|(^|/)tests?\.py$|(^|/)test_[^/]+\.py$|_test\.(go|py|rb|ts|js|exs)$|\.(test|spec)\.[jt]sx?$|_spec\.rb$|Test\.(java|kt)$' | sed 's/^/TESTFILES:/'+# Rust keeps unit tests inside src/, so file names alone miss them+[ -f Cargo.toml ] && git grep -lF '#[test]' -- 'src' >/dev/null 2>&1 && echo "TESTS:rust in-source"# Check opt-out marker[ -f .gstack/no-test-bootstrap ] && echo "BOOTSTRAP_DECLINED"```-**If test framework detected** (config files or test directories found):-Print "Test framework detected: {name} ({N} existing tests). Skipping bootstrap."+Map the markers to the command you will OFFER — never to one you run on a guess:++| Marker | Ecosystem | Candidate command to offer |+|--------|-----------|----------------------------|+| `manage.py` | Django | `python manage.py test` (or `pytest` when pytest-django is in the deps) |+| `pytest.ini` / `tox.ini` / pytest in `pyproject.toml` / `test_*.py` | Python | `pytest` |+| `go.mod` (+ any `*_test.go`) | Go | `go test ./...` |+| `Cargo.toml` | Rust | `cargo test` |+| `pom.xml` | JVM (Maven) | `mvn test` |+| `build.gradle` / `build.gradle.kts` | JVM (Gradle) | `./gradlew test` |+| `Gemfile` / `Rakefile` / `.rspec` | Ruby | `bundle exec rspec`, `bin/rails test`, or `rake test` |+| `mix.exs` | Elixir | `mix test` |+| `composer.json` | PHP | `composer test` or `./vendor/bin/phpunit` |+| `package.json` with a `test` script | Node | that script, run with the package manager the lockfile names |+| `Makefile` with a `test:` target | any | `make test` |++**If ANY existing-test evidence appears** (a config file, a declared test script or make target, a nonzero `TESTFILES:` count, or `TESTS:rust in-source`): the project has tests. **Do NOT bootstrap.** Print "Existing tests detected: {the evidence}." Then get the command the same way Step 5 does — CLAUDE.md/TESTING.md if documented, otherwise AskUserQuestion offering the candidates from the table above plus "Other", and persist the answer to CLAUDE.md's `## Testing` section so it is never asked again. When the ecosystem ships a runner (Django, Go, Rust, Elixir, Maven/Gradle), that runner is the candidate — never install a second framework beside a working one.Read 2-3 existing test files to learn conventions (naming, imports, assertion style, setup patterns).Store conventions as prose context for use in Phase 8e.5 or Step 7. **Skip the rest of bootstrap.**+Absent config files and absent `tests/` directories are NOT evidence of "no tests": Django keeps tests in `<app>/tests.py`, Go in `*_test.go` beside the source, Rust in `#[test]` blocks inside `src/`. A green `python manage.py test` with no `pytest.ini` is a tested project, not a bootstrap candidate.+**If BOOTSTRAP_DECLINED** appears: Print "Test bootstrap previously declined — skipping." **Skip the rest of bootstrap.**-**If NO runtime detected** (no config files found): Use AskUserQuestion:+**If NO ecosystem marker matched:** Use AskUserQuestion:"I couldn't detect your project's language. What runtime are you using?"Options: A) Node.js/TypeScript B) Ruby/Rails C) Python D) Go E) Rust F) PHP G) Elixir H) This project doesn't need tests.+If the runtime you need isn't listed, offer "Other" and take the runtime plus the test command as free text.If user picks H → write `.gstack/no-test-bootstrap` and continue without tests.-**If runtime detected but no test framework — bootstrap:**+**If an ecosystem matched but there is no existing-test evidence at all — bootstrap:**### B2. Research best practices@@ -1051,7 +1110,9 @@ If WebSearch is unavailable, use this built-in knowledge table:| Node.js | vitest + @testing-library | jest + @testing-library || Next.js | vitest + @testing-library/react + playwright | jest + cypress || Python | pytest + pytest-cov | unittest |+| Django | pytest + pytest-django | Django's built-in `manage.py test` (unittest) || Go | stdlib testing + testify | stdlib only |+| JVM (Maven/Gradle) | JUnit 5 + AssertJ | JUnit 5 only || Rust | cargo test (built-in) + mockall | — || PHP | phpunit + mockery | pest || Elixir | ExUnit (built-in) + ex_machina | — |@@ -1380,15 +1441,20 @@ Before analyzing coverage, detect the project's test framework:```bashsetopt +o nomatch 2>/dev/null || true # zsh compat-# Detect project runtime-[ -f Gemfile ] && echo "RUNTIME:ruby"+# Detect project runtime (markers are evidence, not commands to run blind)+[ -f manage.py ] && echo "RUNTIME:python FRAMEWORK:django"+{ [ -f pyproject.toml ] || [ -f pytest.ini ] || [ -f tox.ini ] || [ -f setup.cfg ] || [ -f requirements.txt ]; } && echo "RUNTIME:python"+[ -f Gemfile ] || [ -f Rakefile ] || [ -f .rspec ] && echo "RUNTIME:ruby"[ -f package.json ] && echo "RUNTIME:node"-[ -f requirements.txt ] || [ -f pyproject.toml ] && echo "RUNTIME:python"[ -f go.mod ] && echo "RUNTIME:go"[ -f Cargo.toml ] && echo "RUNTIME:rust"-# Check for existing test infrastructure-ls jest.config.* vitest.config.* playwright.config.* cypress.config.* .rspec pytest.ini phpunit.xml 2>/dev/null-ls -d test/ tests/ spec/ __tests__/ cypress/ e2e/ 2>/dev/null+[ -f pom.xml ] && echo "RUNTIME:jvm BUILD:maven"+{ [ -f build.gradle ] || [ -f build.gradle.kts ]; } && echo "RUNTIME:jvm BUILD:gradle"+# Check for existing test infrastructure — config files, scripts, AND test files+ls jest.config.* vitest.config.* playwright.config.* cypress.config.* .rspec pytest.ini tox.ini phpunit.xml 2>/dev/null+[ -f package.json ] && grep -q '"test"[[:space:]]*:' package.json && echo "SCRIPT:package.json test"+[ -f Makefile ] && grep -qE '^(test|check):' Makefile && echo "TARGET:make test"+git ls-files | grep -cE '(^|/)(tests?|spec|__tests__)/|(^|/)tests?\.py$|(^|/)test_[^/]+\.py$|_test\.(go|py|rb|ts|js|exs)$|\.(test|spec)\.[jt]sx?$|_spec\.rb$|Test\.(java|kt)$' | sed 's/^/TESTFILES:/'```3. **If no framework detected:** falls through to the Test Framework Bootstrap step (Step 4) which handles full setup.@@ -1820,16 +1886,23 @@ Using the plan file already discovered in Step 8, look for a verification sectio### 2. Check for running dev server-Before invoking browse-based verification, check if a dev server is reachable:+Before invoking browse-based verification, find the dev-server URL the way the+project declares it — never trust a hardcoded port list alone:++1. **CLAUDE.md first:** look for a documented dev URL or dev command (a+ `## Development`/`## Testing` section naming a port or URL). Use it.+2. **The plan file:** if the plan's verification section names a URL, use it.+3. **Fallback probe** (common ports, only when 1-2 found nothing):```bash-curl -s -o /dev/null -w '%{http_code}' http://localhost:3000 2>/dev/null || \-curl -s -o /dev/null -w '%{http_code}' http://localhost:8080 2>/dev/null || \-curl -s -o /dev/null -w '%{http_code}' http://localhost:5173 2>/dev/null || \-curl -s -o /dev/null -w '%{http_code}' http://localhost:4000 2>/dev/null || echo "NO_SERVER"+for _p in 3000 8080 5173 4000 4321 8000; do+ _code=$(curl -s -o /dev/null -w '%{http_code}' "http://localhost:$_p" 2>/dev/null)+ [ -n "$_code" ] && [ "$_code" != "000" ] && { echo "DEV_SERVER: http://localhost:$_p ($_code)"; break; }+done+[ -z "${_code:-}" ] || [ "${_code:-000}" = "000" ] && echo "NO_SERVER"```-**If NO_SERVER:** Skip with "No dev server detected — skipping plan verification. Run /qa separately after deploying."+**If NO_SERVER:** Skip with "No dev server detected (checked CLAUDE.md, the plan, and common ports) — skipping plan verification. Run /qa separately after deploying, or document the dev URL in CLAUDE.md so this step finds it next time."### 3. Invoke /qa-only inline@@ -2995,6 +3068,8 @@ glab mr view -F json 2>/dev/null | jq -r 'if .state == "opened" then "MR_EXISTS"If an **open** PR/MR already exists: **update** the PR body using `gh pr edit --body-file "$PR_BODY_FILE"` (GitHub) or `glab mr update -d ...` (GitLab). Always regenerate the PR body from scratch using this run's fresh results (test output, coverage audit, review findings, adversarial review, TODOS summary, documentation_section from Step 18). Never reuse stale PR body content from a prior run. **Run the same redaction scan-at-sink (PR body + title) as the create path (Step 19) before editing — scan the temp file, then `gh pr edit --body-file` from it.**+**REST fallback (#1079):** on some repos `gh pr edit` hard-errors with a GraphQL deprecation mentioning `repository.pullRequest.projectCards` ("Projects (classic) is being deprecated..."). That is a `gh` GraphQL-path problem, not a permissions problem — do not re-ask for auth. Fall back to the REST endpoint, which never touches the deprecated field, using the SAME already-scanned temp file: `PR_NUMBER=$(gh pr view --json number -q .number)` then `gh api "repos/{owner}/{repo}/pulls/$PR_NUMBER" -X PATCH -F body=@"$PR_BODY_FILE"` for the body, and `gh api "repos/{owner}/{repo}/pulls/$PR_NUMBER" -X PATCH -f title="$NEW_TITLE"` when the title edit below hits the same error. Verify with the same self-checks as the primary path.+**Always update the PR title to start with `v$NEW_VERSION`.** PR titles use the workspace-aware format `v<NEW_VERSION> <type>: <summary>` — version ALWAYS first, no exceptions, no "custom title kept intentionally" escape hatch. The shared helper `bin/gstack-pr-title-rewrite.sh` is the single source of truth for the rule.1. Read the current title: `CURRENT=$(gh pr view --json title -q .title)` (or `glab mr view -F json | jq -r .title`).diff --git a/test/fixtures/ios-qa/FixtureApp/Sources/DebugBridgeCore/StateServer.swift b/test/fixtures/ios-qa/FixtureApp/Sources/DebugBridgeCore/StateServer.swiftindex b8441df16..9696ff372 100644--- a/test/fixtures/ios-qa/FixtureApp/Sources/DebugBridgeCore/StateServer.swift+++ b/test/fixtures/ios-qa/FixtureApp/Sources/DebugBridgeCore/StateServer.swift@@ -97,10 +97,12 @@ public final class StateServer {try? bootToken.write(toFile: bootTokenPath, atomically: true, encoding: .utf8)try? FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: bootTokenPath)- // 2. Log the boot token EXACTLY ONCE so the daemon can scrape it.- // The daemon will rotate immediately; this log line is dead within- // seconds.- logger.notice("gstack-ios-qa-bootstrap token=\(self.bootToken, privacy: .public) port=\(self.port, privacy: .public) build=\(self.appBuildId, privacy: .public)")+ // 2. Announce bootstrap WITHOUT the token. The daemon reads the boot+ // token from the 0600 file above (copyFileFromAppContainer); the+ // os_log line that used to carry it had no consumer and handed a+ // live credential to anything reading the unified log during the+ // launch window. Port/build stay for diagnostics.+ logger.notice("gstack-ios-qa-bootstrap port=\(self.port, privacy: .public) build=\(self.appBuildId, privacy: .public)")// 3. Bind both IPv6 and IPv4 loopback. CoreDevice tunnel uses IPv6;// local tooling may use IPv4. Never bind 0.0.0.0 or ::.@@ -149,7 +151,19 @@ public final class StateServer {let params = NWParameters.tcpparams.allowLocalEndpointReuse = true- let listener = try NWListener(using: params, on: NWEndpoint.Port(rawValue: port)!)+ // IPv4 has no CoreDevice tunnel path, so it binds strictly to+ // loopback at the socket level; IPv6 keeps the wildcard bind and+ // relies on the per-connection peer check below for tunnel peers.+ let listener: NWListener+ switch family {+ case .ipv4:+ params.requiredLocalEndpoint = NWEndpoint.hostPort(+ host: NWEndpoint.Host("127.0.0.1"),+ port: NWEndpoint.Port(rawValue: port)!)+ listener = try NWListener(using: params)+ case .ipv6:+ listener = try NWListener(using: params, on: NWEndpoint.Port(rawValue: port)!)+ }listener.stateUpdateHandler = { [weak self] state inTask { @MainActor inif case .ready = state {diff --git a/test/founder-resources-optout.test.ts b/test/founder-resources-optout.test.tsnew file mode 100644index 000000000..46993f0bb--- /dev/null+++ b/test/founder-resources-optout.test.ts@@ -0,0 +1,77 @@+/**+ * #538: the office-hours founder-resources pitch takes no for an answer.+ *+ * The reporter found that memory instructions telling the agent to stop+ * showing the 34-resource pool kept being overridden on every update. The+ * fix is a config key — `founder_resources` — that session context cannot+ * override: `false` skips the entire section silently, forever, until the+ * user re-enables it.+ *+ * Pins: (1) the config key's default, persistence, and validation through+ * the real bin/gstack-config subprocess; (2) the generated section gates on+ * the key BEFORE any resource content; (3) the opt-out write is verified+ * before the skill may promise "never again" (R6 — a failed write must not+ * produce a false promise).+ */++import { describe, test, expect, beforeEach, afterEach } from "bun:test";+import { execFileSync } from "child_process";+import * as fs from "fs";+import * as os from "os";+import * as path from "path";++const ROOT = path.resolve(import.meta.dir, "..");+const CONFIG_BIN = path.join(ROOT, "bin", "gstack-config");+const SECTION = path.join(ROOT, "office-hours", "sections", "design-and-handoff.md");++let tmpHome: string;+beforeEach(() => { tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), "gstack-538-")); });+afterEach(() => { fs.rmSync(tmpHome, { recursive: true, force: true }); });++function cfg(args: string[]): string {+ return execFileSync(CONFIG_BIN, args, {+ encoding: "utf-8",+ env: { ...process.env, GSTACK_HOME: tmpHome },+ }).trim();+}++describe("founder_resources config key (#538)", () => {+ test("defaults to true (pitch stays on for everyone who never opted out)", () => {+ expect(cfg(["get", "founder_resources"])).toBe("true");+ });++ test("set false persists and reads back — the write-verify contract", () => {+ cfg(["set", "founder_resources", "false"]);+ expect(cfg(["get", "founder_resources"])).toBe("false");+ });++ test("invalid values are rejected to the default, never persisted as-is", () => {+ execFileSync(CONFIG_BIN, ["set", "founder_resources", "banana"], {+ encoding: "utf-8", stdio: ["ignore", "pipe", "pipe"],+ env: { ...process.env, GSTACK_HOME: tmpHome },+ });+ expect(cfg(["get", "founder_resources"])).toBe("true");+ });+});++describe("office-hours section gates on the key (#538)", () => {+ const src = fs.readFileSync(SECTION, "utf-8");++ test("the opt-out check precedes any resource content", () => {+ const gate = src.indexOf("gstack-config get founder_resources");+ const pool = src.indexOf("Resource Pool");+ expect(gate).toBeGreaterThan(-1);+ expect(pool).toBeGreaterThan(-1);+ expect(gate).toBeLessThan(pool);+ });++ test("skip is silent and permanent — never means never", () => {+ expect(src).toContain("skip this entire section silently");+ expect(src).toContain("gstack-config set founder_resources true");+ });++ test("the opt-out write is verified before any promise (R6)", () => {+ expect(src).toContain("VERIFY the write");+ expect(src).toMatch(/read back\s*\n?`false`/);+ });+});diff --git a/test/gate-secret-scan.test.ts b/test/gate-secret-scan.test.tsnew file mode 100644index 000000000..2d31a7012--- /dev/null+++ b/test/gate-secret-scan.test.ts@@ -0,0 +1,127 @@+/**+ * CI secret gate contract (R4/R9, fork port wave 2).+ *+ * .github/scripts/gate-secret-scan.mjs pipes a unified diff's ADDED lines+ * into bin/gstack-redact and enforces: HIGH fails (exit 1), MEDIUM is an+ * advisory count only (no human in CI to confirm, so it must never fail+ * the check), clean passes. The workflow-level pathspec excludes keep the+ * planted-bug fixtures out of the diff entirely; this pins the script's+ * own exit contract with live subprocess runs.+ */++import { describe, test, expect } from "bun:test";+import { spawnSync } from "child_process";+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "fs";+import { tmpdir } from "os";+import { join } from "path";++const ROOT = join(import.meta.dir, "..");+const SCRIPT = join(ROOT, ".github", "scripts", "gate-secret-scan.mjs");++function scan(diff: string, cwd: string = ROOT): { code: number; out: string } {+ const res = spawnSync("node", [SCRIPT], {+ cwd,+ input: diff,+ encoding: "utf-8",+ timeout: 60_000,+ });+ return { code: res.status ?? -1, out: `${res.stdout}${res.stderr}` };+}++describe("gate-secret-scan.mjs exit contract", () => {+ test("clean added lines pass", () => {+ const r = scan("+const x = 1;\n+++ b/file.ts\n+// harmless\n");+ expect(r.code).toBe(0);+ expect(r.out).toContain("0 high");+ });++ // The planted PEM is assembled at runtime — header split included — so this+ // FILE never carries a live-format private key: the repo's own prepush+ // credential guard scans pushed diffs and (correctly) blocks any one-line+ // BEGIN…END spelling regardless of body. The scanner under test still+ // receives the true live shape.+ const PEM_BEGIN = ["-----BEGIN RSA ", "PRIVATE KEY-----"].join("");+ const PEM_END = ["-----END RSA ", "PRIVATE KEY-----"].join("");+ const PLANTED_PEM_BODY = ["MIIEow", "IBAAKC", "AQEA"].join("");++ test("a HIGH credential in an added line fails the gate", () => {+ const r = scan(+ `+${PEM_BEGIN}\n+${PLANTED_PEM_BODY}\n+${PEM_END}\n`,+ );+ expect(r.code).toBe(1);+ expect(r.out).toContain("1 high");+ });++ test("removed lines and context are ignored — only additions are scanned", () => {+ const r = scan(+ `-${PEM_BEGIN}\n-${PLANTED_PEM_BODY}\n${PEM_END}\n+just an addition\n`,+ );+ expect(r.code).toBe(0);+ });++ test("MEDIUM findings are advisory only — never fail CI", () => {+ // A Stripe publishable-key shape sits at MEDIUM in the taxonomy+ // (context-variable; a human confirms interactively, CI cannot).+ const r = scan(`+const key = "pk_live_${"a".repeat(24)}";\n`);+ expect(r.code).toBe(0);+ expect(r.out).toMatch(/\d+ advisory/);+ });+});++describe("gate-secret-scan.mjs fail-closed legs", () => {+ test("oversize diff (report.oversize) fails the gate", () => {+ // The script pins --max-bytes 16000000; bin/gstack-redact refuses to scan+ // anything larger and reports oversize:true (fail-closed). The gate must+ // exit 1 rather than pass unscanned bytes. ~17MB of added lines guarantees+ // the joined additions exceed the cap.+ const line = `+${"a".repeat(8190)}\n`;+ const r = scan(line.repeat(2100));+ expect(r.code).toBe(1);+ // Proves the failure came from the parsed report (the engine surfaces+ // oversize as a fail-closed HIGH), not from a crashed subprocess.+ expect(r.out).toContain("1 high");+ }, 60_000);++ test("unexpected gstack-redact exit code fails the gate even when the report is clean", () => {+ // Stub bin/gstack-redact that emits a CLEAN JSON report but exits 1 —+ // not one of the contract codes (0 clean / 2 MEDIUM / 3 HIGH). The gate+ // must treat the unexpected exit as failure: a broken scanner reporting+ // "all clear" is exactly the fail-open shape this leg guards against.+ const dir = mkdtempSync(join(tmpdir(), "gate-secret-scan-stub-"));+ try {+ mkdirSync(join(dir, "bin"));+ writeFileSync(+ join(dir, "bin", "gstack-redact"),+ [+ "#!/usr/bin/env bun",+ 'let input = "";',+ 'process.stdin.setEncoding("utf8");',+ 'process.stdin.on("data", (c) => { input += c; });',+ 'process.stdin.on("end", () => {',+ ' console.log(JSON.stringify({ findings: [], counts: { HIGH: 0, MEDIUM: 0, LOW: 0, WARN: 0 }, repoVisibility: "public", oversize: false }));',+ " process.exit(1);",+ "});",+ "",+ ].join("\n"),+ );+ const r = scan("+const x = 1;\n", dir);+ expect(r.out).toContain("0 high"); // the clean report WAS parsed...+ expect(r.code).toBe(1); // ...and the gate still failed on the exit code+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ test("missing gstack-redact (spawn crash, empty stdout) exits nonzero — never fail-open", () => {+ // cwd with no bin/gstack-redact at all: bun exits module-not-found with+ // empty stdout. Whatever the exact failure shape, the gate must not+ // report success.+ const dir = mkdtempSync(join(tmpdir(), "gate-secret-scan-absent-"));+ try {+ const r = scan("+const x = 1;\n", dir);+ expect(r.code).not.toBe(0);+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });+});diff --git a/test/gbrain-init-voyage-code-3.test.ts b/test/gbrain-init-voyage-code-3.test.tsindex 652de69f6..a9ca731ba 100644--- a/test/gbrain-init-voyage-code-3.test.ts+++ b/test/gbrain-init-voyage-code-3.test.ts@@ -24,6 +24,7 @@ import {mkdirSync,writeFileSync,readFileSync,+ existsSync,rmSync,chmodSync,} from "fs";@@ -39,24 +40,6 @@ interface FakeEnv {cleanup: () => void;}-interface ShellCase {- name: "bash" | "zsh";- command: string;- available: boolean;-}--function shellAvailable(command: string): boolean {- const result = spawnSync(command, ["-c", "exit 0"], {- stdio: "ignore",- });- return result.status === 0;-}--const SHELLS: ShellCase[] = [- { name: "bash", command: "bash", available: shellAvailable("bash") },- { name: "zsh", command: "zsh", available: shellAvailable("zsh") },-];-function makeFakeEnv(): FakeEnv {const tmp = mkdtempSync(join(tmpdir(), "gbrain-voyage-init-"));const home = join(tmp, "home");@@ -69,13 +52,8 @@ function makeFakeEnv(): FakeEnv {// succeeds on init (writes a sentinel pglite config), and returns canned// output for --version. Nothing else is needed for the shape test.const fake = `#!/bin/sh-{- echo "__CALL__"- for arg in "$@"; do- printf 'arg=%s\\n' "$arg"- done- echo "__END__"-} >> "${argvLog}"+echo "$@" >> "${argvLog}"+echo "$#" >> "${argvLog}.argc"case "$1" in--version)echo "gbrain 0.37.1.0"@@ -104,11 +82,11 @@ exit 0}/**- * Verbatim reimplementation of the skill template's voyage-code-3 conditional.- * The template (setup-gbrain/SKILL.md.tmpl Path 3, Step 1.5 inside the- * rollback wrapper, Step 4.5 Path 4 Yes branch) instructs the model to execute- * this shell; we execute the same shell here and assert the argv passed to- * gbrain matches the contract under both bash and zsh.+ * Verbatim reimplementation of the skill template's voyage-code-3+ * conditional. The template (setup-gbrain/SKILL.md.tmpl Path 3, Step 1.5+ * inside the rollback wrapper, Step 4.5 Path 4 Yes branch) instructs the+ * model to execute this bash; we execute the same bash here and assert the+ * argv passed to gbrain matches the contract.** If the template changes the flag set or the env-var name, this test* should fail until the shell here is updated too — by design.@@ -116,15 +94,19 @@ exit 0function runInitWithVoyageGate(env: FakeEnv,voyageKey: string | undefined,- shell: ShellCase,-): string[][] {+ shell: "bash" | "zsh" = "bash",+): string[] {+ // The template's #1798 shape: flags ride the positional params, because an+ // unquoted $VAR does NOT word-split under zsh — the whole flag string+ // arrived as ONE argv word and gbrain silently fell back to its default+ // embedding model.const script = `set -u+set --if [ -n "\${VOYAGE_API_KEY:-}" ]; then- gbrain init --pglite --json --embedding-model voyage:voyage-code-3 --embedding-dimensions 1024-else- gbrain init --pglite --json+ set -- --embedding-model voyage:voyage-code-3 --embedding-dimensions 1024fi+gbrain init --pglite --json "$@"`;const baseEnv: Record<string, string> = {...process.env,@@ -136,86 +118,111 @@ fi} else {baseEnv.VOYAGE_API_KEY = voyageKey;}- const result = spawnSync(shell.command, ["-c", script], {+ const result = spawnSync(shell, ["-c", script], {encoding: "utf-8",env: baseEnv,});if (result.status !== 0) {- throw new Error(- `${shell.name} init script exited ${result.status}: ${result.stderr}`,- );+ throw new Error(`init script exited ${result.status}: ${result.stderr}`);}- return parseArgvLog(env.argvLog);+ return readFileSync(env.argvLog, "utf-8").trim().split("\n");}-function parseArgvLog(argvLog: string): string[][] {- const calls: string[][] = [];- let current: string[] | undefined;+function lastArgc(env: FakeEnv): number {+ const lines = readFileSync(`${env.argvLog}.argc`, "utf-8").trim().split("\n");+ return parseInt(lines[lines.length - 1], 10);+}- for (const line of readFileSync(argvLog, "utf-8").trim().split("\n")) {- if (line === "__CALL__") {- current = [];- continue;- }- if (line === "__END__") {- if (current) calls.push(current);- current = undefined;- continue;+const HAVE_ZSH = spawnSync("zsh", ["-c", "true"]).status === 0;++describe("voyage-code-3 default for gstack-driven PGLite init", () => {+ it("passes voyage-code-3 flags when VOYAGE_API_KEY is set", () => {+ const env = makeFakeEnv();+ try {+ const calls = runInitWithVoyageGate(env, "vk_test_set");+ expect(calls.length).toBe(1);+ const argv = calls[0];+ expect(argv).toContain("init --pglite --json");+ expect(argv).toContain("--embedding-model voyage:voyage-code-3");+ expect(argv).toContain("--embedding-dimensions 1024");+ } finally {+ env.cleanup();}- if (current && line.startsWith("arg=")) {- current.push(line.slice("arg=".length));+ });++ it("omits voyage flags when VOYAGE_API_KEY is unset", () => {+ const env = makeFakeEnv();+ try {+ const calls = runInitWithVoyageGate(env, undefined);+ expect(calls.length).toBe(1);+ const argv = calls[0];+ expect(argv).toContain("init --pglite --json");+ expect(argv).not.toContain("voyage");+ expect(argv).not.toContain("--embedding-model");+ expect(argv).not.toContain("--embedding-dimensions");+ } finally {+ env.cleanup();}- }+ });- return calls;-}+ it("zsh: flags arrive as SEPARATE argv words (#1798 — the shell that broke)", () => {+ if (!HAVE_ZSH) return; // zsh ships on macOS; skip quietly elsewhere+ const env = makeFakeEnv();+ try {+ const calls = runInitWithVoyageGate(env, "vk_test_set", "zsh");+ expect(calls.length).toBe(1);+ expect(calls[0]).toContain("--embedding-model voyage:voyage-code-3");+ // init --pglite --json + 4 flag words = 7 argv entries. The pre-#1798+ // unquoted-var shape produced 4 under zsh (the whole flag string as one+ // word), and gbrain silently fell back to its default embedding model.+ expect(lastArgc(env)).toBe(7);+ } finally {+ env.cleanup();+ }+ });-describe("voyage-code-3 default for gstack-driven PGLite init", () => {- for (const shell of SHELLS) {- const describeShell = shell.available ? describe : describe.skip;-- describeShell(`under ${shell.name}`, () => {- it("passes voyage-code-3 flags as four separate argv entries when VOYAGE_API_KEY is set", () => {- const env = makeFakeEnv();- try {- const calls = runInitWithVoyageGate(env, "vk_test_set", shell);- expect(calls).toEqual([- [- "init",- "--pglite",- "--json",- "--embedding-model",- "voyage:voyage-code-3",- "--embedding-dimensions",- "1024",- ],- ]);- } finally {- env.cleanup();- }+ it("demonstrates the #1798 collision: an unquoted flags var is ONE word under zsh", () => {+ if (!HAVE_ZSH) return;+ const env = makeFakeEnv();+ try {+ const brokenShape = `+set -u+GBRAIN_EMBED_FLAGS="--embedding-model voyage:voyage-code-3 --embedding-dimensions 1024"+gbrain init --pglite --json $GBRAIN_EMBED_FLAGS+`;+ const result = spawnSync("zsh", ["-c", brokenShape], {+ encoding: "utf-8",+ env: { ...process.env, HOME: env.home, PATH: `${env.bindir}:/usr/bin:/bin` },});+ expect(result.status).toBe(0);+ expect(lastArgc(env)).toBe(4); // init, --pglite, --json, "<entire flag string>"+ } finally {+ env.cleanup();+ }+ });- it("omits voyage flags when VOYAGE_API_KEY is unset", () => {- const env = makeFakeEnv();- try {- const calls = runInitWithVoyageGate(env, undefined, shell);- expect(calls).toEqual([["init", "--pglite", "--json"]]);- } finally {- env.cleanup();- }- });+ it("template uses the positional-params shape, not an unquoted flags var", () => {+ const tmpl = readFileSync(+ join(import.meta.dir, "..", "setup-gbrain", "SKILL.md.tmpl"),+ "utf-8",+ );+ expect(tmpl).not.toContain("$GBRAIN_EMBED_FLAGS");+ const sites = tmpl.match(/gbrain init --pglite --json "\$@"/g) || [];+ expect(sites.length).toBe(3);+ const setSites = tmpl.match(/set -- --embedding-model voyage:voyage-code-3 --embedding-dimensions 1024/g) || [];+ expect(setSites.length).toBe(3);+ });- it("treats empty-string VOYAGE_API_KEY the same as unset (no false positive)", () => {- const env = makeFakeEnv();- try {- const calls = runInitWithVoyageGate(env, "", shell);- expect(calls).toEqual([["init", "--pglite", "--json"]]);- } finally {- env.cleanup();- }- });- });- }+ it("treats empty-string VOYAGE_API_KEY the same as unset (no false positive)", () => {+ const env = makeFakeEnv();+ try {+ const calls = runInitWithVoyageGate(env, "");+ expect(calls.length).toBe(1);+ expect(calls[0]).not.toContain("voyage");+ } finally {+ env.cleanup();+ }+ });});describe("template alignment: the .tmpl actually contains the voyage gate", () => {@@ -225,13 +232,11 @@ describe("template alignment: the .tmpl actually contains the voyage gate", () =const TEMPLATE_PATH = join(import.meta.dir, "..", "setup-gbrain", "SKILL.md.tmpl");const tmpl = readFileSync(TEMPLATE_PATH, "utf-8");- it("setup-gbrain template gates the embedding-model flag on VOYAGE_API_KEY without word-splitting", () => {+ it("setup-gbrain template gates the embedding-model flag on VOYAGE_API_KEY", () => {// Should appear at least once (currently 3 init sites use the same gate).expect(tmpl).toContain('if [ -n "${VOYAGE_API_KEY:-}" ]; then');- expect(tmpl).toContain(- "gbrain init --pglite --json --embedding-model voyage:voyage-code-3 --embedding-dimensions 1024",- );- expect(tmpl).not.toContain("GBRAIN_EMBED_FLAGS");+ expect(tmpl).toContain("--embedding-model voyage:voyage-code-3");+ expect(tmpl).toContain("--embedding-dimensions 1024");});it("setup-gbrain template uses the conditional gate at all 3 PGLite init sites", () => {@@ -239,10 +244,5 @@ describe("template alignment: the .tmpl actually contains the voyage gate", () =// init site, update this expectation deliberately.const matches = tmpl.match(/if \[ -n "\$\{VOYAGE_API_KEY:-\}" \]; then/g);expect(matches?.length).toBe(3);-- const voyageInitMatches = tmpl.match(- /gbrain init --pglite --json --embedding-model voyage:voyage-code-3 --embedding-dimensions 1024/g,- );- expect(voyageInitMatches?.length).toBe(3);});});diff --git a/test/gbrain-repo-policy.test.ts b/test/gbrain-repo-policy.test.tsindex d922c8313..c0e87693f 100644--- a/test/gbrain-repo-policy.test.ts+++ b/test/gbrain-repo-policy.test.ts@@ -269,3 +269,105 @@ describe('get without arg (auto-detect from current dir)', () => {}});});++// ── #2140 sync-path chokepoint ──────────────────────────────────────────────+// The tier above is a STORE. This block pins the ENFORCEMENT: a direct+// gstack-gbrain-sync invocation (skill prose bypassed — cron, curiosity,+// automation) must honor deny/read-only at the code-import stage, and the+// egress receipt's "per-repo policy chokepoint (repoPolicyTier)" consent+// string must describe code that exists. Wave-1 shipped the receipt string+// without the function; these tests make that impossible to repeat.++describe('gstack-gbrain-sync code stage honors the repo policy (#2140 sync path)', () => {+ const SYNC = path.join(ROOT, 'bin', 'gstack-gbrain-sync.ts');+ const REPO_URL = 'https://github.com/acme/widget.git';++ let repoDir: string;++ function makeRepo(): void {+ repoDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gbrain-policy-repo-'));+ const git = (...args: string[]) =>+ spawnSync('git', args, { cwd: repoDir, encoding: 'utf-8' });+ git('init', '-q', '.');+ git('remote', 'add', 'origin', REPO_URL);+ fs.writeFileSync(path.join(repoDir, 'README.md'), 'fixture\n');+ git('add', '-A');+ git('-c', 'user.email=t@t', '-c', 'user.name=t', 'commit', '-qm', 'fixture');+ }++ function runSync(): { status: number; text: string; stages: any[] } {+ const res = spawnSync('bun', [SYNC, '--code-only', '--incremental'], {+ cwd: repoDir,+ encoding: 'utf-8',+ timeout: 60_000,+ // HOME also redirected so engine detection can't find a real ~/.gbrain.+ env: { ...process.env, GSTACK_HOME: tmpHome, HOME: tmpHome },+ });+ let stages: any[] = [];+ try {+ stages = JSON.parse(+ fs.readFileSync(path.join(tmpHome, '.gbrain-sync-state.json'), 'utf-8'),+ ).last_stages || [];+ } catch {+ // state file may be absent on early refusal paths — text asserts cover it+ }+ return {+ status: res.status ?? -1,+ text: `${res.stdout || ''}\n${res.stderr || ''}`,+ stages,+ };+ }++ afterEach(() => {+ if (repoDir) fs.rmSync(repoDir, { recursive: true, force: true });+ });++ test('deny → code stage refuses loudly, exit 1, status refused-policy-deny', () => {+ makeRepo();+ expect(run(['set', REPO_URL, 'deny']).status).toBe(0);+ const r = runSync();+ expect(r.status).toBe(1);+ expect(r.text).toContain('refused');+ expect(r.text).toContain('deny');+ const code = r.stages.find((s: any) => s.name === 'code');+ expect(code?.detail?.status).toBe('refused-policy-deny');+ });++ test('read-only → clean skip (exit 0), status skipped-policy-read-only', () => {+ makeRepo();+ expect(run(['set', REPO_URL, 'read-only']).status).toBe(0);+ const r = runSync();+ expect(r.status).toBe(0);+ expect(r.text).toContain('read-only');+ const code = r.stages.find((s: any) => s.name === 'code');+ expect(code?.detail?.status).toBe('skipped-policy-read-only');+ });++ test('store exists but unreadable → fail-closed refusal, never bypassed', () => {+ if (process.platform === 'win32' || process.getuid?.() === 0) return; // chmod semantics differ+ makeRepo();+ expect(run(['set', REPO_URL, 'deny']).status).toBe(0);+ fs.chmodSync(policyFile(), 0o000);+ try {+ const r = runSync();+ expect(r.status).toBe(1);+ expect(r.text).toContain('refus');+ const code = r.stages.find((s: any) => s.name === 'code');+ expect(code?.detail?.status).toBe('refused-policy-unreadable');+ } finally {+ fs.chmodSync(policyFile(), 0o600);+ }+ });++ test('no policy store → fail-open, stage proceeds past the gate (no policy status)', () => {+ makeRepo();+ const r = runSync();+ const code = r.stages.find((s: any) => s.name === 'code');+ // With no engine in the redirected HOME the stage skips for ENGINE+ // reasons — what matters is that no policy refusal fired and the exit+ // is clean, preserving pre-policy behavior for every non-policy user.+ expect(r.status).toBe(0);+ expect(String(code?.detail?.status || '')).not.toContain('policy');+ expect(r.text).not.toContain('refused');+ });+});diff --git a/test/gen-skill-docs.test.ts b/test/gen-skill-docs.test.tsindex 81543bbc2..e9d440e02 100644--- a/test/gen-skill-docs.test.ts+++ b/test/gen-skill-docs.test.ts@@ -1079,8 +1079,11 @@ describe('PLAN_VERIFICATION_EXEC placeholder', () => {expect(shipSkill).toContain('qa-only');});- test('contains localhost reachability check', () => {- expect(shipSkill).toContain('localhost:3000');+ test('contains dev-server discovery (CLAUDE.md first, then a port probe)', () => {+ // Fork port wave 2: the hardcoded 4-port list became read-CLAUDE.md-or-+ // probe; the probe loops common ports instead of naming each once.+ expect(shipSkill).toContain('CLAUDE.md first');+ expect(shipSkill).toContain('http://localhost:$_p');expect(shipSkill).toContain('NO_SERVER');});diff --git a/test/gstack-brain-context-load.test.ts b/test/gstack-brain-context-load.test.tsindex 61985f0fc..5b9337fd8 100644--- a/test/gstack-brain-context-load.test.ts+++ b/test/gstack-brain-context-load.test.ts@@ -7,7 +7,7 @@*/import { describe, it, expect } from "bun:test";-import { chmodSync, mkdtempSync, writeFileSync, mkdirSync, rmSync } from "fs";+import { chmodSync, mkdtempSync, readFileSync, writeFileSync, mkdirSync, rmSync } from "fs";import { tmpdir } from "os";import { delimiter, join } from "path";import { spawnSync } from "child_process";@@ -52,10 +52,47 @@ fichmodSync(fakeBin, 0o755);}+/**+ * Like writeFakeGbrain, but every invocation appends its argv to `logFile`.+ * Still answers `--version` successfully ON PURPOSE: a revert from the+ * memoized PATH stat scan back to the old `gbrain --version` spawn probe+ * would pass every non-logging test — only the argv log catches it.+ */+function writeLoggingGbrain(binDir: string, logFile: string): void {+ if (process.platform === "win32") {+ writeFileSync(+ join(binDir, "gbrain.cmd"),+ `@echo off\r\necho %* >> "${logFile}"\r\nif "%1"=="--version" (\r\n echo gbrain 0.test\r\n) else (\r\n echo fake gbrain %*\r\n)\r\n`,+ "utf-8",+ );+ return;+ }++ const fakeBin = join(binDir, "gbrain");+ writeFileSync(+ fakeBin,+ `#!/bin/sh+printf '%s\\n' "$*" >> "${logFile}"+if [ "$1" = "--version" ]; then+ echo "gbrain 0.test"+else+ echo "fake gbrain $*"+fi+`,+ "utf-8",+ );+ chmodSync(fakeBin, 0o755);+}+function prependPath(binDir: string): Record<string, string> {const pathKey = Object.keys(process.env).find((key) => key.toLowerCase() === "path") || "PATH";const currentPath = process.env[pathKey] || "";- return { [pathKey]: `${binDir}${delimiter}${currentPath}` };+ return {+ [pathKey]: `${binDir}${delimiter}${currentPath}`,+ // Cold process spawns on a loaded machine can exceed the 500ms default+ // budget; the fake gbrain is instant once spawned, so give it headroom.+ GSTACK_BRAIN_TIMEOUT_MS: "10000",+ };}describe("gstack-brain-context-load CLI", () => {@@ -252,6 +289,111 @@ describe("gstack-brain-context-load — graceful gbrain absence", () => {}});+ it("manifest filter: blocks reach gbrain as --filter args with template vars resolved (#1687)", () => {+ const dir = mkdtempSync(join(tmpdir(), "gstack-bcl-"));+ const binDir = join(dir, "bin");+ mkdirSync(binDir);+ writeFakeGbrain(binDir);+ const skillFile = join(dir, "SKILL.md");+ writeFileSync(+ skillFile,+ `---+name: x+gbrain:+ schema: 1+ context_queries:+ - id: prior-sessions+ kind: list+ filter:+ type: ceo-plan+ tags_contains: "repo:{repo_slug}"+ sort: updated_at_desc+ limit: 5+ render_as: "## Prior sessions"+---+`,+ "utf-8"+ );++ try {+ const r = runScript(["--skill-file", skillFile, "--repo", "my-test-repo"], prependPath(binDir));+ expect(r.exitCode).toBe(0);+ expect(r.stdout).toContain("fake gbrain list_pages");+ expect(r.stdout).toContain("--filter type=ceo-plan");+ expect(r.stdout).toContain("--filter tags_contains=repo:my-test-repo");+ expect(r.stdout).toContain("--sort updated_at_desc");+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ it("gbrain detection never spawns gbrain — stat-based PATH scan, not a `--version` probe (revert trap)", () => {+ // The fix replaced a per-query `gbrain --version` spawn probe with a+ // memoized PATH stat scan. The plain writeFakeGbrain shim still ANSWERS+ // --version, so a revert to the spawn probe passes every other test in+ // this file. This fake logs its argv: detection must invoke gbrain zero+ // times, so the only invocations are the 3 default-manifest list_pages+ // queries — a revert adds `--version` lines (and re-probing adds one per+ // query) and fails exactly here.+ const dir = mkdtempSync(join(tmpdir(), "gstack-bcl-"));+ const binDir = join(dir, "bin");+ mkdirSync(binDir);+ const logFile = join(dir, "gbrain-argv.log");+ writeLoggingGbrain(binDir, logFile);++ try {+ const r = runScript(["--repo", "test-repo", "--explain", "--quiet"], prependPath(binDir));+ expect(r.exitCode).toBe(0);+ expect(r.stderr).toContain("queries=3");+ const invocations = readFileSync(logFile, "utf-8").split("\n").filter(Boolean);+ expect(invocations.some((argv) => argv.includes("--version"))).toBe(false);+ // Exactly the 3 real queries — no extra availability spawns of any shape.+ expect(invocations).toHaveLength(3);+ for (const argv of invocations) expect(argv.startsWith("list_pages")).toBe(true);+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ it("availability survives a 1ms query budget — detection is not subject to GSTACK_BRAIN_TIMEOUT_MS", () => {+ // The spawn probe ran under the same MCP_TIMEOUT_MS budget as the queries,+ // so a cold spawn slower than the budget misreported gbrain as MISSING.+ // With the stat scan, a 1ms budget kills the queries themselves (SKIP)+ // but detection still sees the CLI — "gbrain CLI missing" must not appear.+ const dir = mkdtempSync(join(tmpdir(), "gstack-bcl-"));+ const binDir = join(dir, "bin");+ mkdirSync(binDir);+ // A SLOW fake, not the shared instant one: on a fast CI runner the+ // instant fake answered inside even a 1ms budget (observed dur=0ms on+ // ubicloud) and no SKIP ever printed. Sleeping makes the timeout+ // deterministic on every machine; --version stays instant so detection+ // has nothing to wait on.+ const fakeBin = join(binDir, "gbrain");+ writeFileSync(+ fakeBin,+ `#!/bin/sh+if [ "$1" = "--version" ]; then+ echo "gbrain 0.test"+else+ sleep 0.3+ echo "fake gbrain $*"+fi+`,+ "utf-8",+ );+ chmodSync(fakeBin, 0o755);++ try {+ const env = { ...prependPath(binDir), GSTACK_BRAIN_TIMEOUT_MS: "1" };+ const r = runScript(["--repo", "test-repo", "--explain", "--quiet"], env);+ expect(r.exitCode).toBe(0);+ expect(r.stderr).toContain("SKIP");+ expect(r.stderr).not.toContain("gbrain CLI missing");+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });+it("vector + list queries still complete (with SKIP) when gbrain CLI is missing", () => {// We can't easily un-install gbrain; rely on the helper's own missing-binary// detection. The default manifest uses kind: list which calls gbrain. Ifdiff --git a/test/gstack-decision-bins.test.ts b/test/gstack-decision-bins.test.tsindex 3c0d42822..a99209039 100644--- a/test/gstack-decision-bins.test.ts+++ b/test/gstack-decision-bins.test.ts@@ -63,6 +63,39 @@ describe("gstack-decision-log", () => {const r = log("not json", true);expect(r.code).toBe(1);});+ test("--supersede with a replacement body records the replacement, linked to the old id", () => {+ const id = log('{"decision":"old-call","scope":"repo","source":"user"}').out;+ const out = logFlag(+ `--supersede ${id} '{"decision":"new-call","rationale":"better","scope":"repo","source":"user"}'`,+ );+ expect(out).toContain(id);+ expect(search()).toContain("new-call"); // the replacement is NOT silently dropped+ expect(search()).not.toContain("old-call");+ const arr = JSON.parse(search("--json"));+ expect(arr.find((d: any) => d.decision === "new-call")?.supersedes).toBe(id);+ });+ test("--supersede with an INVALID replacement persists nothing (old stays active)", () => {+ const id = log('{"decision":"keep-me","scope":"repo","source":"user"}').out;+ let code = 0;+ try {+ logFlag(`--supersede ${id} '{"decision":""}'`);+ } catch (e: any) {+ code = e.status || 1;+ }+ expect(code).toBe(1);+ expect(search()).toContain("keep-me"); // not retired by a failed replacement+ });+ test("--redact refuses a replacement body instead of dropping it", () => {+ const id = log('{"decision":"redact-target","scope":"repo","source":"user"}').out;+ let code = 0;+ try {+ logFlag(`--redact ${id} '{"decision":"would-be-lost","scope":"repo","source":"user"}'`);+ } catch (e: any) {+ code = e.status || 1;+ }+ expect(code).toBe(1);+ expect(search()).toContain("redact-target"); // nothing happened at all+ });});describe("gstack-decision-search", () => {diff --git a/test/gstack-memory-helpers.test.ts b/test/gstack-memory-helpers.test.tsindex 244a64976..2bc89c83f 100644--- a/test/gstack-memory-helpers.test.ts+++ b/test/gstack-memory-helpers.test.ts@@ -11,7 +11,7 @@* Free-tier (~50ms total). Runs in `bun test`.*/-import { describe, it, expect, beforeEach, afterAll } from "bun:test";+import { describe, it, expect, beforeEach, afterEach } from "bun:test";import { mkdtempSync, writeFileSync, readFileSync, existsSync, rmSync, mkdirSync, chmodSync } from "fs";import { tmpdir } from "os";import { join } from "path";@@ -338,7 +338,11 @@ describe("withErrorContext", () => {process.env.GSTACK_HOME = testHome;});- afterAll(() => {+ // afterEach, not afterAll: the save happens in beforeEach, so an afterAll+ // restore would put back the PREVIOUS test's temp dir (the last beforeEach+ // overwrote savedHome) and leak a gstack-test-home-* dir into every test+ // file that runs after this one in the same bun process.+ afterEach(() => {if (savedHome === undefined) delete process.env.GSTACK_HOME;else process.env.GSTACK_HOME = savedHome;});@@ -414,7 +418,13 @@ describe("detectEngineTier", () => {process.env.HOME = testHome;});- afterAll(() => {+ // afterEach, not afterAll: the save happens in beforeEach, so an afterAll+ // restore would put back the PREVIOUS test's gstack-test-engine-* temp dir+ // (the last beforeEach overwrote the saved values). That leaked+ // HOME/GSTACK_HOME/PATH into every test file that ran after this one in the+ // same bun process — child processes then looked for Playwright's Chromium+ // cache and ~/.gstack config under a throwaway temp HOME.+ afterEach(() => {if (savedHome === undefined) delete process.env.GSTACK_HOME;else process.env.GSTACK_HOME = savedHome;if (savedGbrainHome === undefined) delete process.env.GBRAIN_HOME;diff --git a/test/gstack-next-version.test.ts b/test/gstack-next-version.test.tsindex f4ba06926..f72ec0149 100644--- a/test/gstack-next-version.test.ts+++ b/test/gstack-next-version.test.ts@@ -4,6 +4,7 @@// when the relevant CLI isn't available).import { test, expect, describe } from "bun:test";+import { execFileSync } from "node:child_process";import { mkdirSync, mkdtempSync, writeFileSync, rmSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";@@ -221,6 +222,104 @@ describe("resolveVersionPath (monorepo VERSION-path support)", () => {});});+// Fixture-repo coverage for the default-base detection chain in parseArgs:+// origin/HEAD symbolic-ref → origin/main probe → origin/master probe →+// literal "main". No --base and no --current-version are passed, so the+// detected base is observable through base_version: each fixture branch+// carries a distinct VERSION and readBaseVersion does+// `git show origin/<detected-base>:VERSION`.+describe("default-base detection (no --base)", () => {+ const SCRIPT = join(import.meta.dir, "..", "bin", "gstack-next-version");+ // Point git at a nonexistent global/system config so operator settings+ // (init.defaultBranch, commit.gpgsign, hooks, ...) can't leak into fixtures.+ const noCfg = join(mkdtempSync(join(tmpdir(), "nextver-gitcfg-")), "empty");+ const GIT_ENV = {+ ...process.env,+ GIT_CONFIG_GLOBAL: noCfg,+ GIT_CONFIG_SYSTEM: noCfg,+ GIT_AUTHOR_NAME: "fixture",+ GIT_AUTHOR_EMAIL: "[email protected]",+ GIT_COMMITTER_NAME: "fixture",+ GIT_COMMITTER_EMAIL: "[email protected]",+ };++ function git(cwd: string, ...args: string[]): void {+ execFileSync("git", args, { cwd, env: GIT_ENV, stdio: ["ignore", "pipe", "pipe"] });+ }++ // Origin repo whose branches each hold a distinct VERSION, plus a clone+ // (the clone is the repo the CLI runs in).+ function makeClone(branches: Array<[name: string, version: string]>): { root: string; clone: string } {+ const root = mkdtempSync(join(tmpdir(), "nextver-base-"));+ const origin = join(root, "origin");+ mkdirSync(origin);+ git(origin, "init", "-q", "-b", branches[0][0]);+ for (let i = 0; i < branches.length; i++) {+ const [name, version] = branches[i];+ if (i > 0) git(origin, "checkout", "-q", "-b", name);+ writeFileSync(join(origin, "VERSION"), `${version}\n`);+ git(origin, "add", "VERSION");+ git(origin, "commit", "-q", "--no-gpg-sign", "-m", `VERSION ${version}`);+ }+ git(root, "clone", "-q", "origin", "clone");+ return { root, clone: join(root, "clone") };+ }++ function runWithoutBase(cwd: string): { exitCode: number; parsed: any } {+ const proc = Bun.spawnSync(+ ["bun", "run", SCRIPT, "--bump", "patch", "--workspace-root", "null"],+ { cwd },+ );+ const out = new TextDecoder().decode(proc.stdout);+ return { exitCode: proc.exitCode, parsed: JSON.parse(out) };+ }++ test("origin/HEAD symbolic-ref wins — resolves trunk even though origin/main exists", () => {+ const { root, clone } = makeClone([["main", "1.1.1.1"], ["trunk", "2.2.2.2"]]);+ try {+ git(clone, "symbolic-ref", "refs/remotes/origin/HEAD", "refs/remotes/origin/trunk");+ const { exitCode, parsed } = runWithoutBase(clone);+ expect(exitCode).toBe(0);+ // trunk's VERSION, not main's — the rev-parse probes never ran.+ expect(parsed.base_version).toBe("2.2.2.2");+ expect(parsed.version).toBe("2.2.3.0");+ } finally {+ rmSync(root, { recursive: true, force: true });+ }+ }, 30_000);++ test("no origin/HEAD, no origin/main: the origin/master probe resolves master", () => {+ const { root, clone } = makeClone([["master", "3.3.3.3"]]);+ try {+ // Plain clones that never ran `git remote set-head` have no origin/HEAD.+ git(clone, "remote", "set-head", "origin", "--delete");+ const { exitCode, parsed } = runWithoutBase(clone);+ expect(exitCode).toBe(0);+ // Read at origin/master. The "main" literal fallback would have warned+ // and assumed 0.0.0.0 instead.+ expect(parsed.base_version).toBe("3.3.3.3");+ expect(parsed.version).toBe("3.3.4.0");+ } finally {+ rmSync(root, { recursive: true, force: true });+ }+ }, 30_000);++ test("neither origin/HEAD nor main/master: falls back to the 'main' literal", () => {+ const { root, clone } = makeClone([["develop", "4.4.4.4"]]);+ try {+ git(clone, "remote", "set-head", "origin", "--delete");+ const { exitCode, parsed } = runWithoutBase(clone);+ expect(exitCode).toBe(0);+ // base = literal "main"; origin/main doesn't exist, so readBaseVersion+ // warns and assumes 0.0.0.0 — which pins WHICH base the fallback chose.+ expect(parsed.base_version).toBe("0.0.0.0");+ expect(parsed.warnings.join("\n")).toContain("origin/main");+ } finally {+ rmSync(root, { recursive: true, force: true });+ }+ }, 30_000);+});+// Integration smoke — only runs if gh is available and authenticated. Confirms// the CLI executes end-to-end against real APIs without crashing.describe("integration (smoke)", () => {diff --git a/test/helpers/auq-sdk-capture.ts b/test/helpers/auq-sdk-capture.tsindex a95a4b05b..9bb08acf7 100644--- a/test/helpers/auq-sdk-capture.ts+++ b/test/helpers/auq-sdk-capture.ts@@ -11,6 +11,7 @@* zero rendering loss. The TTY rendering layer is identical for fat and slim* skills, so it is not where token-reduction degradation can hide.*/+import { resolveEvalModel } from '../../lib/eval-model';import * as fs from 'node:fs';import * as os from 'node:os';import * as path from 'node:path';@@ -191,7 +192,7 @@ This is a capture test, not an interactive session. Skip any system-audit / envitimeout: 240_000,testName: opts.testName,runId: opts.runId,- model: opts.model ?? 'claude-opus-4-7',+ model: resolveEvalModel('capture', opts.model),});try {@@ -253,7 +254,7 @@ Rules for this run:timeout: opts.timeout ?? 300_000,testName: opts.testName,runId: opts.runId,- model: opts.model ?? 'claude-opus-4-7',+ model: resolveEvalModel('capture', opts.model),});const readSections = new Set<string>();@@ -334,7 +335,7 @@ Write the verbatim text of that AskUserQuestion (the full decision brief: title,timeout: 240_000,testName: opts.testName,runId: opts.runId,- model: opts.model ?? 'claude-opus-4-7',+ model: resolveEvalModel('capture', opts.model),});try {diff --git a/test/helpers/carve-guards.ts b/test/helpers/carve-guards.tsindex 14a509dc7..40664b651 100644--- a/test/helpers/carve-guards.ts+++ b/test/helpers/carve-guards.ts@@ -99,6 +99,7 @@ export const CARVE_GUARDS: Record<string, CarveGuard> = {ship: {skill: 'ship',expectedSections: [+ 'apple-release.md','tests.md','test-coverage.md','plan-completion.md',@@ -129,7 +130,16 @@ export const CARVE_GUARDS: Record<string, CarveGuard> = {minUnionBytes: 120_000,mustContain: ['VERSION', 'CHANGELOG', 'review', 'merge', 'PR'],// v1.58.5.0: pre-push-guard install (#2077) stacks on the shared first-run-guidance preamble.- maxSizeRatio: 1.08,+ // Fork port wave 2: multi-ecosystem test-detection evidence (Django/JVM+ // markers, test-file census — e3259078 port) + the #1079 gh pr edit REST+ // fallback grew the union to 1.090x; the third-party web-actions+ // contract (consent-gated browser drive for API-key registration etc.)+ // adds ~2.3KB inline judgment, measured 1.103x. The Apple release+ // adapter (14.8KB carved section, 21 live releases of judgment — the+ // wave's headline capability) grows the union to 1.195x. Deliberate:+ // the section is on-demand (loads only for Apple store targets), so+ // per-invocation cost for non-iOS ships is one manifest line.+ maxSizeRatio: 1.22,},'plan-ceo-review': {skill: 'plan-ceo-review',@@ -144,9 +154,10 @@ export const CARVE_GUARDS: Record<string, CarveGuard> = {},behavioral: 'external',externalTest: 'test/skill-e2e-plan-ceo-review-section-loading.test.ts',- // v1.64.1.0: shared-preamble prose from the two parallel v1.64 waves lands- // the skeleton at 90,280 B; +1 KB headroom.- maxSkeletonBytes: 91_000,+ // v1.65 merge: provisional larger-of-both-waves budget; re-measured below.+ // Fork port wave 2 (#703): the repo-doc-preference block in the design+ // check grew every plan-review skeleton ~0.7KB. Measured values noted.+ maxSkeletonBytes: 92_500, // v1.64+v1.65 merge: both waves' preamble growth; measured 92,004minUnionBytes: 80_000,mustContain: ['SCOPE EXPANSION', 'SELECTIVE EXPANSION', 'HOLD SCOPE', 'SCOPE REDUCTION'],// Default-on Codex outside-voice (codexPreflight block + CODEX_MODE branch@@ -167,9 +178,10 @@ export const CARVE_GUARDS: Record<string, CarveGuard> = {behavioral: 'plan',// v1.2.0 activation lift (shared first-run-guidance preamble) + #2077 ask-first scope gate.// +~1 KB: plan-mode auto-select-B scope-gate exceptions (2026-08).- // v1.64.1.0: shared-preamble prose from the two parallel v1.64 waves lands- // the skeleton at 68,163 B; +~1 KB headroom.- maxSkeletonBytes: 69_000,+ // v1.65 merge: provisional larger-of-both-waves budget; re-measured below.+ // Fork port wave 2 (#703): the repo-doc-preference block in the design+ // check grew every plan-review skeleton ~0.7KB. Measured values noted.+ maxSkeletonBytes: 70_000, // measured 68,780minUnionBytes: 70_000,mustContain: ['Architecture', 'Code Quality', 'Test', 'Performance'],// Cross-cutting preamble growth (v1.57.2.0 AUQ-failure prose fallback + the@@ -180,7 +192,7 @@ export const CARVE_GUARDS: Record<string, CarveGuard> = {// 1.08 → 1.10: the scope-gate exceptions block (+ its adversarial-review// hardening: host-anchored mode signal, precedence, passing-mention// guards) and the plan-mode preamble reword land the union at 1.092.- maxSizeRatio: 1.10,+ maxSizeRatio: 1.12, // measured 1.103},'plan-design-review': {skill: 'plan-design-review',@@ -198,13 +210,14 @@ export const CARVE_GUARDS: Record<string, CarveGuard> = {// always-loaded AskUserQuestion Format section.// v1.2.0 activation lift (shared first-run-guidance preamble) + #2077 ask-first scope gate.// +~1.3 KB: plan-mode auto-select-B scope-gate exceptions (2026-08).- // +~340 B: telemetry --error-message/--failed-step flags + prose in the- // shared completion-status preamble (PR #769, 2026-08); this skill was the- // closest to its ceiling (landed 89040 / ratio 1.072).- maxSkeletonBytes: 89_400,+ // Fork port wave 2 (D1): evidence directive adds ~0.45KB to every+ // tier-2+ skeleton (measured 89,184). Main's v1.64.0.0 adds ~340 B more+ // (telemetry --error-message/--failed-step preamble prose, PR #769).+ // Budget covers the sum of both waves.+ maxSkeletonBytes: 91_000,minUnionBytes: 70_000,mustContain: ['design', 'visual'],- maxSizeRatio: 1.08,+ maxSizeRatio: 1.12, // D1 1.104 + main's ~0.008},'plan-devex-review': {skill: 'plan-devex-review',@@ -221,7 +234,9 @@ export const CARVE_GUARDS: Record<string, CarveGuard> = {// +Conductor AUQ-default-prose rule + one-way/destructive prose safety +// continuation protocol in the always-loaded AskUserQuestion Format section.// v1.2.0 activation lift: first-run-guidance section in the shared preamble.- maxSkeletonBytes: 80_000,+ // Fork port wave 2 (#703): the repo-doc-preference block in the design+ // check grew every plan-review skeleton ~0.7KB. Measured values noted.+ maxSkeletonBytes: 82_000, // measured 80,493minUnionBytes: 70_000,mustContain: ['developer experience', 'Getting Started'],// Default-on Codex outside-voice (codexPreflight block + CODEX_MODE branch@@ -244,12 +259,15 @@ export const CARVE_GUARDS: Record<string, CarveGuard> = {behavioral: 'prompt',// v1.2.0 activation lift: first-run-guidance section in the shared preamble,// plus the P1 office-hours closing handoff (AUQ that launches the next skill).- // v1.64.1.0: shared-preamble prose from the two parallel v1.64 waves lands- // the skeleton at 98,193 B; +~1 KB headroom.- maxSkeletonBytes: 99_000,+ // v1.65 merge: provisional larger-of-both-waves budget; re-measured below.+ // Fork port wave 2: the third-party web-actions contract sits inline+ // (judgment must be visible before the workflow directs the user to a+ // vendor site), plus the #703 dual-write + repo-doc-preference block and+ // the #538 opt-out + D1 evidence directive — ratio 1.104 measured.+ maxSkeletonBytes: 101_000,minUnionBytes: 70_000,mustContain: ['design doc', 'problem statement'],- maxSizeRatio: 1.07,+ maxSizeRatio: 1.12,},'document-release': {skill: 'document-release',@@ -267,7 +285,7 @@ export const CARVE_GUARDS: Record<string, CarveGuard> = {// +Conductor AUQ-default-prose rule + one-way/continuation safety in the// always-loaded AskUserQuestion Format section.// v1.2.0 activation lift: first-run-guidance section in the shared preamble.- maxSkeletonBytes: 56_000,+ maxSkeletonBytes: 56_500, // v1.64+v1.65 merge; measured 56,044minUnionBytes: 55_000,mustContain: ['CHANGELOG', 'Diataxis', 'coverage'],// Two intentional additions stack on this small skill: the AUQ-failure prose@@ -295,6 +313,7 @@ export const CARVE_GUARDS: Record<string, CarveGuard> = {// +Conductor AUQ-default-prose rule + one-way/continuation safety in the// always-loaded AskUserQuestion Format section.// v1.2.0 activation lift: first-run-guidance section in the shared preamble.+ // v1.65 merge: provisional larger-of-both-waves budget; re-measured below.// v1.64.1.0: shared-preamble prose from the two parallel v1.64 waves lands// the skeleton at 69,022 B; +~1 KB headroom.maxSkeletonBytes: 70_000,@@ -303,7 +322,8 @@ export const CARVE_GUARDS: Record<string, CarveGuard> = {// Cross-cutting preamble growth (v1.57.2.0 AUQ-failure prose fallback ~2KB +// the cross-session decision-memory nudge) lands this carved skeleton just over// the strict 1.05; headroom for the shared preamble additions.- maxSizeRatio: 1.07,+ // v1.64+v1.65 merge sums both waves' preamble growth; measured 1.073.+ maxSizeRatio: 1.08,},cso: {skill: 'cso',@@ -336,13 +356,14 @@ export const CARVE_GUARDS: Record<string, CarveGuard> = {// +Conductor AUQ-default-prose rule + one-way/continuation safety in the// always-loaded AskUserQuestion Format section.// v1.2.0 activation lift: first-run-guidance section in the shared preamble.- maxSkeletonBytes: 75_000,+ maxSkeletonBytes: 75_800, // v1.64+v1.65 merge; measured 75,364minUnionBytes: 72_000,mustContain: ['OWASP', 'STRIDE', 'daily', 'comprehensive', 'verif'],// cso keeps its mode-dispatch + FP-filtering phases always-loaded, so the// cross-cutting preamble growth (v1.57.2.0 AUQ-failure prose fallback ~2KB + the// decision-memory nudge) lands it just over 1.05; headroom for the shared additions.- maxSizeRatio: 1.07,+ // v1.64+v1.65 merge sums both waves' preamble growth; measured 1.073.+ maxSizeRatio: 1.08,},};diff --git a/test/helpers/claude-pty-runner.ts b/test/helpers/claude-pty-runner.tsindex ea8a46ea1..ef625a194 100644--- a/test/helpers/claude-pty-runner.ts+++ b/test/helpers/claude-pty-runner.ts@@ -21,6 +21,7 @@* tests don't need it).*/+import { resolveEvalModel } from '../../lib/eval-model';import * as fs from 'fs';import * as os from 'os';import * as path from 'path';@@ -459,7 +460,7 @@ ${tail}// below resolveClaudeBinary(), breaking under hermetic PATHs.const result = nodeSpawnSync(resolveClaudeBinary() ?? 'claude',- ['-p', '--model', 'claude-haiku-4-5', '--max-turns', '1'],+ ['-p', '--model', resolveEvalModel('warmup'), '--max-turns', '1'],{input: prompt,stdio: ['pipe', 'pipe', 'pipe'],@@ -1256,7 +1257,15 @@ export const ceoStep0Boundary: Step0BoundaryPredicate = (fp) =>export const engStep0Boundary: Step0BoundaryPredicate = (fp) =>/scope reduction recommendation|cross[\s-]?project learnings/i.test(fp.promptSnippet,- );+ ) ||+ // plan-eng-review's Step 0 may legitimately end with NO scope-reduction /+ // learnings AUQ. When it does, the first answered review-phase question —+ // tagged <gstack-qid:plan-eng-review-...> ({skill}-{slug} convention) —+ // must fire the boundary, or every per-finding AUQ stays classified+ // preReview and the multi-finding batching counter reads 0. Anchor allows+ // the skill-name prefix; live qids observed: plan-eng-review-jitter,+ // plan-eng-review-idempotency, plan-eng-review-todos-e2e-concurrent.+ /gstack-qid:\s*(?:plan-)?eng-review-/i.test(fp.promptSnippet);export const designStep0Boundary: Step0BoundaryPredicate = (fp) =>/design system|design posture|design score|first dimension/i.test(diff --git a/test/helpers/parity-harness.ts b/test/helpers/parity-harness.tsindex 59e372949..75477aaed 100644--- a/test/helpers/parity-harness.ts+++ b/test/helpers/parity-harness.ts@@ -214,7 +214,9 @@ const MONOLITH_INVARIANTS: ParityInvariant[] = [// codexPreflight() block (install + auth tri-state + CODEX_MODE branch prose),// landing ~6.3% over the v1.53.0.0 baseline. Intentional: it adds proper// not-installed vs not-authed handling, not slop.- maxSizeRatio: 1.08,+ // v1.64+v1.65 merge: both waves grew the shared preamble (evidence+ // directive + telemetry failure flags); measured 1.094.+ maxSizeRatio: 1.10,minBytes: 70_000,},{@@ -223,7 +225,11 @@ const MONOLITH_INVARIANTS: ParityInvariant[] = [mustHaveHeadings: ['## Preamble', '## When to invoke'],// v1.2.0 activation lift: the unified first-run-guidance section (P4 scaffold +// P3 loop tip) is added to every skill's shared preamble — intentional, ~1KB.- maxSizeRatio: 1.07,+ // Fork port wave 2: the shared coverage-audit detection block gained the+ // multi-ecosystem markers (Django/JVM, script/target/test-file census —+ // e3259078 port); measured 1.111x. v1.64+v1.65 merge sums both waves'+ // preamble growth; measured 1.125.+ maxSizeRatio: 1.13,minBytes: 50_000,},{@@ -237,7 +243,9 @@ const MONOLITH_INVARIANTS: ParityInvariant[] = [// 1.09 → 1.10: the plan-mode preamble reword (scope-gate auto-select-B// change) adds ~250 B to every skill's shared preamble; investigate was// the closest to its ceiling (landed 1.092).- maxSizeRatio: 1.10,+ // Fork port wave 2 (D1): the evidence-before-claimed-limitations preamble+ // directive adds ~0.45KB to every tier-2+ skill. Measured values noted.+ maxSizeRatio: 1.12, // D1 measuredminBytes: 30_000,},{@@ -245,7 +253,9 @@ const MONOLITH_INVARIANTS: ParityInvariant[] = [mustContain: ['ceo', 'eng', 'design'],mustHaveHeadings: ['## Preamble', '## When to invoke'],// v1.2.0 activation lift: shared first-run-guidance preamble section.- maxSizeRatio: 1.07,+ // Fork port wave 2 (D1): the evidence-before-claimed-limitations preamble+ // directive adds ~0.45KB to every tier-2+ skill. Measured values noted.+ maxSizeRatio: 1.09, // D1 measuredminBytes: 70_000,},];diff --git a/test/helpers/providers/claude.ts b/test/helpers/providers/claude.tsindex ce77767c2..858a30e0d 100644--- a/test/helpers/providers/claude.ts+++ b/test/helpers/providers/claude.ts@@ -1,6 +1,6 @@import type { ProviderAdapter, RunOpts, RunResult, AvailabilityCheck } from './types';import { estimateCostUsd } from '../pricing';-import { execFileSync } from 'child_process';+import { execFileSync, spawnSync } from 'child_process';import * as fs from 'fs';import * as path from 'path';import * as os from 'os';@@ -25,11 +25,30 @@ export class ClaudeAdapter implements ProviderAdapter {if (!resolved) {return { ok: false, reason: 'claude CLI not found on PATH. Install from https://claude.ai/download or npm i -g @anthropic-ai/claude-code (or set GSTACK_CLAUDE_BIN)' };}- // Auth sniff: ~/.claude/.credentials.json OR ANTHROPIC_API_KEY+ // Auth sniff: ~/.claude/.credentials.json OR ANTHROPIC_API_KEY OR (macOS)+ // the Keychain entry subscription installs use instead of the creds file.+ // #1890: the default macOS install stores OAuth under the generic-password+ // service "Claude Code-credentials" and never writes .credentials.json,+ // so the file-or-env sniff reported "No Claude auth found" while+ // `claude -p` worked fine. Metadata probe only (no -w — never reads the+ // secret), and any failure of `security` itself falls through to the+ // not-found reason rather than throwing.const credsPath = path.join(os.homedir(), '.claude', '.credentials.json');const hasCreds = fs.existsSync(credsPath);const hasKey = !!process.env.ANTHROPIC_API_KEY;- if (!hasCreds && !hasKey) {+ let hasKeychain = false;+ if (!hasCreds && !hasKey && process.platform === 'darwin') {+ try {+ const probe = spawnSync('security', ['find-generic-password', '-s', 'Claude Code-credentials'], {+ stdio: 'ignore',+ timeout: 5000,+ });+ hasKeychain = probe.status === 0;+ } catch {+ hasKeychain = false;+ }+ }+ if (!hasCreds && !hasKey && !hasKeychain) {return { ok: false, reason: 'No Claude auth found. Log in via `claude` interactive session, or export ANTHROPIC_API_KEY.' };}return { ok: true };diff --git a/test/ios-qa-stateserver-hardening.test.ts b/test/ios-qa-stateserver-hardening.test.tsnew file mode 100644index 000000000..8a816206a--- /dev/null+++ b/test/ios-qa-stateserver-hardening.test.ts@@ -0,0 +1,48 @@+/**+ * StateServer hardening pins (fork port wave 2, B3 + B5).+ *+ * B3: the boot token must never appear in an os_log statement. The daemon+ * reads it from the 0600 app-container file (copyFileFromAppContainer in+ * tunnel-bootstrap.ts); the old `token=\(self.bootToken, privacy: .public)`+ * announce line had NO consumer and handed a live credential to anything+ * reading the unified log during the launch window.+ *+ * B5: the IPv4 listener has no CoreDevice tunnel path, so it must bind to+ * loopback at the socket level (requiredLocalEndpoint 127.0.0.1), not rely+ * solely on the per-connection peer check. IPv6 keeps the wildcard bind for+ * CoreDevice ULA peers by design.+ *+ * Pinned on BOTH the generated template and the fixture app copy so neither+ * can drift back independently.+ */++import { describe, test, expect } from "bun:test";+import { readFileSync } from "fs";+import { join } from "path";++const ROOT = join(import.meta.dir, "..");+const COPIES = [+ "ios-qa/templates/StateServer.swift.template",+ "test/fixtures/ios-qa/FixtureApp/Sources/DebugBridgeCore/StateServer.swift",+];++describe.each(COPIES)("StateServer hardening — %s", (rel) => {+ const src = readFileSync(join(ROOT, rel), "utf-8");++ test("no os_log statement interpolates the boot token (B3)", () => {+ const logLines = src.split("\n").filter((l) => /logger\.(notice|info|error|debug|log)/.test(l));+ for (const line of logLines) {+ expect(line).not.toContain("bootToken");+ }+ // The bootstrap announce survives (diagnostics), token-free.+ expect(src).toContain('gstack-ios-qa-bootstrap port=');+ expect(src).not.toContain("gstack-ios-qa-bootstrap token=");+ });++ test("IPv4 listener binds loopback at the socket level (B5)", () => {+ expect(src).toContain("requiredLocalEndpoint");+ expect(src).toContain('NWEndpoint.Host("127.0.0.1")');+ // IPv6 wildcard + peer-check path must survive (CoreDevice tunnel peers).+ expect(src).toMatch(/case \.ipv6:\s*\n\s*listener = try NWListener\(using: params, on:/);+ });+});diff --git a/test/memory-ingest-include-gitignored.test.ts b/test/memory-ingest-include-gitignored.test.tsindex 89245530d..51b9d7ae9 100644--- a/test/memory-ingest-include-gitignored.test.ts+++ b/test/memory-ingest-include-gitignored.test.ts@@ -22,7 +22,7 @@import { describe, it, expect } from "bun:test";import { execFileSync } from "child_process";-import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "fs";+import { mkdtempSync, mkdirSync, rmSync, writeFileSync, symlinkSync, realpathSync } from "fs";import { tmpdir } from "os";import { join } from "path";import { readFileSync } from "fs";@@ -45,11 +45,70 @@ describe("gstack-memory-ingest: gbrain import must not be filtered by .gitignoreconst stripped = stripComments(readFileSync(SOURCE_PATH, "utf-8"));// Match the spawn call's argument array and assert both the subcommand// and the flag live in it, so the flag can't drift onto another call.- const call = stripped.match(/spawnGbrainAsync\(\s*\[[^\]]*"import"[^\]]*\]/s);+ // [\s\S]*? bridges the conditional-spread's nested brackets (main's+ // capability-probed --include-gitignored merged with our baseEnv defense).+ const call = stripped.match(/spawnGbrainAsync\(\s*\[[\s\S]*?"import"[\s\S]*?\]/s);expect(call).not.toBeNull();expect(call![0]).toContain("--include-gitignored");});+ it("sets a realpath'd GIT_CEILING_DIRECTORIES on the import child (defense-in-depth)", () => {+ const stripped = stripComments(readFileSync(SOURCE_PATH, "utf-8"));+ // Second #2144 layer: the ceiling env must be built from the staging+ // dir's REAL parent path and merged into the spawn's baseEnv, so a+ // git-enumerating collector fails out of the git fast path even when+ // the flag's semantics drift, and symlinked staging paths still match.+ expect(stripped).toContain("GIT_CEILING_DIRECTORIES");+ expect(stripped).toMatch(/realpathSync\(dirname\(stagingDir\)\)/);+ const call = stripped.match(/spawnGbrainAsync\(\s*\[[\s\S]*?"import"[\s\S]*?\]\s*,\s*\{\s*baseEnv\s*\}/s);+ expect(call).not.toBeNull();+ });++ it("proves the ceiling stops git discovery from the staging dir — including through a symlink", () => {+ const dir = mkdtempSync(join(tmpdir(), "gstack-ingest-ceiling-"));+ try {+ const git = (args: string[], cwd: string, env?: NodeJS.ProcessEnv) =>+ execFileSync("git", args, {+ cwd,+ encoding: "utf-8",+ env: { ...process.env, ...env },+ });+ // ~/.gstack shape: a git repo whose root ignores everything, with the+ // staging dir as a direct child.+ const home = join(dir, "gstack-home");+ mkdirSync(home, { recursive: true });+ git(["init", "-q", "."], home);+ writeFileSync(join(home, ".gitignore"), "*\n", "utf-8");+ const staging = join(home, ".staging-ingest-12345-1700000000000");+ mkdirSync(staging, { recursive: true });++ // Without a ceiling: discovery from the staging dir finds the repo —+ // this is the git fast path that collects zero files.+ const found = git(["rev-parse", "--show-toplevel"], staging).trim();+ expect(realpathSync(found)).toBe(realpathSync(home));++ // With the ceiling at the staging dir's REAL parent: discovery fails,+ // which is exactly what pushes a collector onto its plain FS walk.+ const ceiling = realpathSync(home);+ expect(() =>+ git(["rev-parse", "--show-toplevel"], staging, { GIT_CEILING_DIRECTORIES: ceiling }),+ ).toThrow();++ // Symlink variant (the OV4 trap): reach the same staging dir through a+ // symlinked path. A realpath'd ceiling still stops discovery.+ const linked = join(dir, "linked-home");+ symlinkSync(home, linked);+ const stagingViaLink = join(linked, ".staging-ingest-12345-1700000000000");+ expect(() =>+ git(["rev-parse", "--show-toplevel"], stagingViaLink, {+ GIT_CEILING_DIRECTORIES: ceiling,+ }),+ ).toThrow();+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });+it("demonstrates the collision: an ignore-everything root hides staged pages", () => {const dir = mkdtempSync(join(tmpdir(), "gstack-ingest-gitignore-"));try {diff --git a/test/migrations-v1.27.0.0.test.ts b/test/migrations-v1.27.0.0.test.tsindex 7a1a9908c..0c62a8c22 100644--- a/test/migrations-v1.27.0.0.test.ts+++ b/test/migrations-v1.27.0.0.test.ts@@ -71,7 +71,11 @@ function run(extraEnv: Record<string, string> = {}, input = ''): { code: number;PATH: `${fakeBinDir}:${path.join(ROOT, 'bin')}:/usr/bin:/bin:/opt/homebrew/bin`,HOME: tmpHome,USER: 'testuser',- // Disable interactive prompt: empty stdin = treat as non-interactive.+ // Empty stdin = non-interactive. Since #1383 the script SKIPS by+ // default in that context (a remote repo rename is consent-shaped);+ // the harness opts in explicitly, simulating a consenting unattended+ // run. The default-skip contract has its own test below.+ GSTACK_MIGRATE_ASSUME_YES: '1',...extraEnv,},encoding: 'utf-8',@@ -168,6 +172,67 @@ describe('v1.27.0.0 migration — GitHub host (non-interactive)', () => {});});+describe('v1.27.0.0 migration — #1383 consent + failure-stays-pending contract', () => {+ beforeEach(() => {+ fs.writeFileSync(+ path.join(tmpHome, '.gstack-brain-remote.txt'),+ 'https://github.com/testuser/gstack-brain-testuser\n'+ );+ fs.writeFileSync(+ path.join(tmpHome, '.gstack/config.yaml'),+ 'gbrain_sync_mode: full\n'+ );+ makeFakeGh({});+ });++ test('non-interactive without opt-in: skips for now, touches NOTHING', () => {+ const r = run({ GSTACK_MIGRATE_ASSUME_YES: '0' });+ expect(r.code).toBe(0);+ expect(r.stderr).toContain('skipping for now');+ expect(r.stderr).toContain('GSTACK_MIGRATE_ASSUME_YES=1');+ // The remediation must be REAL: a direct invocation of this script.+ // `/setup-gbrain --rerun-migration` never existed, and the runners'+ // version windows never re-select a passed migration, so "will ask+ // again next upgrade" was false.+ expect(r.stderr).toContain('v1.27.0.0.sh');+ expect(r.stderr).not.toContain('--rerun-migration');+ expect(r.stderr).not.toContain('ask again');+ // Old state untouched, nothing recorded as done.+ expect(fs.existsSync(path.join(tmpHome, '.gstack-brain-remote.txt'))).toBe(true);+ expect(fs.existsSync(path.join(tmpHome, '.gstack-artifacts-remote.txt'))).toBe(false);+ expect(fs.existsSync(path.join(tmpHome, '.gstack/.migrations/v1.27.0.0.done'))).toBe(false);+ });++ test('gh rename failure: step stays pending, migration exits INCOMPLETE, retry succeeds', () => {+ makeFakeGh({ renameSucceeds: false });+ const r = run();+ // Failure must be loud and the migration visibly incomplete — the old+ // behavior marked the failed step done and wrote the done touchfile,+ // permanently stranding a half-renamed install (#1383).+ expect(r.code).toBe(1);+ expect(r.stderr).toContain('PENDING');+ expect(r.stderr).toContain('INCOMPLETE');+ // Honest remediation: direct invocation, not the nonexistent+ // /setup-gbrain --rerun-migration flag.+ expect(r.stderr).toContain('Re-run manually with:');+ expect(r.stderr).toContain('GSTACK_MIGRATE_ASSUME_YES=1');+ expect(r.stderr).not.toContain('--rerun-migration');+ expect(fs.existsSync(path.join(tmpHome, '.gstack/.migrations/v1.27.0.0.done'))).toBe(false);+ const journal = fs.readFileSync(+ path.join(tmpHome, '.gstack/.migrations/v1.27.0.0.journal'),+ 'utf-8'+ );+ expect(journal).not.toContain('gh_repo_renamed');+ // Later steps DID run and are journaled (independent of step 1)...+ expect(journal).toContain('remote_txt_renamed');+ // ...so a retry with working gh only redoes step 1 and completes.+ makeFakeGh({});+ const r2 = run();+ expect(r2.code).toBe(0);+ expect(fs.existsSync(path.join(tmpHome, '.gstack/.migrations/v1.27.0.0.done'))).toBe(true);+ });+});+describe('v1.27.0.0 migration — interruption resume', () => {beforeEach(() => {fs.writeFileSync(diff --git a/test/migrations-v1.65.0.0.test.ts b/test/migrations-v1.65.0.0.test.tsnew file mode 100644index 000000000..554120513--- /dev/null+++ b/test/migrations-v1.65.0.0.test.ts@@ -0,0 +1,240 @@+/**+ * v1.65.0.0 migration — remove rebrand-poisoned Chromium bundles (#2242)+ * and re-fetch a clean one, gating .done on a VERIFIED end state.+ *+ * Exercises the migration in a hermetic temp HOME + temp Playwright cache+ * (HOME / GSTACK_HOME / PLAYWRIGHT_BROWSERS_PATH all redirected) with a+ * stubbed bunx on PATH — nothing touches the real cache. Covers:+ * - whole-revision-dir removal (INSTALLATION_COMPLETE marker included, so+ * `playwright install` can't no-op with "is already downloaded")+ * - clean bundles untouched+ * - re-fetch runs from the gstack install root (repo-pinned playwright)+ * - .done only written once a Chromium executable verifiably exists+ * - failed re-fetch → warning + retry on next run (needs-refetch sentinel)+ * - stranded revision dir (markers without .app) re-triggers the re-fetch+ * - idempotent re-run after success+ * - non-Darwin early exit+ */++import { describe, test, expect, beforeEach, afterEach } from 'bun:test';+import * as fs from 'fs';+import * as os from 'os';+import * as path from 'path';+import { spawnSync } from 'child_process';++const ROOT = path.resolve(import.meta.dir, '..');+const MIGRATION = path.join(ROOT, 'gstack-upgrade', 'migrations', 'v1.65.0.0.sh');++let tmpHome: string;+let fakeBinDir: string;+let pwCache: string;++const POISONED_PLIST =+ '<plist><dict><key>CFBundleName</key><string>GStack Browser</string></dict></plist>';+const CLEAN_PLIST =+ '<plist><dict><key>CFBundleName</key><string>Google Chrome for Testing</string></dict></plist>';++/** Build a Playwright-cache-shaped bundle: <revDir>/chrome-mac/<name>.app */+function makeBundle(+ revDir: string,+ opts: { plist: string; withExecutable?: boolean; withMarkers?: boolean }+): string {+ const appDir = path.join(revDir, 'chrome-mac', 'Google Chrome for Testing.app');+ const contents = path.join(appDir, 'Contents');+ fs.mkdirSync(contents, { recursive: true });+ fs.writeFileSync(path.join(contents, 'Info.plist'), opts.plist);+ if (opts.withExecutable) {+ const macos = path.join(contents, 'MacOS');+ fs.mkdirSync(macos, { recursive: true });+ fs.writeFileSync(path.join(macos, 'Google Chrome for Testing'), '#!/bin/sh\n', {+ mode: 0o755,+ });+ }+ if (opts.withMarkers ?? true) {+ fs.writeFileSync(path.join(revDir, 'INSTALLATION_COMPLETE'), '');+ fs.writeFileSync(path.join(revDir, 'DEPENDENCIES_VALIDATED'), '');+ }+ return appDir;+}++/**+ * Stub bunx: records every invocation (args + cwd) and, unless told+ * otherwise, simulates a successful `playwright install chromium` by+ * creating a fresh revision dir with an executable in the temp cache.+ */+function makeFakeBunx(opts: { createsExecutable?: boolean } = {}): string {+ const creates = opts.createsExecutable ?? true;+ const callLog = path.join(fakeBinDir, 'bunx-calls.log');+ const script = `#!/bin/bash+echo "bunx $@ (pwd=$(pwd))" >> "${callLog}"+${+ creates+ ? `FRESH="\${PLAYWRIGHT_BROWSERS_PATH}/chromium-9999/chrome-mac/Chromium.app/Contents/MacOS"+mkdir -p "\${FRESH}"+printf '#!/bin/sh\\n' > "\${FRESH}/Chromium"+chmod 755 "\${FRESH}/Chromium"+touch "\${PLAYWRIGHT_BROWSERS_PATH}/chromium-9999/INSTALLATION_COMPLETE"`+ : '# simulates an offline / failed download: no files created'+}+exit 0+`;+ fs.writeFileSync(path.join(fakeBinDir, 'bunx'), script, { mode: 0o755 });+ return callLog;+}++function run(extraEnv: Record<string, string> = {}): {+ code: number;+ stdout: string;+ stderr: string;+} {+ const r = spawnSync(MIGRATION, [], {+ env: {+ PATH: `${fakeBinDir}:/usr/bin:/bin`,+ HOME: tmpHome,+ GSTACK_HOME: path.join(tmpHome, '.gstack'),+ PLAYWRIGHT_BROWSERS_PATH: pwCache,+ ...extraEnv,+ },+ encoding: 'utf-8',+ cwd: tmpHome,+ });+ return { code: r.status ?? -1, stdout: r.stdout || '', stderr: r.stderr || '' };+}++const doneFile = () => path.join(tmpHome, '.gstack', '.migrations', 'v1.65.0.0.done');++beforeEach(() => {+ tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), 'mig-v1.65-'));+ fakeBinDir = fs.mkdtempSync(path.join(os.tmpdir(), 'mig-v1.65-fake-'));+ pwCache = path.join(tmpHome, 'pw-cache', 'ms-playwright');+ fs.mkdirSync(pwCache, { recursive: true });+ fs.mkdirSync(path.join(tmpHome, '.gstack'), { recursive: true });+ // The migration gates on `uname -s` = Darwin; on the Linux CI runner the+ // real uname made every test early-exit with empty output. Shim Darwin so+ // the Darwin-path tests run everywhere; the non-Darwin test overwrites+ // this shim with its own Linux uname.+ fs.writeFileSync(path.join(fakeBinDir, 'uname'), '#!/bin/bash\necho Darwin\n', {+ mode: 0o755,+ });+});++afterEach(() => {+ fs.rmSync(tmpHome, { recursive: true, force: true });+ fs.rmSync(fakeBinDir, { recursive: true, force: true });+});++describe('v1.65.0.0 migration — poisoned bundle removal', () => {+ test('poisoned revision dir removed WHOLE (markers included); clean bundle untouched; verified re-fetch → .done', () => {+ const poisonedRev = path.join(pwCache, 'chromium-1234');+ makeBundle(poisonedRev, { plist: POISONED_PLIST });+ const cleanRev = path.join(pwCache, 'chromium-5678');+ const cleanApp = makeBundle(cleanRev, { plist: CLEAN_PLIST, withExecutable: true });+ const log = makeFakeBunx();++ const r = run();+ expect(r.code).toBe(0);++ // The WHOLE revision dir is gone — .app AND the INSTALLATION_COMPLETE /+ // DEPENDENCIES_VALIDATED markers. Removing only the .app leaves markers+ // that make `playwright install chromium` no-op ("is already+ // downloaded"), stranding the user with NO browser + a success message.+ expect(fs.existsSync(poisonedRev)).toBe(false);++ // Clean bundle untouched.+ expect(fs.existsSync(path.join(cleanApp, 'Contents', 'Info.plist'))).toBe(true);+ expect(fs.existsSync(path.join(cleanRev, 'INSTALLATION_COMPLETE'))).toBe(true);++ // Re-fetch invoked...+ const calls = fs.readFileSync(log, 'utf-8');+ expect(calls).toContain('playwright install chromium');+ // ...from the gstack install root (repo-pinned playwright version), not+ // from the arbitrary cwd the migration runner happened to use.+ const realRoot = fs.realpathSync(ROOT);+ expect(calls.includes(`pwd=${ROOT}`) || calls.includes(`pwd=${realRoot}`)).toBe(true);++ // Verified end state → .done written.+ expect(fs.existsSync(doneFile())).toBe(true);+ });++ test('re-fetch produces no executable → WARNING, .done NOT written; next run retries and completes', () => {+ makeBundle(path.join(pwCache, 'chromium-1234'), { plist: POISONED_PLIST });+ const log = makeFakeBunx({ createsExecutable: false });++ const r = run();+ expect(r.code).toBe(0); // non-fatal per the migration contract+ expect(r.stderr).toContain('WARNING');+ expect(r.stderr).toContain('bunx playwright install chromium');+ // Removal succeeded but the end state is "no browser": .done must NOT+ // be written so a re-run retries instead of recording success.+ expect(fs.existsSync(doneFile())).toBe(false);++ // Re-run with a working fetch: the pending state re-triggers the+ // re-fetch even though the scans have nothing left to remove.+ fs.rmSync(log, { force: true });+ makeFakeBunx({ createsExecutable: true });+ const r2 = run();+ expect(r2.code).toBe(0);+ expect(fs.readFileSync(log, 'utf-8')).toContain('playwright install chromium');+ expect(fs.existsSync(doneFile())).toBe(true);+ });++ test('stranded revision dir (install markers, no .app) re-triggers removal + re-fetch', () => {+ // The state an older version of this migration could leave behind:+ // .app removed, INSTALLATION_COMPLETE still present → `playwright+ // install` no-ops while the user has no browser at all.+ const strandedRev = path.join(pwCache, 'chromium-1234');+ fs.mkdirSync(path.join(strandedRev, 'chrome-mac'), { recursive: true });+ fs.writeFileSync(path.join(strandedRev, 'INSTALLATION_COMPLETE'), '');+ const log = makeFakeBunx();++ const r = run();+ expect(r.code).toBe(0);+ expect(fs.existsSync(strandedRev)).toBe(false);+ expect(fs.readFileSync(log, 'utf-8')).toContain('playwright install chromium');+ expect(fs.existsSync(doneFile())).toBe(true);+ });++ test('clean cache → no-op, no bunx call, .done written', () => {+ const cleanRev = path.join(pwCache, 'chromium-5678');+ const cleanApp = makeBundle(cleanRev, { plist: CLEAN_PLIST, withExecutable: true });+ const log = makeFakeBunx();++ const r = run();+ expect(r.code).toBe(0);+ expect(r.stderr).toContain('no-op');+ expect(fs.existsSync(log)).toBe(false); // bunx never invoked+ expect(fs.existsSync(path.join(cleanApp, 'Contents', 'Info.plist'))).toBe(true);+ expect(fs.existsSync(doneFile())).toBe(true);+ });++ test('second run after success → silent no-op (no rescan, no bunx)', () => {+ makeBundle(path.join(pwCache, 'chromium-1234'), { plist: POISONED_PLIST });+ const log = makeFakeBunx();+ const r1 = run();+ expect(r1.code).toBe(0);+ expect(fs.existsSync(doneFile())).toBe(true);++ fs.rmSync(log, { force: true });+ const r2 = run();+ expect(r2.code).toBe(0);+ expect(r2.stderr).toBe('');+ expect(fs.existsSync(log)).toBe(false);+ });++ test('non-Darwin → early exit, cache untouched, no bunx, .done written', () => {+ const poisonedApp = makeBundle(path.join(pwCache, 'chromium-1234'), {+ plist: POISONED_PLIST,+ });+ makeFakeBunx();+ // The script gates on `uname -s` != Darwin; shadow uname on PATH.+ fs.writeFileSync(path.join(fakeBinDir, 'uname'), '#!/bin/bash\necho Linux\n', {+ mode: 0o755,+ });++ const r = run();+ expect(r.code).toBe(0);+ expect(fs.existsSync(poisonedApp)).toBe(true); // nothing removed+ expect(fs.existsSync(path.join(fakeBinDir, 'bunx-calls.log'))).toBe(false);+ expect(fs.existsSync(doneFile())).toBe(true);+ });+});diff --git a/test/mktemp-portability.test.ts b/test/mktemp-portability.test.tsnew file mode 100644index 000000000..e9c2811e3--- /dev/null+++ b/test/mktemp-portability.test.ts@@ -0,0 +1,57 @@+/**+ * Regression pin for #2091: /codex was broken on every macOS install because+ * its mktemp templates carried a suffix after the X's ("codex-err-XXXXXX.txt").+ * BSD mktemp (macOS) requires the X's to be the trailing characters of the+ * template; with a suffix it fails ("mkstemp failed ... File exists"), the+ * temp file never exists, and the skill dies before Codex ever runs.+ *+ * GNU mktemp accepts a --suffix flag but ALSO rejects inline suffixes in the+ * template argument on BusyBox, so the portable form is: X's last, no suffix.+ *+ * This scans every .tmpl (the sources of truth — generated SKILL.md files+ * follow at regen time) for the broken shape.+ */++import { describe, it, expect } from "bun:test";+import { execFileSync } from "child_process";+import { readFileSync } from "fs";+import { join } from "path";++const ROOT = join(import.meta.dir, "..");++function trackedTmplFiles(): string[] {+ const out = execFileSync("git", ["ls-files", "*.tmpl", "**/*.tmpl"], {+ cwd: ROOT,+ encoding: "utf-8",+ });+ return out.split("\n").filter(Boolean);+}++describe("mktemp portability (#2091)", () => {+ it("no .tmpl file uses a mktemp template with characters after XXXXXX", () => {+ const offenders: string[] = [];+ for (const rel of trackedTmplFiles()) {+ const src = readFileSync(join(ROOT, rel), "utf-8");+ src.split("\n").forEach((line, i) => {+ // Broken shape: the X-run followed by a non-quote, non-whitespace,+ // non-closing character inside a mktemp invocation. X{6,} is greedy,+ // so longer X-runs (spec's XXXXXXXX) stay valid — only a genuine+ // suffix after the final X trips it.+ if (/mktemp[^\n]*X{6,}[^"'\s)X]/.test(line)) {+ offenders.push(`${rel}:${i + 1}: ${line.trim()}`);+ }+ });+ }+ expect(offenders).toEqual([]);+ });++ it("BSD-portable form actually works on this platform", () => {+ // Live sanity: the exact template shape the skills now emit.+ const tmp = process.env.TMPDIR || "/tmp";+ const created = execFileSync("mktemp", [`${tmp.replace(/\/$/, "")}/gstack-portability-XXXXXX`], {+ encoding: "utf-8",+ }).trim();+ expect(created.length).toBeGreaterThan(0);+ execFileSync("rm", ["-f", created]);+ });+});diff --git a/test/no-stale-gstack-brain-refs.test.ts b/test/no-stale-gstack-brain-refs.test.tsindex 5aa007d67..9557c3fe2 100644--- a/test/no-stale-gstack-brain-refs.test.ts+++ b/test/no-stale-gstack-brain-refs.test.ts@@ -88,6 +88,12 @@ const SCAN_PATHS = ['review/SKILL.md.tmpl','ship/SKILL.md.tmpl','test/',+ // Fork port wave 2: docs were deliberately excluded and that exact gap let+ // a dead command (gstack-brain-init) survive ~36 releases as a+ // command-not-found instruction. Docs are user-facing surface; scan them.+ 'docs/',+ 'README.md',+ 'USING_GBRAIN_WITH_GSTACK.md',];function grepRefs(pattern: string): string[] {diff --git a/test/ship-apple-gate.test.ts b/test/ship-apple-gate.test.tsnew file mode 100644index 000000000..e9163de58--- /dev/null+++ b/test/ship-apple-gate.test.ts@@ -0,0 +1,56 @@+/**+ * R2 pin (fork port wave 2): the Apple release adapter loads BEFORE ship's+ * branch gate, and the non-Apple gate is byte-unchanged.+ *+ * Two failure modes this prevents: a future ship-template refactor that+ * re-blocks store releases behind "ship from a feature branch" (the exact+ * live failure the fork hit — a solo dev with a clean tree on main shipping+ * to TestFlight got aborted over branch topology), and the reverse — the+ * Apple path accidentally weakening the branch gate for normal+ * repository-landing ships.+ */++import { describe, test, expect } from "bun:test";+import { readFileSync } from "fs";+import { join } from "path";++const ROOT = join(import.meta.dir, "..");+const SKELETON = readFileSync(join(ROOT, "ship", "SKILL.md"), "utf-8");++const GATE_TEXT =+ 'If on the base branch or the repo\'s default branch, **abort**: "You\'re on the base branch. Ship from a feature branch."';++describe("ship Apple gate ordering (R2)", () => {+ test("the Apple adapter read directive precedes the branch gate", () => {+ const appleRead = SKELETON.indexOf("sections/apple-release.md");+ const gate = SKELETON.indexOf(GATE_TEXT);+ expect(appleRead).toBeGreaterThan(-1);+ expect(gate).toBeGreaterThan(-1);+ expect(appleRead).toBeLessThan(gate);+ });++ test("store distribution explicitly bypasses the branch/PR ceremony", () => {+ expect(SKELETON).toContain("Store distribution proceeds");+ expect(SKELETON).toMatch(/branch gate and repository-landing pipeline below apply ONLY to\s*\n?repository-landing asks/);+ });++ test("the non-Apple branch gate is byte-unchanged and appears exactly once", () => {+ const first = SKELETON.indexOf(GATE_TEXT);+ expect(first).toBeGreaterThan(-1);+ expect(SKELETON.indexOf(GATE_TEXT, first + 1)).toBe(-1);+ });++ test("the adapter section exists in the union with its battle-tested spine", () => {+ const section = readFileSync(join(ROOT, "ship", "sections", "apple-release.md"), "utf-8");+ for (const anchor of [+ "one authorization moment",+ "fastlane spaceauth",+ "iris/v1/apiKeys",+ "appPriceSchedules",+ "CLASSIFY the error before touching credentials",+ "Never abort an App Store release over branch topology",+ ]) {+ expect(section).toContain(anchor);+ }+ });+});diff --git a/test/ship-test-detection-markers.test.ts b/test/ship-test-detection-markers.test.tsnew file mode 100644index 000000000..fb0c80f88--- /dev/null+++ b/test/ship-test-detection-markers.test.ts@@ -0,0 +1,113 @@+/**+ * Regression: /ship Step 4 test-framework detection was blind to Django.+ *+ * A real Django project (manage.py + <app>/tests.py, green `python manage.py+ * test`, no pytest.ini and no tests/ directory) read as "no test framework",+ * so /ship bootstrapped pytest on top of a working suite. Same blindness hit+ * any config-less-but-tested project (Go *_test.go, in-source Rust #[test],+ * package.json with only a test script).+ *+ * These run the resolver's OWN emitted detection block against fixtures, so+ * the shell is checked, not just the prose — and the test is independent of+ * generated-SKILL.md regen state.+ *+ * Ported from time-attack/gstack commit e3259078 (GStack 2), adapted from the+ * fork's generated-markdown target to our resolver source of truth.+ */+import { describe, test, expect } from 'bun:test';+import { execFileSync } from 'node:child_process';+import * as fs from 'fs';+import * as os from 'os';+import * as path from 'path';++import { generateTestBootstrap } from '../scripts/resolvers/testing';++const section = generateTestBootstrap({} as never);++/** The detection block the skill tells the agent to run (first bash fence). */+function detectionScript(): string {+ const open = section.indexOf('```bash\n');+ expect(open).toBeGreaterThan(-1);+ const start = open + '```bash\n'.length;+ const end = section.indexOf('```', start);+ return section.slice(start, end);+}++/** Run the detection block in a throwaway git repo laid out by `files`. */+function detect(files: Record<string, string>): string {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'ship-detect-'));+ try {+ for (const [rel, body] of Object.entries(files)) {+ const abs = path.join(dir, rel);+ fs.mkdirSync(path.dirname(abs), { recursive: true });+ fs.writeFileSync(abs, body);+ }+ const script = path.join(dir, '.detect.sh');+ fs.writeFileSync(script, detectionScript());+ const git = (...args: string[]) => execFileSync('git', args, { cwd: dir });+ git('init', '-q', '.');+ git('add', '-A');+ git('-c', 'user.email=t@t', '-c', 'user.name=t', 'commit', '-qm', 'fixture');+ // The block's last line is a `[ -f marker ] && echo`, so a clean project+ // exits 1 by design — read stdout, don't trust the status.+ return execFileSync('bash', [script], { cwd: dir, encoding: 'utf-8' });+ } catch (err: unknown) {+ const e = err as { stdout?: string };+ if (typeof e.stdout === 'string') return e.stdout;+ throw err;+ } finally {+ fs.rmSync(dir, { recursive: true, force: true });+ }+}++const testFileCount = (out: string): number =>+ Number(/^TESTFILES:(\d+)$/m.exec(out)?.[1] ?? -1);++describe('/ship Step 4 detection is multi-ecosystem', () => {+ test('Django project reports manage.py and its existing tests', () => {+ const out = detect({+ 'manage.py': '#!/usr/bin/env python\n',+ 'requirements.txt': 'Django==5.0\n',+ 'polls/tests.py': 'from django.test import TestCase\n',+ });+ expect(out).toContain('MARKER:manage.py');+ expect(out).toContain('FRAMEWORK:django');+ expect(testFileCount(out)).toBeGreaterThan(0);+ });++ test('config-less projects with tests still report test evidence', () => {+ expect(testFileCount(detect({+ 'go.mod': 'module x\n',+ 'x_test.go': 'package x\n',+ }))).toBeGreaterThan(0);++ const node = detect({+ 'package.json': '{"name":"n","scripts":{"test":"node --test"}}\n',+ });+ expect(node).toContain('SCRIPT:package.json test');++ const rust = detect({+ 'Cargo.toml': '[package]\nname="x"\n',+ 'src/lib.rs': '#[cfg(test)]\nmod t{ #[test] fn x(){} }\n',+ });+ expect(rust).toContain('TESTS:rust in-source');+ });++ test('a genuinely untested project reports no test evidence', () => {+ const out = detect({ 'go.mod': 'module x\n', 'x.go': 'package x\n' });+ expect(out).toContain('RUNTIME:go');+ expect(testFileCount(out)).toBe(0);+ expect(out).not.toContain('TESTS:');+ });++ test('every ecosystem marker maps to a command to OFFER, not to run blind', () => {+ expect(section).toContain('never a command to run blind');+ for (const marker of ['manage.py', 'go.mod', 'Cargo.toml', 'pom.xml',+ 'build.gradle', 'mix.exs', 'composer.json', 'Gemfile', 'pytest.ini']) {+ expect(section).toContain(marker);+ }+ // The ask-and-persist contract, not a hardcoded project command.+ expect(section).toContain('AskUserQuestion');+ expect(section).toContain('persist the answer to CLAUDE.md');+ });+});diff --git a/test/skill-e2e-auto-decide-preserved.test.ts b/test/skill-e2e-auto-decide-preserved.test.tsindex 5d3ec36d3..4f5d8e308 100644--- a/test/skill-e2e-auto-decide-preserved.test.ts+++ b/test/skill-e2e-auto-decide-preserved.test.ts@@ -111,7 +111,7 @@ describeE2E('AUTO_DECIDE opt-in preserved under Conductor flags (periodic)', ()skillName: 'plan-ceo-review',inPlanMode: true,extraArgs: ['--disallowedTools', 'AskUserQuestion'],- timeoutMs: 300_000,+ timeoutMs: 540_000,env: { GSTACK_HOME: tmpHome, CONDUCTOR_WORKSPACE_PATH: tmpHome },});@@ -135,5 +135,5 @@ describeE2E('AUTO_DECIDE opt-in preserved under Conductor flags (periodic)', ()} finally {try { fs.rmSync(tmpHome, { recursive: true, force: true }); } catch { /* best-effort */ }}- }, 360_000);+ }, 660_000);});diff --git a/test/skill-e2e-brain-privacy-gate.test.ts b/test/skill-e2e-brain-privacy-gate.test.tsindex 762b7bdc4..1ce7c94de 100644--- a/test/skill-e2e-brain-privacy-gate.test.ts+++ b/test/skill-e2e-brain-privacy-gate.test.ts@@ -34,6 +34,12 @@ describeE2E('gbrain-sync privacy gate fires once via preamble', () => {// Stage a fresh GSTACK_HOME with artifacts_sync_mode_prompted=false.const gstackHome = fs.mkdtempSync(path.join(os.tmpdir(), 'privacy-gate-gstack-'));const fakeBinDir = fs.mkdtempSync(path.join(os.tmpdir(), 'privacy-gate-bin-'));+ // Fresh HOME with NO ~/.claude.json: on a machine where gbrain is+ // registered type=http, the preamble's remote-mode detection reads the+ // operator's ~/.claude.json and echoes "ARTIFACTS_SYNC: remote-mode" —+ // and the local privacy gate legitimately never fires. An empty HOME+ // makes the detection find nothing.+ const tempHome = fs.mkdtempSync(path.join(os.tmpdir(), 'privacy-gate-home-'));// Seed the config so the gate's condition passes.fs.writeFileSync(@@ -59,12 +65,16 @@ describeE2E('gbrain-sync privacy gate fires once via preamble', () => {const askUserQuestions: Array<{ input: Record<string, unknown> }> = [];const binary = resolveClaudeBinary();- // Ambient env mutations — restored in finally so other tests in the file- // don't inherit them.- const origGstackHome = process.env.GSTACK_HOME;- const origPath = process.env.PATH;- process.env.GSTACK_HOME = gstackHome;- process.env.PATH = `${fakeBinDir}:${process.env.PATH ?? '/usr/bin:/bin:/opt/homebrew/bin'}`;+ // Per-test env, merged LAST by the hermetic env builder (safe post-v1.39:+ // the runner always passes a COMPLETE hermetic env, so overrides can't+ // break auth). Ambient process.env.GSTACK_HOME mutation does NOT work+ // here — hermetic-env scrubs GSTACK_* and repoints GSTACK_HOME at its+ // own singleton dir, so the staged config would never reach the child.+ const childEnv = {+ GSTACK_HOME: gstackHome,+ HOME: tempHome,+ PATH: `${fakeBinDir}:${process.env.PATH ?? '/usr/bin:/bin:/opt/homebrew/bin'}`,+ };try {// Pick a small skill with the preamble and load it via Read to force@@ -85,12 +95,7 @@ describeE2E('gbrain-sync privacy gate fires once via preamble', () => {workingDirectory: gstackHome,maxTurns: 10,allowedTools: ['Read', 'Grep', 'Glob', 'Bash'],- // NOTE: do NOT pass `env:` here. When the Agent SDK gets an explicit- // env object, its auth pipeline doesn't pick up ANTHROPIC_API_KEY the- // same way as when env is undefined (SDK-internal detail, verified- // against the plan-mode-no-op test which passes no env and auths- // cleanly). Instead, mutate process.env before the call so the SDK- // inherits our overrides ambiently.+ env: childEnv,...(binary ? { pathToClaudeCodeExecutable: binary } : {}),canUseTool: async (toolName, input) => {if (toolName === 'AskUserQuestion') {@@ -141,13 +146,9 @@ describeE2E('gbrain-sync privacy gate fires once via preamble', () => {// (The preamble is supposed to be idempotent within a session.)expect(privacyQuestions.length).toBe(1);} finally {- // Restore ambient env before other tests.- if (origGstackHome === undefined) delete process.env.GSTACK_HOME;- else process.env.GSTACK_HOME = origGstackHome;- if (origPath === undefined) delete process.env.PATH;- else process.env.PATH = origPath;fs.rmSync(gstackHome, { recursive: true, force: true });fs.rmSync(fakeBinDir, { recursive: true, force: true });+ fs.rmSync(tempHome, { recursive: true, force: true });}}, 180_000);@@ -155,6 +156,10 @@ describeE2E('gbrain-sync privacy gate fires once via preamble', () => {// Same staging, but prompted=true this time. Gate should be silent.const gstackHome = fs.mkdtempSync(path.join(os.tmpdir(), 'privacy-gate-off-'));const fakeBinDir = fs.mkdtempSync(path.join(os.tmpdir(), 'privacy-gate-off-bin-'));+ // Fresh HOME without a .claude.json — same rationale as the first test:+ // without it the operator's ~/.claude.json flips the preamble into+ // remote-mode and this negative test passes vacuously.+ const tempHome = fs.mkdtempSync(path.join(os.tmpdir(), 'privacy-gate-off-home-'));fs.writeFileSync(path.join(gstackHome, 'config.yaml'),@@ -171,11 +176,13 @@ describeE2E('gbrain-sync privacy gate fires once via preamble', () => {const askUserQuestions: Array<{ input: Record<string, unknown> }> = [];const binary = resolveClaudeBinary();- // Ambient env mutations (see note on the first test).- const origGstackHome = process.env.GSTACK_HOME;- const origPath = process.env.PATH;- process.env.GSTACK_HOME = gstackHome;- process.env.PATH = `${fakeBinDir}:${process.env.PATH ?? '/usr/bin:/bin:/opt/homebrew/bin'}`;+ // Per-test env, merged LAST by the hermetic env builder (see note on the+ // first test — ambient GSTACK_HOME mutation is scrubbed by hermetic-env).+ const childEnv = {+ GSTACK_HOME: gstackHome,+ HOME: tempHome,+ PATH: `${fakeBinDir}:${process.env.PATH ?? '/usr/bin:/bin:/opt/homebrew/bin'}`,+ };try {await runAgentSdkTest({@@ -185,6 +192,7 @@ describeE2E('gbrain-sync privacy gate fires once via preamble', () => {workingDirectory: gstackHome,maxTurns: 4,allowedTools: ['Read', 'Grep', 'Glob', 'Bash'],+ env: childEnv,...(binary ? { pathToClaudeCodeExecutable: binary } : {}),canUseTool: async (toolName, input) => {if (toolName === 'AskUserQuestion') {@@ -216,12 +224,9 @@ describeE2E('gbrain-sync privacy gate fires once via preamble', () => {});expect(privacyQuestions.length).toBe(0);} finally {- if (origGstackHome === undefined) delete process.env.GSTACK_HOME;- else process.env.GSTACK_HOME = origGstackHome;- if (origPath === undefined) delete process.env.PATH;- else process.env.PATH = origPath;fs.rmSync(gstackHome, { recursive: true, force: true });fs.rmSync(fakeBinDir, { recursive: true, force: true });+ fs.rmSync(tempHome, { recursive: true, force: true });}}, 180_000);});diff --git a/test/skill-e2e-context-skills.test.ts b/test/skill-e2e-context-skills.test.tsindex add602026..64a78ce6b 100644--- a/test/skill-e2e-context-skills.test.ts+++ b/test/skill-e2e-context-skills.test.ts@@ -447,8 +447,13 @@ Do NOT use AskUserQuestion.`,// Match by filename timestamp (stable, unambiguous) plus a looser// prose check.const showsMain = /20260101-120000|main-work/.test(out);- const hidesAlpha = !/20260202-120000/.test(out);- const hidesBeta = !/20260303-120000/.test(out);+ // Hide checks scope to the FINAL text output only: fullOutputSurface+ // includes bash tool_results, and a legitimate `ls` of the checkpoint+ // dir lists every branch's filename. The filtering under test happens+ // in the user-facing list, not in the agent's intermediate reads.+ const finalText = result.output ?? '';+ const hidesAlpha = !/20260202-120000|LISTCURR_ALPHA_TOKEN/.test(finalText);+ const hidesBeta = !/20260303-120000|LISTCURR_BETA_TOKEN/.test(finalText);const routed = skillCalls(result).includes('context-save');const exitOk = ['success', 'error_max_turns'].includes(result.exitReason);diff --git a/test/skill-e2e-design.test.ts b/test/skill-e2e-design.test.tsindex 2966412dc..5c832554c 100644--- a/test/skill-e2e-design.test.ts+++ b/test/skill-e2e-design.test.ts@@ -126,7 +126,7 @@ Write DESIGN.md and CLAUDE.md (or update it) in the working directory.`,'Color': ['color', 'colour', 'palette', 'colors'],'Spacing': ['spacing', 'space', 'whitespace', 'gap'],'Layout': ['layout', 'grid', 'structure', 'composition'],- 'Motion': ['motion', 'animation', 'transition', 'movement'],+ 'Motion': ['motion', 'animation', 'transition', 'movement', 'easing', 'duration', 'micro-interaction'],};const missingSections = Object.entries(sectionSynonyms).filter(([_, synonyms]) => !synonyms.some(s => designContent.toLowerCase().includes(s))@@ -152,7 +152,9 @@ Write DESIGN.md and CLAUDE.md (or update it) in the working directory.`,expect(['success', 'error_max_turns']).toContain(result.exitReason);expect(designExists).toBe(true);if (designExists) {- expect(missingSections).toHaveLength(0);+ // join() so a failure names the offending section(s) — a bare+ // toHaveLength(0) failure never prints WHICH synonym set missed.+ expect(missingSections.join(', ')).toBe('');}if (claudeExists) {const claude = fs.readFileSync(claudePath, 'utf-8');diff --git a/test/skill-e2e-plan.test.ts b/test/skill-e2e-plan.test.tsindex a1aac4f45..7b2badde2 100644--- a/test/skill-e2e-plan.test.ts+++ b/test/skill-e2e-plan.test.ts@@ -81,7 +81,10 @@ Write your complete review directly to ${planDir}/review-output.mdFocus on reviewing the plan content: architecture, error handling, security, and performance.`,workingDirectory: planDir,maxTurns: 15,- timeout: 360_000,+ // 540s: the evidence-before-claimed-limitations directive and the+ // design-doc discovery block (fork port wave 2) add real probing turns;+ // main cleared this at 243s, the enriched skill needs more headroom.+ timeout: 540_000,testName: 'plan-ceo-review',runId,model: 'claude-opus-4-7',@@ -100,7 +103,7 @@ Focus on reviewing the plan content: architecture, error handling, security, andconst review = fs.readFileSync(reviewPath, 'utf-8');expect(review.length).toBeGreaterThan(200);}- }, 420_000);+ }, 660_000);});// --- Plan CEO Review (SELECTIVE EXPANSION) E2E ---@@ -168,7 +171,7 @@ Write your complete review directly to ${planDir}/review-output-selective.mdFocus on reviewing the plan content: architecture, error handling, security, and performance.`,workingDirectory: planDir,maxTurns: 15,- timeout: 360_000,+ timeout: 540_000,testName: 'plan-ceo-review-selective',runId,model: 'claude-opus-4-7',@@ -185,7 +188,7 @@ Focus on reviewing the plan content: architecture, error handling, security, andconst review = fs.readFileSync(reviewPath, 'utf-8');expect(review.length).toBeGreaterThan(200);}- }, 420_000);+ }, 660_000);});// --- Plan CEO Review SCOPE EXPANSION energy (V1.1 mode-posture regression gate) ---diff --git a/test/skill-e2e-qa-workflow.test.ts b/test/skill-e2e-qa-workflow.test.tsindex 516cf1789..ff33b90ec 100644--- a/test/skill-e2e-qa-workflow.test.ts+++ b/test/skill-e2e-qa-workflow.test.ts@@ -406,7 +406,9 @@ Do NOT fix any bugs. Do NOT use AskUserQuestion — just pick vitest.`,}, 120_000);});-// Module-level afterAll — finalize eval collector after all tests complete+// Module-level afterAll — finalize eval collector after all tests complete.+// Explicit 60s timeout: finalize does a JSON save + cross-run comparison and+// has been observed at 6.26s, past bun's 5s default hook timeout.afterAll(async () => {await finalizeEvalCollector(evalCollector);-});+}, 60_000);diff --git a/test/skill-e2e-setup-gbrain-remote.test.ts b/test/skill-e2e-setup-gbrain-remote.test.tsindex ed2cf116b..c310cd641 100644--- a/test/skill-e2e-setup-gbrain-remote.test.ts+++ b/test/skill-e2e-setup-gbrain-remote.test.ts@@ -130,15 +130,16 @@ describeE2E('/setup-gbrain Path 4 (Remote MCP) — happy path', () => {const askUserQuestions: Array<{ input: Record<string, unknown> }> = [];const binary = resolveClaudeBinary();- // Ambient env mutations. Restored in finally.- const orig = {- gstackHome: process.env.GSTACK_HOME,- pathEnv: process.env.PATH,- mcpToken: process.env.GBRAIN_MCP_TOKEN,+ // Per-test child env, passed via opts.env (merges last over the complete+ // hermetic env). Ambient process.env mutations DO NOT reach children:+ // hermetic-env scrubs GBRAIN_*/GSTACK_* by allowlist — this test's token+ // silently never arrived from the day hermetic env landed, and the child+ // correctly stopped at Step 4c with NEEDS_CONTEXT.+ const childEnv = {+ GSTACK_HOME: gstackHome,+ GBRAIN_MCP_TOKEN: SECRET_TOKEN,+ PATH: `${fakeBinDir}:${path.join(path.resolve(import.meta.dir, '..'), 'bin')}:${process.env.PATH ?? '/usr/bin:/bin:/opt/homebrew/bin'}`,};- process.env.GSTACK_HOME = gstackHome;- process.env.PATH = `${fakeBinDir}:${path.join(path.resolve(import.meta.dir, '..'), 'bin')}:${process.env.PATH ?? '/usr/bin:/bin:/opt/homebrew/bin'}`;- process.env.GBRAIN_MCP_TOKEN = SECRET_TOKEN;let modelTextOutput = '';@@ -146,6 +147,7 @@ describeE2E('/setup-gbrain Path 4 (Remote MCP) — happy path', () => {const skillPath = path.resolve(import.meta.dir, '..', 'setup-gbrain', 'SKILL.md');const result = await runAgentSdkTest({systemPrompt: { type: 'preset', preset: 'claude_code' },+ env: childEnv,userPrompt:`Read the skill file at ${skillPath} and follow Path 4 (Remote MCP) only. ` +`Use this MCP URL: ${stubServer.url}. ` +@@ -195,6 +197,19 @@ describeE2E('/setup-gbrain Path 4 (Remote MCP) — happy path', () => {// Assertion 2: claude mcp add was called with --transport http.const calls = fs.existsSync(callLog) ? fs.readFileSync(callLog, 'utf-8') : '';+ if (!/mcp add.*--transport http/.test(calls)) {+ // Failure evidence: without this, the transcript dies with the test+ // and every triage pass starts blind (three did).+ const bashCmds = result.toolCalls+ .filter((t) => t.tool === 'Bash')+ .map((t) => String((t.input as { command?: string })?.command ?? '').slice(0, 200));+ console.error(+ `[setup-gbrain-remote] mcp-add never hit the fake shim.\n` ++ `exitReason=${result.exitReason} turns=${result.turnsUsed}\n` ++ `--- bash commands (${bashCmds.length}) ---\n${bashCmds.join('\n')}\n` ++ `--- final text (last 1500 chars) ---\n${result.output.slice(-1500)}`,+ );+ }expect(calls).toMatch(/mcp add.*--transport http/);// Assertion 3: the secret token NEVER appears in the final CLAUDE.md.@@ -207,14 +222,16 @@ describeE2E('/setup-gbrain Path 4 (Remote MCP) — happy path', () => {// Assertion 5: classifier — the model didn't write findings before// asking. The Path 4 prose has 5 STOP gates; if any of them got// skipped, that's the wrote_findings_before_asking pattern.- const wroteBefore = /## GSTACK REVIEW REPORT|critical_gaps/i.test(modelTextOutput);+ // Scan the ASSISTANT's text only: modelTextOutput serializes every+ // event including the child's Read of the skill file, whose generated+ // footer contains the literal "GSTACK REVIEW REPORT" — a guaranteed+ // false positive on both trees.+ const wroteBefore = /## GSTACK REVIEW REPORT|critical_gaps/i.test(result.output);// Setup-gbrain doesn't have a review report contract, so this is// a structural shape check, not a hard failure mode.expect(wroteBefore).toBe(false);} finally {- if (orig.gstackHome === undefined) delete process.env.GSTACK_HOME; else process.env.GSTACK_HOME = orig.gstackHome;- if (orig.pathEnv === undefined) delete process.env.PATH; else process.env.PATH = orig.pathEnv;- if (orig.mcpToken === undefined) delete process.env.GBRAIN_MCP_TOKEN; else process.env.GBRAIN_MCP_TOKEN = orig.mcpToken;+ // (no ambient process.env mutations to restore — env goes via opts.env)await stubServer.close();fs.rmSync(gstackHome, { recursive: true, force: true });fs.rmSync(fakeBinDir, { recursive: true, force: true });diff --git a/test/skill-e2e-ship-idempotency.test.ts b/test/skill-e2e-ship-idempotency.test.tsindex 322bf9f8f..4faa78b4f 100644--- a/test/skill-e2e-ship-idempotency.test.ts+++ b/test/skill-e2e-ship-idempotency.test.ts@@ -158,7 +158,7 @@ describeE2E('/ship idempotency E2E (periodic, real-PTY)', () => {const session = await launchClaudePty({permissionMode: 'plan',cwd: fixture.workTree,- timeoutMs: 720_000,+ timeoutMs: 1_080_000,// Disable network-y pieces so the agent can't reach actual github.env: { GH_TOKEN: 'mock-not-real', NO_COLOR: '1' },seedSkills: true,@@ -172,7 +172,7 @@ describeE2E('/ship idempotency E2E (periodic, real-PTY)', () => {const since = session.mark();session.send('/ship\r');- const budgetMs = 600_000;+ const budgetMs = 900_000;const start = Date.now();let lastPermSig = '';while (Date.now() - start < budgetMs) {@@ -234,6 +234,12 @@ describeE2E('/ship idempotency E2E (periodic, real-PTY)', () => {break;}}+ // Budget exhausted without a terminal signal: capture the tail NOW,+ // while the session is still alive. Only the break paths above set+ // evidence — without this, the timeout throw ships evidence: "".+ if (outcome === 'timeout') {+ evidence = session.visibleSince(since).slice(-3000);+ }} finally {await session.close();}@@ -273,6 +279,6 @@ describeE2E('/ship idempotency E2E (periodic, real-PTY)', () => {try { fs.rmSync(path.dirname(fixture.workTree), { recursive: true, force: true }); } catch { /* ignore */ }}},- 900_000, // 15 min wall clock+ 1_200_000, // 20 min wall clock);});diff --git a/test/skill-validation.test.ts b/test/skill-validation.test.tsindex 1439f9d7c..8266a4857 100644--- a/test/skill-validation.test.ts+++ b/test/skill-validation.test.ts@@ -1216,9 +1216,11 @@ describe('Step 3.4 test coverage audit', () => {describe('ship step numbering', () => {// Allowed sub-steps that are resolver-generated and intentionally nested:- // 8.1 (Plan Verification), 8.2 (Scope Drift), 9.1 (Review Army), 9.2 (Findings Merge),- // 9.3 (Cross-review dedup), 15.0 (WIP squash — continuous checkpoint), 15.1 (Bisectable commits).- const ALLOWED_SUBSTEPS = new Set(['8.1', '8.2', '9.1', '9.2', '9.3', '15.0', '15.1']);+ // 0.9 (Apple target detection — MUST precede Step 1's branch gate, R2-pinned+ // by test/ship-apple-gate.test.ts), 8.1 (Plan Verification), 8.2 (Scope+ // Drift), 9.1 (Review Army), 9.2 (Findings Merge), 9.3 (Cross-review dedup),+ // 15.0 (WIP squash — continuous checkpoint), 15.1 (Bisectable commits).+ const ALLOWED_SUBSTEPS = new Set(['0.9', '8.1', '8.2', '9.1', '9.2', '9.3', '15.0', '15.1']);test('ship/SKILL.md.tmpl contains no unexpected fractional step numbers', () => {const tmpl = fs.readFileSync(path.join(ROOT, 'ship', 'SKILL.md.tmpl'), 'utf-8');diff --git a/test/tasks-section-jq.test.ts b/test/tasks-section-jq.test.tsnew file mode 100644index 000000000..78f8de9cf--- /dev/null+++ b/test/tasks-section-jq.test.ts@@ -0,0 +1,106 @@+/**+ * Regression pin for #2018: /autoplan Phase 4's task aggregator emitted zero+ * tasks on every run, forever, for everyone.+ *+ * Root cause: the branch+commit filter in scripts/resolvers/tasks-section.ts+ * piped to the split commit array and THEN referenced `.commit` —+ *+ * select(.branch == $branch and ($commits | split("|") | index(.commit) != null))+ *+ * In jq, the pipe rebinds the context, so `.commit` was evaluated against the+ * split ARRAY ("Cannot index array with string \"commit\""), every input line+ * errored, stderr went to /dev/null, `|| true` swallowed the exit code, and+ * the aggregate was empty. A dead feature indistinguishable from "no tasks".+ *+ * These tests run the ACTUAL jq program extracted from the resolver source+ * against fixture JSONL, so they were RED against the broken filter and stay+ * red if anyone reintroduces a context-rebinding shape.+ */++import { describe, it, expect } from "bun:test";+import { execFileSync } from "child_process";+import { readFileSync } from "fs";+import { join } from "path";++const SOURCE_PATH = join(import.meta.dir, "..", "scripts", "resolvers", "tasks-section.ts");++/**+ * Extract the emitted jq filter program from the resolver source. The+ * resolver builds bash inside a TS template literal, so `\\` in source is a+ * bash line-continuation `\` — strip it when unescaping. We match the+ * single-quoted jq program on the line that filters by $branch + $commits.+ */+function extractBranchCommitFilter(): string {+ const src = readFileSync(SOURCE_PATH, "utf-8");+ const m = src.match(/'([^']*select\(\.branch == \$branch[^']*)'/);+ if (!m) throw new Error("branch+commit jq filter not found in tasks-section.ts");+ return m[1].replace(/\\\\/g, "\\");+}++function runJq(program: string, inputLines: string[], branch: string, commits: string): string[] {+ const out = execFileSync(+ "jq",+ ["-c", "--arg", "branch", branch, "--arg", "commits", commits, program],+ { input: inputLines.join("\n"), encoding: "utf-8" },+ );+ return out.split("\n").filter(Boolean);+}++const RECORD = (branch: string, commit: string) =>+ JSON.stringify({+ phase: "ceo-review",+ run_id: "20260814T000000Z-1",+ branch,+ commit,+ id: "T1",+ priority: "P1",+ component: "demo",+ files: ["a.ts"],+ effort_human: "~1h",+ effort_cc: "~5min",+ title: "demo task",+ source_finding: "demo finding",+ });++describe("tasks-section jq filter (#2018)", () => {+ it("matches a record whose branch and commit are in the window", () => {+ const program = extractBranchCommitFilter();+ const matched = runJq(+ program,+ [RECORD("feature/x", "abc123")],+ "feature/x",+ "abc123|def456",+ );+ // The broken filter returned [] here (every line errored) — the exact+ // #2018 symptom: reviews produced tasks, the aggregate table showed none.+ expect(matched).toHaveLength(1);+ expect(JSON.parse(matched[0]).id).toBe("T1");+ });++ it("filters out other branches and out-of-window commits", () => {+ const program = extractBranchCommitFilter();+ const matched = runJq(+ program,+ [+ RECORD("feature/x", "abc123"),+ RECORD("other-branch", "abc123"),+ RECORD("feature/x", "zzz999"),+ ],+ "feature/x",+ "abc123|def456",+ );+ expect(matched).toHaveLength(1);+ });++ it("errors on no input line at all rather than fabricating output", () => {+ const program = extractBranchCommitFilter();+ expect(runJq(program, [], "feature/x", "abc123")).toHaveLength(0);+ });++ it("source does not reference .commit after a context-rebinding pipe", () => {+ const src = readFileSync(SOURCE_PATH, "utf-8");+ // The bug shape: split("|") piped, then a bare `.commit` in the new array+ // context. Binding first (`.commit as $c`) is the required form.+ expect(src).not.toMatch(/split\("\|"\)\s*\|\s*index\(\.commit\)/);+ });+});diff --git a/test/telemetry-repo-strip.test.ts b/test/telemetry-repo-strip.test.tsindex 31ba9186a..db25934c8 100644--- a/test/telemetry-repo-strip.test.ts+++ b/test/telemetry-repo-strip.test.ts@@ -12,14 +12,20 @@* (bin/gstack-telemetry-log)** gstack-telemetry-sync MUST strip every one of those fields before the remote- * POST (bin/gstack-telemetry-sync). This test enforces that contract three ways:+ * POST (bin/gstack-telemetry-sync). The script has TWO strip paths — jq del()+ * is PRIMARY (structural, escape-proof), sed is the jq-less fallback — and+ * this test enforces the contract on both:*- * 1. Coverage — every repo/branch field the producers emit is also stripped.- * Catches "added a new repo field, forgot to strip it" (the rename-to-_repo- * landmine, or any future producer drift).- * 2. Behavior — run the ACTUAL sed strip expressions from the sync script over- * a sample event line and assert no repo/branch field survives, while benign- * fields do. Catches a broken/edited regex, not just a missing line.+ * 1. Coverage — every repo/branch field the producers emit is also stripped,+ * by every jq del() list AND by the sed expressions. Catches "added a new+ * repo field, forgot to strip it" (the rename-to-_repo landmine, or any+ * future producer drift) on whichever path a machine takes.+ * 2. Behavior — run the ACTUAL jq expression and the ACTUAL sed strip+ * expressions from the sync script over a sample event line and assert no+ * repo/branch field survives, while benign fields do. Catches a+ * broken/edited filter, not just a missing line. The jq leg also pins the+ * malformed-line contract: a line jq can't parse is dropped, never+ * forwarded unstripped.* 3. Floor — the three known fields are always in the stripped set, so deleting* a strip rule fails CI even if a producer also stops emitting it.*/@@ -45,6 +51,16 @@ function extractSedExprs(scriptText: string): string[] {return [...scriptText.matchAll(/-e\s+'(s\/[^']*)'/g)].map((m) => m[1]);}+/** Pull every `jq -c 'del(...)'` filter out of the sync script, verbatim. */+function extractJqDelFilters(scriptText: string): string[] {+ return [...scriptText.matchAll(/jq -c '(del\([^']*\))'/g)].map((m) => m[1]);+}++/** The JSON keys a jq del() filter removes, e.g. `del(._repo_slug, .repo)`. */+function fieldsFromJqDel(filter: string): string[] {+ return [...filter.matchAll(/\.([A-Za-z_][A-Za-z0-9_]*)/g)].map((m) => m[1]);+}+/** The JSON key a strip expression targets, e.g. `,"repo":"[^"]*"` -> `repo`. */function fieldFromSedExpr(expr: string): string | null {const m = expr.match(/,"([A-Za-z_][A-Za-z0-9_]*)":/);@@ -73,6 +89,25 @@ describe('telemetry no-repo-identity-egress invariant', () => {const strippedFields = new Set(strippedRepoExprs.map(fieldFromSedExpr).filter((f): f is string => f !== null),);+ const jqFilters = extractJqDelFilters(syncText);++ // Repo-identity fields the producers emit into the synced file — computed+ // once, asserted against BOTH strip paths (jq primary, sed fallback). Only+ // emission lines that target the synced file (skill-usage.jsonl) count: the+ // preamble appends directly; gstack-telemetry-log builds the synced event+ // with a `printf '{"v":1,...` line into $JSONL_FILE (= skill-usage.jsonl).+ const preambleSynced = fs+ .readFileSync(PREAMBLE, 'utf-8')+ .split('\n')+ .filter((l) => l.includes('skill-usage.jsonl'));+ const telLogSynced = fs+ .readFileSync(TEL_LOG, 'utf-8')+ .split('\n')+ .filter((l) => l.includes('"v":1') || l.includes('skill-usage'));+ const emitted = new Set<string>([+ ...emittedRepoFields(preambleSynced),+ ...emittedRepoFields(telLogSynced),+ ]);test('floor: the three known repo-identity fields are stripped', () => {for (const field of REPO_IDENTITY_FLOOR) {@@ -80,33 +115,34 @@ describe('telemetry no-repo-identity-egress invariant', () => {}});- test('coverage: every repo/branch field the producers emit into skill-usage.jsonl is stripped', () => {- // Only emission lines that target the synced file (skill-usage.jsonl). The- // preamble appends directly; gstack-telemetry-log builds the synced event- // with a `printf '{"v":1,...` line into $JSONL_FILE (= skill-usage.jsonl).- const preambleSynced = fs- .readFileSync(PREAMBLE, 'utf-8')- .split('\n')- .filter((l) => l.includes('skill-usage.jsonl'));- const telLogSynced = fs- .readFileSync(TEL_LOG, 'utf-8')- .split('\n')- .filter((l) => l.includes('"v":1') || l.includes('skill-usage'));- const emitted = new Set<string>([- ...emittedRepoFields(preambleSynced),- ...emittedRepoFields(telLogSynced),- ]);+ test('coverage: every repo/branch field the producers emit into skill-usage.jsonl is stripped (sed fallback path)', () => {// The preamble must emit "repo" — guards against the test silently passing// because a regex stopped matching the producer.expect(emitted.has('repo')).toBe(true);for (const field of emitted) {expect(strippedFields.has(field),- `producer emits repo-identity field "${field}" but gstack-telemetry-sync does not strip it (would leak to remote)`,+ `producer emits repo-identity field "${field}" but gstack-telemetry-sync's sed fallback does not strip it (would leak to remote)`,).toBe(true);}});+ test('coverage: every jq del() list (the PRIMARY strip path) covers every emitted repo-identity field', () => {+ // Both tiers run a del() filter; each must strip full repo identity on its+ // own — a machine only ever takes one branch.+ expect(jqFilters.length).toBeGreaterThanOrEqual(2);+ expect(emitted.has('repo')).toBe(true); // producer-regex canary, as above+ for (const filter of jqFilters) {+ const delFields = new Set(fieldsFromJqDel(filter));+ for (const field of [...emitted, ...REPO_IDENTITY_FLOOR]) {+ expect(+ delFields.has(field),+ `jq filter "${filter}" does not del repo-identity field "${field}" (primary strip path would leak it to remote)`,+ ).toBe(true);+ }+ }+ });+test('behavior: the real sed expressions remove repo identity, keep benign fields', () => {const sample ='{"v":1,"ts":"2026-06-02T00:00:00Z","skill":"design-shotgun",' +@@ -134,4 +170,51 @@ describe('telemetry no-repo-identity-egress invariant', () => {expect(cleaned).toContain('"sessions":3');expect(cleaned).toContain('"ts":"2026-06-02T00:00:00Z"');});++ test('behavior: the real jq del() filters strip repo identity and drop malformed lines', () => {+ if (!Bun.which('jq')) return; // jq-less machine: the sed-fallback behavior test above is the live path++ const sample =+ '{"v":1,"ts":"2026-06-02T00:00:00Z","skill":"design-shotgun",' ++ '"repo":"my-secret-repo","_repo_slug":"acme-my-secret-repo","_branch":"feature-x",' ++ '"sessions":3,"installation_id":"abc123"}';++ // The identified-tier filter (no installation_id in its del list) and the+ // anonymous-tier filter (installation_id included) — run each verbatim.+ const identified = jqFilters.find((f) => !f.includes('installation_id'));+ const anonymous = jqFilters.find((f) => f.includes('installation_id'));+ expect(identified).toBeTruthy();+ expect(anonymous).toBeTruthy();++ const runJq = (filter: string, input: string) => {+ const out = spawnSync(['jq', '-c', filter], { stdin: Buffer.from(input) });+ return { exitCode: out.exitCode, stdout: out.stdout.toString().trim() };+ };++ const id = runJq(identified!, sample);+ expect(id.exitCode).toBe(0);+ // No repo/branch identity survives, value or key.+ expect(id.stdout).not.toContain('my-secret-repo');+ expect(id.stdout).not.toContain('feature-x');+ expect(id.stdout).not.toContain('"repo"');+ expect(id.stdout).not.toContain('_repo_slug');+ expect(id.stdout).not.toContain('_branch');+ // Benign fields are untouched; identified tier keeps installation_id.+ expect(id.stdout).toContain('"skill":"design-shotgun"');+ expect(id.stdout).toContain('"sessions":3');+ expect(id.stdout).toContain('"installation_id":"abc123"');++ // Anonymous tier additionally drops installation_id.+ const anon = runJq(anonymous!, sample);+ expect(anon.exitCode).toBe(0);+ expect(anon.stdout).not.toContain('installation_id');+ expect(anon.stdout).not.toContain('my-secret-repo');++ // Malformed line: jq fails and emits nothing — the sync script's+ // `|| CLEAN=""` + `[ -z "$CLEAN" ] && continue` drops it, so bytes the+ // strip never touched are never forwarded.+ const bad = runJq(identified!, '{"v":1,"repo":"my-secret-repo"');+ expect(bad.exitCode).not.toBe(0);+ expect(bad.stdout).toBe('');+ });});diff --git a/test/verify-gate.test.ts b/test/verify-gate.test.tsnew file mode 100644index 000000000..99bf9670b--- /dev/null+++ b/test/verify-gate.test.ts@@ -0,0 +1,359 @@+/**+ * gstack-verify-gate — Stop-hook enforcement tier.+ *+ * Pins the behaviours the gate exists for:+ * trust — a declared command NEVER runs until the user records it via+ * `gstack-verify-gate --trust` (per-repo command trust store).+ * block — trusted check fails, exit 2, turn cannot end.+ * allow — trusted check passes, exit 0.+ * fail open — nothing declared, exit 0. Absence never blocks.+ *+ * Plus the two safety branches: the Stop re-entry guard, and the static+ * opt-in contract (our adaptation): ./setup never registers the gate; the+ * settings-hook helper.+ */++import { describe, test, expect, beforeEach, afterEach } from 'bun:test';+import * as fs from 'fs';+import * as path from 'path';+import * as os from 'os';+import { createHash } from 'crypto';+import { spawnSync } from 'child_process';++const ROOT = path.resolve(import.meta.dir, '..');+const GATE = path.join(ROOT, 'bin', 'gstack-verify-gate');++let dir: string;+let gstackHome: string;++beforeEach(() => {+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-verify-gate-'));+ gstackHome = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-verify-gate-home-'));+});++afterEach(() => {+ fs.rmSync(dir, { recursive: true, force: true });+ fs.rmSync(gstackHome, { recursive: true, force: true });+});++/** Declare a verification command in the project's CLAUDE.md (comment form). */+function declareCheck(command: string): void {+ fs.writeFileSync(path.join(dir, 'CLAUDE.md'), `# Fixture\n\n<!-- gstack:verify: ${command} -->\n`);+}++/** Write the check script the declaration points at. Touches `check-ran` when executed. */+function check(exitCode: number, message: string): void {+ const script = path.join(dir, 'check.sh');+ fs.writeFileSync(script, `#!/bin/sh\ntouch check-ran\necho "${message}"\nexit ${exitCode}\n`);+ fs.chmodSync(script, 0o755);+}++/** Did the declared check actually execute? */+function checkRan(): boolean {+ return fs.existsSync(path.join(dir, 'check-ran'));+}++interface RunOpts {+ stopHookActive?: boolean;+ cwd?: string;+ /** When false, CLAUDE_PROJECT_DIR is removed from the child env (walk-up mode). */+ projectDirEnv?: boolean;+ /** Hook-input session id, keys the re-entry attempt counter. */+ sessionId?: string;+}++function gateEnv(projectDirEnv: boolean): NodeJS.ProcessEnv {+ const env: NodeJS.ProcessEnv = { ...process.env, GSTACK_HOME: gstackHome };+ if (projectDirEnv) env.CLAUDE_PROJECT_DIR = dir;+ else delete env.CLAUDE_PROJECT_DIR;+ return env;+}++function runGate(opts: RunOpts = {}): { code: number; stdout: string; stderr: string } {+ const input: Record<string, unknown> = { stop_hook_active: opts.stopHookActive ?? false };+ if (opts.sessionId) input.session_id = opts.sessionId;+ const r = spawnSync(GATE, {+ cwd: opts.cwd ?? dir,+ input: JSON.stringify(input),+ encoding: 'utf-8',+ timeout: 15000,+ env: gateEnv(opts.projectDirEnv ?? true),+ });+ return { code: r.status ?? 1, stdout: r.stdout || '', stderr: r.stderr || '' };+}++/** Record the currently-declared command in the trust store. */+function trust(opts: RunOpts = {}): { code: number; stdout: string; stderr: string } {+ const r = spawnSync(GATE, ['--trust'], {+ cwd: opts.cwd ?? dir,+ encoding: 'utf-8',+ timeout: 15000,+ env: gateEnv(opts.projectDirEnv ?? true),+ });+ return { code: r.status ?? 1, stdout: r.stdout || '', stderr: r.stderr || '' };+}++describe('gstack-verify-gate trust store', () => {+ test('an untrusted declared command is NOT executed and does not block', () => {+ declareCheck('touch sentinel-ran');++ const r = runGate();++ expect(r.code).toBe(0);+ expect(fs.existsSync(path.join(dir, 'sentinel-ran'))).toBe(false);+ expect(r.stderr).toContain('--trust');+ expect(r.stderr).toContain('touch sentinel-ran');+ });++ test('--trust records the command and prints a confirmation naming it', () => {+ declareCheck('./check.sh');+ check(0, 'all good');++ const t = trust();++ expect(t.code).toBe(0);+ expect(t.stdout).toContain('./check.sh');+ });++ test('after --trust the hook executes the command and block semantics work', () => {+ declareCheck('./check.sh');+ check(1, 'totals mismatch');++ expect(trust().code).toBe(0);+ const r = runGate();++ expect(checkRan()).toBe(true);+ expect(r.code).toBe(2);+ expect(r.stderr).toContain('FAILED');+ expect(r.stderr).toContain('totals mismatch');+ });++ test('a changed command is not executed until re-trusted', () => {+ declareCheck('true');+ expect(trust().code).toBe(0);++ // Attacker (or anyone) edits the declaration after trust was granted.+ declareCheck('touch sentinel-ran');+ const r = runGate();++ expect(r.code).toBe(0);+ expect(fs.existsSync(path.join(dir, 'sentinel-ran'))).toBe(false);+ expect(r.stderr).toContain('--trust');++ // Re-trusting the new command restores execution.+ expect(trust().code).toBe(0);+ const r2 = runGate();+ expect(r2.code).toBe(0);+ expect(fs.existsSync(path.join(dir, 'sentinel-ran'))).toBe(true);+ });++ test('walk-up: hook run from a nested subdir keys trust on the CLAUDE.md root', () => {+ declareCheck('./check.sh');+ check(0, 'all good');+ const nested = path.join(dir, 'a', 'b');+ fs.mkdirSync(nested, { recursive: true });++ // No CLAUDE_PROJECT_DIR: both trust and hook must walk up from $PWD.+ expect(trust({ cwd: nested, projectDirEnv: false }).code).toBe(0);+ const r = runGate({ cwd: nested, projectDirEnv: false });++ expect(r.code).toBe(0);+ expect(r.stdout).toContain('passed');+ expect(checkRan()).toBe(true);+ });++ test('non-comment declaration form (gstack:verify: cmd without <!-- -->) is honored', () => {+ fs.writeFileSync(path.join(dir, 'CLAUDE.md'), '# Fixture\n\ngstack:verify: ./check.sh\n');+ check(0, 'all good');++ expect(trust().stdout).toContain('./check.sh');+ const r = runGate();++ expect(r.code).toBe(0);+ expect(r.stdout).toContain('passed');+ expect(checkRan()).toBe(true);+ });++ test('the trust store file is created 0600 under GSTACK_HOME', () => {+ declareCheck('./check.sh');+ check(0, 'all good');+ expect(trust().code).toBe(0);++ const store = path.join(gstackHome, 'verify-gate-trust');+ expect(fs.existsSync(store)).toBe(true);+ expect(fs.statSync(store).mode & 0o777).toBe(0o600);+ });++ test('--trust fails cleanly when nothing is declared', () => {+ fs.writeFileSync(path.join(dir, 'CLAUDE.md'), '# Fixture\n\nNothing declared here.\n');++ const t = trust();++ expect(t.code).not.toBe(0);+ });+});++describe('gstack-verify-gate', () => {+ test('blocks the turn when the trusted check fails', () => {+ declareCheck('./check.sh');+ check(1, 'totals mismatch');+ expect(trust().code).toBe(0);++ const r = runGate();++ expect(r.code).toBe(2);+ expect(r.stderr).toContain('FAILED');+ expect(r.stderr).toContain('totals mismatch');+ });++ test('allows the turn when the trusted check passes', () => {+ declareCheck('./check.sh');+ check(0, 'all good');+ expect(trust().code).toBe(0);++ const r = runGate();++ expect(r.code).toBe(0);+ expect(r.stdout).toContain('passed');+ });++ test('fails open when CLAUDE.md declares no check', () => {+ fs.writeFileSync(path.join(dir, 'CLAUDE.md'), '# Fixture\n\nNothing declared here.\n');++ const r = runGate();++ expect(r.code).toBe(0);+ expect(r.stdout).toContain("declares no 'gstack:verify:' command");+ });++ test('fails open when there is no CLAUDE.md at all', () => {+ const r = runGate();++ expect(r.code).toBe(0);+ expect(r.stdout).toContain('no CLAUDE.md');+ });++ test('never invents a command: an empty declaration fails open', () => {+ fs.writeFileSync(path.join(dir, 'CLAUDE.md'), '<!-- gstack:verify: -->\n');++ const r = runGate();++ expect(r.code).toBe(0);+ expect(r.stdout).toContain("declares no 'gstack:verify:' command");+ });++});++describe('gstack-verify-gate re-entry enforcement (no one-shot bypass)', () => {+ test('re-entry with a still-failing trusted check is blocked again', () => {+ declareCheck('./check.sh');+ check(1, 'still failing');+ expect(trust().code).toBe(0);++ const r = runGate({ stopHookActive: true, sessionId: 'sess-refail' });++ expect(r.code).toBe(2);+ expect(r.stderr).toContain('FAILED');+ expect(r.stderr).toContain('still failing');+ expect(checkRan()).toBe(true);+ });++ test('re-entry after the check now passes is allowed', () => {+ declareCheck('./check.sh');+ check(1, 'totals mismatch');+ expect(trust().code).toBe(0);+ expect(runGate({ sessionId: 'sess-fixed' }).code).toBe(2);++ check(0, 'fixed now');+ const r = runGate({ stopHookActive: true, sessionId: 'sess-fixed' });++ expect(r.code).toBe(0);+ expect(r.stdout).toContain('passed');+ });++ test('attempt bound: repeated failing re-entries allow with a loud warning at the bound', () => {+ declareCheck('./check.sh');+ check(1, 'never passing');+ expect(trust().code).toBe(0);+ const sid = 'sess-bound';++ // First entry blocks and resets the episode counter.+ expect(runGate({ sessionId: sid }).code).toBe(2);++ // Re-entries: bounded number of blocks, then allow-with-warning.+ const codes: number[] = [];+ let final: { code: number; stdout: string; stderr: string } | null = null;+ for (let i = 0; i < 6; i++) {+ const r = runGate({ stopHookActive: true, sessionId: sid });+ codes.push(r.code);+ if (r.code === 0) {+ final = r;+ break;+ }+ expect(r.code).toBe(2);+ }++ expect(codes).toEqual([2, 2, 2, 0]);+ expect(final).not.toBeNull();+ expect(final!.stdout + final!.stderr).toContain('WARNING');++ // A fresh first-entry run starts a new episode: blocked again, not allowed.+ expect(runGate({ sessionId: sid }).code).toBe(2);+ });++ test('re-entry with an untrusted command keeps the exit-0-with-hint path', () => {+ declareCheck('touch sentinel-ran');++ const r = runGate({ stopHookActive: true, sessionId: 'sess-untrusted' });++ expect(r.code).toBe(0);+ expect(fs.existsSync(path.join(dir, 'sentinel-ran'))).toBe(false);+ expect(r.stderr).toContain('--trust');+ });+});++describe('gstack-verify-gate trust-grant audit trail', () => {+ test('every --trust grant appends a JSON audit line (right sha256, 0600, verbatim cmd)', () => {+ declareCheck('./check.sh');+ check(0, 'all good');++ const t = trust();+ expect(t.code).toBe(0);+ // --trust prints the VERBATIM command being trusted.+ expect(t.stdout).toContain('./check.sh');++ const log = path.join(gstackHome, 'security', 'verify-gate-trust-grants.jsonl');+ expect(fs.existsSync(log)).toBe(true);+ expect(fs.statSync(log).mode & 0o777).toBe(0o600);++ const lines = fs.readFileSync(log, 'utf-8').trim().split('\n');+ expect(lines.length).toBe(1);+ const entry = JSON.parse(lines[0]);+ expect(entry.cmd).toBe('./check.sh');+ expect(entry.cmd_sha256).toBe(createHash('sha256').update('./check.sh').digest('hex'));+ expect(entry.root).toBe(fs.realpathSync(dir));+ expect(typeof entry.tty).toBe('boolean');+ expect(entry.ts).toMatch(/^\d{4}-\d{2}-\d{2}T/);++ // A second grant appends, never truncates.+ declareCheck('true');+ expect(trust().code).toBe(0);+ const lines2 = fs.readFileSync(log, 'utf-8').trim().split('\n');+ expect(lines2.length).toBe(2);+ expect(JSON.parse(lines2[1]).cmd).toBe('true');+ });+});++describe('opt-in contract (adapted from the fork: NOT registered by default)', () => {+ const setup = fs.readFileSync(path.join(ROOT, 'setup'), 'utf-8');+ const gate = fs.readFileSync(GATE, 'utf-8');++ test('./setup does NOT register the gate — a Stop hook running the verify command after every turn is opt-in', () => {+ expect(setup).not.toContain('verify-gate');+ });++ test('the bin documents its own registration and removal commands', () => {+ expect(gate).toContain('remove-source --source verify-gate');+ expect(gate).toContain('gstack:verify:');+ });+});