Files
gstack/test/gstack-doctor.test.ts
T
Garry Tanandcapy-ai[bot] 0bf9d50808 v1.91.107.0 fix: the GBRA-40 field list (one Bun for install and check, rec gate approval, pregate never silent) (#3190)
* fix(autoplan): empty findings fences, repo-relative rows, PLAN_REALITY flags, pending/--all/provider (Lane B: B3 B6 B7 B8 B9 B10 B11)

B3  parseFences: the body group is optional (lazy), so an LF/CRLF empty fence is zero
    findings in both the canonical and record grammars; opener without closer still
    RESULT_FINDINGS_MISSING.
B6  plan-reality/3: item/section references are not quantities; backtick phrases are
    exempt only from the plan-scope rule-phrase check (B-f); a measured number inside
    backticks stays flagged in review scope. vaguePlanTerms() feeds an advisory
    `flagged: PLAN_REALITY ...` line under the p1 approval item (never blocking).
B7  canonical rows: absolute repo paths become repo-relative; snapshot/active-plan
    citations become the plan file name with the source line mapped (or dropped).
B8  `status` prints `PENDING: <id> phase=<p> voice=<v> result=<file>` per open attempt.
B9  `gstack-gate render --all`; paged output says to relay every page.
B10 `gstack-plan-reality check --plan <snapshot>`: a number in a "quoted" span copied
    verbatim from the reviewed plan needs no receipt (reviewer scope only).
B11 submit defaults the provider to host-subagent when --runner is omitted.

Lane B files: lib/autoplan-reconcile.ts lib/plan-reality.ts lib/autoplan-gate.ts
lib/gate-list.ts lib/autoplan-plan-text.ts lib/autoplan-run.ts bin/gstack-gate
bin/gstack-plan-reality scripts/resolvers/plan-reality.ts autoplan/sections/ceo-phase.md
autoplan/sections/eng-phase.md test/plan-reality.test.ts test/autoplan-gate-artifacts.test.ts

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix(ubicloud): ubi-runner up/run -S accepts only Ubicloud's storage sizes, before any API call (A11)

Files: scripts/ubicloud/ubi-runner.sh, test/ubicloud-runner.test.ts
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix(issue-links): promotion candidates, Related PRs, validated flake issues, body/receipt consistency (Lane D: D1-D3)

D1: the GBRA-40 fix wave's gbrain #6279 body had no `## Issues` section and no
receipt (it was not composed by /ship, so gstack-issue-links never ran), and
#6252 appeared only as a subject parenthetical `(#6252)`, which the closure
rule correctly treats as Refs. The rule is kept. Same-repo references are now
printed as promotion candidates (`(promote: fix #N)`, `candidates` in --json),
and `gstack-ship-receipt write --issues ... --body` refuses a body that lacks a
line its issues object records (ISSUE_LINKS_MISSING), so a /ship body can no
longer drop its closing lines.

D2: open PRs by other authors whose closing set overlaps this PR's Fixes are
`Related: #N (@author)` (paged GraphQL closedByPullRequestsReferences; viewer
and this branch excluded; cross-repo PRs keep owner/repo#N). `Supersedes` and
`Contributed by` only with --supersedes/--credit; --no-auto-links skips the
lookup; the stderr preview names each added line's source. A failed lookup is
ISSUE_LOOKUP_FAILED (installer form with docs anchor) and keeps the other lines.

D3: a --ci-run match becomes a Flake line only for a bot-opened issue of this
repository that names that run (flake:json first_seen.run_id or this repo's
actions/runs URL) and a test; duplicates of one test keep the lowest number;
every refused match prints its reason.

Files: bin/gstack-issue-links, bin/gstack-ship-receipt, lib/issue-links.ts,
lib/ship-receipt.ts, lib/headless-artifacts.ts (ship-receipt issues.related),
lib/result-codes.ts (ISSUE_LOOKUP_FAILED, ISSUE_LINKS_MISSING,
resultLineWithDocs), bin/gstack-doctor-components.sh (regenerated),
docs/pregate.md, docs/troubleshooting.md, test/ship-issue-intent.test.ts,
test/helpers/pregate-fixture.ts (gh shim: repo view, api graphql, full issue rows).

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix(ship): link issues by intent at publish and handoff; Fixes: trailer at commit (Lane D: D1, D2, D-a)

- Step 15: a commit fixing a user-named issue carries a `Fixes: #<n>` trailer
  (offset by tightening Step 15 so the skeleton stays at 80,998 <= 81,000).
- pr-body: an explicit "Issue links" step runs gstack-issue-links before the
  body is composed (previously only a placeholder inside the body template);
  interactive runs ask once about `(promote: fix #N)` references and add
  `--supersedes`/`--credit` only on the owner's confirmation; unattended runs
  keep Refs and list unpromoted candidates, Related lines and lookup failures
  in the completion message; `ISSUE_LINKS_MISSING` from the receipt write.
- handoff (no-PR lanes): runs gstack-issue-links and passes --issues to the
  receipt; the completion message gains an `issues:` line.
- Regenerated ship/SKILL.md and sections; refreshed the four ship goldens.
- Parity: union 309,431 / 187,706 = 1.6485 (> 1.6450 by 655 bytes); maxSizeRatio
  raised to the measured 1.6485 with its justification, as previous waves did.

Files: ship/SKILL.md.tmpl, ship/SKILL.md, ship/sections/pr-body.md.tmpl,
ship/sections/pr-body.md, ship/sections/handoff.md.tmpl, ship/sections/handoff.md,
test/fixtures/golden/{claude,codex,factory,agy}-ship-SKILL.md,
test/helpers/carve-guards.ts (ship maxSizeRatio).

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix(install): one Bun resolution contract, versioned runtime store, verdict per (checkout, project), drift and wrapper rows (A1-A3, A5, A6, A8, A-c, A-d, A-f, A-h, A-i)

- bin/gstack-bun-version.sh: GSTACK_BUN_DEFAULT=1.4.3 beside the 1.4.2 floor,
  gstack_bun_install_version (GSTACK_BUN_INSTALL_VERSION override),
  gstack_bun_store, portable gstack_realpath, and gstack_bun_resolve (pin and
  default in the store, $BUN_INSTALL/bin, ~/.bun/bin, PATH; first candidate
  satisfying every pin; shim-marked files never returned). gstack_bun_launch_dir
  is replaced by it.
- lib/pregate/runtime.ts: resolveBun, the TypeScript twin; launchRuntime runs
  the Bun the install verdict recorded under the admission condition and
  explains the skip otherwise.
- bin/gstack-capy-install: install and --check resolve through the contract;
  verified archives publish atomically to <state root>/runtimes/bun/<v>/bun
  under ~/.gstack-runtime.lock and ~/.bun/bin is never written; the "no Bun
  satisfies" line names the candidates judged; --check reports
  BUN_RESOLUTION_DRIFT with one converging fix.
- bin/gstack-install-verdict.sh, lib/install-verdict.ts: schema 2 verdicts
  keyed by (checkout, project) with pin, bun_path, bun_version, bun_rule;
  schema 1 path still read; admission binds test-running workflows to the
  project and refuses a running Bun the verdict did not record.
- bin/gstack-doctor-check.sh, lib/doctor-components.ts: wrapper core row
  (CAPY_WRAPPER_STALE by active provenance, WARN for stale Drive copies),
  runtime drift row, shim note, install-version note.
- lib/result-codes.ts: BUN_RESOLUTION_DRIFT, BUN_INSTALL_VERSION_INVALID;
  CAPY_WRAPPER_STALE fix names the workaround and the owner action.

Files: bin/gstack-bun-version.sh, bin/gstack-capy-install,
bin/gstack-doctor-check.sh, bin/gstack-doctor-components.sh (generated),
bin/gstack-install-verdict.sh, lib/doctor-components.ts,
lib/install-verdict.ts, lib/pregate/runtime.ts, lib/result-codes.ts,
test/bun-resolve.test.ts, test/gstack-capy-install.test.ts,
test/gstack-doctor.test.ts, test/install-verdict.test.ts,
test/pregate-guards.test.ts

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix(issue-links): --author for the Related lookup when gh runs as an app (Lane D: D2)

On a Capy machine the gh viewer is `capy-ai[bot]`, not the owner (checked live
against garrytan/gbrain #6252), so "other authors" needs the PR author named:
`--author <login>` overrides the viewer; the pr-body Issue links step says to
pass it when gh runs as an app.

Files: bin/gstack-issue-links, docs/pregate.md, ship/sections/pr-body.md.tmpl,
ship/sections/pr-body.md, test/ship-issue-intent.test.ts,
test/helpers/carve-guards.ts (ship maxSizeRatio re-measured: 309,483 / 187,706 = 1.6488).

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* docs(troubleshooting): BUN_RESOLUTION_DRIFT and BUN_INSTALL_VERSION_INVALID anchors; CAPY_WRAPPER_STALE covers the wrapper row (A5, A8, A-f, G1)

Files: docs/troubleshooting.md, bin/gstack-capy-install, bin/gstack-doctor-check.sh, test/gstack-capy-install.test.ts
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* feat(install): marked per-directory bun and bunx shims for fresh Capy shells (A4, A-e)

gstack-capy-install (install mode, Capy machines only, GSTACK_BUN_SHIM=0 opts
out) writes ~/.local/bin/bun and bunx under ~/.gstack-runtime.lock. The shim
bakes the store, verdict directory, checkout and install default, walks up to
.git without spawning git, runs the Bun the (checkout, project) verdict
recorded, else a store Bun matching the .bun-version/package.json subset
(stderr names the --check to run when none matches), else the install
default, else the next unmarked bun on PATH. A foreign file or dangling link
is never touched. GSTACK_BUN_SHIM_EXPLAIN=1 prints project, record, choice and
rule; the doctor's runtime row shows the shim and its target.

Files: bin/gstack-capy-install, test/gstack-capy-install.test.ts, test/gstack-doctor.test.ts
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix(pregate): test stage never hangs silently; small machines record the remote gate (Lane C, GBRA-95)

C1 diagnosis (gbrain 92f0ea87, a core edit selecting 3,683 local files, 358
serial; Bun 1.4.2 and 1.4.3 identical): --timeout was applied per runner
spawn (unit group plus one per serial file), so the check was unbounded, and
spawnSync buffered all output until it returned: 360 s with 0 bytes on stdout
and stderr. A backgrounded child holding stdout made spawnSync wait the full
timeout and then report exit 0 (a silent wait, then green). Not the Bun 1.4.2
spawnSync hang.

C2/C-b: test-tier commands (lanes runner, guards, the --remote gate) run via
lib/pregate/supervise.ts: own process group (setsid), stdout/stderr appended
to a log file (no pipes), async supervision; CheckDef.run may return a
promise and runPregate/withFingerprint await it (a rejection is incomplete).
Leftover group members are killed after exit; SIGINT/SIGTERM to pregate
SIGKILLs running groups, writes no pregate.json, exits 130/143. Windows:
taskkill /T /F (reparented or detached descendants can survive; documented).

C3/C-a: --timeout bounds the whole check; groups past the deadline are not
started. --stall-timeout <s> (default stall_timeout_s, else 300; 0 disables)
kills a group whose log stops growing and records PREGATE_STALLED naming the
last file started. Live stderr: PREGATE_TEST per file (bun test adapter; any
runner for one-file runs), PREGATE_HEARTBEAT after 60 s without progress,
PREGATE: tests <verdict>. --json stdout unchanged.

C4/C-c: under 8 cores, a base-branch remote_gate or a non-local test_backend
records the local tier as a requires-remote obligation with its command
(pregate.json/remote_gate or test_backend/<backend>). --remote runs the
declared remote_gate now (needs --allow-repo-commands, never --policy-from
head) under --spend-cap/GSTACK_SPEND_CAP_USD; it clears only on
PREGATE_REMOTE: tree=<tested tree> tests>0 failed=0 with exit 0, and reports
spent/reserved/unknown.

G1: new code PREGATE_STALLED has its result-codes row, troubleshooting anchor
and the installer-form error line (CODE; url#anchor).

Files (G2): lib/pregate/supervise.ts (new), lib/pregate/types.ts,
lib/pregate/context.ts, lib/pregate/index.ts, lib/pregate/checks/lanes.ts,
lib/pregate/checks/guards.ts, lib/pregate/config.ts, lib/headless-artifacts.ts,
lib/result-codes.ts, bin/gstack-pregate, bin/gstack-doctor-components.sh
(generated), docs/pregate.md, docs/troubleshooting.md,
test/pregate-supervise.test.ts (new), test/pregate-remote.test.ts (new).

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* docs(ship): Step 5 pre-gate text for stalls and the small-machine remote gate (Lane C-c)

The pre-gate paragraph now says `incomplete` blocks (a stall is incomplete)
and that `requires-remote` covers the remote gate under 8 cores, cleared by
`gstack-pregate clear` or `--remote --spend-cap <usd>` only under a cap the
user gave. Kept within the ship parity size cap (union 308,771 of 308,776
bytes; base 308,767), so the `--explain` hint moved to docs/pregate.md. The
handoff's escalation line already names any `requires-remote` lane; unchanged.

Files (G2): ship/sections/tests.md.tmpl, ship/sections/tests.md (generated).

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix(install): one ok-trailer grammar with requested, pins-skipped and latest notes; bootstrapper revision 2 exports origin's VERSION (A9, A-a)

Notes ride only on the ok trailer in fixed order; the failure head is
unchanged, pinned by a test that runs the Capy skill's dispatch examples
against real doctor output. The latest note comes only from
GSTACK_CAPY_REMOTE_VERSION, which the bootstrapper sets from a fetch in this
run and unsets otherwise (a stale FETCH_HEAD never reaches the installer).

Files: bin/gstack-capy-install, bin/gstack-capy-session,
capy/skill/gstack/scripts/install.sh, capy/skill/gstack/SKILL.md,
test/gstack-capy-install.test.ts, test/capy-skill-wrapper.test.ts,
test/gstack-doctor.test.ts

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix(upgrade): every success path certifies the caller's project; a pins failure keeps the move, ends on gstack: fail pins, exit 1, no pending marker (A7, A-b)

gstack-upgrade captures the caller's directory and git toplevel before any
cd. Already-current, fast-forwarded and resumed-pending paths run
bin/gstack-capy-install --project <it> on Capy (installing a verified pinned
Bun) or gstack-doctor --check --require runtime,pins elsewhere. The
reinstall's own trailer is held back when a project certification follows,
so no ok precedes a pins failure; a RUNTIME_PIN_CONFLICT stop becomes
gstack: fail pins — <conflict>. --check and --ff-only-no-reinstall certify
nothing.

Files: bin/gstack-upgrade, test/gstack-upgrade-bin.test.ts
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix(install): fresh-install log lines name the clone and every host installed (A10)

gstack-capy-install prints `cloned <repo> at <sha> (<version>)` for a checkout
it cloned, or one the bootstrapper (revision 2, GSTACK_CAPY_CLONED) cloned in
this run, instead of `reusing`. setup's final line is
`gstack ready (<hosts>)` from the same rows as its summary table, including
the --refresh-registered upgrade summary.

Files: bin/gstack-capy-install, bin/gstack-capy-session,
capy/skill/gstack/scripts/install.sh, setup, test/gstack-capy-install.test.ts,
test/host-conformance.test.ts

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix(pregate): --remote runs the gate only when local tests are selected (Lane C4)

With only platform lanes selected, --remote no longer launches the remote
gate with an empty file list; the existing no-local-lane path applies.

Files (G2): lib/pregate/checks/lanes.ts.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix(autoplan): one-word rec, verified pairing, sealed attempt results, deferred reopen (Lane B: B1 B2 B4 B5)

B1/B-b/B-c  `rec` (aliases: all, approve all, accept all, take all recommendations)
    takes every recommendation, plan changes included; `as-is` keeps every
    direction. The render offers `rec` first and prints what it resolves to
    with gate_rev and rec_hash. `gstack-autoplan recommend` changes one
    recommendation before relay (provenance recorded, p1 and decisions follow)
    and bumps rec_rev, so a `rec` without the new --rec-hash is refused
    (GATE_REC_STALE). An agent answer needs the owner's words verbatim
    (--owner-reply <text>|-, --owner-reply-file; OWNER_REPLY_REQUIRED); a
    parseable owner reply that resolves differently from the relay is refused
    (GATE_OWNER_REPLY_MISMATCH). Supersedes field-wave R1 per the owner's
    gate_rev 1 decision.
B2/B-a  reconcile associates by title first; a file:line-only match is
    `unverified` (associated, never confirmed). `b` is recommended only for a
    confirmed pair with the same `changes` and one shared proposal (override)
    or the same normalized remedy; the basis says which. Negative control and
    positives copied from run-20261014225954 (test/fixtures/autoplan-pairing).
B4/B-e  each attempt writes <phase>-<voice>.<attempt>.md; submit refuses another
    attempt's file (ATTEMPT_MISMATCH) and binds a sealed 0444
    <phase>-<voice>.<attempt>.bound.md copy, so a late write changes nothing
    bound; reopen keeps sealed copies in place.
B5/B-d  answer records accepted changes as amendments (status amend_pending) and
    reopens nothing; revise reopens what changed. `revise --settle <id|d4>`
    discharges a packaging/ordering change on an unchanged plan
    (AMENDMENT_NOT_SETTLEABLE otherwise). APPLY/NEXT/status lines say which.

DRIVER.md and the reply table move to the rec grammar.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* feat(autoplan): durable checkpoint and resume --from; Capy checklist (Lane B: B12)

With GSTACK_AUTOPLAN_CHECKPOINT_DIR set, every command that leaves a run at
rest (gate_pending, amend_pending, complete, incomplete) publishes
<dir>/<run>/: checkpoint.json listing every file's sha256, the run under run/,
the owner's plan file under plan-input/ when it lives outside the run, and
restore.md as the human index. Publication swaps in a fully written sibling.
Checkpointing at every rest state, not only gate_pending, keeps accepted
decisions from rolling back on restore.

`gstack-autoplan resume --out <new dir> --from <checkpoint>` checks
containment (no absolute or .. paths, regular files only) and every hash
before publishing the run with one rename. It restores a missing plan file
into the run, journals `restored` with both hosts, and takes the lock.
CHECKPOINT_INVALID and CHECKPOINT_TARGET_EXISTS each get a result-codes row
and a troubleshooting anchor. Journal and revise staging paths are now
run-relative, so a moved run recovers.

DRIVER.md and the Capy skill's autoplan section get a short Capy checklist:
always drive gstack-autoplan, never present a hand review as an autoplan run,
relay every gate page with rec as the default, pass --owner-reply, and point
the checkpoint at the private project-user Drive folder.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* A-g: run the quick free tier on GSTACK_BUN_DEFAULT in CI; drift test pins it

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* docs(autoplan): unattended contract and reply-unparsed fix move to rec, sealed results, settle and checkpoints (Lane B)

docs/unattended.md: rec/as-is/rec except grammar, --owner-reply and recommend/--rec-hash, unverified pairing and the shared-proposal rule for b, amend_pending and revise --settle, attempt-owned result paths with the sealed .bound.md copy, render --all, and the checkpoint/resume --from paragraph. GATE_REPLY_UNPARSED's fix names rec/as-is (DRIVER.md regenerated).

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* docs/capy-install: resolver, versioned store, bun shim, trailer notes; wrapper minimum 2

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix(pregate): --timeout bounds each runner process again, not the whole lanes check

Lane C made --timeout a deadline for the whole lanes check, so a repo whose
unit group and serial files each fit in 600 s but exceed it together ended
incomplete and blocked /ship. --timeout is per runner process again (unit
group, each serial file); the stall timeout still catches hung or silent
processes. A timed-out process is incomplete naming its last file, and the
next serial file still runs. Regression: three 1.5 s serial files under
--timeout 3 pass; one 5 s file is incomplete.

Files (G2): lib/pregate/checks/lanes.ts, bin/gstack-pregate (help),
docs/pregate.md, test/pregate-supervise.test.ts.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix(pins): CI exact pins for this platform are alternatives; the installer prefers a non-CI exact pin, else the install default among CI alternatives, else the highest verified (integration item 1)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix(pregate): clear validates the remote gate receipt; test_backend run URLs are attested

`gstack-pregate clear` accepted any --run-url for a small machine's
obligation. A pregate.json/remote_gate obligation now clears only with
--receipt <file> holding the gate's PREGATE_REMOTE: line, validated as
--remote validates it (tree equals the tested tree, tests > 0, failed = 0;
shared parseRemoteReport/remoteReportProblem); a run URL is usage (exit 2)
and a bad receipt is PREGATE_RECEIPT_INVALID (exit 1, obligation unchanged).
A test_backend/<backend> obligation has no machine-checkable receipt: its
--run-url is recorded as attested:<url> and the output says attested, not
validated. Platform lanes are unchanged. Hints name the right clear form.

New code PREGATE_RECEIPT_INVALID: result-codes row, troubleshooting anchor,
installer-form error line, regenerated doctor components.

Files (G2): lib/pregate/index.ts, lib/pregate/checks/lanes.ts,
bin/gstack-pregate, lib/result-codes.ts, bin/gstack-doctor-components.sh
(generated), docs/pregate.md, docs/troubleshooting.md,
test/pregate-remote.test.ts.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix(issue-links): derive this PR's author when gh runs as an app, so handoff and pr-body exclude the owner's own PRs (Lane D fix 1)

The handoff ran gstack-issue-links without --author, and the pr-body step only
asked the agent to pass one, so under Capy's app identity (viewer
`capy-ai[bot]`) the owner's own open PRs were listed as `Related:`. The bin now
derives the author itself: --author, else the gh viewer, else (for a `…[bot]`
viewer) the HEAD commit's GitHub user, else the owner of a user-owned
repository; with none it keeps every PR and reports ISSUE_LOOKUP_FAILED.
`--json` gains `author: {login, source}`; the stderr preview names it. Both ship
steps work unchanged, so the pr-body `--author` clause is dropped (union
309,487 -> 309,435 bytes, under the unchanged 1.6488 cap; skeleton 80,998).

Files: bin/gstack-issue-links, lib/result-codes.ts (ISSUE_LOOKUP_FAILED row),
docs/troubleshooting.md (#issue-lookup-failed), docs/pregate.md,
ship/sections/pr-body.md.tmpl, ship/sections/pr-body.md,
test/helpers/pregate-fixture.ts (gh stub: PR-author query),
test/ship-issue-intent.test.ts.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix(wrapper): GSTACK_CAPY_MIN_WRAPPER back to 1; an active wrapper below the minimum is a WARN; gstack-upgrade never leaves a pending marker for the wrapper row and maps every installer stop to a trailer (integration items 2, 9)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix(shim): validate and contain store pins, read the 'none' record outside projects and in the checkout, fall back in the resolver's order, stay quiet without a pin; quote baked paths; publish bunx and replace store entries without a window (integration items 3, 4, 6, 9)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix(install): --check fails BUN_RESOLUTION_DRIFT only when the recorded Bun is gone, changed or no longer satisfies the pins; a newer candidate is a note and the recorded Bun stays the launch Bun (integration item 5)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix(install): one final 'gstack ready (claude, codex)' after both host setups (integration item 7)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix(pregate): lanes and guards validate the install verdict like admission and return incomplete (INSTALL_UNVERIFIED, BUN_RESOLUTION_DRIFT) before launching; the checkout binds the 'none' verdict (integration item 8)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* docs: CI pin alternatives, shim order and containment, drift note, wrapper WARN, final ready line

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix(autoplan): settle after or with a revise, title pairs need the same remedy, legacy gates refuse rec (integration items 1, 7, 8)

1. A gate with a scope change (uc1) and a packaging change (uc2) answered
   `rec` deadlocked: after `revise --plan v2 --incorporates uc1` reopened the
   phases, `revise --settle uc2` compared against the first phase snapshot
   (now undefined) and was refused forever. Settle evidence is now the plan
   hash recorded when the owner accepted the change (Amendment.plan_sha256)
   or a later plan_revised hash, plus "the plan file has no unrevised edits".
   `--settle` may ride the same revise as `--plan/--incorporates` and binds
   to the revision's hash. Settling the last amendment after a reopen leaves
   the run `running` (the reopened phases rerun) instead of approving it.
   NEXT and PLAN_AMEND_PENDING list the settle step before the edit step.
7. A title association alone no longer confirms: the same remedy confirms,
   opposite remedies (one keeps, drops or negates what the other changes)
   disagree, different or missing remedies stay `unverified`. The pairing
   fixture gains same-title negative controls (opposite and different
   remedies) and a same-remedy positive, for ordinary findings and user
   challenges.
8. A gate.json without rec_rev (written by 1.91.101.0, whose render said
   `all` leaves b items pending) refuses rec/all/approve all/`all except`
   with GATE_REC_STALE until a re-render binds --rec-hash; explicit tokens
   still answer. New gates carry rec_rev: 0.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix(autoplan): checkpoints never touch the live run; generations, newest-valid restore, validated staging (integration items 2-6)

2. checkpointRun canonicalizes the collection and the run directory (symlinks
   resolved through the deepest existing ancestor) and refuses, before
   touching anything, when they are the same or one contains the other
   (CHECKPOINT_OVERLAP); restore applies the same check to source, target and
   staging. Before, <root>/<run> equal to the live run replaced it.
3. Publication writes an immutable generation (generations/g<revision>-…),
   renames it into place complete, then switches current.json with one
   rename; the previous generation is kept, so an interruption at the publish
   boundary (fault hook checkpoint-before-pointer) leaves the last checkpoint
   current. A generation never replaces a newer one (higher run revision):
   "CHECKPOINT: skipped … newer". Publication and restore hold the
   collection's .lock; restore also holds <out>.lock.
4. Restore checks every listed file's real path stays inside the generation
   (an ancestor symlink no longer copies outside files), parses run.json and
   runs validateRun on the staged run before publishing; a refusal leaves
   --out absent. readState reroots plan_input and plan_source for moved runs,
   and a restore with the owner's plan file gone points both at the restored
   copy, so a second restore cycle and a later revise work.
5. A checkpoint failure after a committed command prints
   "CHECKPOINT: failed for <run>: … ; the command's result stands" on stderr
   and keeps the command's exit code.
6. `gstack-autoplan checkpoints --from <dir>` lists generations newest first
   (run, gate_rev, status, revision, time, hash ok|bad, current).
   `resume --from <collection or root>` restores the newest generation that
   verifies, printing each corrupt newer one it skipped; a root holding
   several runs must name one.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* chore: budget the Capy skill's autoplan checklist and trim its install notes

Files: capy/skill/gstack/SKILL.md, test/fixtures/context-budget.json (capy/skill/gstack ceiling only: 2364 tok x 1.10)
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* chore: release 1.91.102.0 (tentative stamp) — GBRA-40 field list

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* test: supply _setup_ready_line to setup-tail harnesses, register the pairing fixture, make the admission test runner-Bun independent; announce shim writes

Files: test/setup-hook-syntax-gate.test.ts, test/redact-prepush-hook.test.ts, test/setup-playwright-best-effort.test.ts, test/helpers/free-fixtures-data.ts, test/pregate-guards.test.ts, bin/gstack-capy-install
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* ci: run quick-bun-default on the ubicloud-standard-8 class the free suite uses

The ubuntu-24.04 runner timed out two Swift typecheck tests at 30 s (render @Observable marker, ios-qa-regen); both pass on Bun 1.4.3 on Ubicloud.

Files: .github/workflows/free-tests.yml
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix(pregate): read bun test's GitHub Actions group headers; exclude pregate-remote from the Windows subset; give quick-bun-default the free suite's flake policy

Files: lib/pregate/supervise.ts, test/pregate-supervise.test.ts, scripts/lib/windows-curation.ts, .github/workflows/free-tests.yml
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* test: run the Capy wrapper and shim doctor-row tests on POSIX only (Git Bash prints MSYS paths)

Files: test/gstack-doctor.test.ts
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* chore: restamp 1.91.107.0 (1.91.106.0 is claimed by #3209)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix(pregate): spawn the supervised shell through lib/script-invocation (#3197 tripwire)

The supervisor now resolves bash via bashCommandInvocation, so Windows uses
Git Bash instead of a PATH bash, and an unresolvable bash reports spawn-failed.
guards.ts and lanes.ts no longer spawn bash (they run through supervise.ts),
so their KNOWN_SITES entries are removed.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* test(qa-functional): disable auto gc and maintenance in the fixture repo

On eval-slices (9), qa-functional-webhook-fix failed mid-run with 100+
'directory watch lost: .git/objects/..' entries and forbidden writes to
.git/info/refs and .git/objects/pack. That is git's detached auto
maintenance repacking the fixture under the write observer. This applies the
same gc.auto=0 / maintenance.auto=false config qa-callers-fixture uses.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* test(autoplan-guard-pty): say Phase 2 starts without waiting for user input

On eval-slices (1), haiku published Phase 1 and then ended its turn with
'Waiting for next invocation to continue with step 8'. Step 5 tells it to end
its turn while the reviewer runs, so step 8's 'In a later message' read as a
later user turn. Phase 2 never started, the guard logged 2 of the 4 expected
allows, and the run hit its deadline. Step 8 now says to continue in the next
assistant message, still separate from the step 7 publication message.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

---------

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
2026-10-16 23:09:23 +00:00

893 lines
54 KiB
TypeScript

/**
* gstack-doctor: one row per readiness check, each ok / warn / not configured
* / fail with a fix line when not ok; only fail makes the exit non-zero; fix
* lines name helpers by absolute install-root path; the paid Codex model probe
* runs only with --live. Also pins the `./setup --status` Codex row and its
* trailing doctor path. Every run uses a fixture install root (copies of the
* real helpers plus a stub gstack-codex-probe), a fixture state root, stub
* bun/codex/claude on PATH and an explicit HOME. Scripts run through explicit
* bash argv, so the file is in the curated Windows lane.
*/
import { afterEach, describe, expect, test } from 'bun:test';
import { spawnSync } from 'child_process';
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
// setup builds browse/dist/browse.exe on Windows (Git Bash), browse/dist/browse elsewhere.
const BROWSE_BIN = process.platform === 'win32' ? 'browse/dist/browse.exe' : 'browse/dist/browse';
const EXE = process.platform === 'win32' ? '.exe' : '';
const OTHER_BINS = ['browse/dist/find-browse', 'design/dist/design', 'make-pdf/dist/pdf', 'bin/gstack-global-discover'].map(rel => rel + EXE);
const REPO = path.resolve(import.meta.dir, '..');
const COPIED = [
'setup', 'VERSION',
'bin/gstack-doctor', 'bin/gstack-codex-status.sh', 'bin/gstack-state-root.sh', 'bin/gstack-install-registry.sh',
'bin/gstack-render-claude.sh', 'bin/gstack-bun-version.sh', 'bin/gstack-hook-check', 'bin/gstack-config',
'autoplan/SKILL.md', // its frontmatter registers the autoplan hook the hooks-row test breaks
'bin/gstack-launch-probe.sh',
'bin/gstack-doctor-check.sh', 'bin/gstack-doctor-components.sh', 'bin/gstack-runtime-pins.ts', 'lib/runtime-pins.ts',
];
const bases: string[] = [];
afterEach(() => { for (const b of bases.splice(0)) fs.rmSync(b, { recursive: true, force: true }); });
const write = (file: string, text: string, mode = 0o644) => {
fs.mkdirSync(path.dirname(file), { recursive: true });
fs.writeFileSync(file, text, { mode });
};
const script = (file: string, lines: string[]) => write(file, ['#!/usr/bin/env bash', ...lines].join('\n') + '\n', 0o755);
/** The fixture's PATH entries minus every directory holding a real bun, codex or claude. */
function hostPath(base: string): string {
const names = ['bun', 'codex', 'claude'];
const exts = process.platform === 'win32' ? ['', '.exe', '.cmd', '.ps1'] : [''];
return (process.env.PATH ?? process.env.Path ?? '').split(path.delimiter).filter(Boolean).map((dir, i) => {
if (!names.some(n => exts.some(e => fs.existsSync(path.join(dir, n + e))))) return dir;
const shim = path.join(base, `host-${i}`);
fs.mkdirSync(shim, { recursive: true });
for (const name of fs.readdirSync(dir)) {
if (names.some(n => exts.some(e => name === n + e))) continue;
try { fs.symlinkSync(path.join(dir, name), path.join(shim, name)); } catch { /* unreadable entry */ }
}
return shim;
}).join(path.delimiter);
}
interface Fixture { base: string; root: string; state: string; home: string; work: string; stub: string; probeLog: string; env: Record<string, string> }
function makeFixture(): Fixture {
const base = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-doctor-')));
bases.push(base);
const root = path.join(base, 'gstack');
const state = path.join(base, 'state');
const home = path.join(base, 'home');
const work = path.join(base, 'work');
const stub = path.join(base, 'stub');
const probeLog = path.join(base, 'probe-calls');
for (const dir of [state, home, work, stub]) fs.mkdirSync(dir, { recursive: true });
for (const rel of COPIED) {
fs.mkdirSync(path.dirname(path.join(root, rel)), { recursive: true });
fs.copyFileSync(path.join(REPO, rel), path.join(root, rel));
fs.chmodSync(path.join(root, rel), fs.statSync(path.join(REPO, rel)).mode);
}
script(path.join(root, 'bin/gstack-codex-probe'), [
'echo "$*" >> "$DOCTOR_PROBE_LOG"',
'case "$1" in',
' select-model) [ "${STUB_SELECT_FAIL:-}" = 1 ] && { echo "gstack-codex-probe: cannot find its scripts dir" >&2; exit 1; }',
' echo "CODEX_SEL: gpt-stub-5"; echo "CODEX_SEL_KIND: $2"; echo "CODEX_MODEL: gpt-stub-5 ($2; source: codex config.toml)" >&2 ;;',
' check-auth) [ "${STUB_AUTH_FAIL:-}" = 1 ] && { echo AUTH_FAILED; exit 1; }; echo AUTH_OK ;;',
' show-sandbox) echo "CODEX_SANDBOX: read-only" ;;',
' check-sandbox|check-version) ;;',
' probe-model) echo "CODEX_PROBE_STATE: ${STUB_PROBE_STATE:-ok}"; exit "${STUB_PROBE_EXIT:-0}" ;;',
' *) exit 64 ;;',
'esac',
]);
const listed = spawnSync('bash', [path.join(root, 'bin/gstack-hook-check'), '--list', root], { encoding: 'utf8', timeout: 20_000 });
const hooks = listed.stdout.split('\n').map(line => line.trim()).filter(Boolean);
if (!hooks.includes('autoplan/bin/phase-publication-hook')) throw new Error(`gstack-hook-check --list missed the autoplan hook: ${listed.stdout}${listed.stderr}`);
for (const hook of hooks) write(path.join(root, hook), '#!/bin/sh\nexit 0\n', 0o755);
// The doctor launches each compiled binary's --version (#2595), so the
// stand-ins answer it like the real binaries do.
for (const rel of [BROWSE_BIN, ...OTHER_BINS]) write(path.join(root, rel), '#!/bin/sh\necho built\n', 0o755);
for (const rel of ['browse/dist/server-node.mjs', 'browse/dist/.build-complete']) write(path.join(root, rel), 'built\n', 0o755);
const version = fs.readFileSync(path.join(root, 'VERSION'), 'utf8').trim();
write(path.join(state, 'installs.tsv'),
['claude', 'global', '-', path.join(home, '.claude/skills'), root, root, version, 'false', 'committed', '2026-10-07T00:00:00Z'].join('\t') + '\n');
// The stub answers --version; anything else (the pins row runs bin/gstack-runtime-pins.ts) goes to the real bun.
script(path.join(stub, 'bun'), ['[ "$1" = --version ] && { echo "${STUB_BUN_VERSION:-1.4.2}"; exit 0; }', `exec "${process.execPath}" "$@"`]);
script(path.join(stub, 'codex'), ['[ "$1" = --version ] && { echo "codex-cli 0.130.0"; exit 0; }', 'echo "unexpected codex call: $*" >> "$DOCTOR_PROBE_LOG"', 'exit 9']);
script(path.join(stub, 'claude'), ['[ "$1" = --version ] && { echo "2.1.292 (Claude Code)"; exit 0; }', 'exit 9']);
const env: Record<string, string> = {
PATH: [stub, hostPath(base)].join(path.delimiter),
HOME: home, GSTACK_STATE_ROOT: state, TMPDIR: base, DOCTOR_PROBE_LOG: probeLog,
};
if (process.env.SYSTEMROOT) env.SYSTEMROOT = process.env.SYSTEMROOT;
return { base, root, state, home, work, stub, probeLog, env };
}
function doctor(f: Fixture, args: string[] = [], extra: Record<string, string> = {}) {
const r = spawnSync('bash', [path.join(f.root, 'bin/gstack-doctor'), ...args], { cwd: f.work, encoding: 'utf8', env: { ...f.env, ...extra }, timeout: 60_000 });
const out = `${r.stdout}${r.stderr}`;
return { status: r.status, out, row: (name: string) => rowOf(r.stdout, name) };
}
/** The named row and its fix line: { state, detail, fix }. */
function rowOf(stdout: string, name: string) {
const lines = stdout.split('\n');
const i = lines.findIndex(l => l.slice(16, 32).trim() === name);
if (i < 0) throw new Error(`no row "${name}" in:\n${stdout}`);
const fix = lines[i + 1]?.startsWith(' '.repeat(32) + 'fix: ') ? lines[i + 1].slice(37) : '';
return { state: lines[i].slice(0, 16).trim(), detail: lines[i].slice(32), fix };
}
/** How bash spells a directory (Git Bash on Windows prints /c/...). */
const bashPath = (dir: string) => spawnSync('bash', ['-c', 'cd "$1" && pwd', '_', dir], { encoding: 'utf8', timeout: 10_000 }).stdout.trim();
const probeCalls = (f: Fixture) => fs.existsSync(f.probeLog) ? fs.readFileSync(f.probeLog, 'utf8') : '';
const iso = (secondsAgo: number) => new Date(Date.now() - secondsAgo * 1000).toISOString().replace(/\.\d+Z$/, 'Z');
const syncOn = (f: Fixture, status: Record<string, unknown>) => {
fs.mkdirSync(path.join(f.state, '.git'), { recursive: true });
write(path.join(f.state, 'config.yaml'), 'artifacts_sync_mode: artifacts-only\n');
write(path.join(f.state, '.brain-sync-status.json'), JSON.stringify(status).replace(/":/g, '": ').replace(/,"/g, ', "') + '\n');
};
describe('gstack-doctor', () => {
test('a healthy fixture: every core row ok, exit 0, and no paid probe', () => {
const f = makeFixture();
const r = doctor(f);
expect(r.status, r.out).toBe(0);
for (const name of ['install root', 'state root', 'bun', 'hooks', 'browse bundle']) expect(r.row(name).state, `${name}\n${r.out}`).toBe('ok');
expect(r.row('install root').detail).toContain('claude global current');
expect(r.row('state root').detail).toContain('GSTACK_STATE_ROOT');
expect(r.row('bun').detail).toContain('1.4.2');
expect(r.row('codex').state).toBe('ok');
expect(r.row('codex').detail).toContain('gpt-stub-5 (source: codex config.toml)');
expect(r.row('codex probe').state).toBe('warn');
expect(r.row('codex probe').detail).toContain('not probed');
expect(r.row('codex probe').fix).toBe(`${bashPath(f.root)}/bin/gstack-doctor --live (one short paid Codex call)`);
expect(r.row('artifacts sync').state).toBe('not configured');
expect(r.row('claude code').detail).toContain('2.1.292');
expect(r.row('guard log').detail).toBe('no guard decisions logged');
expect(probeCalls(f)).not.toContain('probe-model');
expect(probeCalls(f)).toContain('select-model exec');
expect(r.out).toMatch(/\d+ ok, \d+ warn, \d+ not configured, 0 fail/);
});
test('each DX-8 state appears, and only fail makes the exit non-zero', () => {
const f = makeFixture();
const warn = doctor(f, [], { STUB_BUN_VERSION: '1.4.0' });
expect(warn.row('bun').state).toBe('warn');
expect(warn.row('bun').fix).toContain('bun upgrade');
expect(warn.status, warn.out).toBe(0);
write(path.join(f.state, 'config.yaml'), 'codex_reviews: disabled\n');
const off = doctor(f);
expect(off.row('codex').state).toBe('not configured');
expect(off.row('codex').detail).toContain('outside reviews in /review, /ship, /autoplan and /codex');
expect(off.row('codex').fix).toBe(`${bashPath(f.root)}/bin/gstack-config set codex_reviews enabled`);
expect(off.status, off.out).toBe(0);
expect(probeCalls(f)).not.toContain('probe-model');
const fail = doctor(f, [], { STUB_BUN_VERSION: '1.3.2' });
expect(fail.row('bun').state).toBe('fail');
expect(fail.row('bun').fix).toContain('bun upgrade');
expect(fail.status, fail.out).toBe(1);
expect(fail.out).toMatch(/, 1 fail/);
});
test('Codex: absent CLI is not configured, unauthenticated warns, a failed self-locate fails', () => {
const f = makeFixture();
fs.rmSync(path.join(f.stub, 'codex'));
const absent = doctor(f);
expect(absent.row('codex').state).toBe('not configured');
expect(absent.row('codex').detail).toContain('Codex CLI not installed');
expect(absent.row('codex').fix).toContain('npm install -g @openai/codex');
expect(absent.status).toBe(0);
const g = makeFixture();
const unauthed = doctor(g, [], { STUB_AUTH_FAIL: '1' });
expect(unauthed.row('codex').state).toBe('warn');
expect(unauthed.row('codex').detail).toContain('not_authed');
expect(unauthed.row('codex').fix).toContain('codex login');
expect(unauthed.status).toBe(0);
const broken = doctor(g, [], { STUB_SELECT_FAIL: '1' });
expect(broken.row('codex').state).toBe('fail');
expect(broken.row('codex').detail).toContain('helper_unavailable');
expect(broken.row('codex').fix).toContain(`${bashPath(g.root)}/bin/gstack-codex-probe select-model exec`);
expect(broken.status).toBe(1);
});
test('the cached probe is reported with its age and is never re-run without --live', () => {
const f = makeFixture();
const now = Math.floor(Date.now() / 1000);
write(path.join(f.state, '.codex-model-probe'), `MODEL_OK ${now - 7300} 123456789\n`);
const cached = doctor(f);
expect(cached.row('codex probe').state).toBe('ok');
expect(cached.row('codex probe').detail).toBe('cached MODEL_OK, 2h ago (not re-run; --live probes now)');
write(path.join(f.state, '.codex-model-probe'), `MODEL_QUOTA_EXHAUSTED ${now - 125} 123456789\nCodex says: try again at 5pm sk-should-not-print\n`);
const quota = doctor(f);
expect(quota.row('codex probe').state).toBe('warn');
expect(quota.row('codex probe').detail).toContain('cached MODEL_QUOTA_EXHAUSTED, 2m ago');
expect(quota.out).not.toContain('sk-should-not-print');
write(path.join(f.state, '.codex-model-probe'), `$(rm -rf ~) ${now} x\n`);
expect(doctor(f).row('codex probe').detail).toContain('unrecognized');
expect(probeCalls(f)).not.toContain('probe-model');
});
test('--live runs probe-model once and maps its exit to the codex probe row', () => {
const f = makeFixture();
const live = doctor(f, ['--live']);
expect(probeCalls(f).match(/probe-model exec/g)?.length).toBe(1);
expect(live.row('codex probe').state).toBe('ok');
expect(live.row('codex probe').detail).toContain('live probe: ok');
const unusable = doctor(f, ['--live'], { STUB_PROBE_EXIT: '1', STUB_PROBE_STATE: 'model_unusable' });
expect(unusable.row('codex probe').state).toBe('warn');
expect(unusable.row('codex probe').detail).toContain('model_unusable');
const brokenInstall = doctor(f, ['--live'], { STUB_PROBE_EXIT: '2', STUB_PROBE_STATE: 'broken_install' });
expect(brokenInstall.row('codex probe').state).toBe('fail');
expect(brokenInstall.status).toBe(1);
});
test('a hook shim that does not parse fails the hooks row', () => {
const f = makeFixture();
write(path.join(f.root, 'autoplan/bin/phase-publication-hook'), '#!/bin/sh\nif then\n', 0o755);
const r = doctor(f);
expect(r.row('hooks').state).toBe('fail');
expect(r.row('hooks').detail).toContain('autoplan/bin/phase-publication-hook');
expect(r.row('hooks').fix).toContain('./setup');
expect(r.status).toBe(1);
});
test('artifacts sync: a hostile status clamps to unknown and is never echoed', () => {
const f = makeFixture();
syncOn(f, { status: 'AKIAIOSFODNN7EXAMPLE leaked', message: 'blocked: AKIAIOSFODNN7EXAMPLE in /secret/path.md', ts: iso(10) });
const r = doctor(f);
expect(r.row('artifacts sync').state).toBe('warn');
expect(r.row('artifacts sync').detail).toBe('status unknown');
expect(r.row('artifacts sync').fix).toBe(`${bashPath(f.root)}/bin/gstack-brain-sync --status`);
expect(r.out).not.toContain('AKIA');
expect(r.out).not.toContain('/secret/path.md');
expect(r.out).not.toContain('.brain-sync-status.json');
});
test('artifacts sync: held, then ok', () => {
const f = makeFixture();
syncOn(f, { status: 'held', message: 'held 2 file(s): sk-ant-secret', held_count: 2, held: [{ path: 'projects/p/notes.md', rule: 'anthropic_key', dependents: [], fixes: ['edit', 'skip'] }, { path: 'projects/p/b.md', rule: 'anthropic_key', dependents: [], fixes: ['edit', 'skip'] }], drainable: 0, last_drain_at: iso(60), last_push_at: iso(60) });
const held = doctor(f);
expect(held.row('artifacts sync').state).toBe('warn');
expect(held.row('artifacts sync').detail).toBe('status held (2 file(s) held by the secret scanner)');
expect(held.out).not.toContain('sk-ant');
syncOn(f, { status: 'ok', message: 'pushed 3 file(s)', drainable: 0, last_drain_at: iso(60), last_push_at: iso(60) });
expect(doctor(f).row('artifacts sync').state).toBe('ok');
});
test('artifacts sync: stale push and stale drain warn, a fresh push clears them', () => {
const f = makeFixture();
syncOn(f, { status: 'ok', message: 'x', drainable: 4, last_drain_at: iso(60), last_push_at: iso(90_000) });
const stalePush = doctor(f).row('artifacts sync');
expect(stalePush.state).toBe('warn');
expect(stalePush.detail).toContain('no push for 24h while 4 record(s) wait');
write(path.join(f.state, '.brain-queue.d/1-1-a.json'), '{}\n');
syncOn(f, { status: 'idle', message: 'x', drainable: 0, last_drain_at: iso(200_000), last_push_at: iso(60) });
const staleDrain = doctor(f).row('artifacts sync');
expect(staleDrain.state).toBe('warn');
expect(staleDrain.detail).toContain('no drain for 24h while 1 record(s) are queued');
syncOn(f, { status: 'ok', message: 'pushed' });
expect(doctor(f).row('artifacts sync').state).toBe('ok');
});
test('triage rows: Claude Code absent, largest journal, last five schema-1 guard codes', () => {
const f = makeFixture();
fs.rmSync(path.join(f.stub, 'claude'));
expect(doctor(f).row('claude code').state).toBe('not configured');
expect(doctor(f).row('session journal').detail).toBe('no session journals for this project');
const cwd = process.platform === 'win32'
? spawnSync('bash', ['-c', 'pwd -W'], { cwd: f.work, encoding: 'utf8', timeout: 10_000 }).stdout.trim()
: f.work;
const project = path.join(f.home, '.claude/projects', cwd.replace(/[^A-Za-z0-9]/g, '-'));
write(path.join(project, 'a.jsonl'), 'x'.repeat(1000));
write(path.join(project, 'b.jsonl'), 'x'.repeat(3 * 1024 * 1024));
const journal = doctor(f).row('session journal');
expect(journal.state).toBe('ok');
expect(journal.detail).toBe('largest of 2: 3.0 MiB');
const line = (schema: unknown, code: string | null, decision = 'deny') =>
JSON.stringify({ schema, ts: '2026-10-07T00:00:00Z', decision, ...(code ? { reason_code: code } : {}), path: 'journal', cc_version: '2.1.292', disposition: 'hard' });
write(path.join(f.state, 'analytics/autoplan-guard.jsonl'), [
line(1, 'code_one'), line(2, 'future_schema'), line(1, 'code_two'), line(1, null, 'allow'), 'not json',
line(1, 'code_three'), line(1, 'code_four'), line('1', 'string_schema'), line(1, 'code_five'), line(1, 'code_six'),
].join('\n') + '\n');
const guard = doctor(f).row('guard log');
expect(guard.state).toBe('ok');
expect(guard.detail).toBe('7 decisions (6 denied); last codes: code_two, code_three, code_four, code_five, code_six');
});
test('every fix line names gstack helpers by absolute install-root path', () => {
const f = makeFixture();
write(path.join(f.state, 'config.yaml'), 'codex_reviews: disabled\n');
fs.rmSync(path.join(f.root, BROWSE_BIN));
const other = path.join(f.base, 'other');
write(path.join(f.state, 'installs.tsv'), ['codex', 'global', '-', path.join(f.home, '.codex/skills'), other, other, '1', 'false', 'committed', 'x'].join('\t') + '\n');
const r = doctor(f, [], { STUB_BUN_VERSION: '1.3.2' });
const fixes = r.out.split('\n').filter(l => l.trimStart().startsWith('fix: '));
expect(fixes.length).toBeGreaterThanOrEqual(5);
expect(r.row('install root').fix).toContain(`${other}/bin/gstack-doctor`);
const bin = `${bashPath(f.root)}/bin/`;
for (const fix of fixes) {
const scrubbed = fix.split(bin).join('<BIN>/').split(`${other}/bin/`).join('<OTHER>/').split(bashPath(f.base)).join('<BASE>');
for (const m of scrubbed.matchAll(/gstack-[a-z]/g)) expect(/<(BIN|OTHER)>\/$/.test(scrubbed.slice(0, m.index)), fix).toBe(true);
}
expect(r.row('browse bundle').state).toBe('warn');
expect(r.row('browse bundle').detail).toContain('/browse, /qa, /qa-only, /design-review, /make-pdf, /pair-agent');
});
test('usage errors exit 2', () => {
const f = makeFixture();
expect(doctor(f, ['--bogus']).status).toBe(2);
const help = doctor(f, ['--help']);
expect(help.status).toBe(0);
expect(help.out).toContain('--live');
});
});
describe('./setup --status Codex row', () => {
const status = (f: Fixture) => spawnSync('bash', [path.join(f.root, 'setup'), '--status'], { cwd: f.work, encoding: 'utf8', env: f.env, timeout: 60_000 });
test('reports install, version, codex_reviews and the cached probe, then ends with the doctor path', () => {
const f = makeFixture();
write(path.join(f.state, '.codex-model-probe'), `MODEL_UNUSABLE ${Math.floor(Date.now() / 1000) - 600} 1\n`);
const r = status(f);
expect(r.status, r.stderr).toBe(0);
expect(r.stdout).toContain('Codex: installed (codex-cli 0.130.0); codex_reviews=enabled; model probe: MODEL_UNUSABLE 10m ago');
expect(r.stdout.trimEnd().split('\n').at(-1)).toBe(`Readiness check: ${bashPath(f.root)}/bin/gstack-doctor`);
expect(probeCalls(f)).toBe('');
});
test('without Codex the row says so, and nothing is written', () => {
const f = makeFixture();
fs.rmSync(path.join(f.stub, 'codex'));
write(path.join(f.state, 'config.yaml'), 'codex_reviews: disabled\n');
const before = fs.readdirSync(f.state).sort();
const r = status(f);
expect(r.stdout).toContain('Codex: not installed (codex_reviews=disabled;');
expect(fs.readdirSync(f.state).sort()).toEqual(before);
});
});
describe('bug-report template and README (DX-2, DX-12)', () => {
const template = fs.readFileSync(path.join(REPO, '.github/ISSUE_TEMPLATE/bug_report.md'), 'utf8');
test('the template asks for the doctor output with the Claude Code path and a lookup for other hosts', () => {
expect(template).toContain('~/.claude/skills/gstack/bin/gstack-doctor');
expect(template).toContain('./setup --status');
expect(template).toContain('/bin/gstack-paths --get GSTACK_STATE_ROOT');
});
test('the template names no bare gstack- command', () => {
for (const m of template.matchAll(/gstack-[a-z]/g)) expect(template.slice(0, m.index).endsWith('/bin/'), template.slice(m.index! - 40, m.index! + 20)).toBe(true);
});
test('README troubleshooting points at the doctor by absolute path', () => {
const readme = fs.readFileSync(path.join(REPO, 'README.md'), 'utf8');
const section = readme.slice(readme.indexOf('## Troubleshooting'));
expect(section).toContain('`~/.claude/skills/gstack/bin/gstack-doctor`');
});
});
// #2595/#2124 and #3071: compiled binaries by launch state, and CSO from the
// build-result record. A blocked binary is simulated by the application-control
// message reporters captured (#2595), which works on every OS.
describe('gstack-doctor launch and CSO rows', () => {
const BLOCKED = `#!/bin/sh\necho "Program 'x.exe' failed to run: An Application Control policy has blocked this file" >&2\nexit 1\n`;
const record = (f: Fixture, text: string) => write(path.join(f.root, 'bin/.gstack-cso-build-result'), text);
const cso = (f: Fixture) => { for (const name of ['gstack-cso-launcher', 'gstack-cso-core']) write(path.join(f.root, 'bin', name + EXE), '#!/bin/sh\necho cso\n', 0o755); };
test('healthy binaries are ok; a blocked browse says blocked, not "not built"', () => {
const f = makeFixture();
let r = doctor(f);
expect(r.row('binaries').state).toBe('ok');
expect(r.row('binaries').detail).toContain('(4 of 4)');
write(path.join(f.root, BROWSE_BIN), BLOCKED, 0o755);
r = doctor(f);
expect(r.row('browse bundle').state).toBe('warn');
expect(r.row('browse bundle').detail).toContain('built, but blocked at launch (Program');
expect(r.row('browse bundle').detail).not.toContain('not built');
expect(r.row('browse bundle').fix).toContain(process.platform === 'win32' ? 'Smart App Control' : 'the OS refused to execute it');
expect(r.status).toBe(0);
});
test('blocked, broken and missing binaries are told apart', () => {
const f = makeFixture();
write(path.join(f.root, OTHER_BINS[1]), BLOCKED, 0o755);
let r = doctor(f);
expect(r.row('binaries').detail).toContain('blocked at launch: design');
expect(r.row('binaries').detail).toContain('unavailable: /design-consultation');
write(path.join(f.root, OTHER_BINS[1]), '#!/bin/sh\necho ok\n', 0o755);
write(path.join(f.root, OTHER_BINS[2]), '#!/bin/sh\necho "usage" >&2\nexit 2\n', 0o755);
r = doctor(f);
expect(r.row('binaries').detail).toBe('launched but failed: pdf (exit 2: usage)');
expect(r.row('binaries').fix).toBe(`cd ${bashPath(f.root)} && bun run build`);
fs.rmSync(path.join(f.root, OTHER_BINS[2]));
r = doctor(f);
expect(r.row('binaries').detail).toBe('not built: pdf');
});
test('the CSO row reads the build-result record', () => {
const f = makeFixture();
const none = doctor(f).row('cso');
expect(none.state).toBe('not configured');
expect(none.detail).toBe('native helper not built; /cso reports not assessed');
expect(none.fix).toContain('./setup (it names any missing build prerequisite)');
record(f, 'result=failed\nstage=build\nreason=exit 42\nrevision=1.2 (abc)\ninstalled=\nlauncher=no\ndiagnostic=/x/cso.log\n');
let r = doctor(f);
expect(r.row('cso').state).toBe('warn');
expect(r.row('cso').detail).toBe('unavailable: the build step failed (exit 42); /cso reports not assessed');
expect(r.row('cso').fix).toContain('bun run build:cso && ./setup (log: /x/cso.log;');
cso(f);
record(f, 'result=failed\nstage=publish\nreason=exit 1\nrevision=1.2 (abc)\ninstalled=1.1 (def)\nlauncher=yes\ndiagnostic=/x/cso.log\n');
expect(doctor(f).row('cso').detail).toBe('publish step failed (exit 1) for 1.2 (abc); previous CSO kept: 1.1 (def)');
record(f, 'result=ok\nstage=publish\nreason=committed\nrevision=1.2 (abc)\ninstalled=1.2 (abc)\nlauncher=yes\ndiagnostic=x\n');
r = doctor(f);
expect(r.row('cso')).toEqual({ state: 'ok', detail: 'native helper 1.2 (abc)', fix: '' });
expect(r.status).toBe(0);
});
});
// A1: `--check` is the one-line verdict a parent agent greps. Rows are
// `PASS | FAIL | SKIP <id>` from lib/doctor-components.ts; the trailer is
// `gstack: ok <revision> for=<what>` (exit 0) or `gstack: fail <ids>` (exit 1).
// Pinned on tokens, ids, exit codes and the JSON shape, not prose.
describe('gstack-doctor --check', () => {
const VERSION = fs.readFileSync(path.join(REPO, 'VERSION'), 'utf8').trim();
const row = (f: Fixture, args: string[], extra: Record<string, string> = {}) => {
const r = doctor(f, ['--check', ...args], extra);
const lines = r.out.split('\n');
const rows = Object.fromEntries(lines.filter(l => /^(PASS|FAIL|SKIP) /.test(l)).map(l => {
const m = l.match(/^(PASS|FAIL|SKIP) ([a-z-]+)(?:\s(.*))?$/)!;
return [m[2], { status: m[1], rest: m[3] ?? '' }];
}));
const trailer = lines.filter(l => l.startsWith('gstack: ')).at(-1) ?? '';
const required = lines.find(l => l.startsWith('required: '))?.slice(10).split(' ') ?? [];
return { status: r.status, out: r.out, rows, trailer, required, trailers: lines.filter(l => l.startsWith('gstack: ')).length };
};
/** Register a Codex install from this checkout and render a review skill, with or without the Astra patch. */
const installCodex = (f: Fixture, patch = true) => {
const dest = path.join(f.home, '.codex/skills');
fs.appendFileSync(path.join(f.state, 'installs.tsv'),
['codex', 'global', '-', dest, path.join(dest, 'gstack'), f.root, VERSION, 'true', 'committed', '2026-10-07T00:00:00Z'].join('\t') + '\n');
fs.mkdirSync(path.join(dest, 'gstack'), { recursive: true });
write(path.join(dest, 'gstack-review/SKILL.md'), `---\nname: gstack-review\n---\n# Review\n${patch ? '\n## Model-Specific Behavioral Patch (gpt-6-astra)\n' : ''}`);
return dest;
};
const installPlaywrightStub = (f: Fixture, launches: boolean) => write(path.join(f.root, 'node_modules/playwright/index.js'),
launches
? 'module.exports.chromium = { launch: async () => ({ version: () => "141.0.1", close: async () => {}, newPage: async () => ({ setContent: async () => {}, title: async () => "gstack smoke test" }) }) };'
: 'module.exports.chromium = { launch: async () => { throw new Error("browserType.launch: Executable doesn\'t exist"); } };');
test('healthy Claude + Codex installs: every required row PASS, exactly one trailer, exit 0, no paid probe', () => {
const f = makeFixture();
installCodex(f);
const r = row(f, []);
expect(r.status, r.out).toBe(0);
expect(r.required).toEqual(['claude', 'codex', 'runtime', 'pins', 'state-root', 'privacy', 'cores', 'revision', 'wrapper']);
for (const id of r.required.filter(x => x !== 'pins' && x !== 'wrapper')) expect(r.rows[id]?.status, `${id}\n${r.out}`).toBe('PASS');
// The work dir is not a git repository, so there is no project to read pins from: SKIP with the reason, never silent.
expect(r.rows.pins).toEqual({ status: 'SKIP', rest: expect.stringContaining('no project') });
// No ~/.capy/drive skill copy and no active wrapper: not a Capy machine.
expect(r.rows.wrapper).toEqual({ status: 'SKIP', rest: expect.stringContaining('not a Capy machine') });
expect(r.rows.patch.status).toBe('PASS');
expect(r.rows['codex-cli'].status).toBe('PASS');
expect(r.rows.browser).toEqual({ status: 'SKIP', rest: '(lazy; gstack-browser-ensure installs on first use)' });
expect(r.rows.cso.status).toBe('SKIP');
expect(r.trailer).toBe(`gstack: ok ${VERSION} for=installed-hosts:claude,codex`);
expect(r.trailers).toBe(1);
expect(r.rows.runtime.rest).toContain('floor 1.3.3, supported minimum 1.4.2');
expect(r.rows.privacy.rest).toBe('telemetry=off artifacts_sync=off codex_reviews=enabled update_check=true');
expect(r.rows['state-root'].rest).toContain('durable=yes');
expect(probeCalls(f)).not.toContain('probe-model');
});
test('--for autoplan: healthy Capy machine with Claude subagents as the outside voice and no Codex CLI passes', () => {
const f = makeFixture();
installCodex(f);
fs.rmSync(path.join(f.stub, 'codex'));
const r = row(f, ['--for', 'autoplan']);
expect(r.status, r.out).toBe(0);
expect(r.required).toEqual(['claude', 'codex', 'patch', 'runtime', 'pins', 'state-root', 'privacy', 'cores', 'revision', 'wrapper']);
expect(r.rows.patch).toEqual({ status: 'PASS', rest: 'gpt-6-astra (gstack-review/SKILL.md)' });
expect(r.rows['codex-cli'].status).toBe('SKIP');
expect(r.rows['codex-cli'].rest).toContain('optional');
expect(r.trailer).toBe(`gstack: ok ${VERSION} for=autoplan`);
// The same machine with a stale Codex render fails the patch row.
installCodex(f, false);
const noPatch = row(f, ['--for', 'autoplan']);
expect(noPatch.status).toBe(1);
expect(noPatch.rows.patch.status).toBe('FAIL');
expect(noPatch.rows.patch.rest).toContain('fix: ');
expect(noPatch.rows.patch.rest).toContain('(COMPONENT_MISSING; ');
expect(noPatch.rows.patch.rest).toContain('--host codex --model');
expect(noPatch.trailer).toBe('gstack: fail patch');
});
test('an empty installed-host set is never ok: claude is required and FAILs', () => {
const f = makeFixture();
write(path.join(f.state, 'installs.tsv'), '');
const r = row(f, []);
expect(r.status).toBe(1);
expect(r.required).toContain('claude');
expect(r.rows.claude.status).toBe('FAIL');
expect(r.rows.claude.rest).toContain(`fix: cd ${bashPath(f.root)} && ./setup --host claude --no-prefix`);
expect(r.trailer).toBe('gstack: fail claude');
expect(JSON.parse(doctor(f, ['--json']).out).for).toBe('installed-hosts:none(claude required)');
});
test('wrong host: an install registered from another checkout does not count; --require names what is missing', () => {
const f = makeFixture();
const other = path.join(f.base, 'other');
write(path.join(f.state, 'installs.tsv'), ['codex', 'global', '-', path.join(f.home, '.codex/skills'), other, other, VERSION, 'false', 'committed', 'x'].join('\t') + '\n');
const r = row(f, ['--require', 'codex,patch']);
expect(r.status).toBe(1);
expect(r.rows.codex.status).toBe('FAIL');
expect(r.rows.patch.status).toBe('FAIL');
expect(r.rows.claude.status).toBe('SKIP');
expect(r.trailer).toBe('gstack: fail codex,patch');
expect(JSON.parse(doctor(f, ['--json', '--require', 'codex,patch']).out).for).toBe('codex,patch');
});
test('missing authentication: --for codex needs the CLI; absent, unauthenticated and present are told apart, --live probes once', () => {
const f = makeFixture();
installCodex(f);
const unauthed = row(f, ['--for', 'codex'], { STUB_AUTH_FAIL: '1' });
expect(unauthed.status).toBe(1);
expect(unauthed.rows['codex-cli'].status).toBe('FAIL');
expect(unauthed.rows['codex-cli'].rest).toContain('not authenticated');
expect(unauthed.rows['codex-cli'].rest).toContain('codex login --with-api-key');
expect(unauthed.trailer).toBe('gstack: fail codex-cli');
const authed = row(f, ['--for', 'codex']);
expect(authed.status, authed.out).toBe(0);
expect(authed.rows['codex-cli'].rest).toContain('paid probe not run; add --live');
expect(probeCalls(f)).not.toContain('probe-model');
const live = row(f, ['--for', 'codex', '--live']);
expect(live.status, live.out).toBe(0);
expect(live.rows['codex-cli'].rest).toContain('live probe ok');
expect(probeCalls(f).match(/probe-model exec/g)?.length).toBe(1);
fs.rmSync(path.join(f.stub, 'codex'));
const absent = row(f, ['--for', 'codex']);
expect(absent.rows['codex-cli'].status).toBe('FAIL');
expect(absent.rows['codex-cli'].rest).toContain('npm install -g @openai/codex');
});
test('runtime mismatch: the supported minimum (1.4.2) and the floor (1.3.3) both FAIL in --check', () => {
const f = makeFixture();
const untested = row(f, [], { STUB_BUN_VERSION: '1.3.14' });
expect(untested.status).toBe(1);
expect(untested.rows.runtime.status).toBe('FAIL');
expect(untested.rows.runtime.rest).toContain('below the supported minimum 1.4.2');
expect(untested.rows.runtime.rest).toContain('(RUNTIME_BELOW_MINIMUM; ');
expect(untested.trailer).toBe('gstack: fail runtime');
const old = row(f, [], { STUB_BUN_VERSION: '1.3.2' });
expect(old.rows.runtime.rest).toContain('below the security floor 1.3.3');
expect(old.trailer).toBe('gstack: fail runtime');
});
test('bun removed from PATH: the doctor still reports, runtime FAILs, pins SKIPs with a reason, one trailer', () => {
const f = makeFixture();
fs.rmSync(path.join(f.stub, 'bun'));
const r = row(f, []);
expect(r.status).toBe(1);
expect(r.rows.runtime.status).toBe('FAIL');
expect(r.rows.runtime.rest).toContain('bun not found on PATH');
expect(r.rows.pins).toEqual({ status: 'SKIP', rest: expect.stringContaining('no bun to evaluate the project pins') });
expect(r.rows.claude.status).toBe('PASS');
expect(r.trailer).toBe('gstack: fail runtime');
expect(r.trailers).toBe(1);
});
test('project pins: --project reads the target repository, a range mismatch FAILs with its source, a match PASSes', () => {
const f = makeFixture();
const project = path.join(f.base, 'project');
write(path.join(project, 'package.json'), '{\n "engines": {\n "bun": ">=1.4.2"\n }\n}\n');
const bad = row(f, ['--project', project], { STUB_BUN_VERSION: '1.3.14' });
expect(bad.rows.pins.status).toBe('FAIL');
expect(bad.rows.pins.rest).toContain('bun 1.3.14 outside engines.bun >=1.4.2 (package.json:3)');
expect(bad.rows.pins.rest).toContain('(PROJECT_PIN_MISMATCH; ');
expect(bad.trailer).toBe('gstack: fail runtime,pins');
const good = row(f, ['--project', project]);
expect(good.rows.pins).toEqual({ status: 'PASS', rest: `${project}: bun >=1.4.2 (engines.bun, package.json:3)` });
const none = row(f, ['--project', f.work]);
expect(none.rows.pins.status).toBe('PASS');
expect(none.rows.pins.rest).toContain('pins no runtime');
const missing = row(f, ['--project', path.join(f.base, 'nope')]);
expect(missing.rows.pins.status).toBe('SKIP');
});
test('project pins on Capy: the PROJECT_PIN_MISMATCH fix is the exact bootstrapper command, which installs a verified pinned Bun', () => {
const f = makeFixture();
const project = path.join(f.base, 'project');
write(path.join(project, 'package.json'), '{\n "engines": {\n "bun": ">=1.4.2"\n }\n}\n');
const wrapper = '/drive/skills/gstack/scripts/install.sh';
const capy = row(f, ['--project', project], { STUB_BUN_VERSION: '1.3.14', GSTACK_CAPY_WRAPPER_PATH: wrapper });
expect(capy.rows.pins.status).toBe('FAIL');
expect(capy.rows.pins.rest).toContain(`fix: bash ${wrapper} (installs the project's pinned Bun when it is a verified version: 1.4.2 1.4.3; otherwise it names the conflict), or change the pin in ${project}`);
expect(capy.rows.pins.rest).toContain('(PROJECT_PIN_MISMATCH; ');
const forSkill = row(f, ['--project', project, '--for', 'review'], { STUB_BUN_VERSION: '1.3.14', GSTACK_CAPY_WRAPPER_PATH: wrapper });
expect(forSkill.rows.pins.rest).toContain(`fix: bash ${wrapper} --for review (installs`);
const plain = row(f, ['--project', project], { STUB_BUN_VERSION: '1.3.14' });
expect(plain.rows.pins.rest).toContain('fix: install the pinned version for this platform');
expect(plain.rows.pins.rest).not.toContain(wrapper);
});
test('--revision: a matching VERSION passes, an unmet revision is never ok', () => {
const f = makeFixture();
const ok = row(f, ['--revision', VERSION]);
expect(ok.status, ok.out).toBe(0);
expect(ok.rows.revision.status).toBe('PASS');
const unmet = row(f, ['--revision', 'v9.9.9.9']);
expect(unmet.status).toBe(1);
expect(unmet.rows.revision.status).toBe('FAIL');
expect(unmet.rows.revision.rest).toContain(`installed ${VERSION}`);
expect(unmet.rows.revision.rest).toContain('(requested v9.9.9.9)');
expect(unmet.rows.revision.rest).toContain('(REVISION_UNMET; ');
expect(unmet.trailer).toBe('gstack: fail revision');
});
test('browser skills: the bundle and a Chromium launch plus render are required; planning skills never launch it', () => {
const f = makeFixture();
installCodex(f);
installPlaywrightStub(f, false);
const broken = row(f, ['--for', 'qa']);
expect(broken.status).toBe(1);
expect(broken.rows['browse-bundle'].status).toBe('PASS');
expect(broken.rows.browser.status).toBe('FAIL');
expect(broken.rows.browser.rest).toContain("Executable doesn't exist");
expect(broken.rows.browser.rest).toContain(`fix: ${bashPath(f.root)}/bin/gstack-browser-ensure (BROWSER_UNAVAILABLE; `);
expect(broken.trailer).toBe('gstack: fail browser');
installPlaywrightStub(f, true);
const ok = row(f, ['--for', 'qa']);
expect(ok.status, ok.out).toBe(0);
expect(ok.rows.browser).toEqual({ status: 'PASS', rest: 'Chromium 141.0.1 launched and rendered (node)' });
fs.rmSync(path.join(f.root, BROWSE_BIN));
const noBundle = row(f, ['--for', 'browse']);
expect(noBundle.rows['browse-bundle'].status).toBe('FAIL');
expect(noBundle.rows['browse-bundle'].rest).toContain('fix: cd ');
installPlaywrightStub(f, false);
expect(row(f, ['--for', 'autoplan']).rows.browser.status).toBe('SKIP');
});
test('cso: optional by default (SKIP, never silent), required by --for cso', () => {
const f = makeFixture();
expect(row(f, []).rows.cso).toEqual({ status: 'SKIP', rest: '(optional; toolchain absent or helper not built)' });
const r = row(f, ['--for', 'cso']);
expect(r.rows.cso.status).toBe('FAIL');
expect(r.trailer).toBe('gstack: fail cso');
for (const name of ['gstack-cso-launcher', 'gstack-cso-core']) write(path.join(f.root, 'bin', name + EXE), '#!/bin/sh\necho cso\n', 0o755);
expect(row(f, ['--for', 'cso']).rows.cso.status).toBe('PASS');
});
test('state root: GSTACK_EPHEMERAL=1 reports durable=no in --check (PASS) and warns in the dashboard', () => {
const f = makeFixture();
const r = row(f, [], { GSTACK_EPHEMERAL: '1' });
expect(r.rows['state-root'].status).toBe('PASS');
expect(r.rows['state-root'].rest).toContain(`${f.state} durable=no`);
expect(r.rows['state-root'].rest).toContain('GSTACK_EPHEMERAL=1');
expect(r.status, r.out).toBe(0);
const dash = doctor(f, [], { GSTACK_EPHEMERAL: '1' });
expect(dash.row('state root').state).toBe('warn');
expect(dash.row('state root').detail).toContain('durable=no');
expect(dash.row('state root').fix).toContain('GSTACK_STATE_ROOT');
expect(doctor(f).row('state root').detail).toContain('durable=yes');
});
test('--json: the same rows as objects keyed by the component ids, ok/failed/required and the trailer', () => {
const f = makeFixture();
installCodex(f);
const r = doctor(f, ['--json', '--for', 'autoplan'], { STUB_BUN_VERSION: '1.3.14' });
expect(r.status).toBe(1);
const json = JSON.parse(r.out.trim().split('\n').at(-1)!);
expect(json.schema_version).toBe(1);
expect(json.revision).toBe(VERSION);
expect(json.for).toBe('autoplan');
expect(json.ok).toBe(false);
expect(json.failed).toEqual(['runtime']);
expect(json.required).toEqual(['claude', 'codex', 'patch', 'runtime', 'pins', 'state-root', 'privacy', 'cores', 'revision', 'wrapper']);
expect(json.rows.map((x: { id: string }) => x.id)).toEqual(['claude', 'codex', 'patch', 'codex-cli', 'browse-bundle', 'browser', 'cso', 'runtime', 'pins', 'state-root', 'privacy', 'cores', 'revision', 'wrapper']);
const runtime = json.rows.find((x: { id: string }) => x.id === 'runtime');
expect(runtime.status).toBe('FAIL');
expect(runtime.code).toBe('RUNTIME_BELOW_MINIMUM');
expect(runtime.anchor).toBe('doctor-runtime-below-minimum');
expect(runtime.fix).toContain('gstack-capy-install');
expect(json.trailer).toBe('gstack: fail runtime');
expect(r.out.trim().split('\n')).toHaveLength(1);
const ok = JSON.parse(doctor(f, ['--json']).out.trim());
expect(ok.ok).toBe(true);
expect(ok.trailer).toBe(`gstack: ok ${VERSION} for=installed-hosts:claude,codex`);
});
test('usage: --for with --require, an unknown skill or component, and a flag without a value exit 2', () => {
const f = makeFixture();
expect(doctor(f, ['--check', '--for', 'autoplan', '--require', 'claude']).status).toBe(2);
expect(doctor(f, ['--for', 'no-such-skill']).status).toBe(2);
expect(doctor(f, ['--require', 'claude,bogus']).status).toBe(2);
expect(doctor(f, ['--check', '--project']).status).toBe(2);
expect(doctor(f, ['--help']).out).toContain('--check');
});
});
// Field wave lane A: the trailer agrees with the Bun workflows run (A3), a
// remote minimum fails the revision row (A2), and planning-only workflows do
// not fail on a repo test-pin mismatch (A3 amendment).
describe('gstack-doctor --check: launch Bun, supported minimum, planning-only pins', () => {
const VERSION = fs.readFileSync(path.join(REPO, 'VERSION'), 'utf8').trim();
const check = (f: Fixture, args: string[], extra: Record<string, string> = {}) => {
const r = doctor(f, ['--check', ...args], extra);
const lines = r.out.split('\n');
const rows = Object.fromEntries(lines.filter(l => /^(PASS|FAIL|SKIP) /.test(l)).map(l => {
const m = l.match(/^(PASS|FAIL|SKIP) ([a-z-]+)(?:\s(.*))?$/)!;
return [m[2], { status: m[1], rest: m[3] ?? '' }];
}));
return { status: r.status, out: r.out, rows, trailer: lines.filter(l => l.startsWith('gstack: ')).at(-1) ?? '' };
};
/** A verified Bun in $HOME/.bun/bin (off PATH) that answers --version and runs TypeScript. */
const verifiedBun = (f: Fixture, version = '1.4.2') =>
script(path.join(f.home, '.bun/bin/bun'), [`[ "$1" = --version ] && { echo "${version}"; exit 0; }`, `exec "${process.execPath}" "$@"`]);
test('PATH Bun 1.3.14 with a verified 1.4.2 off PATH: runtime FAILs naming where it was found; with the launch PATH it PASSes', () => {
const f = makeFixture();
verifiedBun(f);
const fresh = check(f, [], { STUB_BUN_VERSION: '1.3.14' });
expect(fresh.rows.runtime.status).toBe('FAIL');
const home = bashPath(f.home);
expect(fresh.rows.runtime.rest).toContain(`bun 1.4.2 found at ${home}/.bun/bin (not on PATH)`);
expect(fresh.rows.runtime.rest).toContain(`fix: export PATH="${home}/.bun/bin:$PATH" or prefix commands with the GSTACK_LAUNCH line`);
expect(fresh.rows.runtime.rest).toContain('(RUNTIME_BELOW_MINIMUM; ');
const launched = check(f, [], { STUB_BUN_VERSION: '1.3.14', PATH: `${f.home}/.bun/bin${path.delimiter}${f.env.PATH}` });
expect(launched.rows.runtime.status, launched.out).toBe('PASS');
expect(launched.rows.runtime.rest).toContain(`at ${home}/.bun/bin/bun`);
});
test('--min-revision: below FAILs with REVISION_BELOW_MINIMUM naming the upgrade command; at or above PASSes; unknown says so and never claims the minimum', () => {
const f = makeFixture();
const below = check(f, ['--min-revision', '99.0.0.0']);
expect(below.status).toBe(1);
expect(below.rows.revision.status).toBe('FAIL');
expect(below.rows.revision.rest).toContain(`installed ${VERSION}`);
expect(below.rows.revision.rest).toContain('below the supported minimum 99.0.0.0');
expect(below.rows.revision.rest).toContain(`${bashPath(f.root)}/bin/gstack-upgrade`);
expect(below.rows.revision.rest).toContain('(REVISION_BELOW_MINIMUM; ');
expect(below.trailer).toBe('gstack: fail revision');
const wrapped = check(f, ['--min-revision', '99.0.0.0'], { GSTACK_CAPY_WRAPPER_PATH: '/drive/skills/gstack/scripts/install.sh' });
expect(wrapped.rows.revision.rest).toContain('fix: bash /drive/skills/gstack/scripts/install.sh (fast-forwards)');
const at = check(f, ['--min-revision', VERSION]);
expect(at.rows.revision.status, at.out).toBe('PASS');
expect(at.rows.revision.rest).toContain(`>= supported minimum ${VERSION}`);
const unknown = check(f, ['--min-revision', 'unknown']);
expect(unknown.rows.revision.status).toBe('PASS');
expect(unknown.rows.revision.rest).toContain('remote minimum unknown (fetch failed)');
expect(unknown.rows.revision.rest).not.toContain('>= supported minimum');
});
test('planning-only workflows SKIP a repo test-pin mismatch; test-running workflows and --require keep pins required', () => {
const f = makeFixture();
const project = path.join(f.base, 'project');
write(path.join(project, '.bun-version'), '1.4.2\n');
const planning = check(f, ['--for', 'autoplan', '--project', project], { STUB_BUN_VERSION: '1.4.3' });
expect(planning.rows.pins.status, planning.out).toBe('SKIP');
expect(planning.rows.pins.rest).toMatch(/^\(planning-only; repo pins .*1\.4\.2.*, launch bun 1\.4\.3\)$/);
for (const args of [['--for', 'review'], ['--for', 'ship'], ['--require', 'claude']]) {
const tests = check(f, [...args, '--project', project], { STUB_BUN_VERSION: '1.4.3' });
expect(tests.rows.pins.status, args.join(' ')).toBe('FAIL');
}
});
});
// Plan A8/A-h: the Capy skill copy. Active-wrapper provenance decides; without
// it the Drive copies do, failing only when every copy is stale. The printed
// workaround (the checkout's own wrapper) certifies with the stale Drive copy
// left unchanged. Plan A5: a drifted resolution is a runtime FAIL.
describe('gstack-doctor --check: wrapper and runtime drift', () => {
const posixPathTest = process.platform === 'win32' ? test.skip : test;
const PRE_BOOTSTRAPPER = '#!/usr/bin/env bash\n# gstack Capy skill installer (pre-bootstrapper)\nset -u\nroot="${GSTACK_CAPY_ROOT:-$HOME/.local/share/gstack}"\nexec "$root/bin/gstack-capy-install" "$@"\n';
const parse = (f: Fixture, args: string[], extra: Record<string, string> = {}) => {
const r = doctor(f, ['--check', ...args], extra);
const line = (id: string) => r.out.split('\n').find(l => new RegExp(`^(PASS|FAIL|SKIP|WARN) ${id}\\b`).test(l)) ?? '';
return { status: r.status, out: r.out, line, trailer: r.out.split('\n').filter(l => l.startsWith('gstack: ')).at(-1) ?? '' };
};
const drive = (f: Fixture, scope: string, text: string) => { const file = path.join(f.home, '.capy/drive', scope, 'skills/gstack/scripts/install.sh'); write(file, text); return file; };
const withSupport = (f: Fixture, min = 1) => write(path.join(f.root, 'capy/support.env'), `GSTACK_MIN_REVISION=1.0.0.0\nGSTACK_CAPY_MIN_WRAPPER=${min}\n`);
const current = fs.readFileSync(path.join(REPO, 'capy/skill/gstack/scripts/install.sh'), 'utf8');
const currentRev = current.match(/^GSTACK_CAPY_WRAPPER=(\d+)$/m)![1];
posixPathTest('direct doctor run: a pre-bootstrapper Drive copy (no revision line) fails wrapper with both fixes; a current copy is not flagged', () => {
const f = makeFixture();
withSupport(f);
const stale = drive(f, 'user-garry-tan', PRE_BOOTSTRAPPER);
const r = parse(f, []);
expect(r.status).toBe(1);
expect(r.trailer).toBe('gstack: fail wrapper');
const row = r.line('wrapper');
expect(row).toContain(`FAIL wrapper — every Capy skill copy is stale (minimum wrapper 1): ${stale} (wrapper 0); fix: bash ${f.root}/capy/skill/gstack/scripts/install.sh --check (this session); owner: copy ${f.root}/capy/skill/gstack/ over the Drive skill folder, or have Capy re-sync it; this recurs every session until the Drive copy changes`);
expect(row).toContain('(CAPY_WRAPPER_STALE; https://github.com/garrytan/gstack/blob/main/docs/troubleshooting.md#capy-wrapper-stale)');
write(stale, current);
const fresh = parse(f, []);
expect(fresh.line('wrapper')).toBe(`PASS wrapper Drive copy ${stale} (wrapper ${currentRev}) (minimum 1)`);
expect(fresh.status, fresh.out).toBe(0);
});
posixPathTest('two Drive copies, one current: PASS naming the stale one; GSTACK_CAPY_WRAPPER_PATH alone decides when set without a revision', () => {
const f = makeFixture();
withSupport(f);
const stale = drive(f, 'org', PRE_BOOTSTRAPPER);
const good = drive(f, 'user', current);
const r = parse(f, []);
expect(r.line('wrapper')).toBe(`PASS wrapper Drive copy ${good} (wrapper ${currentRev}) (minimum 1); stale copies: ${stale} (wrapper 0)`);
expect(parse(f, [], { GSTACK_CAPY_WRAPPER_PATH: stale }).trailer).toBe('gstack: fail wrapper');
});
posixPathTest('the printed workaround certifies: a current active wrapper passes with the stale Drive copy unchanged (WARN, owner action); a stale active wrapper is a WARN too', () => {
const f = makeFixture();
withSupport(f);
const stale = drive(f, 'user-garry-tan', PRE_BOOTSTRAPPER);
const checkoutCopy = path.join(f.root, 'capy/skill/gstack/scripts/install.sh');
const r = parse(f, [], { GSTACK_CAPY_WRAPPER_REV: '1', GSTACK_CAPY_WRAPPER_PATH: checkoutCopy });
expect(r.status, r.out).toBe(0);
expect(r.trailer).toMatch(/^gstack: ok /);
expect(r.line('wrapper')).toBe(`WARN wrapper — active wrapper 1 (${checkoutCopy}) is current; stale Drive copies (minimum 1): ${stale} (wrapper 0); owner action: copy ${f.root}/capy/skill/gstack/ over the Drive skill folder, or have Capy re-sync it; this recurs every session until the Drive copy changes (CAPY_WRAPPER_STALE; https://github.com/garrytan/gstack/blob/main/docs/troubleshooting.md#capy-wrapper-stale)`);
expect(fs.readFileSync(stale, 'utf8')).toBe(PRE_BOOTSTRAPPER);
const json = JSON.parse(doctor(f, ['--check', '--json'], { GSTACK_CAPY_WRAPPER_REV: '1', GSTACK_CAPY_WRAPPER_PATH: checkoutCopy }).out);
expect(json.ok).toBe(true);
expect(json.rows.find((x: { id: string }) => x.id === 'wrapper')).toMatchObject({ status: 'WARN', code: 'CAPY_WRAPPER_STALE' });
withSupport(f, 2);
const old = parse(f, [], { GSTACK_CAPY_WRAPPER_REV: '1', GSTACK_CAPY_WRAPPER_PATH: stale });
// Integration item 2: an active copy below the minimum still works, so it
// is an owner-action WARN and the trailer stays ok.
expect(old.status, old.out).toBe(0);
expect(old.trailer).toMatch(/^gstack: ok /);
expect(old.line('wrapper')).toBe(`WARN wrapper — the active Capy skill copy ${stale} is wrapper 1, minimum 2 (it still works); owner action: copy ${f.root}/capy/skill/gstack/ over the Drive skill folder, or have Capy re-sync it; this recurs every session until the Drive copy changes (CAPY_WRAPPER_STALE; https://github.com/garrytan/gstack/blob/main/docs/troubleshooting.md#capy-wrapper-stale)`);
});
test('a drifted Bun resolution is a runtime FAIL carrying the installer\'s detail, fix and BUN_RESOLUTION_DRIFT', () => {
const f = makeFixture();
const r = parse(f, [], { GSTACK_DOCTOR_RUNTIME_DRIFT: 'recorded bun 1.4.3 at /s/bun (home), now no eligible bun; changed: the recorded binary is gone', GSTACK_DOCTOR_RUNTIME_DRIFT_FIX: 'bash /d/install.sh --for review' });
expect(r.trailer).toBe('gstack: fail runtime');
expect(r.line('runtime')).toBe('FAIL runtime — bun resolution drifted: recorded bun 1.4.3 at /s/bun (home), now no eligible bun; changed: the recorded binary is gone; fix: bash /d/install.sh --for review (BUN_RESOLUTION_DRIFT; https://github.com/garrytan/gstack/blob/main/docs/troubleshooting.md#bun-resolution-drift)');
});
posixPathTest('the runtime row shows gstack\'s bun shim and where it resolves from here, or names a foreign ~/.local/bin/bun it left alone', () => {
const f = makeFixture();
const shim = path.join(f.home, '.local/bin/bun');
write(shim, '#!/bin/sh\n# gstack-bun-shim: gstack-owned; delete this file to remove it\n[ "$GSTACK_BUN_SHIM_EXPLAIN" = 1 ] && echo "gstack bun shim: project=none record=none chose=/store/1.4.3/bun rule=default" >&2\necho 1.4.3\n', 0o755);
expect(parse(f, []).line('runtime')).toContain(`; shim ${shim} -> /store/1.4.3/bun`);
write(shim, '#!/bin/sh\necho mine\n', 0o755);
expect(parse(f, []).line('runtime')).toContain(`; ${shim} is not gstack's shim (no marker), left untouched: launch with the GSTACK_LAUNCH line`);
expect(parse(f, [], { GSTACK_BUN_INSTALL_VERSION: '1.4.2' }).line('runtime')).toContain('; install version 1.4.2 from GSTACK_BUN_INSTALL_VERSION');
});
test('A-a: the Capy skill\'s dispatch examples (fail revision, fail runtime,pins, fail pins) match the real failure heads, unchanged', () => {
const skill = fs.readFileSync(path.join(REPO, 'capy/skill/gstack/SKILL.md'), 'utf8');
const step = skill.split('\n').find(l => l.includes('If the trailer names `revision`, `runtime` or `pins`'))!;
const examples = [...step.matchAll(/`(gstack: fail [^`]+)`/g)].map(m => m[1]);
expect(examples).toEqual(['gstack: fail revision …', 'gstack: fail runtime,pins', 'gstack: fail pins']);
const f = makeFixture();
const project = path.join(f.base, 'project');
write(path.join(project, '.bun-version'), '1.4.2\n');
const real: Record<string, string> = {
revision: parse(f, ['--require', 'claude', '--min-revision', '99.0.0.0']).trailer,
'runtime,pins': parse(f, ['--require', 'claude', '--project', project], { STUB_BUN_VERSION: '1.3.14' }).trailer,
pins: parse(f, ['--require', 'claude', '--project', project], { STUB_BUN_VERSION: '1.4.3' }).trailer,
};
for (const example of examples) {
const ids = example.slice('gstack: fail '.length).replace(/ …$/, '');
const head = real[ids];
expect(head === `gstack: fail ${ids}` || head.startsWith(`gstack: fail ${ids} — `), `${example} vs ${head}`).toBe(true);
expect(head.match(/^gstack: fail ([a-z,-]+)/)?.[1].split(',')).toEqual(ids.split(','));
}
});
});