v1.91.106.0 fix: the 2026-10-15 issue wave (#3209)

* docs(designs): add fix wave 2026-10-15 plan (revision 3, approved)

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

* fix(cso): invoke docker as argv0 docker so OrbStack's multicall binary dispatches

executable() returns the canonical path, and OrbStack installs docker as a
symlink to docker-tools, which dispatches on argv[0] and exits 127 with
'unsupported argv0 "docker-tools"'. Every Docker call failed, so doctor
reported local-docker-isolation and every scanner missing and setup could
not preload the qualified images.

runProcess takes an argv0 option; docker.ts routes every Docker call
through runDocker, which passes 'docker'. The native watchdog's execve
calls pass "docker" as argv[0] too, so its container cleanup works on the
same installs. The executed file is still the verified canonical path.

Fixes #3187

* test(cso): cover Docker and watchdog invocation through a multicall binary

A compiled fake that refuses any argv[0] but docker stands in for
OrbStack's docker-tools. Both behavior tests fail on the previous code.

Refs #3187

* fix(cso): bound the argv0 test's socket helper and probe images through OrbStack's multicall docker (#3187)

Follow-up to #3188 by Bryan Stone (@aegixx):
- the python3 spawnSync that binds the fake daemon socket gets a 30 s
  timeout; without it test/spawnsync-timeout-tripwire.test.ts fails.
- reviewer test: dockerExactImagePresent, a production probe, admits an
  image when the endpoint's canonical executable is a multicall binary
  that refuses any argv0 other than "docker". It fails on 47d639a
  (returns false) and passes with #3188.

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

* fix(autoplan): own the conversation after a Claude Code 2.1.300 compaction

Claude Code 2.1.300 keeps a compaction's last records in place and lists
them in compactMetadata.preservedMessages. The segment's tail, which is
also the boundary's logicalParentUuid, is written after the boundary
under the compact summary, so the parent links form a cycle that the
owned causal order never reaches. Every record after the compaction was
dropped, and the publication guard denied each later phase entry with
close_incomplete.

Such a boundary now continues from the last preserved record that is a
node of the file and not its own descendant. Boundaries without that
metadata, with a foreign preserved uuid, or with nothing kept in place
still supply no ownership.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(autoplan): report a compaction-explained unreachable component as unrecognized_shape (#3194)

Follow-up to #3196 by vilano93. After the ownership walk, an owned node
the walk never reached was silently dropped, and the phase guard answered
the next phase entry with close_incomplete, which the user cannot satisfy.
When the unreachable node's ancestry ends in a cycle through a compact
boundary's logical parent, ownedCausalOrder now returns
unrecognized_shape:compaction_unreachable, the guard's existing
unverified disposition (allow with a visible warning and a guard-log
row). Orphans whose ancestor is missing (not flushed yet) and other roots
keep today's behaviour, so the fail-open surface does not widen beyond
compaction. Each node is walked once.

Gate-integrity edit: a close_incomplete denial becomes an unverified
allow for that shape only. Negative controls kept: the existing guard,
hook, guard-reasons and captured-fixture tests still deny (356 pass), and
a new case with the boundary not yet flushed still denies close_incomplete.

Intentional pin changes in #3196's own test file: the three "fails
closed" cases (tail-only segment, missing preserved metadata, foreign
preserved uuid) and the "without compactMetadata" case now expect
unrecognized_shape:compaction_unreachable instead of close_incomplete or
a silently cut transcript.

Reviewer tests: three compactions in one session stay owned and pass the
next phase entry; a 50k-record history with three compactions is decided
in ~300 ms (budget 1000 ms), so descends needs no memo.

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

* feat(lib): one echo sanitizer for external strings, with a Bash twin

lib/sanitize-echo.ts and bin/gstack-sanitize-echo.sh flatten CR/LF/TAB to
spaces, remove every other ASCII control byte (ESC included) and DEL,
collapse runs of spaces, and cap the result at 200 bytes of valid UTF-8
with no leading or trailing space. Every external string gstack echoes
into a message, a log line or a key=value state file goes through it
(fix wave 2026-10-15, plan rev 3 DX F8). test/sanitize-echo.test.ts runs
both twins on one table under bash, bash --posix and zsh, including a
"\nstages=" injection, ESC sequences and UTF-8 characters cut by the cap.

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

* fix(bun-version): judge the Bun floor under zsh and hold on an unreadable version (#3195)

Reported by mochafreddo. _gstack_bun_below word-split $_gb_core, which
zsh does not do: `[ -ne ]` errored and every error path read as "not
below", so /gstack-upgrade Step 4 accepted Bun 1.3.2 in a zsh tool shell.

- _gstack_bun_below copies the release's parsed fields into quoted
  positional parameters and compares with $((10#...)); no new _gb_*
  globals. It returns 2 when either side cannot be parsed.
- gstack_bun_status prints malformed for an unparseable version or floor
  (never ok); gstack_bun_incoming_hold holds on it with
  bun-version-unreadable: ... (BUN_VERSION_UNREADABLE), the bun path and
  its output passed through gstack_sanitize_echo. setup's own malformed
  warning is unchanged.
- /gstack-upgrade Step 4 runs the check through `bash -c` and stops on
  BUN_VERSION_UNREADABLE with a reinstall fix (never "bun upgrade").
- New result code BUN_VERSION_UNREADABLE with its troubleshooting entry;
  bin/gstack-doctor-components.sh regenerated from the table.

test/bun-version-shells.test.ts: one version table (1.3.2,
1.3.3-canary.1, 1.3.3, 1.3.14, 1.4.2, 1.10.0, 01.04.02, 2.0.0, garbage)
drives bash, bash --posix, zsh and the TypeScript twin's below();
`zsh -c '. bin/gstack-bun-version.sh; gstack_bun_status 1.3.2'` printed
ok on 47d639a and prints too-old now.

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

* style(cso): format #3188's runDocker call so format:cso:check passes (#3187)

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

* fix(cso): keep scanner JSON reports parseable after redaction (#3185)

Reported in #3185. The scanner path splices redactions into raw JSON, and
redactFindingSpans replaced a bare 10+ digit number
("max_memory_bytes":1145427776, an epoch) with an unquoted marker, so
JSON.parse failed and every non-trivial Semgrep run was INVALID_OUTPUT.

- lib/redact-engine.ts: redactJsonFindingSpans, a string- and
  escape-aware lexical tokenizer over one or more top-level values
  (NDJSON included). A span inside a number replaces that whole token
  (-, fraction, exponent) with the quoted marker, number by number; a
  span inside a string keeps the in-string marker, widened to whole
  escapes; a span touching several tokens, whitespace, a literal or a
  structural character returns null (withhold). Non-JSON text gets the
  plain splice. redactFindingSpans is unchanged for every other caller.
- The scan operation's declared format rides the real capture path:
  scanner-executor (scan stdout, or the report file read for outputPath
  plans) -> DockerGroup.execCapture -> runProcess -> spliceRedaction,
  which redacts the concatenated stdout once and maps each interleaved
  run onto it. Version probes and stderr stay plain; marker-only
  withholding and the cross-stream views check are kept, and the output
  is a fixpoint of that check.

Behavior change: a redacted number in a scanner report is now the string
"<REDACTED-...>" instead of an unquoted marker; non-JSON streams keep the
unquoted form (test/cso-eval.test.ts unchanged).

Intentional pin change: test/cso-scanner-release.test.ts pinned the
report read as capture(['/bin/cat', plan.outputPath]); it now pins
capture(['/bin/cat', plan.outputPath], plan.format), so the read also
carries the declared JSON format (stricter, not weaker).

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

* fix(browse): recover when the last tab is closed outside the CLI

Closing the last tab outside browse (for example, closing the headed
Chromium window) left the daemon wedged: the page 'close' handler removed
the tab and set activeTabId to 0, and executeCommand called
getActiveSession() first, so every later command (goto, status, even stop)
failed with "No active page" until the daemon PID was killed by hand.

closeTab() already opens a blank tab when the last tab closes; the external
close path never did. Add BrowserManager.ensureActiveTab(), which reselects
a remaining tab or opens one blank tab (concurrent callers share one
recovery), and call it before resolving the active session in
executeCommand.

Fixes #3167

* fix(browse): status and stop answer after an external close; recovery says what it did (#3167)

Follow-up to #3179 by aftabkh4n, which reopens a tab on demand.
- BrowserManager.ensureCommandTab runs before every command: status,
  stop and restart never open a tab, so a daemon whose browser or context
  is gone can still report and be stopped; any other command gets an
  active tab. A failed recovery is BROWSE_TAB_UNRECOVERABLE carrying the
  restart command (cause passed through sanitizeEcho), and a command that
  ran on a newly opened tab prints a one-line warning first.
- server.ts reads the session inside the read and write branches instead
  of before dispatch (2223 lines, cap 2224) and exposes browserManager
  and handleCommandInternal on __testInternals__ for the dispatch test.
- meta-commands.ts: handleMetaCommand no longer reads the active session
  before its switch (only snapshot and resume used it), and status prints
  getCurrentUrl() so it works with zero tabs. This file is outside the
  lane's listed ownership; no other lane or #3190 touches browse/.
- New result code BROWSE_TAB_UNRECOVERABLE and troubleshooting entries
  for it and for the old "No active page" wedge.

Reviewer test browse/test/tab-external-close-dispatch.test.ts drives the
real dispatch in a child process: status, text, goto and stop after an
external close, and the closed-context case. On 47d639a (with only the
test seam added) all five fail with "No active page".

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

* docs(troubleshooting): /cso INVALID_OUTPUT on Semgrep reports and OrbStack's argv0 refusal (#3185, #3187)

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

* fix(session-update): name the reinstall fix when an unreadable Bun holds the auto-update (#3195)

Item 11 makes every caller of gstack_bun_incoming_hold treat a Bun
version it cannot read as a hold (bun-version-unreadable,
BUN_VERSION_UNREADABLE). The session-start banner only knew
bun-too-old, so the new reason fell through to "git pull did not
finish ... gstack is not updating" with a pull-and-setup fix that does
not help.

- bin/gstack-session-update: a bun-version-unreadable banner case with
  the reinstall fix and the troubleshooting anchor; the comment that
  said a malformed version passes is corrected.

Intentional pin change: test/session-update-stages.test.ts "supported
or unparseable Bun (bun-dev (local build)) proceeds: setup decides" is
split. 1.3.14 still proceeds; bun-dev (local build) now holds with
BUN_VERSION_UNREADABLE, leaves the checkout and setup untouched, and
the banner names the reinstall fix. The fixture installs
bin/gstack-sanitize-echo.sh beside the floor helper, as a real install
of this release does. The new case fails on 47d639a.

Ownership exception granted by the coordinator for Lane A
(bin/gstack-session-update is Lane B's file; PR 1b stacks on 1a).

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

* fix(session-update): recover a conflicting autostash by its unmerged files

The auto-updater fast-forwards with `merge --ff-only --autostash`. When
the carried-over local edits conflict with the incoming revision, git
2.56 still exits 0 from that merge, pops the edits with conflict markers
into the live checkout, and keeps the stash entry. The recovery only ran
on a non-zero exit with "autostash" in stderr, so on git 2.56 it never
ran: the updater logged UPDATED and ran setup over a half-merged tree,
in the directory Claude Code runs hooks from. When it did run, it had two
more problems:
- `git checkout -- .` refuses unmerged paths ("error: path 'f' is
  unmerged", exit 1), so it left the markers in place anyway.
- `git stash drop` dropped stash@{0}, whatever that was. refs/stash is
  shared with every worktree of the repository, and when
  refs/stash.lock is held git cannot store the autostash at all, so the
  top entry can be someone else's.

Now the merge is judged by `git ls-files -u`, whatever its exit code.
On unmerged files after the fast-forward, autostash_recover finds the
autostash commit by the id git prints ("cannot store <id>" first, then
"Created autostash: <id>", with the merge run under LC_ALL=C and
core.abbrev=40). A moved refs/stash is only the fallback. When that id
is not a stash entry, it is anchored under refs/gstack-autostash/<UTC>.
The tree is reset to the fast-forwarded revision, which the hook check
already passed, and the stash is kept. The log line is
AUTOSTASH_CONFLICT_RECOVERED tree_reset=1 kept_stash=<id> kept_ref=<ref>.
The update then continues, so the regenerable patches are re-rendered
and setup runs as for any other move. If the commit cannot be found,
nothing is reset: the markers stay for a person, the run logs
PULL_FAILED, and setup does not run.

Files that are already unmerged before the update, from someone's own
merge, rebase or stash pop, now hold the update with PULL_FAILED
"unmerged files ...". Without that check, the recovery would take them
for its own and reset them away.

core.abbrev=40, not "no": "no" is accepted from git 2.31.0 (its release
notes), and `merge --autostash` exists from 2.27.0, so "no" would fail
every update on git 2.27-2.30.

Files:
- bin/gstack-session-update: autostash_recover, the unmerged-files check
  before the merge, the C-locale merge with its stdout kept for the id,
  and removal of the old grep-and-drop block.
- test/session-update-autostash.test.ts: 7 cases in a new describe block.
  A conflicting pop leaves no markers, keeps the edits and still runs
  setup. A user's own stash entry survives. A held refs/stash.lock gets
  the edits anchored. With a git whose merge prints nothing, a moved
  refs/stash still finds the edits; with the lock held as well, nothing
  is reset. Pre-existing unmerged files hold the checkout. A
  non-conflicting edit rides over the update (control).

Tests, on upstream 15ebd85cd:
- 5 of the 7 new cases fail against the previous session-update; the
  unmerged-files guard and the control pass on both.
- Two mutants are each caught by one new case: dropping the refs/stash
  fallback, and resetting when the edits cannot be found.
- session-update-autostash, session-update-stages,
  session-update-hook-hold and team-mode pass 63/0 with
  `--timeout 60000`. At bun's 5 s default under heavy load (one
  reading: load average 169), the three shared files timed out 8 tests
  on this branch and 17 with the previous script.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(session-update): trust only git's autostash id; owe setup on a stop

An independent review of the autostash recovery (Codex gpt-6-astra,
high effort, verdict BLOCK high=1 med=2) found three defects on its rare
paths. All three are fixed here, each with a case that failed first.

- [high] The refs/stash fallback could erase local edits. When git's
  messages were unavailable, recovery took any change to refs/stash as
  its own autostash. refs/stash is shared with every worktree: if a
  sibling pushed a stash while refs/stash.lock kept git from storing
  this one, recovery took the sibling's entry and reset the checkout,
  erasing edits nothing held. Now only git's own printed id counts. A
  missing id resets nothing: the markers stay, the run logs
  PULL_FAILED. Recovery needs git's messages, so when the temp file for
  them cannot be created the update is held before the merge
  (HELD temp-file-unavailable), not merged blind.
- [med] A stop after the checkout moved lost the setup it owed. The
  failure recorded only the pull reason. Once the person resolved the
  conflict, the next check saw an unchanged HEAD and no pending stage,
  logged UP_TO_DATE, and never set up the new revision. Now a failure
  after HEAD moved records `setup` as a pending stage, retried at once.
  The unmerged-files check holds it until the conflict is resolved, and
  the pull reason is the stage's reason, so the session-start line says
  what to resolve.
- [med] An unreadable index read as "no conflicts". Both `git ls-files
  -u` checks discarded the exit status, so a failed read after a
  conflicting pop (which git exits 0 for) let setup run over the markers.
  Now a failed read stops the update with PULL_FAILED "cannot read the
  index", before the merge or after it.

Files:
- bin/gstack-session-update: autostash_recover drops the refs/stash
  fallback (and STASH_BEFORE). The temp-file hold. The ls-files exit
  status checked at both points. The pending setup stage on a failure
  after HEAD moved.
- test/session-update-autostash.test.ts: a shim(fx, name, tool, body)
  helper; the fallback case now expects a refusal; the refusal case runs
  on through resolution to setup; three new cases (unreadable index
  before and after the merge, no temp file for git's messages).

Tests, on upstream 15ebd85cd:
- The 5 changed or new cases failed on the previous commit, each on its
  defect: refs/stash trusted and recovered; UP_TO_DATE with no setup
  after resolution; UPDATED over an unreadable index, before and after
  the merge; a blind merge with no temp file.
- Against upstream's own session-update, 8 of the block's 10 cases fail.
- session-update-autostash, session-update-stages,
  session-update-hook-hold and team-mode pass 66/0 with
  `--timeout 90000`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(session-update): reap heartbeat and its sleeper on exit

The lock heartbeat subshell left its sleep 300 child orphaned when the
updater exited, so heartbeats accumulated across sessions. Track and
reap the heartbeat job (with a job-table fallback for signals between
fork and $!), give the subshell its own exit trap that kills and waits
its sleeper, and map HUP/INT/TERM to exits so the EXIT trap always runs.
Adds a fixture-driven regression test.

* test(session-update): repin the lock trap and heartbeat to #3191's cleanup shape

Intentional pin change: test/session-update-autostash.test.ts 'reclaim is
TOCTOU-safe' and 'EXIT trap is ownership-checked' pinned the one-line
EXIT trap and the 'while :; do sleep 300; ...' loop that #3191 (Jess
Sullivan) replaces with cleanup_session_update and a 'sleep 300 & wait'
heartbeat. The pins still assert the ownership-checked rm -rf, the EXIT
trap, MYPID, and that the heartbeat is killed.

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

* fix(session-update): move installs only through gstack-ff-update; extract hooks without tar (#3184)

Item 2 (#3189, #3191 adopted in the previous commits) and item 3 of the
fix-wave plan.

bin/gstack-ff-update <dir> <rev> is now the only code that moves an
install's tree. Inside an install-scoped lock (absolute git common dir,
the updater's TTL and mv-aside reap, a heartbeat reaped on exit) it
captures the working tree and the staged state through private indexes,
carries edits that merge cleanly (as an autostash pop would), lets the
regenerable SKILL.md/sections footprint take the target when it
conflicts, and shelves any other conflicting edit, staged change or
unmerged file into refs/gstack/rescue/<oid> (first parent the pre-update
HEAD, second the staged state; compare-and-create; gstack rescue
identity). The move is a two-way read-tree on the private index, so a
late edit or an untracked file in the way refuses with
autostash-unrecoverable and changes nothing. It sources nothing so the
held-install recovery can fetch it from the new revision.

gstack-session-update calls it instead of merge --autostash, holds a
checkout with unmerged files (unmerged-files:), and names shelved edits
at session start at most once a day with inspect, export-the-delta and
delete commands. The incoming revision is extracted for the hook check
through a private index and checkout-index with core.symlinks=false,
never tar (MSYS tar cannot create connect-chrome before its target), and
the held reason carries the failing command's flattened, control-free
stderr. Held lines print before the stage line, one case per reason
with its anchor, every path shell-quoted, no setup fix while unmerged
files exist. docs/troubleshooting.md gains the held-install recovery
forms (Git Bash, PowerShell 5.1, trial and go-back) and entries for each
new line.

design: kept_ref is refs/gstack/rescue/<oid>, refs/stash is never
touched, the quiet-merge cases become a pre-existing-ref refusal and its
recovery, pre-existing unmerged files are a HELD unmerged-files, and the
git shim pins the real binary through git --exec-path.

Intentional pin changes in existing tests:
- test/session-update-stages.test.ts: printed paths are shell-quoted;
  the bun-too-old fix runs gstack-ff-update instead of git pull.
- test/session-update-hook-hold.test.ts: the order pin looks for
  'bash "$FF_UPDATE"' instead of 'merge --ff-only'; the
  hook-check-unavailable fix no longer recommends git pull --autostash;
  installedUpdater copies gstack-ff-update beside the updater.

Reported by wengweiling (#3184).

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

* fix(gstack-upgrade): Step 4 fast-forwards through gstack-ff-update (#3189)

Item 2 of the fix-wave plan, kept in its own commit so PR 1b can be
rebased onto PR 1a (which edits only Step 4's Bun floor-check line).

Step 4's `git pull --ff-only --autostash` had the same hole the
auto-updater had: a conflicting autostash exits 0 and leaves conflict
markers in the install, and the skill printed FF_OK. It now runs
bin/gstack-ff-update . origin/main after the fetch and the floor check:
exit 0 runs setup (a rescued line is relayed with its inspect, export
and delete commands), exit 4 (not a fast-forward) is the only way into
the gated reset fallback, and any other refusal stops with nothing
changed. The footprint discard moves to the reset fallback, ahead of
its stash, where the warning text already promised it.

Intentional pin changes:
- test/upgrade-template-pins.test.ts: the ff-before-reset pin looks for
  'bash bin/gstack-ff-update . origin/main'.
- test/gstack-upgrade-fresh-shell.test.ts: the C9 fence marker is
  'bash bin/gstack-ff-update'; the gstack-like fixture ships the bin.
- test/upgrade-setup-recovery.test.ts: the git-path fixtures ship
  gstack-ff-update (a stub where git itself is a stub).

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

* fix(setup.ps1): run under Windows PowerShell 5.1's legacy argument passing (#3130)

Item 4 of the fix-wave plan. Windows PowerShell 5.1 strips the double
quotes inside native arguments, so the bash -c script setup.ps1 handed
Git Bash arrived broken ("unexpected EOF while looking for matching").
The script now holds no double quote: `set -f; IFS=; mapfile -d '' -t
argv < $1; rm -f -- $1; exec ./setup ${argv[@]}` (empty IFS and no
globbing keep $1 and each argv entry whole). That form drops an empty
argument, so setup.ps1 refuses one before anything runs
(SETUP_PS1_EMPTY_ARGUMENT, with its troubleshooting entry).

test/setup-ps1.test.ts runs the adversarial arguments under legacy
passing (pwsh with $PSNativeCommandArgumentPassing = 'Legacy', and
powershell.exe itself on Windows) with a space in TMPDIR, plus the
empty-argument refusal. Intentional pin change: the pinned bash -c
line in "passes arguments NUL-separated through a private file to a
constant bash script" now names the quote-free script and asserts it
holds no double quote.

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

* fix(setup): register hooks at the $HOME path when CLAUDE_CONFIG_DIR links back to it

A per-session CLAUDE_CONFIG_DIR whose skills symlink to ~/.claude/skills
passed the split-brain guard, so its temporary path was written into the
global settings.json and the hooks broke once the session directory was
removed. Fall back to $HOME/.claude/skills/gstack whenever both spellings
resolve to the same tree.

Fixes #3180

* fix(setup): one sourced helper picks the hook root for setup and gstack-memorable (#3180)

bin/gstack-memorable carried a verbatim copy of setup's old canonical-root
block, so `gstack-memorable enable` under a per-session CLAUDE_CONFIG_DIR
still baked the session path into settings.json after #3181 fixed setup.
The choice now lives in bin/gstack-claude-root.sh
(gstack_canonical_claude_root), sourced by both.

Intentional test changes:
- test/setup-hook-canonical-paths.test.ts: #3181's source-slicing block
  test is rewritten to source the helper (with a spawnSync timeout, which
  the sliced version lacked and the tripwire flags); the
  "honors CLAUDE_CONFIG_DIR" pin moves from setup to the helper, and a new
  pin requires both callers to source it. Adds a no-$HOME-install case.
- test/setup-hook-syntax-gate.test.ts: the hook-section slice starts at the
  new assignment and the harness sources the helper.
- test/setup-claude-code-migration.test.ts, test/team-mode.test.ts: the
  partial-checkout fixtures copy the new helper setup sources.

Reviewer test: gstack-memorable enable under a per-session config dir that
links back to ~/.claude registers the $HOME path (fails on main).

Builds on #3181 by NetrioGit.

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

* fix(setup): remove 1.31-era unprefixed Cursor skill folders (#3133)

A 1.31 setup run from a checkout under ~/.cursor/skills linked unprefixed
<skill>/ folders there, each holding a SKILL.md symlink into the checkout.
Current setup links gstack-<skill>/ folders, and the retired-skill prune
only looks at gstack-* names, so the old folders stayed: Cursor loaded
autoplan, review and the rest twice, or kept dangling links once the
checkout moved.

Run the Claude flat-name cleanup on ~/.cursor/skills as well. Cursor
installs only gstack-* names, so no prefix gate is needed, and the helper
removes only entries proven to link into gstack (#2119), so user-owned
folders stay. It runs after linking, so a run that fails before the new
links exist keeps the old folders. Reported by @andrewkjankowski in #3084.

Fixes #3133

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(setup): name the skills dir in the flat-name cleanup line (#3133)

`./setup --host cursor` now runs the flat-name cleanup on
~/.cursor/skills as well as ~/.claude/skills, so the "cleaned up old
entries" line says which directory the folders were removed from.

Reviewer test for #3152 (szsunyuan): a real dir whose SKILL.md links into
gstack loses only that link and keeps the user's file; SKILL.md links into
a sibling repo named gstack-fork, a relative link, and a dangling link
outside any gstack checkout are all kept; the printed line names the
removed folders and the Cursor skills dir.

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

* fix(setup): install Chromium with `bun x`, and name exit 127 for what it is (#3131)

A Bun installed with winget ships no `bunx`, so setup's
`bunx playwright install chromium` exited 127 and was reported as
"offline, proxy, or blocked download?". setup now runs
`bun_cmd x playwright install chromium` through its existing bun resolver
($BUN_CMD), and bin/gstack-browser-ensure runs the bun it found on PATH
with `x`. Exit 127 gets its own text naming the resolved bun, Bun from
bun.sh, and the skip commands for Git Bash and PowerShell; other codes
keep the network hint. New troubleshooting entry:
#chromium-install-exit-127.

Intentional test changes:
- test/setup-playwright-best-effort.test.ts: the installer stub is now a
  `bun_cmd()` stub (was `bunx()`), its mark renamed bun-x-called and now
  records the args; the block under test calls bun_cmd. New winget-shaped
  cases (bun on PATH, no bunx anywhere) run setup's real bun_cmd.
- test/gstack-browser-ensure.test.ts: the fixture is winget-shaped (the
  `bun` stub handles `x`, no `bunx` on PATH); the exit-7 pin now reads
  `<stub>/bun x playwright install chromium exited 7 (...)`.

--help in gstack-browser-ensure prints the comment header only (3,24p).

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

* ci(windows): prove setup.ps1 on PowerShell 5.1 and the held-install recovery natively (#3130, #3184)

windows-setup job:
- setup.ps1 joins the path filter (with bin/gstack-ff-update,
  bin/gstack-claude-root.sh, bin/gstack-browser-ensure,
  docs/troubleshooting.md and test/setup-ps1.test.ts).
- powershell.exe must be Windows PowerShell 5; test/setup-ps1.test.ts runs
  with a space in TEMP and must report exactly 4 pass, 0 fail, 1 skip
  (the Linux-only missing-prerequisite case).
- A copy of the built checkout under a path with a space installs through
  `powershell.exe -File setup.ps1 --host codex`.

held-install-journey job (new, parallel):
- origin's main is this PR's tree on top of the v1.91.101.0 tree
  (47d639abf); fix-branch adds one file.
- A prefix-mode v1.91.101.0 install at the runner's ~/.claude path in
  three states (clean, dirty-conflicting, already-unmerged), with
  auto_upgrade=true and the throttle cleared: the old updater must log
  `HELD hook-check-unavailable`; the PowerShell recovery form, read
  verbatim from docs/troubleshooting.md and run under powershell.exe,
  must reach main with every local edit (only those) in one rescue ref.
  The dirty state runs it with its .\setup.ps1; the others replace that
  step with a marker.
- The trial and go-back forms move the install to fix-branch (detached)
  and back to main.
- Only then a later release whose symlink sorts before its target is
  pushed, and the new updater must log UPDATED and reach it.
- Both jobs assert the exact list of cases that ran.

The journey steps ran locally on Linux with pwsh in Legacy argument
mode as powershell.exe, a git exec-path whose ../../../bin/bash.exe is
bash, and a failing tar standing in for MSYS tar (all 9 cases passed);
the windows-latest run itself happens on the PR.

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

* test(ff-update): a killed step-4 run fails the status check instead of the type check

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

* ci(windows): the held-install job runs without the bun cache step

The cache key line is a secret-scanner false positive on added lines
(env.kv); the fixture's own setup installs its packages either way.

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

* test(fixtures): register #3191's heartbeat fixture as free

test/free-fixtures.test.ts failed on the frozen-branch Ubicloud run:
test/fixtures/session-update-heartbeat.sh (adopted with #3191) was in no
paid touchfile and not in FREE_FIXTURES. Its only consumer is
test/session-update-heartbeat.test.ts.

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

* fix(session-update): leave the bun-version-unreadable banner case to item 11 (PR 1a)

PR 1a owns the bun-version-unreadable hold (BUN_VERSION_UNREADABLE), its
banner case and its troubleshooting entry; this branch is rebased onto 1a.
Drops the case, the docs entry and the banner test this branch had added.

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

* fix(setup.ps1): resolve Git Bash in the shared order, with GSTACK_BASH as an alias and a BASH_UNAVAILABLE refusal

Follows lib/script-invocation.ts (Lane C, PR 2): GSTACK_GIT_BASH is the
override and GSTACK_BASH its deprecated alias at the same precedence;
when both are set and differ GSTACK_GIT_BASH wins and one warning prints.
An override that does not exist is refused, never skipped. Without one:
the install git --exec-path belongs to (behind a scoop shim, or a
portable Git), the folders around git.exe, %LOCALAPPDATA%\Programs\Git,
%ProgramFiles%\Git, and last a bash on PATH whose uname -s reports MSYS;
WSL's bash (System32, WindowsApps) is rejected. A miss lists every
candidate with its rejection, then the PowerShell user-variable and
~/.claude/settings.json env recipes (BASH_UNAVAILABLE, #bash-unavailable).

test/setup-ps1.test.ts gains a 14-row pwsh-on-Linux table with every
location injected (override, alias, both set, missing override and alias,
scoop shim, per-user, portable and machine-wide Git, MSYS PATH bash, WSL
and non-MSYS rejections, missing); 11 rows fail on main. The rows mirror
Lane C's table in test/script-invocation.test.ts; they are not wired to
it, since that branch is not available here. The Windows job's expected
skip count for this file moves from 1 to 15 (the table is Linux-only).

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

* fix(setup.ps1): give the empty-argument refusal its result code (SETUP_PS1_EMPTY_ARGUMENT)

Adds the row to lib/result-codes.ts (anchor #setup-ps1-empty-argument,
which setup.ps1 already prints). bin/gstack-doctor-components.sh is
regenerated from the table (generated; resolved by regeneration at merge).

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

* ci(windows): silence SC2016 on the PowerShell version probe (the $ is PowerShell's, not bash's)

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

* ci(windows-setup): give tar a POSIX path for the spaced checkout

MSYS tar reads `D:\a\_temp/...` as host:path (rsh syntax) and fails with
'Cannot open: No such file or directory' before setup.ps1 runs. The copy
target now goes through cygpath -u; setup.ps1 still gets the Windows form.

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

* ci(windows-setup): dereference symlinks when copying the spaced checkout

MSYS tar cannot extract connect-chrome, a symlink that precedes its target
(the #3184 failure mode), so the copy died before setup.ps1 ran. tar -h
stores the target instead.

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

* fix(windows): one Git Bash resolver for gstack's shebang bins (#3197)

Windows has no shebangs, and gstack had three conflicting bash lookups:
the hooks fell back to a bare PATH `bash` (often WSL's launcher), the
gbrain sync checked three fixed paths, and setup.ps1 walked up from
git.exe. lib/script-invocation.ts is now the only TypeScript resolver:
GSTACK_GIT_BASH (GSTACK_BASH as a deprecated alias, same precedence,
warning when they differ, a missing value refused), bash next to
`git --exec-path` (scoop, per-user, portable Git), the known install
paths, then a PATH bash only when `uname -s` reports MSYS/MINGW. WSL
launchers are rejected unprobed. A miss is BASH_UNAVAILABLE, listing
every candidate with its rejection reason.

Bun-shebang bins run under Bun (process.execPath, or the PATH bun inside
a compiled binary). Hooks' runBin resolves through a state-root cache
keyed by git.exe path and mtime, written by temp file plus rename, so
the hot path spawns nothing extra; the override is never cached.
wtreeFingerprint({cwd, timeoutMs}) returns {tree} | {error, kind} with
GIT_OPTIONAL_LOCKS=0 and 40-64 hex ids; the consumers move next.

Intentional pin change: test/gbrain-spawn-windows-shell.test.ts expects
forward-slashed bash paths (WIN_BASH and the GSTACK_BASH override), the
form the shared resolver returns because Bun's spawnSync on Windows
returns ENOENT for a backslash exe path containing spaces.
The copied-tree adapters in test/timeline-stop-hook-slug.test.ts and
test/plan-tune-cathedral.test.ts list the two modules spawn-bin.ts now
imports; the new fixture is registered in test/helpers/free-fixtures-data.ts. bin/gstack-doctor-components.sh is
regenerated for the new result-code row.

Reported by @exGeni.

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

* fix(windows): fingerprint and gstack bins through the shared invocation (#3197)

bin/gstack-wtree was spawned by path in lib/regen.ts, lib/gate-diff/git.ts,
lib/restamp.ts and bin/gstack-evidence; gstack-slug in restamp, gate-diff
and evidence; gstack-redact in the pregate secrets check; and a bare
`bash -c` in regen, the lane selection manifest and gstack-evidence run.
On Windows each one failed to launch. All now go through
lib/script-invocation.ts, and each fingerprint consumer keeps its fail
direction while saying why:

- gstack-regen check: incomplete, `cannot fingerprint the working tree
  (gstack-wtree exited 1: <helper's own repair>)` instead of
  `(gstack-wtree failed)`; write keeps the registry label as its run id.
- gstack-gate-diff: `+nowtree` candidate, with the cause.
- gstack-restamp: RESTAMP_CONFLICT carrying the launch or exit detail
  (Windows printed `()` before).
- gstack-evidence: records without wtree (grades STALE) and warns once;
  SHA-256 repositories now get a 64-hex fingerprint.

lib/regen.ts keeps a string-returning wtreeFingerprint(repoRoot) wrapper
for lib/pregate/context.ts and lib/pregate/index.ts (files #3190 changes);
item 10b migrates them. test/script-invocation-tripwire.test.ts fails on a
new by-path or bare-bash spawn under lib/, hosts/ or a Bun bin; five sites
outside this change are listed with their owners and may only shrink.

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

* fix(pregate): keep framework route paths from a selection manifest (#3176)

laneFileSet parsed manifest output with `[\w.-]+` path segments, so
`app/(shop)/[id]/page.test.ts` came back as `page.test.ts`. The selected
test then matched no platform lane, its remote receipt obligation
vanished and it fell back to a local run. manifestTestPaths keeps route
segments whole (`(group)`, `[id]`, `[...slug]`, `[[lang]]`, `@slot`,
`$param`, `+page`), reads every path-shaped token on a line (JSON
arrays, quoted, `path:line`, parenthesized), and decides what is a test
file with the import graph's own isTestFile, so a test-file rule change
there (bats, #3177) reaches manifests without a second regex. A manifest
that cannot start is "unknown" (widens), like a non-zero exit.

This is the manifest-parser half of #3176 by @vocodestudios; the
import-graph half (tsconfig aliases, Next.js route mapping) ships in a
separate PR. test/pregate-manifest-paths.test.ts drives the CLI with a
bracketed route test in the fixture's Windows-only lane and asserts its
requires-remote obligation; it failed on main (requires_remote was []).

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

* ci(windows): windows-pregate-e2e drives the #3197 paths natively

A windows-latest job (Bun 1.4.2) builds a fixture repository and runs
gstack-restamp --dry-run, gstack-regen check and write, gstack-evidence
run and gstack-gate-diff from their TypeScript entry points, asserting a
real tree fingerprint each time; times a question-log hook cold and warm
and checks it cached its Git Bash resolution; and checks that a missing
GSTACK_GIT_BASH refuses with BASH_UNAVAILABLE and lists the candidate.
The journey runs twice: under the runner's Git for Windows and under a
pinned PortableGit 2.56.0.2 (SHA-256 verified), found only through
`git --exec-path`. gstack-pregate run joins it with item 10b. The workflow is registered in
scripts/test-pr-profile.ts FREE_ONLY_PR_FILES (no paid case reads it), recorded
as a non-behavioral HARNESS_VERSION decision in scripts/harness-version.json.

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

* fix(setup.ps1): resolve Git Bash by the shared fixture table (#3197)

test/setup-ps1.test.ts now drives setup.ps1 through every row of
test/fixtures/windows-bash-resolution.json, the table that pins
lib/script-invocation.ts, instead of a hand-mirrored copy. Two rows
failed and are fixed here:
- an override and alias that differ only in slash direction no longer
  print the differ warning;
- the root git --exec-path names is also searched for usr\bin\bash.exe
  (Git for Windows on arm64).

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

* test(windows): isolate the no-bash case and launch pregate as the product does (#3197, #3176)

windows-free-tests run 38813751242 failed two tests this layer added. Both
were fixture defects on a real Windows host, not product defects:
- gbrain-spawn-windows-shell "returns null when Windows has no bash" stubbed
  only `exists`. The resolver's PATH step asks the real Bun.which and found
  the runner's MSYS bash, which is correct. The case now also stubs
  `which` and `gitExecPath`, so it really means "no bash anywhere".
- pregate-manifest-paths spawned the extensionless bin/gstack-pregate
  directly. CreateProcess cannot exec a shebang, so nothing ran and stdout
  was "". It now launches through lib/script-invocation's runScriptSync,
  gstack's own Windows invocation, so the case runs the manifest lane end
  to end on Windows instead of being excluded.

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

* ci(windows): the missing-bash step survives the refusal it expects (#3197)

GitHub runs `shell: bash` as `bash -eo pipefail`, and the step's own
`set -uo pipefail` does not turn -e off. So when gstack-restamp refused, as
the step expects, `OUT=$(...)` aborted the script before `CODE=$?` and before
any output was printed: exit 1 after 0.5 s with nothing in the log (PR #3209,
job 116729693492). The capture is now `OUT=$(...) && CODE=0 || CODE=$?`.

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

* test(pregate): the manifest-lane case expects the host's own remote lanes (#3176)

Once 8b2f297cc made the case run on Windows, windows-free-tests run
38824886195 (shard 4) showed the expectation itself was Linux-only. pregate
owes a lane remotely when its runner platform is not the host's
(lib/pregate/workflows.ts). On a Windows host the fixture's Windows lane
runs locally, and the Ubuntu `free-tests.yml/unit` lane is the remote
obligation; that is the record Windows produced.

The case now derives the owed lanes from the host the same way. On Windows
it also requires `ran: node --test 'app/(shop)/[id]/page.test.js'`: there the
route reaches the local run only through the manifest's whole path. With a
cut manifest path (page.test.js) the local set is empty, checked through
buildContext({ platform: 'win32' }) + selectLanes.

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

* ci(windows-setup): expect 31 skipped setup.ps1 cases now that the shared table drives it

Layer 2 drives setup.ps1 through the 16 shared rows of
test/fixtures/windows-bash-resolution.json; like the 14 existing resolution
rows they run under pwsh on Linux and skip on Windows. The case list is still
asserted exactly (4 pass, 0 fail, 31 skip).

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

* test(ship-measure): give the CLI tests a private HOME (#3162)

Every bun run test left ~/.gstack/projects/ship-measure-cli-*/evals and
sweep-cli-fake-*/evals in the developer's real home, and the free-suite
runner flagged them ("real home changed ... Give the writer a private
HOME/GSTACK_HOME"). ship-measure's diagnostic-dir check calls
getProjectEvalDir(), which builds the eval dir from os.homedir(), and
these two CLI tests passed the real HOME while overriding only the
state root.

Both now set HOME and USERPROFILE to the test's own state dir. The
sweep test also runs on the Windows lane, where os.homedir() reads
USERPROFILE. test/ship-measure.test.ts:79 already gives its config test
a private HOME the same way. getProjectEvalDir() itself is unchanged:
whether eval history should follow GSTACK_HOME is left open in #3162.

Fixes #3162

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(ship-measure): prove the sweep CLI never writes under the parent HOME (#3162)

Reviewer test for #3163 (adopted from y$un_, forrest.sun527): points the
parent HOME at a sentinel with a stub global gstack-slug and asserts no
.gstack dir appears there. Fails on 47d639a (the sentinel gets
.gstack/projects/leaked-slug/evals); passes with #3163.

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

* test(redact): isolate fixture git from inherited hooks

Fixture git was spawned with the parent environment, so a developer's
core.hooksPath ran on the local push and rejected it (#2967). The
helper blanks the global and system files and drops GIT_CONFIG_COUNT
and GIT_CONFIG_PARAMETERS. A hooksPath set in the fixture repo still runs.

* test(redact): blank GIT_CONFIG_GLOBAL with /dev/null on every platform (#2967)

Follow-up to #3156 (adopted from Lockyer228): Git for Windows rejects
GIT_CONFIG_GLOBAL=NUL (the repo convention is EMPTY_GLOBAL_GIT_CONFIG =
'/dev/null' in lib/cso/process.ts), so both fixture helpers use /dev/null
everywhere. Reviewer test: a hooksPath in the default global files under
HOME/.gitconfig and XDG_CONFIG_HOME/git/config cannot reject the fixture
push; it fails with the inherited environment (the 47d639a behavior) and
passes with the isolated env.

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

* fix: gstack-config compares whole root paths and prints a runnable recovery command

- report_root_disagreement compared word-split values, so two variables naming
  the same directory with a space were reported as disagreeing. Compare each
  complete value instead.
- The privacy-key recovery hint single-quoted the root and left the script
  path bare; an apostrophe or space made it unrunnable. Quote with printf %q.
- On Bash 3.2 (macOS /bin/bash) a failed `.` under set -e exits before the
  `||` fallback, so a missing gstack-state-root.sh exited 1 silently and
  test/state-root-resolver-failure.test.ts failed there. Check readability first.
- The merge fixture now lives under a path with a space and an apostrophe,
  executes the printed command, and asserts same-directory variables agree.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(config): pin the %q-quoted recovery command and run it from a spaced install path

Follow-up to #3186 (adopted from davidfragnoli-lang). Intentional pin
change: the fix line's GSTACK_STATE_ROOT='<legacy>' pin becomes the exact
bash printf %q form of the legacy root (the PR loosened it to a prefix
check; this restores an exact pin) and the original test name is kept.
Reviewer test: copy bin/ to a path containing a space and an apostrophe;
the printed fix: command runs cleanly and flips the merged value. Fails on
47d639a (unquoted $_SELF), passes with #3186.

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

* test(gstack-gbrain-sync): fail when a star gitignore already ignores the pin

ensureGbrainSourceGitignored appends .gbrain-source even when git
check-ignore already excludes that path. The extra line dirties a
tracked ignore-everything gitignore.

* fix(gstack-gbrain-sync): skip the pin line when git already ignores it

ensureGbrainSourceGitignored asked only for a literal .gbrain-source
line. An ignore-everything star already excludes the pin, and the extra
line left the tracked gitignore dirty.

* fix(gbrain-sync): only a tracked .gitignore can stand in for the pin line

Follow-up to #3178 (adopted from KuroChen). The skip now requires
`git -c core.excludesFile= check-ignore -v` to name a tracked .gitignore
(not global excludes, not .git/info/exclude, not a negation), so a pin
ignored only on this machine still gets the shared line teammates need
(#1384). Tests: the two git init spawns get timeouts (they failed the
spawnSync tripwire), fixtures isolate HOME/XDG_CONFIG_HOME, and the PR's
star-gitignore fixture stages its .gitignore (intentional fixture change:
the contract is a tracked file). Reviewer tests: global excludes only,
info/exclude only, an untracked star .gitignore, and a re-include each
still append; all three fail on the PR head.

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

* fix(skill-end): log the completion event before the final drain (#3198)

gstack-skill-end drained and pushed before it appended its own completed
timeline event, and gstack-timeline-log backgrounded its enqueue, so a
full-tier end boundary returned with its latest event unpushed. The
completion log now runs before the drain and the logger waits for its
enqueue (one config read and a spool write; it exits early when sync is
off or the session is unattended). Every consent, secret-scan and
queue-lock gate is unchanged; the stale "local-only, never sent anywhere"
comment is replaced.

Patch and regression test from Kkkkkuro (#3198): 2 pass / 5 fail on
47d639a, 8/8 with the fix. Reviewer test: with artifacts_sync_mode off the
completion is written locally with no queue entry and no push.

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

* fix(pregate): map Next.js route paths and tsconfig path aliases to their tests

QUOTED excluded ( ) [ ] +, so a test naming app/(app)/page.tsx in a string
never matched. resolveRef never read tsconfig compilerOptions.paths, so an
import through @/ resolved to nothing. Both were PREGATE_NO_LANE false
negatives in a Next.js App Router repo whose tests did name the files.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(pregate): TypeScript alias precedence, relative extends and a no-lane explanation

Follow-up to #3176 (adopted from vocodestudios). Path aliases now follow
TypeScript's choice: an exact pattern, else the wildcard with the longest
prefix, targets tried in order. When the chosen pattern resolves nothing,
every plausible reading (other matching patterns, baseUrl, the repo root)
gains the edge, so uncertainty selects more tests, never fewer. Relative
extends chains are followed up to MAX_TSCONFIG_EXTENDS (4) hops, with
baseUrl and paths resolved against the config that declares them.
Trailing commas are dropped by the JSONC tokenizer (never inside a string)
instead of a whole-text regex.

A touched file with no lane now gets explain lines naming the import
specifiers in test files that resolved to no repo file, any extends hop
that was not followed (with the limit), and the hint to declare the file
under dependencies or report the resolver gap. The lines ride testsFor's
provenance, which lanes already pushes to --explain.

Reviewer tests: overlapping aliases in both key orders, exact vs
wildcard, target fallback, the union case, a two-hop extends chain, a
string containing ',]', and the depth-limit explanation. Five fail on the
PR head; all 12 pass. The manifest-parser half of #3176's follow-up
(lane-selection.ts) ships in PR 2.

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

* fix(browse): reap PTY children on agent shutdown

* fix(browse): reap a terminal-agent PTY's whole process group at shutdown (#3147)

Follow-up to #3148 (adopted from Y4NN777). The PTY child leads its own
session and process group; its identity (pgid, sid, leader start time) is
recorded at spawn and stays checkable after the leader exits. Disposal
schedules a group reap after PTY_SHUTDOWN_GRACE_MS that, unlike the
direct-child SIGKILL fallback, is not cancelled when the leader exits, and
shutdown reaps every pending group before exiting, so descendants that
ignore SIGHUP no longer outlive the agent. Only proven members are
signalled: same pgid and sid, started no earlier than the leader, and
nothing at all when the leader's PID is held by a process with another
start time. Linux only (/proc); other platforms keep the direct-child
behavior. During the shutdown grace the server answers 503 and no new PTY
is spawned.

Test changes to the PR's own test (intentional): the agent is spawned
with process.execPath and the PTY child traps INT TERM HUP, so the case
proves the SIGKILL fallback instead of passing on the kernel hangup.
Reviewer tests: a HUP-immune grandchild is dead within the grace plus 1 s;
an early-exiting leader's surviving descendant is reaped; a session that
completed before shutdown still has its group reaped; unit cases for a
foreign group and a reused leader PID. All four integration cases fail on
47d639a; three fail on the PR head.

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

* build(deps): bump the github-actions group with 5 updates

Bumps the github-actions group with 5 updates:

| Package | From | To |
| --- | --- | --- |
| [actions/upload-artifact](https://github.com/actions/upload-artifact) | `7.0.1` | `7.0.2` |
| [actions/download-artifact](https://github.com/actions/download-artifact) | `8.0.1` | `8.0.2` |
| [actions/setup-node](https://github.com/actions/setup-node) | `7.0.0` | `7.1.0` |
| [ossf/scorecard-action](https://github.com/ossf/scorecard-action) | `2.4.4` | `2.5.0` |
| [github/codeql-action/upload-sarif](https://github.com/github/codeql-action) | `4.38.2` | `4.38.3` |

Updates `actions/upload-artifact` from 7.0.1 to 7.0.2
- [Release notes](https://github.com/actions/upload-artifact/releases)
- [Commits](https://github.com/actions/upload-artifact/compare/043fb46d1a93c77aae656e7c1c64a875d1fc6a0a...cf430e030ddbb5b0abf93d22962f4752f3646cd9)

Updates `actions/download-artifact` from 8.0.1 to 8.0.2
- [Release notes](https://github.com/actions/download-artifact/releases)
- [Commits](https://github.com/actions/download-artifact/compare/3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c...9000827ccba6bdab643e8b6fd33ac0654aef8333)

Updates `actions/setup-node` from 7.0.0 to 7.1.0
- [Release notes](https://github.com/actions/setup-node/releases)
- [Commits](https://github.com/actions/setup-node/compare/820762786026740c76f36085b0efc47a31fe5020...949feb2413d6458794dcd2491c4babbbce0c15c1)

Updates `ossf/scorecard-action` from 2.4.4 to 2.5.0
- [Release notes](https://github.com/ossf/scorecard-action/releases)
- [Changelog](https://github.com/ossf/scorecard-action/blob/main/RELEASE.md)
- [Commits](https://github.com/ossf/scorecard-action/compare/2d1146689b8cda280b9bc96326124645441f03bc...fa7117db83c52d787ae5a89f350999701505d78e)

Updates `github/codeql-action/upload-sarif` from 4.38.2 to 4.38.3
- [Release notes](https://github.com/github/codeql-action/releases)
- [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md)
- [Commits](https://github.com/github/codeql-action/compare/2892aa5e19bbd11bc0cff5427e3b750a04d9e3c2...24c54180a607b1449ed407dd24f251e4e9147c8d)

---
updated-dependencies:
- dependency-name: actions/upload-artifact
  dependency-version: 7.0.2
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: github-actions
- dependency-name: actions/download-artifact
  dependency-version: 8.0.2
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: github-actions
- dependency-name: actions/setup-node
  dependency-version: 7.1.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: github-actions
- dependency-name: ossf/scorecard-action
  dependency-version: 2.5.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: github-actions
- dependency-name: github/codeql-action/upload-sarif
  dependency-version: 4.38.3
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: github-actions
...

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

* test(model-policy): track the upload-artifact v7.0.2 pin from #3175

Intentional pin change: test/model-policy-workflow.test.ts asserted
actions/upload-artifact@043fb46d…; dependabot #3175 moves the workflow to
cf430e03… (v7.0.2, verified against the upstream tag). The pin tracks the
workflow. #3175's free-tests.yml hunk is left out of this PR (free-tests.yml
is a #3190 file; it is re-bumped in PR 5).

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

* test(model-policy): its upload-artifact pin matches the eval workflows' pin

Reviewer test for dependabot #3175: the model-policy workflow's single
upload-artifact pin equals the pin evals.yml, evals-periodic.yml and
windows-free-tests.yml use, so a group bump that misses one workflow (or
the hard-coded pin above) is caught here.

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

* build(deps): hold Playwright minor/major bumps behind the windowsHide patch (#2923)

Dependabot #2923 bumped playwright to ^1.64.0 and dropped the
patchedDependencies entry keyed to playwright-core@1.62.1, which keeps
windowsHide on Windows (#2160, #1989). The bun ecosystem now ignores only
semver-minor and semver-major updates for playwright and playwright-core;
patch updates still flow. The 1.64 migration (re-key the patch, the
Dia/cookie qualification pins, the arm64 artifact name) is filed with
owner Garry, revisit 2026-11-15. Test fails on 47d639a (no ignore rule).

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

* docs(readme): drop the stale skill lists users pasted into CLAUDE.md (#3169)

README's install prompt and troubleshooting block each carried a skill
list for CLAUDE.md; both were stale (18 shipped skills missing) and they
disagreed. Claude Code lists installed skills itself, so both now keep
only the /browse rule, and the troubleshooting entry says to delete an
old pasted list. New free test: any comma-separated skill list in
README.md or CLAUDE.md must name exactly the shipped skills (with a
negative control for the detector). Fails on 47d639a; passes now.
Reported by the #3169 issue author. The matching doctor warning for
pasted lists ships in PR 5.

Intentional pin change: test/test-value-bar.test.ts no longer expects the
README skill list to name /test-audit twice; it now expects that list to
be gone (0 occurrences), the registration this commit removes on purpose.

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

* chore(osv): image-size has a fix; html-to-docx's ^1.0.0 pin blocks it (#2753)

The image-size ledger said no fixed release exists. OSV lists 2.0.3 as
fixed for GHSA-5p2g-fcmc-qvqq and GHSA-w3rx-r6r6-pgpr (checked against
api.osv.dev), but html-to-docx@1.8.0 pins image-size ^1.0.0 and there is
no fixed 1.x, so the fix is a cross-major override. Both entries now say
so and name the upgrade trigger; the 2026-11-30 expiry is kept. New test
checks the wording and that bun.lock still shows the stated pin (it fails
on 47d639a). Correction first raised on #2753 by sonukapoor.

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

* feat(ios-qa): forward GSTACK_IOS_LAUNCH_ENV to devicectl launches (#1796)

Reimplements only the launch-environment half of #1796 (credit
Bmathews721; the session-cache half is superseded by #3132's design and
had state-root and symlink-write problems). devicectl.ts parses
GSTACK_IOS_LAUNCH_ENV as a JSON object of string to string;
launchEnvArgs() returns the --environment-variables argv (empty when
unset or {}) and launchApp passes it before the bundle id. Invalid JSON, a
non-object, a non-string value, a bad name or a key in the debug bridge's
reserved GSTACK_ namespace refuses before any launch with the new result
code IOS_LAUNCH_ENV_INVALID (the detail names keys and types, never
values). launchEnvArgs is exported for the forced-relaunch path in
tunnel-bootstrap.ts.

Adds the result-code row (bin/gstack-doctor-components.sh regenerated by
gen:skill-docs), a troubleshooting entry under its exact text, the
pregate-no-lane entry's explain note, and the how-to section with an
example. New test fails on 47d639a (module load: no parseLaunchEnv).

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

* fix(deps): declare sharp and clear two transitive advisories

sharp is imported in four files, including browse/src/screenshot-size-guard.ts,
and test/dependency-security.test.ts asserts a >=0.35.4 floor on it and loads
it. It was declared in no dependency field, reaching the tree only through
@huggingface/transformers with the overrides pin forcing the version. Declare it
at ^0.35.4, matching the floor that test already asserts.

Upgrade @huggingface/transformers to ^4.3.0, which clears sprintf-js@1.1.3 and
aligns the sharp override with what the parent declares: 4.2.0 declared
sharp ^0.34.5 while the override pins 0.35.5, which is outside that range, and
4.3.0 declares ^0.35.4.

Upgrade @anthropic-ai/claude-agent-sdk to 0.2.141, which clears
@anthropic-ai/sdk@0.81.0.

The existing overrides entry for sharp is left in place.

* test(deps): sharp is declared and its override satisfies every asking range

Reviewer test for #3145 (adopted from sonukapoor): sharp must be a
declared dependency, and the pinned overrides.sharp must satisfy both
that declaration and every lockfile package that depends on sharp
(@huggingface/transformers included). Fails on 47d639a (sharp not
declared; transformers 4.2.0 asked for ^0.34.5 against a 0.35.5 pin).

Classifier smoke on the changed tree (transformers 4.3.0,
onnxruntime-node 1.30.0, sharp 0.35.5, claude-agent-sdk 0.2.141): the real
sidecar entry bundled for Node with a private state root, and the
classifier in-process under Bun, each downloaded the TestSavantAI model
fresh, reported testsavant: ok, and returned scores identical to
47d639a's tree on five inputs, including a >512-token input that
exercises the truncation override. dependency-security, deps-smoke,
overlay-sdk-cancel-eof, security-classifier and screenshot-size-guard
pass; typecheck:test reports no new diagnostics.

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

* fix(gbrain-sync): the no-bash skip names GSTACK_GIT_BASH and how to set it (#3197)

The brain-sync stage's Windows skip line told users to set GSTACK_BASH.
After the fix wave the canonical override is GSTACK_GIT_BASH, with
GSTACK_BASH as a deprecated alias (plan correction 9). The summary is now
the exported NO_BASH_SUMMARY: it names GSTACK_GIT_BASH first and GSTACK_BASH
as the old name, and gives the two recipes that reach Claude Code (a
PowerShell user environment variable plus a Claude Code restart, or the
"env" block of ~/.claude/settings.json).

Minimal on purpose: once PR 2 lands, this switches to
lib/script-invocation.ts noBashMessage(). Until then lib/gbrain-exec.ts
still reads only GSTACK_BASH, so this line is accurate only with PR 2
merged first.

New test test/gbrain-sync-no-bash-message.test.ts fails on the previous
commit (NO_BASH_SUMMARY not exported) and passes now.
Handoff from Lane C (PR 2).

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

* fix(ios-qa): the forced relaunch carries GSTACK_IOS_LAUNCH_ENV too (#1796)

bootstrapTunnel's relaunchApp (an app whose boot token an earlier daemon
consumed is relaunched once with --terminate-existing) built its own
devicectl argv and dropped GSTACK_IOS_LAUNCH_ENV, so an env-gated debug
bridge vanished after the one relaunch the howto says carries it. It now
uses launchEnvArgs(); an invalid value refuses the relaunch with
launch_failed and the IOS_LAUNCH_ENV_INVALID detail before anything is
terminated.

Two new tests in ios-qa/daemon/test/devicectl-launch-env.test.ts drive
bootstrapTunnel through a consumed-token device: both fail on the previous
commit (relaunch argv lacks --environment-variables; the invalid value
still terminates and relaunches) and pass now. ios-qa daemon: 167 pass.
tunnel-bootstrap.ts was assigned to Lane D by the coordinator for this fix.

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

* ci(version-gate): check the version queue only on PRs into main

Stacked layer PRs carry no VERSION stamp by design (the release layer stamps
once), so the queue check failed on any layer touching package.json. The
queue and its collision rule only describe main; a PR into main is still
checked exactly as before.

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

* test(browse): scope the SIGTERM PTY-reap case to POSIX signals (#3147)

windows-free-tests run 38813751242 (shard 6) failed "SIGTERM reaps every
active PTY child before terminal-agent exits" with "timed out waiting for
pty-child.pid", serially and on retry.

Diagnosis: invalid test expectation on Windows, not an agent defect the
test can observe. The contract under test is the agent's graceful
shutdown, its process.on('SIGTERM'/'SIGINT') cleanup in terminal-agent.ts.
On Windows, Bun's subprocess.kill('SIGTERM') is libuv's TerminateProcess,
so that handler never runs there; and the PTY fixture is an extension-less
`#!/bin/bash` script, which CreateProcess cannot launch, so the child never
starts (the timeout is at the pid file, after the port, token, grant and
WebSocket all succeeded). The file's other integration cases were already
Linux-scoped; this one now skips only on win32 and still runs on Linux and
macOS. The pure ownership unit tests in the file keep running on Windows.

Open, not covered by any test: whether a ConPTY child outlives a
hard-terminated agent on Windows. Testing it needs a Windows-launchable
terminal fixture, which BROWSE_TERMINAL_BINARY (one executable, fixed argv)
cannot express without a product change.

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

* fix(plan-review): bound the native outside voice without TaskOutput (#3182)

Claude Code 2.1.277 removed TaskOutput, so the plan-review native fallback's
preflight always failed and users without the Codex CLI never got a second
voice. The fallback now uses primitives the host still enforces: a background
`sleep 300` Bash timer (its exit re-invokes the parent; the 2.1.300 sleep block
applies only to foreground commands), a background Plan dispatch whose
completion arrives as a <task-notification>, and TaskStop for whichever task
loses. Only a matching completed notification that beats the timer counts;
interim ("is waiting on its own background work"), turn-limit, foreground and
late results get no credit. The "[Subagent hand-back]" header (2.1.277) is
treated as framing.

The unavailable line now names its cause and fix, ends with
OUTSIDE_VOICE_UNAVAILABLE (new result code + troubleshooting entry), and the
review-log row carries unavailable_reason. The bounded-wait prose was
tightened so plan-ceo-review and plan-eng-review stay under their existing
size ceilings (no ratchet raise for this item).

Intentional pin change: test/run-in-background-guidance.test.ts
hasBoundedOutsideVoiceWait and the dispatch-contract cases now pin the
timer/notification/TaskStop contract instead of TaskOutput's envelope.
bin/gstack-doctor-components.sh is regenerated from lib/result-codes.ts.

Reported by HuellintonMota in #3182.

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

* feat(bin): gstack-ceo-plan-find locates the CEO plan for a branch (#280)

/plan-ceo-review saves its scope decisions under the state root's
ceo-plans/, but no plan review can find them: only /design-html reads
that directory, newest file first. This helper is the CEO-plan sibling of
gstack-design-doc-find, so /plan-eng-review can call one command instead
of a glob in prose.

It prints the newest top-level plan whose "Branch:" header names the
branch, compared the way gstack-slug writes BRANCH (feat/x matches
feat-x), else the newest plan, else nothing. Subdirectories are not
read. A usage error exits 2.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(plan-eng-review): read the CEO plan in the Design Doc Check (#280)

/plan-eng-review never looked in ceo-plans/, so an eng review after
/plan-ceo-review ran without the scope that review accepted, deferred or
skipped. capy-ai closed #414 asking for this focused fix, and TODOS.md
scopes it as a gstack-ceo-plan-find sibling of gstack-design-doc-find.

The Design Doc Check now prints "CEO plan found: <path>" or "No CEO plan
found" after the design doc line, and the prose says what to read the
plan for. The data-not-instructions rule names the CEO plan too, since
another agent may have written it. Only plan-eng-review changes: the
shared {{DESIGN_DOC_DISCOVERY}} block and the branch-scoped review log
are untouched. Reported by @chancheuklap in #280.

main left plan-eng-review 4 bytes under its parity cap, so the +325
bytes raise maxSizeRatio to the measured 1.2196, noted the way earlier
growth was.

Fixes #280

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(plan-eng-review): disclose a CEO plan borrowed from another branch (#280)

Review changes on top of #3159 (szsunyuan / y$un_):
- gstack-ceo-plan-find keeps stdout a bare path or empty; when it falls back
  to another branch's plan it prints one stderr line,
  "CEO plan found (from branch <b>, not <current>): <path>", with control
  characters stripped from the plan header ("unknown" when it has none).
- The Design Doc Check tells an interactive reviewer to ask before using such
  a plan, and a spawned session to use it and quote the disclosure.
- The Design Doc Check prose is tightened so plan-eng-review fits the
  owner-approved 1.2196 ceiling (measured 151,950 / 124,597 = 1.2195).

Reviewer tests: test/ceo-plan-find-cross-branch.test.ts (5 of 7 fail on the

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
#3159 head). The design-doc finder's matching disclosure stays deferred.

* fix(test): credit abutting section chunks whose edge bytes repeat (#3182)

detectSectionReads trims the longest suffix/prefix overlap between
consecutive Bash outputs. Two chunks that abut exactly (tail -c +N after a
chunk ending at N-1) can share an edge byte by chance; the trim then drops a
real byte and a fully printed section reads as incomplete. #3182's
review-sections edit moved plan-ceo-review's 66,999-byte boundary onto
"cur|rent", which turned the existing byte-range test red. The detector now
also checks the plain concatenation; a gap still refuses.

Detector/fixture defect, not a product change. New regression case in
test/section-capture-native-tools.test.ts fails without the fix.

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

* docs(changelog): fix wave 2026-10-15 release notes

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

* v1.91.104.0 fix: the 2026-10-15 issue wave

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

* fix(qa): probe each documented input rule, not only its boundary values

The paid gate's qa-functional-cli-report run (38829994639) probed zero and an
unsafe integer but never a non-digit amount, so it missed the planted
parseInt defect ("Amounts contain only ASCII digits") and reported no
defect. The functional contract map's invalid-input row now asks for one
probe per documented input rule (allowed characters, format, sign, range,
arity).

test/qa-functional-prompt.test.ts replays a captured CI Read of
system-functional.md; its completed-method variant now feeds the current
section bytes, so the validator check keeps its omitted/pending negative
controls without pinning the old wording.

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

* v1.91.106.0: restamp the fix wave above v1.91.105.0

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

* fix(release): keep the wave's dependency bumps through the main merge

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

---------

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
Co-authored-by: Bryan Stone <aegixx@gmail.com>
Co-authored-by: vilano93 <244097767+vilano93@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: aftabkh4n <akobkz@gmail.com>
Co-authored-by: Benjamin D. Smith <benjamin.smith@binarysword.com>
Co-authored-by: Jess Sullivan <jess@sulliwood.org>
Co-authored-by: NetrioGit <5wngh@naver.com>
Co-authored-by: y$un_ <forrest.sun527@gmail.com>
Co-authored-by: Lockyer <135391289+Lockyer228@users.noreply.github.com>
Co-authored-by: davidfragnoli-lang <249433777+davidfragnoli-lang@users.noreply.github.com>
Co-authored-by: KuroChen <kurochen_macmini@KuroChendeMac-mini.local>
Co-authored-by: AV <vo.quanganh@gmail.com>
Co-authored-by: Y4NN777 <171065166+Y4NN777@users.noreply.github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Sonu Kapoor <sonukapoor@gmail.com>
This commit is contained in:
145 files changed
+8254 -714

No files matched your search

@@ -0,0 +1,167 @@
/**
* Claude Code 2.1.300 auto-compaction no longer copies the kept conversation
* (#3107's 2.1.293 shape). It keeps the last records in place and names them in
* `compactMetadata.preservedSegment` / `preservedMessages`. The boundary's
* logicalParentUuid is the segment's tail, but the tail is written after the
* boundary, relinked under the compact summary (the segment's anchor):
*
* ... -> head -> ... -> last kept record (pre-boundary, in place)
* boundary(parentUuid null, logicalParentUuid tail) -> attachments -> summary -> tail -> ...
*
* Followed literally, the parent links form a cycle (boundary -> tail -> summary
* -> boundary) that never reaches the session root, so every record after the
* compaction was dropped from ownership. The guard then answered each later
* phase entry with `close_incomplete` (the full close packet Read was invisible)
* and retrying could not help.
*/
import { afterEach, describe, expect, test } from 'bun:test';
import * as fs from 'node:fs';
import { randomUUID } from 'node:crypto';
import { guardFixture, section, codeOf, denial, type GuardFixture } from './helpers/autoplan-guard-fixture';
import { readOwnedClaudePublicTranscript } from '../lib/claude-public-transcript';
import { OWNED_READ_APPROVAL } from '../autoplan/bin/owned-read';
type Row = Record<string, any>;
const fixtures: GuardFixture[] = [];
afterEach(() => { for (const f of fixtures.splice(0)) f.cleanup(); });
const rowsOf = (f: GuardFixture): Row[] => fs.readFileSync(f.transcript, 'utf8').trim().split('\n').map(line => JSON.parse(line));
const write = (f: GuardFixture, rows: Row[]) => fs.writeFileSync(f.transcript, rows.map(r => JSON.stringify(r)).join('\n') + '\n');
const usesTool = (r: Row, id: string) => Array.isArray(r.message?.content) && r.message.content.some((b: Row) => b.type === 'tool_use' && b.id === id);
/**
* A Phase 1 run whose close packet is read once in part (line 1) before an
* auto-compaction and in full after it, then published: the order a long
* session produced on Claude Code 2.1.300.
*/
function fixture(history?: Row[]): GuardFixture {
const f = guardFixture(); fixtures.push(f);
const at = f.steps.findIndex(s => s.kind === 'use' && s.id === 'close');
f.read('close-head', f.packet.closePacketPath, 1, 1);
f.steps.splice(at, 0, ...f.steps.splice(-2));
f.publish(); f.journal(f.steps.length, at => at === -1 && history ? history as any : []);
return f;
}
/**
* Insert a 2.1.300-shaped compaction before the record that uses `splitAt`:
* the kept segment is the last `keep` records before it, in place; the tail is
* a new attachment written after the summary; records from `splitAt` on hang
* under the post-compaction attachments.
*/
function compact300(f: GuardFixture, opts: { splitAt?: string; keep?: number; shape?: (boundary: Row) => void } = {}) {
const rows = rowsOf(f), split = rows.findIndex(r => usesTool(r, opts.splitAt ?? 'close'));
const before = rows.slice(0, split), after = rows.slice(split), last = before.at(-1)!;
const stamp = (ms: number) => new Date(Date.parse(last.timestamp) + ms).toISOString();
const base = { isSidechain: false, cwd: last.cwd, sessionId: last.sessionId, version: '2.1.300', userType: 'external', entrypoint: 'cli' };
const keep = opts.keep ?? 4, kept = (keep ? before.slice(-keep) : []).map(r => r.uuid);
const tail = randomUUID(), summary = randomUUID(), boundary = randomUUID();
const attachment = (uuid: string, parentUuid: string, type: string, ms: number) =>
({ ...base, parentUuid, uuid, timestamp: stamp(ms), type: 'attachment', attachment: { type } });
const boundaryRow: Row = { ...base, parentUuid: null, logicalParentUuid: tail, type: 'system', subtype: 'compact_boundary',
content: 'Conversation compacted', level: 'info', uuid: boundary, timestamp: stamp(2000),
compactMetadata: { trigger: 'auto', preTokens: 964539, postTokens: 21605,
preservedSegment: { headUuid: kept[0] ?? tail, anchorUuid: summary, tailUuid: tail },
preservedMessages: { anchorUuid: summary, uuids: [...kept, tail], allUuids: [...kept, tail] } } };
opts.shape?.(boundaryRow);
const instructions = randomUUID(), files = randomUUID();
const compacted = [
boundaryRow,
attachment(instructions, boundary, 'instructions', 2000),
{ ...base, parentUuid: instructions, uuid: summary, timestamp: stamp(1900), type: 'user', isCompactSummary: true,
isVisibleInTranscriptOnly: true, promptId: randomUUID(),
message: { role: 'user', content: 'This session is being continued from a previous conversation that ran out of context.' } },
// The tail keeps its pre-compaction timestamp but is first written here, under the summary.
attachment(tail, summary, 'total_tokens_reminder', 50),
attachment(files, tail, 'compact_file_reference', 2000),
];
after[0] = { ...after[0], parentUuid: files };
write(f, [...before, ...compacted, ...after]);
return { boundary, tail, summary };
}
const nextPhase = (f: GuardFixture) => f.input('next', 'Read', { file_path: section('design-phase.md') });
const toolIds = (f: GuardFixture) => readOwnedClaudePublicTranscript(f.transcript, f.cwd, f.sessionId).events
.filter(e => e.kind === 'use').map(e => (e as any).toolUseId);
describe('Claude Code 2.1.300 compaction with a preserved segment', () => {
test('without the compaction the fixture passes (control)', async () => {
const f = fixture();
expect(await f.hook(nextPhase(f))).toEqual(OWNED_READ_APPROVAL);
});
test('records written after the boundary stay owned', () => {
const f = fixture(); compact300(f);
expect(toolIds(f)).toEqual(['init', 'entry', 'close-head', 'close', expect.stringMatching(/^noop-/)]);
});
test('the next phase entry passes once the close packet is read in full after the compaction', async () => {
const f = fixture(); compact300(f);
expect(await f.hook(nextPhase(f))).toEqual(OWNED_READ_APPROVAL);
});
test('a preserved segment of only the tail (nothing kept in place) names no anchor and is reported as an unrecognized shape', async () => {
const f = fixture(); compact300(f, { keep: 0 });
expect(toolIds(f)).not.toContain('close');
expectUnrecognizedCompaction(f, await f.hook(nextPhase(f)));
});
test('a boundary without compactMetadata whose logical parent cycles back is reported, not silently cut', async () => {
const f = fixture(); compact300(f, { shape: b => { delete b.compactMetadata; } });
expect(readOwnedClaudePublicTranscript(f.transcript, f.cwd, f.sessionId).transcript)
.toMatchObject({ status: 'missing', reason: 'unrecognized_shape:compaction_unreachable' });
expectUnrecognizedCompaction(f, await f.hook(nextPhase(f)));
});
test('a boundary whose logical parent cycles back without a matching preserved tail is reported as an unrecognized shape', async () => {
const f = fixture();
compact300(f, { shape: b => { delete b.compactMetadata.preservedSegment; delete b.compactMetadata.preservedMessages; } });
expect(toolIds(f)).not.toContain('close');
expectUnrecognizedCompaction(f, await f.hook(nextPhase(f)));
});
test('a preserved list naming a record outside this session does not anchor the boundary', async () => {
const f = fixture();
compact300(f, { shape: b => { b.compactMetadata.preservedMessages.uuids = [randomUUID(), b.logicalParentUuid]; } });
expect(toolIds(f)).not.toContain('close');
expectUnrecognizedCompaction(f, await f.hook(nextPhase(f)));
});
test('a compaction whose boundary is not flushed yet still drops what follows and denies (negative control)', async () => {
const f = fixture();
const { boundary } = compact300(f);
write(f, rowsOf(f).filter(r => r.uuid !== boundary));
expect(toolIds(f)).not.toContain('close');
expect(codeOf(await f.hook(nextPhase(f)))).toBe('close_incomplete');
});
test('three compactions in one session stay owned and the next phase entry passes', async () => {
const f = fixture();
for (const splitAt of ['entry', 'close-head', 'close']) compact300(f, { splitAt });
expect(rowsOf(f).filter(r => r.subtype === 'compact_boundary')).toHaveLength(3);
expect(toolIds(f)).toEqual(['init', 'entry', 'close-head', 'close', expect.stringMatching(/^noop-/)]);
expect(await f.hook(nextPhase(f))).toEqual(OWNED_READ_APPROVAL);
});
test('a 50k-record history with three compactions is decided inside the hook budget', async () => {
const history: Row[] = [{ type: 'user', message: { role: 'user', content: 'Review the retry change first.' },
extra: { origin: { kind: 'human' }, promptSource: 'typed', promptId: randomUUID() } }];
for (let i = 0; i < 50_000; i++) history.push({ type: 'assistant', message: { role: 'assistant', id: `msg_pad${i}`, content: [{ type: 'text', text: 'ok' }] } });
history.push({ type: 'assistant', message: { role: 'assistant', id: 'msg_earlier_end', content: [{ type: 'text', text: 'Done.' }], stop_reason: 'end_turn' } });
const f = fixture(history);
for (const splitAt of ['entry', 'close-head', 'close']) compact300(f, { splitAt });
const started = performance.now();
const output = await f.hook(nextPhase(f));
const elapsed = performance.now() - started;
expect(output).toEqual(OWNED_READ_APPROVAL);
expect(elapsed).toBeLessThan(1000);
});
});
/** The guard allows the call with a visible warning and logs the unverified decision; it never denies with close_incomplete. */
function expectUnrecognizedCompaction(f: GuardFixture, output: any) {
expect(denial(output)).toBeUndefined();
expect(codeOf(output)).toBe('unrecognized_shape:compaction_unreachable');
expect(output.systemMessage).toContain('phase publication was NOT verified');
expect(f.log().at(-1)).toMatchObject({ decision: 'allow', disposition: 'unverified', code: 'unrecognized_shape:compaction_unreachable' });
}
+114
View File
@@ -0,0 +1,114 @@
import { afterEach, describe, expect, test } from 'bun:test';
import { spawnSync } from 'node:child_process';
import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
import { checkInstallAdmission } from '../lib/install-verdict';
// #3195: the Bun floor check is sourced from whatever shell runs it; under zsh
// it must still judge (no word splitting), and a version it cannot read holds
// the update with BUN_VERSION_UNREADABLE instead of reading as "not below".
// One version table drives bash, zsh, bash --posix and the TypeScript twin.
const ROOT = path.resolve(import.meta.dir, '..');
const VERSIONS = path.join(ROOT, 'bin', 'gstack-bun-version.sh');
const hasZsh = spawnSync('zsh', ['-c', 'true'], { timeout: 10_000 }).status === 0;
const SHELLS: Array<[string, string[]]> = [['bash', ['bash']], ['bash --posix', ['bash', '--posix']], ['zsh', ['zsh']]];
const bases: string[] = [];
afterEach(() => { for (const b of bases.splice(0)) fs.rmSync(b, { recursive: true, force: true }); });
/** Status against the floor 1.3.3 and the tested 1.4.2. */
const TABLE: Record<string, 'too-old' | 'untested' | 'ok' | 'malformed'> = {
'1.3.2': 'too-old',
'1.3.3-canary.1': 'too-old',
'1.3.3': 'untested',
'1.3.14': 'untested',
'1.4.2': 'ok',
'1.10.0': 'ok',
'01.04.02': 'ok',
'2.0.0': 'ok',
garbage: 'malformed',
};
function run(shell: string[], script: string, args: string[] = [], env: Record<string, string> = {}) {
return spawnSync(shell[0]!, [...shell.slice(1), '-c', script, '_', VERSIONS, ...args], {
encoding: 'utf8', timeout: 10_000, env: { ...process.env, ...env },
});
}
/** A git checkout whose HEAD carries this release's bin/ and VERSION, plus a `bun` that prints `version`. */
function install(version: string) {
const base = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-bun-shells-')));
bases.push(base);
const repo = path.join(base, 'install'), stub = path.join(base, 'stub');
fs.mkdirSync(path.join(repo, 'bin'), { recursive: true });
fs.mkdirSync(stub);
for (const f of ['gstack-bun-version.sh', 'gstack-sanitize-echo.sh']) if (fs.existsSync(path.join(ROOT, 'bin', f))) fs.copyFileSync(path.join(ROOT, 'bin', f), path.join(repo, 'bin', f));
fs.writeFileSync(path.join(repo, 'VERSION'), '9.9.9.9\n');
const git = (...a: string[]) => expect(spawnSync('git', ['-C', repo, ...a], { encoding: 'utf8', timeout: 10_000,
env: { ...process.env, GIT_CONFIG_NOSYSTEM: '1', GIT_AUTHOR_NAME: 't', GIT_AUTHOR_EMAIL: 't@t', GIT_COMMITTER_NAME: 't', GIT_COMMITTER_EMAIL: 't@t' } }).status).toBe(0);
git('init', '-q'); git('add', '-A'); git('commit', '-qm', 'release');
fs.writeFileSync(path.join(stub, 'bun'), `#!/bin/sh\nprintf '%s\\n' '${version.replace(/'/g, "'\\''")}'\n`, { mode: 0o755 });
return { repo, env: { PATH: `${stub}:${process.env.PATH}` }, bun: path.join(stub, 'bun') };
}
describe.skipIf(process.platform === 'win32')('Bun floor check in every shell (#3195)', () => {
for (const [label, shell] of SHELLS) {
test.skipIf(label === 'zsh' && !hasZsh)(`${label}: gstack_bun_status judges the version table`, () => {
const got = Object.fromEntries(Object.keys(TABLE).map(v => [v, run(shell, '. "$1"; gstack_bun_status "$2"', [v]).stdout.trim()]));
expect(got).toEqual(TABLE);
});
}
test.skipIf(!hasZsh)('zsh: Bun 1.3.2 is too old (the issue repro)', () => {
const r = run(['zsh'], '. "$1"; gstack_bun_status 1.3.2');
expect(r.stdout.trim()).toBe('too-old');
expect(r.stderr).not.toContain('integer expression expected');
});
test('a floor the comparison cannot parse is malformed, never ok', () => {
for (const [label, shell] of SHELLS) {
if (label === 'zsh' && !hasZsh) continue;
expect(run(shell, '. "$1"; gstack_bun_status 1.4.2 "$2"', ['1.x.3']).stdout.trim()).toBe('malformed');
}
});
test('the TypeScript twin below() agrees with the same table', () => {
const base = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-bun-twin-'));
bases.push(base);
const refused = (version: string, release: string) => {
fs.mkdirSync(path.join(base, release, 'bin'), { recursive: true });
fs.writeFileSync(path.join(base, release, 'bin', 'gstack-bun-version.sh'), `GSTACK_BUN_TESTED="${release}"\n`);
return checkInstallAdmission({ skill: 'review', gstackRoot: path.join(base, release), bunVersion: version,
env: { GSTACK_SESSION_KIND: 'unattended' } }).status === 'runtime';
};
const got = Object.fromEntries(Object.keys(TABLE).map(v => [v,
v === 'garbage' ? (refused(v, '1.3.3') ? 'malformed' : 'accepted')
: refused(v, '1.3.3') ? 'too-old' : refused(v, '1.4.2') ? 'untested' : 'ok']));
expect(got).toEqual(TABLE);
});
for (const [label, shell] of SHELLS) {
test.skipIf(label === 'zsh' && !hasZsh)(`${label}: the incoming hold holds below the floor and on an unreadable version`, () => {
const old = install('1.3.2');
const held = run(shell, '. "$1"; gstack_bun_incoming_hold "$2" HEAD; echo "rc=$?"', [old.repo], old.env);
expect(held.stdout).toContain(`bun-too-old: found Bun 1.3.2 at ${old.bun}; gstack 9.9.9.9 needs 1.3.3 or newer`);
expect(held.stdout).toContain('rc=0');
const bad = install("bun\x1b[2J\nstages=setup it's");
const unreadable = run(shell, '. "$1"; gstack_bun_incoming_hold "$2" HEAD; echo "rc=$?"', [bad.repo], bad.env);
expect(unreadable.stdout).toBe(`bun-version-unreadable: could not read the version of Bun at ${bad.bun} (bun --version printed 'bun[2J'); ` +
'gstack 9.9.9.9 needs 1.3.3 or newer (BUN_VERSION_UNREADABLE)\nrc=0\n');
const fine = install('1.4.2');
expect(run(shell, '. "$1"; gstack_bun_incoming_hold "$2" HEAD; echo "rc=$?"', [fine.repo], fine.env).stdout).toBe('rc=1\n');
});
}
test('/gstack-upgrade Step 4 runs the floor check through bash, whatever the tool shell is', () => {
const tmpl = fs.readFileSync(path.join(ROOT, 'gstack-upgrade', 'SKILL.md.tmpl'), 'utf8');
expect(tmpl).toContain(`HOLD=$(bash -c '. bin/gstack-bun-version.sh && gstack_bun_incoming_hold . origin/main' 2>/dev/null)`);
expect(tmpl).not.toMatch(/HOLD=\$\(\. bin\/gstack-bun-version\.sh/);
expect(tmpl).toContain('BUN_VERSION_UNREADABLE');
});
});
+99
View File
@@ -0,0 +1,99 @@
import { afterEach, describe, expect, test } from 'bun:test';
import { spawnSync } from 'node:child_process';
import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
import { between } from './helpers/prompt-structure';
// #280 review changes to #3159: stdout stays a bare path (the $DESIGN-style
// API); a plan borrowed from another branch is disclosed on its own stderr
// line, and the skill tells the reviewer what to do with it.
const ROOT = path.resolve(import.meta.dir, '..');
const BIN = path.join(ROOT, 'bin/gstack-ceo-plan-find');
const temps: string[] = [];
afterEach(() => { for (const dir of temps.splice(0)) fs.rmSync(dir, { recursive: true, force: true }); });
function fixture(stateName = 'state') {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'ceo-plan-xb-'));
temps.push(dir);
const home = path.join(dir, 'home');
const state = path.join(dir, stateName);
const plans = path.join(state, 'projects/proj/ceo-plans');
fs.mkdirSync(home, { recursive: true });
fs.mkdirSync(plans, { recursive: true });
const write = (name: string, header: string | null, ageSeconds: number) => {
const file = path.join(plans, name);
fs.writeFileSync(file, `# CEO Plan: Feature\n${header === null ? '' : `${header}\n`}Repo: acme/widgets\n`);
const t = Date.now() / 1000 - ageSeconds;
fs.utimesSync(file, t, t);
return file;
};
const env = { PATH: process.env.PATH!, HOME: home, GSTACK_HOME: state };
const find = (branch = 'feat-x') => {
const r = spawnSync(BIN, ['proj', branch], { cwd: dir, env, encoding: 'utf8', timeout: 10_000 });
return { status: r.status, stdout: r.stdout, stderr: r.stderr };
};
return { dir, home, state, write, env, find };
}
describe('gstack-ceo-plan-find cross-branch disclosure', () => {
test('a plan for this branch prints only its path', () => {
const f = fixture();
const mine = f.write('2026-10-01-mine.md', 'Branch: feat/x | Mode: HOLD SCOPE', 500);
f.write('2026-10-03-other.md', 'Branch: main | Mode: HOLD SCOPE', 10);
expect(f.find()).toEqual({ status: 0, stdout: `${mine}\n`, stderr: '' });
});
test('a fallback plan keeps stdout a bare path and names its branch on stderr', () => {
const f = fixture();
const other = f.write('2026-10-03-other.md', 'Branch: main | Mode: HOLD SCOPE', 10);
expect(f.find()).toEqual({ status: 0, stdout: `${other}\n`, stderr: `CEO plan found (from branch main, not feat-x): ${other}\n` });
});
test('a fallback plan without a Branch line says the branch is unknown', () => {
const f = fixture();
const headerless = f.write('2026-10-03-headerless.md', null, 10);
expect(f.find().stderr).toBe(`CEO plan found (from branch unknown, not feat-x): ${headerless}\n`);
});
test('control characters in a plan header never reach the disclosure line', () => {
const f = fixture();
const other = f.write('2026-10-03-other.md', 'Branch: ma\x1b[31min\x07 | Mode: x', 10);
const { stdout, stderr } = f.find();
expect(stdout).toBe(`${other}\n`);
expect(stderr).toBe(`CEO plan found (from branch ma[31min, not feat-x): ${other}\n`);
});
test("a state root containing a space and an apostrophe still resolves", () => {
const f = fixture("it's state");
const mine = f.write('2026-10-01-mine.md', 'Branch: feat-x | Mode: x', 10);
expect(f.find()).toEqual({ status: 0, stdout: `${mine}\n`, stderr: '' });
});
});
describe('plan-eng-review uses a cross-branch CEO plan only knowingly', () => {
const rendered = fs.readFileSync(path.join(ROOT, 'plan-eng-review/SKILL.md'), 'utf8');
const check = between(rendered, '### Design Doc Check', '### Step 0');
test('the rendered block shows the disclosure next to the found line', () => {
const at = check.indexOf('CEO_PLAN=$(~/.claude/skills/gstack/bin/gstack-ceo-plan-find');
expect(at).toBeGreaterThanOrEqual(0);
const block = check.slice(at).split('\n').slice(0, 2).join('\n');
const f = fixture();
const installed = path.join(f.home, '.claude/skills/gstack/bin');
fs.mkdirSync(installed, { recursive: true });
for (const bin of ['gstack-ceo-plan-find', 'gstack-paths', 'gstack-state-root.sh']) {
fs.copyFileSync(path.join(ROOT, 'bin', bin), path.join(installed, bin));
fs.chmodSync(path.join(installed, bin), 0o755);
}
const other = f.write('2026-10-03-other.md', 'Branch: main | Mode: HOLD SCOPE', 10);
const r = spawnSync('bash', ['-c', `SLUG=proj; BRANCH=feat-x; {\n${block}\n} 2>&1`], { cwd: f.dir, env: f.env, encoding: 'utf8', timeout: 10_000 });
expect(r.stdout.trim().split('\n')).toEqual([`CEO plan found (from branch main, not feat-x): ${other}`, `CEO plan found: ${other}`]);
});
test('interactive sessions ask before using it; spawned sessions use it and quote the disclosure', () => {
const prose = check.replace(/\s+/g, ' ');
expect(prose).toContain('If printed `from branch`, ask before using it; spawned sessions use it and quote that line.');
});
});
+173
View File
@@ -0,0 +1,173 @@
import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { spawn, spawnSync } from 'node:child_process';
import * as fs from 'node:fs';
import * as net from 'node:net';
import * as os from 'node:os';
import { join, resolve } from 'node:path';
import { dockerExactImagePresent, runDocker } from '../lib/cso/docker';
import { childEnvironment, runProcess } from '../lib/cso/process';
// OrbStack installs docker as a symlink to a multicall binary that dispatches
// on argv[0]; the CSO resolves the symlink, so it must still pass "docker" as
// argv[0]. A #! script never sees argv[0], so the fake is compiled C.
const FAKE_MULTICALL = String.raw`
#include <stdio.h>
#include <string.h>
int main(int argc, char **argv) {
const char *slash = strrchr(argv[0], '/');
const char *name = slash ? slash + 1 : argv[0];
if (strcmp(name, "docker") != 0) {
fprintf(stderr, "unsupported argv0 \"%s\"\n", name);
return 127;
}
FILE *log = fopen(LOG_PATH, "a");
if (log) {
for (int i = 1; i < argc; i++) fprintf(log, "%s%s", i > 1 ? " " : "", argv[i]);
fputc('\n', log);
fclose(log);
}
if (argc >= 3 && strcmp(argv[1], "context") == 0 && strcmp(argv[2], "show") == 0) {
puts("orbstack");
return 0;
}
if (argc >= 3 && strcmp(argv[1], "image") == 0 && strcmp(argv[2], "inspect") == 0) {
printf("{\"Os\":\"linux\",\"Architecture\":\"amd64\",\"Id\":\"sha256:%064d\",\"RepoDigests\":[\"%s\"],\"Config\":{\"Entrypoint\":[\"/opt/cso/entrypoint\"]}}\n", 0, argv[argc - 1]);
return 0;
}
for (int i = 1; i < argc; i++)
if (strcmp(argv[i], "ps") == 0 && strncmp(argv[argc - 1], "id=", 3) == 0) puts(argv[argc - 1] + 3);
return 0;
}
`;
describe.skipIf(process.platform === 'win32')('CSO Docker invocation through a multicall binary', () => {
let root = '';
let multicall = '';
let log = '';
beforeAll(() => {
root = fs.realpathSync(fs.mkdtempSync(join(os.tmpdir(), 'cso-argv0-')));
log = join(root, 'docker.log');
const source = join(root, 'docker-tools.c');
fs.writeFileSync(source, FAKE_MULTICALL);
multicall = join(root, 'docker-tools');
const built = spawnSync('/usr/bin/cc', ['-std=c11', `-DLOG_PATH="${log}"`, source, '-o', multicall], {
encoding: 'utf8',
timeout: 30_000,
});
expect(built.status).toBe(0);
fs.symlinkSync('docker-tools', join(root, 'docker'));
});
afterAll(() => {
fs.rmSync(root, { recursive: true, force: true });
});
test('the fake refuses its canonical name, as OrbStack does', async () => {
const r = await runProcess(multicall, ['context', 'show'], {
cwd: root,
env: childEnvironment(root),
raw: true,
});
expect(r.code).toBe(127);
expect(r.stderr).toContain('unsupported argv0 "docker-tools"');
});
test('runDocker invokes the canonical path as docker', async () => {
const r = await runDocker(multicall, ['context', 'show'], {
cwd: root,
env: childEnvironment(root),
raw: true,
});
expect(r.code).toBe(0);
expect(r.stdout.trim()).toBe('orbstack');
});
test('a production image probe admits an image through the multicall binary', async () => {
const socket = join(root, 'probe.sock');
const server = net.createServer().listen(socket);
await new Promise((done) => server.once('listening', done));
try {
const stat = fs.statSync(socket);
const image = `registry.example/cso/semgrep@sha256:${'b'.repeat(64)}`;
const present = await dockerExactImagePresent(
{ uri: `unix://${socket}`, socket, executable: multicall, device: stat.dev, inode: stat.ino },
root,
image,
'linux/amd64',
);
expect(present).toBe(true);
expect(fs.readFileSync(log, 'utf8')).toContain(`image inspect --format {{json .}} ${image}`);
} finally {
server.close();
}
});
test('runProcess refuses an argv0 that is not a bare command name', async () => {
await expect(
runProcess(multicall, ['context', 'show'], { cwd: root, env: childEnvironment(root), argv0: '../docker' }),
).rejects.toThrow('Invalid child argv0');
});
test('the watchdog cleans up through the canonical multicall path', async () => {
const watchdog = join(root, 'watchdog');
const built = spawnSync(
'/usr/bin/cc',
[
'-std=c11',
'-D_POSIX_C_SOURCE=200809L',
'-O2',
resolve(import.meta.dir, '../lib/cso/watchdog.c'),
'-o',
watchdog,
],
{ encoding: 'utf8', timeout: 30_000 },
);
expect(built.status).toBe(0);
const run = join(root, 'run');
const lease = join(run, 'lease');
fs.mkdirSync(lease, { recursive: true });
const token = 'c'.repeat(32);
fs.writeFileSync(join(lease, 'lease.json'), '{}');
fs.writeFileSync(join(lease, 'lease.token'), `${token}\n`);
const id = 'a'.repeat(64);
fs.writeFileSync(join(run, 'resources.journal'), `container:${id}\n`, { mode: 0o600 });
const socket = join(run, 'daemon.sock');
const made = spawnSync('/usr/bin/python3', [
'-c',
'import socket,sys; s=socket.socket(socket.AF_UNIX); s.bind(sys.argv[1]); s.close()',
socket,
], { timeout: 30_000 });
expect(made.status).toBe(0);
const stat = fs.lstatSync(socket);
const owner = spawn('/bin/sleep', ['0.2'], { stdio: 'ignore' });
const child = spawn(
watchdog,
[
'--owner',
String(owner.pid),
'--deadline',
String(Math.ceil((Date.now() + 10_000) / 1000)),
'--run-dir',
run,
'--docker',
multicall,
'--endpoint',
`unix://${socket}`,
'--socket-device',
String(stat.dev),
'--socket-inode',
String(stat.ino),
'--run-label',
'argv0-label',
'--lease-path',
lease,
'--lease-token',
token,
],
{ stdio: 'ignore' },
);
expect(await new Promise<number | null>((done) => child.on('close', done))).toBe(0);
expect(fs.readFileSync(log, 'utf8')).toContain(`rm --force --volumes ${id}`);
expect(fs.readFileSync(join(run, 'watchdog.event'), 'utf8')).toContain('cleanup complete');
expect(fs.existsSync(lease)).toBe(false);
});
});
+141
View File
@@ -0,0 +1,141 @@
import { afterEach, describe, expect, spyOn, test } from 'bun:test';
import * as fs from 'node:fs';
import * as os from 'node:os';
import { join } from 'node:path';
import * as dockerModule from '../lib/cso/docker';
import { DockerGroup } from '../lib/cso/docker';
import { runProcess } from '../lib/cso/process';
import { createDockerScannerRunner } from '../lib/cso/scanner-executor';
import { parseScannerOutput, scannerPlans } from '../lib/cso/scanners';
import { redactFindingSpans, redactJsonFindingSpans } from '../lib/redact-engine';
// #3185: a scanner's JSON report must stay parseable after redaction. A bare
// 10+ digit number (Semgrep's time.max_memory_bytes, an epoch) used to become an
// unquoted marker, JSON.parse failed and /cso reported INVALID_OUTPUT.
const roots: string[] = [];
const restores: Array<() => void> = [];
afterEach(() => {
for (const restore of restores.splice(0).reverse()) restore();
for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true });
});
const tmp = () => {
const dir = fs.realpathSync(fs.mkdtempSync(join(os.tmpdir(), 'cso-json-redaction-')));
roots.push(dir);
return dir;
};
const PHONE = '<REDACTED-pii.phone.e164>';
const json = (input: string) => {
const result = redactJsonFindingSpans(input);
expect(result).not.toBeNull();
// The released text is a fixpoint: a second scan finds nothing (the views check in lib/cso/process.ts).
expect(redactFindingSpans(result!.body)).toBe(result!.body);
return result!.body;
};
const semgrepPlan = () => scannerPlans({ snapshotRoot: '/source', offline: true, selected: ['semgrep'], semgrepRules: '/policy/catalog/semgrep.yml' })[0]!;
const SEMGREP_REPORT = {
results: [{ check_id: 'test-rule', path: '/source/app.js', start: { line: 1, col: 1 }, extra: { message: 'Candidate code defect', severity: 'ERROR' } }],
errors: [], paths: { scanned: ['/source/app.js'] }, time: { max_memory_bytes: 1145427776 },
};
describe('redactJsonFindingSpans', () => {
test('a bare number becomes a quoted marker and the document parses', () => {
expect(JSON.parse(json('{"a":4155551234}'))).toEqual({ a: PHONE });
expect(JSON.parse(json('{"time":{"max_memory_bytes":1145427776}}'))).toEqual({ time: { max_memory_bytes: PHONE } });
});
test('the whole number token is replaced: negative, exponent, every finding id', () => {
expect(JSON.parse(json('{"a":-4155551234}'))).toEqual({ a: PHONE });
expect(JSON.parse(json('{"x":1e-4155551234}'))).toEqual({ x: PHONE });
expect(JSON.parse(json('{"when": 1757012345678}'))).toEqual({ when: '<REDACTED-pii.cc+pii.phone.e164>' });
});
test('arrays, whitespace, several top-level values and NDJSON', () => {
expect(JSON.parse(json('[4155551234,4155551235]'))).toEqual([PHONE, PHONE]);
expect(JSON.parse(json('{ "a" :\n 4155551234 }'))).toEqual({ a: PHONE });
expect(json('{"k":1}\n{"k":4155551234}\n{"k":4155551235}\n').trim().split('\n').map(line => JSON.parse(line)))
.toEqual([{ k: 1 }, { k: PHONE }, { k: PHONE }]);
expect(json('{"k":4155551234}{"k":true}')).toBe(`{"k":"${PHONE}"}{"k":true}`);
});
test('spans inside strings keep the in-string marker, around punctuation and escaped quotes', () => {
expect(JSON.parse(json('{"t":"call 415-555-1234, ok"}'))).toEqual({ t: `call ${PHONE}, ok` });
expect(JSON.parse(json('{"t":"x\\"4155551234\\"y"}'))).toEqual({ t: `x"${PHONE}"y` });
expect(JSON.parse(json('{"t":"4155551234\\n"}'))).toEqual({ t: `${PHONE}\n` });
});
test('a span across several tokens withholds; marker-only findings withhold', () => {
expect(redactFindingSpans('[4111 1111 1111 1111]')).toBe('[<REDACTED-pii.cc+pii.phone.e164>]');
expect(redactJsonFindingSpans('[4111 1111 1111 1111]')).toBeNull();
expect(redactJsonFindingSpans(['{"k":"-----BEGIN RSA ', 'PRIVATE KEY-----\\nMIIE"}'].join(''))).toBeNull();
});
test('a stream that is not JSON keeps the plain splice', () => {
expect(json('plain 4155551234 text')).toBe(redactFindingSpans('plain 4155551234 text')!);
expect(redactFindingSpans('{"a":4155551234}')).toBe(`{"a":${PHONE}}`);
});
});
describe.skipIf(process.platform === 'win32')('scan stdout through the process boundary', () => {
test('a JSON-declared stdout parses after redaction; stderr and undeclared streams stay plain', async () => {
const dir = tmp();
const script = `printf '{"time":{"max_memory_bytes":11454'; sleep .05; printf 'peak 4155551234 bytes' >&2; sleep .05; printf '27776}}'`;
const declared = await runProcess('/bin/sh', ['-c', script], { cwd: dir, env: { PATH: '/usr/bin:/bin' }, redaction: 'splice', stdoutFormat: 'json' });
expect(JSON.parse(declared.stdout)).toEqual({ time: { max_memory_bytes: PHONE } });
expect(declared.stderr).toBe(`peak ${PHONE} bytes`);
const plain = await runProcess('/bin/sh', ['-c', `printf '{"a":4155551234}'`], { cwd: dir, env: { PATH: '/usr/bin:/bin' }, redaction: 'splice' });
expect(plain.stdout).toBe(`{"a":${PHONE}}`);
});
test('a secret split across channels is still withheld with a JSON-declared stdout', async () => {
const dir = tmp();
const r = await runProcess('/bin/sh', ['-c', "printf '{\"k\":\"ghp_abcdefghijklmnop'; printf 'qrstuvwxyz1234567890\"}' >&2"],
{ cwd: dir, env: { PATH: '/usr/bin:/bin' }, redaction: 'splice', stdoutFormat: 'json' });
expect(r.stdout + r.stderr).not.toContain('abcdefghijklmnop');
expect(r.stdout).toBe('[sensitive process output redacted]');
});
});
describe.skipIf(process.platform === 'win32')('Semgrep through the real executor capture path', () => {
test('version then scan with stderr interleaved: the spliced report is complete', async () => {
const dir = tmp();
const report = JSON.stringify(SEMGREP_REPORT), cut = report.indexOf('1145427776') + 4;
fs.writeFileSync(join(dir, 'part1'), report.slice(0, cut));
fs.writeFileSync(join(dir, 'part2'), report.slice(cut));
const docker = join(dir, 'docker');
fs.writeFileSync(docker, [
'#!/bin/sh',
'for last; do :; done',
`if [ "$last" = --version ]; then printf 'semgrep 1.179.0 (max 4155551234)\\n'; exit 0; fi`,
`cat '${join(dir, 'part1')}'; sleep .05; printf 'Scanning 1 file with 4155551234 bytes\\n' >&2; sleep .05; cat '${join(dir, 'part2')}'`,
].join('\n') + '\n', { mode: 0o755 });
const endpoint = { uri: 'unix:///run/fake.sock', socket: '/run/fake.sock', executable: docker, device: 0, inode: 0 };
const spies = [
spyOn(dockerModule, 'dockerEndpoint').mockResolvedValue(endpoint),
spyOn(DockerGroup, 'create').mockImplementation(async (_e, runId, groupDir, deadline) => {
const group = new (DockerGroup as any)(endpoint, runId, groupDir, deadline, {}) as DockerGroup;
spyOn(group, 'createContainer').mockResolvedValue('c'.repeat(64));
spyOn(group, 'start').mockResolvedValue(undefined);
spyOn(group, 'cleanup').mockResolvedValue(undefined);
return group;
}),
];
for (const spy of spies) restores.push(() => spy.mockRestore());
const plan = semgrepPlan();
const runner = await createDockerScannerRunner({
input: { id: 'semgrep', runDir: dir, watchdogPath: '/trusted/test-watchdog' } as any,
plan, profile: { image: `ghcr.io/garrytan/gstack/cso-scanners/semgrep-amd64@sha256:${'a'.repeat(64)}`, executable: '/opt/cso/bin/scanner' } as any,
deadline: Date.now() + 60_000,
});
const version = await runner.version();
const scan = await runner.scan();
await runner.cleanup();
expect(version.stdout).toBe(`semgrep 1.179.0 (max ${PHONE})\n`);
expect(scan.stderr).toBe(`Scanning 1 file with ${PHONE} bytes\n`);
expect(JSON.parse(scan.stdout).time).toEqual({ max_memory_bytes: PHONE });
const outcome = parseScannerOutput(plan, { ...scan, version: version.stdout });
expect(outcome.gaps).toEqual([]);
expect(outcome.status).toBe('complete');
expect(outcome.candidates).toHaveLength(1);
});
});
+1 -1
View File
@@ -136,7 +136,7 @@ describe('CSO scanner qualification workflow', () => {
else expect(scannerBuildMatrix(inputs).include).toHaveLength(12);
const dockerfile = fs.readFileSync(path.join(ROOT, 'lib/cso/scanner-images/scanner.Dockerfile'), 'utf8');
for (const value of ['/opt/cso/entrypoint', '/opt/cso/bin/scanner', 'USER 10001:10001', 'test -x /bin/sleep', 'test -x /bin/cat']) expect(dockerfile).toContain(value);
expect(fs.readFileSync(path.join(ROOT, 'lib/cso/scanner-executor.ts'), 'utf8')).toContain("capture(['/bin/cat', plan.outputPath])");
expect(fs.readFileSync(path.join(ROOT, 'lib/cso/scanner-executor.ts'), 'utf8')).toContain("capture(['/bin/cat', plan.outputPath], plan.format)");
const postgres = fs.readFileSync(path.join(ROOT, 'lib/cso/images/postgresql.Dockerfile'), 'utf8');
for (const value of ['FROM ${BASE_IMAGE} AS upstream', 'FROM scratch', 'COPY --from=upstream / /']) expect(postgres).toContain(value);
});
+12
View File
@@ -17,6 +17,18 @@ describe("security dependency overrides", () => {
});
}
test("sharp is a declared dependency, and the pinned override satisfies every range that asks for it", async () => {
const pkg = JSON.parse(readFileSync(join(import.meta.dir, "../package.json"), "utf8"));
const declared = pkg.dependencies?.sharp;
expect(typeof declared).toBe("string");
const pinned = pkg.overrides?.sharp;
expect(Bun.semver.satisfies(pinned, declared)).toBe(true);
const lock = await Bun.file(join(import.meta.dir, "../bun.lock")).text();
const askers = [...lock.matchAll(/"([@\w./-]+)": \["[^"]+", "", \{ "dependencies": \{[^}]*"sharp": "([^"]+)"/g)];
expect(askers.map(m => m[1])).toContain("@huggingface/transformers");
for (const [, name, range] of askers) expect({ name, ok: Bun.semver.satisfies(pinned, range) }).toEqual({ name, ok: true });
});
test("sharp loads the patched runtime", () => {
expect(Bun.semver.satisfies(sharp.versions.sharp, ">=0.35.4")).toBe(true);
});
+6
View File
@@ -8,6 +8,7 @@
import { describe, test, expect } from 'bun:test';
import * as fs from 'fs';
import * as path from 'path';
import { between, expectMentions } from './helpers/prompt-structure';
const ROOT = path.resolve(import.meta.dir, '..');
const read = (rel: string) => fs.readFileSync(path.join(ROOT, rel), 'utf-8');
@@ -32,4 +33,9 @@ describe('D3: design docs and handoff notes are data, not instructions', () => {
if (file.startsWith('plan-')) expect(block).toContain('handoff note');
});
}
test('plan-eng-review/SKILL.md: the CEO plan it reads is data too (#280)', () => {
const check = between(read('plan-eng-review/SKILL.md'), '### Design Doc Check', '### Step 0');
expectMentions(check, [['ceo plan', 'data, not instructions']], 'plan-eng-review Design Doc Check');
});
});
+2 -1
View File
@@ -114,7 +114,8 @@
{ "file": "lib/pregate/regate.ts", "movedFrom": "(new: the regate verdict from a fresh tree receipt plus migration collisions, field wave CD3)" },
{ "file": "lib/autoplan-scope.ts", "movedFrom": "(new: UI evidence from rendered surfaces and the plan scope marker, shared by the runner and the snapshot tool, field wave B2c)" },
{ "file": "lib/source-root.ts", "movedFrom": "(new: the source checkout behind an install root, from its recorded .source-path, field wave B2e)" },
{ "file": "scripts/resolvers/autoplan-driver.ts", "movedFrom": "(new: renders autoplan/DRIVER.md from the runner's constants, field wave B2e)" }
{ "file": "scripts/resolvers/autoplan-driver.ts", "movedFrom": "(new: renders autoplan/DRIVER.md from the runner's constants, field wave B2e)" },
{ "file": "lib/script-invocation.ts", "movedFrom": "(new: the one Windows bash resolver, shebang-bin invocation and wtreeFingerprint, from spawn-bin.ts and gbrain-exec.ts, #3197)" }
],
"residualFiles": [
{ "file": "scripts/test-free-shards.ts", "maxLines": 2361, "reason": "free lane policy after the shard engine took spawn, sandbox, logs, seeds and flags" },
+99
View File
@@ -0,0 +1,99 @@
#!/usr/bin/env bash
# Exercise the actual updater heartbeat block without git, setup or account state.
set +e
source_file=$1
MODE=$2
FIXTURE=$3
export MODE FIXTURE
mkdir "$FIXTURE/bin" || exit 90
cat > "$FIXTURE/bin/sleep" <<'SH'
#!/usr/bin/env bash
if [ "$1" = 300 ]; then
echo "$$" > "$FIXTURE/sleeper.pid"
exec /bin/sleep 30
fi
exec /bin/sleep "$@"
SH
chmod 700 "$FIXTURE/bin/sleep"
export PATH="$FIXTURE/bin:/usr/bin:/bin"
# Only this bounded lifecycle block is evaluated; never the full updater.
lifecycle=$(sed -n '/^ # In-flight heartbeat:/,/^ # ── Fetch, check/{ /^ # ── Fetch, check/d; p; }' "$source_file")
[ -n "$lifecycle" ] || exit 91
cat > "$FIXTURE/holder.sh" <<'SH'
set +e
LOCK_DIR="$FIXTURE/lock"
mkdir "$LOCK_DIR" || exit 92
MYPID="${BASHPID:-$(sh -c 'echo $PPID')}"
echo "$MYPID" > "$LOCK_DIR/pid"
SH
printf '%s\n' "$lifecycle" >> "$FIXTURE/holder.sh"
cat >> "$FIXTURE/holder.sh" <<'SH'
echo "$HB_PID" > "$FIXTURE/heartbeat.pid"
attempt=0
while [ "$attempt" -lt 100 ]; do
[ -f "$FIXTURE/sleeper.pid" ] && break
/bin/sleep .01
attempt=$((attempt + 1))
done
[ -f "$FIXTURE/sleeper.pid" ] || exit 93
touch "$FIXTURE/ready"
while [ ! -f "$FIXTURE/finish" ]; do /bin/sleep .01; done
[ "$MODE" = failure ] && exit 7
exit 0
SH
/bin/sleep 30 &
sentinel=$!
holder=""
cleanup_fixture() {
# These exact PIDs were created in this private fixture, never process groups.
[ -n "$holder" ] && kill "$holder" 2>/dev/null
for file in heartbeat.pid sleeper.pid; do
if [ -f "$FIXTURE/$file" ]; then
candidate=$(cat "$FIXTURE/$file")
kill -0 "$candidate" 2>/dev/null && kill "$candidate" 2>/dev/null
fi
done
kill "$sentinel" 2>/dev/null
wait "$sentinel" 2>/dev/null
[ -n "$holder" ] && wait "$holder" 2>/dev/null
}
trap cleanup_fixture EXIT
bash "$FIXTURE/holder.sh" &
holder=$!
attempt=0
while [ "$attempt" -lt 100 ]; do
[ -f "$FIXTURE/ready" ] && break
/bin/sleep .01
attempt=$((attempt + 1))
done
[ -f "$FIXTURE/ready" ] || exit 94
heartbeat=$(cat "$FIXTURE/heartbeat.pid")
sleeper=$(cat "$FIXTURE/sleeper.pid")
case "$MODE" in
TERM|HUP) kill -s "$MODE" "$holder" ;;
reclaimed) echo "$sentinel" > "$FIXTURE/lock/pid"; touch "$FIXTURE/finish" ;;
normal|failure) touch "$FIXTURE/finish" ;;
*) exit 95 ;;
esac
wait "$holder"
status=$?
holder=""
expected=0
case "$MODE" in
failure) expected=7 ;;
TERM) expected=143 ;;
HUP) expected=129 ;;
esac
[ "$status" = "$expected" ] || exit 96
kill -0 "$sentinel" 2>/dev/null || exit 97
! kill -0 "$heartbeat" 2>/dev/null || exit 98
! kill -0 "$sleeper" 2>/dev/null || exit 99
if [ "$MODE" = reclaimed ]; then
[ "$(cat "$FIXTURE/lock/pid")" = "$sentinel" ] || exit 100
else
[ ! -e "$FIXTURE/lock" ] || exit 101
fi
# Successful assertions precede fixture-owned sentinel cleanup.
printf 'closed status=%s sentinel=alive heartbeat=absent sleeper=absent\n' "$status"
+109
View File
@@ -0,0 +1,109 @@
{
"$comment": "One table for Windows bash discovery (#3197). Drives lib/script-invocation.ts resolveWindowsBash in test/script-invocation.test.ts. Paths in `exists` are the forward-slashed form the resolver checks. `which` maps a command to its PATH hit; `uname` is what that PATH bash reports for `uname -s`.",
"rows": [
{
"name": "override",
"env": { "GSTACK_GIT_BASH": "D:\\tools\\git\\bin\\bash.exe" },
"exists": ["D:/tools/git/bin/bash.exe", "C:/Program Files/Git/bin/bash.exe"],
"gitExecPath": "C:/Program Files/Git/mingw64/libexec/git-core",
"expect": { "bash": "D:/tools/git/bin/bash.exe", "source": "GSTACK_GIT_BASH" }
},
{
"name": "alias",
"env": { "GSTACK_BASH": "D:\\tools\\git\\bin\\bash.exe" },
"exists": ["D:/tools/git/bin/bash.exe", "C:/Program Files/Git/bin/bash.exe"],
"expect": { "bash": "D:/tools/git/bin/bash.exe", "source": "GSTACK_BASH" }
},
{
"name": "override and alias differ: the canonical name wins, with a warning",
"env": { "GSTACK_GIT_BASH": "D:/a/bash.exe", "GSTACK_BASH": "D:/b/bash.exe" },
"exists": ["D:/a/bash.exe", "D:/b/bash.exe"],
"expect": { "bash": "D:/a/bash.exe", "source": "GSTACK_GIT_BASH" },
"warning": "GSTACK_GIT_BASH (D:/a/bash.exe) and the deprecated GSTACK_BASH (D:/b/bash.exe) differ; using GSTACK_GIT_BASH"
},
{
"name": "override and alias agree: no warning",
"env": { "GSTACK_GIT_BASH": "D:\\a\\bash.exe", "GSTACK_BASH": "D:/a/bash.exe" },
"exists": ["D:/a/bash.exe"],
"expect": { "bash": "D:/a/bash.exe", "source": "GSTACK_GIT_BASH" },
"warning": null
},
{
"name": "override that does not exist is refused, never skipped",
"env": { "GSTACK_GIT_BASH": "D:/gone/bash.exe" },
"exists": ["C:/Program Files/Git/bin/bash.exe"],
"expect": { "refused": true, "mentions": ["GSTACK_GIT_BASH D:/gone/bash.exe: does not exist"] }
},
{
"name": "scoop shim: git --exec-path resolves through the shim",
"env": { "USERPROFILE": "C:\\Users\\u" },
"which": { "git": "C:\\Users\\u\\scoop\\shims\\git.exe" },
"gitExecPath": "C:\\Users\\u\\scoop\\apps\\git\\current\\mingw64\\libexec\\git-core",
"exists": ["C:/Users/u/scoop/apps/git/current/bin/bash.exe"],
"expect": { "bash": "C:/Users/u/scoop/apps/git/current/bin/bash.exe", "source": "git --exec-path" }
},
{
"name": "per-user Git",
"env": { "LOCALAPPDATA": "C:\\Users\\u\\AppData\\Local" },
"gitExecPath": "C:/Users/u/AppData/Local/Programs/Git/mingw64/libexec/git-core",
"exists": ["C:/Users/u/AppData/Local/Programs/Git/bin/bash.exe"],
"expect": { "bash": "C:/Users/u/AppData/Local/Programs/Git/bin/bash.exe", "source": "git --exec-path" }
},
{
"name": "per-user Git without git on PATH: the known install path",
"env": { "LOCALAPPDATA": "C:\\Users\\u\\AppData\\Local" },
"exists": ["C:/Users/u/AppData/Local/Programs/Git/bin/bash.exe"],
"expect": { "bash": "C:/Users/u/AppData/Local/Programs/Git/bin/bash.exe", "source": "install path" }
},
{
"name": "portable Git",
"gitExecPath": "D:/PortableGit/mingw64/libexec/git-core",
"exists": ["D:/PortableGit/bin/bash.exe"],
"expect": { "bash": "D:/PortableGit/bin/bash.exe", "source": "git --exec-path" }
},
{
"name": "Git for Windows on arm64",
"gitExecPath": "C:/Program Files/Git/clangarm64/libexec/git-core",
"exists": ["C:/Program Files/Git/usr/bin/bash.exe"],
"expect": { "bash": "C:/Program Files/Git/usr/bin/bash.exe", "source": "git --exec-path" }
},
{
"name": "standard install, git missing from PATH",
"exists": ["C:/Program Files/Git/bin/bash.exe"],
"expect": { "bash": "C:/Program Files/Git/bin/bash.exe", "source": "install path" }
},
{
"name": "MSYS2 bash on PATH",
"which": { "bash": "C:\\msys64\\usr\\bin\\bash.exe" },
"uname": "MSYS_NT-10.0-22631",
"exists": ["C:/msys64/usr/bin/bash.exe"],
"expect": { "bash": "C:/msys64/usr/bin/bash.exe", "source": "PATH" }
},
{
"name": "WSL rejection: System32 bash.exe",
"which": { "bash": "C:\\Windows\\System32\\bash.exe" },
"uname": "Linux",
"exists": ["C:/Windows/System32/bash.exe"],
"expect": { "refused": true, "mentions": ["PATH C:/Windows/System32/bash.exe: WSL launcher, not Git Bash", "GSTACK_GIT_BASH"] }
},
{
"name": "WSL rejection: WindowsApps bash.exe",
"which": { "bash": "C:\\Users\\u\\AppData\\Local\\Microsoft\\WindowsApps\\bash.exe" },
"uname": "Linux",
"exists": ["C:/Users/u/AppData/Local/Microsoft/WindowsApps/bash.exe"],
"expect": { "refused": true, "mentions": ["WSL launcher, not Git Bash"] }
},
{
"name": "a non-MSYS PATH bash is no longer used",
"which": { "bash": "C:\\cygwin64\\bin\\bash.exe" },
"uname": "CYGWIN_NT-10.0",
"exists": ["C:/cygwin64/bin/bash.exe"],
"expect": { "refused": true, "mentions": ["PATH C:/cygwin64/bin/bash.exe: uname -s reports CYGWIN_NT-10.0, not MSYS/MINGW"] }
},
{
"name": "missing: every candidate is listed with its reason",
"exists": [],
"expect": { "refused": true, "mentions": ["GSTACK_GIT_BASH (unset): not set", "git --exec-path (git): git not found or failed", "install path C:/Program Files/Git/bin/bash.exe: not found", "PATH bash: not on PATH", "(BASH_UNAVAILABLE)"] }
}
]
}
+87
View File
@@ -10,6 +10,7 @@
import { describe, it, expect, beforeEach, afterEach } from "bun:test";
import { mkdtempSync, writeFileSync, readFileSync, existsSync, rmSync, chmodSync, statSync } from "fs";
import { spawnSync } from "child_process";
import { tmpdir } from "os";
import { join } from "path";
@@ -18,14 +19,35 @@ import { ensureGbrainSourceGitignored } from "../bin/gstack-gbrain-sync";
describe("ensureGbrainSourceGitignored", () => {
let root: string;
let home: string;
const saved: Record<string, string | undefined> = {};
const ISOLATED = ["HOME", "XDG_CONFIG_HOME", "GIT_CONFIG_GLOBAL", "GIT_CONFIG_NOSYSTEM"] as const;
beforeEach(() => {
root = mkdtempSync(join(tmpdir(), "gstack-gbrain-gitignore-"));
home = mkdtempSync(join(tmpdir(), "gstack-gbrain-gitignore-home-"));
for (const key of ISOLATED) saved[key] = process.env[key];
process.env.HOME = home;
process.env.XDG_CONFIG_HOME = join(home, ".config");
delete process.env.GIT_CONFIG_GLOBAL;
process.env.GIT_CONFIG_NOSYSTEM = "1";
});
afterEach(() => {
for (const key of ISOLATED) {
if (saved[key] === undefined) delete process.env[key];
else process.env[key] = saved[key];
}
rmSync(root, { recursive: true, force: true });
rmSync(home, { recursive: true, force: true });
});
const git = (...args: string[]) => {
const r = spawnSync("git", args, { cwd: root, encoding: "utf-8", timeout: 10_000 });
expect(r.status).toBe(0);
return r;
};
it("creates .gitignore with the pin entry when none exists", () => {
const gitignorePath = join(root, ".gitignore");
expect(existsSync(gitignorePath)).toBe(false);
@@ -81,6 +103,71 @@ describe("ensureGbrainSourceGitignored", () => {
expect(hits.length).toBe(1);
});
it("does not append when git already ignores the pin", () => {
const gitignorePath = join(root, ".gitignore");
const canonical = "# gstack-artifacts sync: ignore-everything base.\n*\n";
writeFileSync(gitignorePath, canonical);
const init = spawnSync("git", ["init", "-q"], { cwd: root, timeout: 10_000 });
expect(init.status).toBe(0);
git("add", "-f", ".gitignore");
ensureGbrainSourceGitignored(root);
expect(readFileSync(gitignorePath, "utf-8")).toBe(canonical);
});
it("still appends in a git repo whose patterns do not ignore the pin", () => {
const gitignorePath = join(root, ".gitignore");
writeFileSync(gitignorePath, "node_modules\n");
const init = spawnSync("git", ["init", "-q"], { cwd: root, timeout: 10_000 });
expect(init.status).toBe(0);
ensureGbrainSourceGitignored(root);
expect(readFileSync(gitignorePath, "utf-8")).toBe("node_modules\n.gbrain-source\n");
});
it("still appends when only the user's global excludes ignore the pin", () => {
const gitignorePath = join(root, ".gitignore");
writeFileSync(gitignorePath, "node_modules\n");
git("init", "-q");
git("add", ".gitignore");
const excludes = join(home, "global-excludes");
writeFileSync(excludes, ".gbrain-source\n");
writeFileSync(join(home, ".gitconfig"), `[core]\n\texcludesFile = ${JSON.stringify(excludes)}\n`);
expect(spawnSync("git", ["check-ignore", "-q", ".gbrain-source"], { cwd: root, timeout: 10_000 }).status).toBe(0);
ensureGbrainSourceGitignored(root);
expect(readFileSync(gitignorePath, "utf-8")).toBe("node_modules\n.gbrain-source\n");
});
it("still appends when only .git/info/exclude ignores the pin", () => {
const gitignorePath = join(root, ".gitignore");
writeFileSync(gitignorePath, "node_modules\n");
git("init", "-q");
git("add", ".gitignore");
writeFileSync(join(root, ".git", "info", "exclude"), ".gbrain-source\n");
ensureGbrainSourceGitignored(root);
expect(readFileSync(gitignorePath, "utf-8")).toBe("node_modules\n.gbrain-source\n");
});
it("still appends when the ignoring .gitignore is untracked, or re-includes the pin", () => {
const gitignorePath = join(root, ".gitignore");
writeFileSync(gitignorePath, "*\n");
git("init", "-q");
ensureGbrainSourceGitignored(root);
expect(readFileSync(gitignorePath, "utf-8")).toBe("*\n.gbrain-source\n");
writeFileSync(gitignorePath, "*\n!.gbrain-source\n");
git("add", "-f", ".gitignore");
ensureGbrainSourceGitignored(root);
expect(readFileSync(gitignorePath, "utf-8")).toBe("*\n!.gbrain-source\n.gbrain-source\n");
});
it("does not throw when the .gitignore is read-only", () => {
const gitignorePath = join(root, ".gitignore");
writeFileSync(gitignorePath, "node_modules\n");
+8 -3
View File
@@ -58,7 +58,10 @@ describe("#1731 gbrain spawns carry the Windows shell flag", () => {
});
describe("bashScriptInvocation", () => {
const WIN_BASH = "C:\\Program Files\\Git\\bin\\bash.exe";
// Forward-slashed: the one resolver (lib/script-invocation.ts) normalizes
// every candidate, because Bun's spawnSync on Windows returns ENOENT for a
// backslash exe path containing spaces.
const WIN_BASH = "C:/Program Files/Git/bin/bash.exe";
test("POSIX execs the script directly, no interpreter needed", () => {
const inv = bashScriptInvocation("/home/u/.claude/skills/gstack/bin/gstack-brain-sync", ["--once"], {
@@ -106,16 +109,18 @@ describe("bashScriptInvocation", () => {
const custom = "D:\\tools\\git\\bin\\bash.exe";
const inv = bashScriptInvocation("C:\\x\\gstack-brain-sync", [], {
platform: "win32",
exists: (p) => p === custom || p === WIN_BASH,
exists: (p) => p === "D:/tools/git/bin/bash.exe" || p === WIN_BASH,
env: { GSTACK_BASH: custom },
});
expect(inv?.cmd).toBe(custom);
expect(inv?.cmd).toBe("D:/tools/git/bin/bash.exe");
});
test("returns null when Windows has no bash, so the caller can say why", () => {
const inv = bashScriptInvocation("C:\\x\\gstack-brain-sync", [], {
platform: "win32",
exists: () => false,
gitExecPath: () => null,
which: () => null,
env: {},
});
expect(inv).toBeNull();
+32
View File
@@ -0,0 +1,32 @@
/**
* The brain-sync stage of gstack-gbrain-sync skips with a one-line summary
* when Windows has no bash. That line must name the canonical override
* GSTACK_GIT_BASH (GSTACK_BASH is the deprecated alias) and say how to set it
* so Claude Code sees it: a Git Bash `export` reaches only that shell.
*/
import { describe, expect, test } from "bun:test";
import * as fs from "node:fs";
import * as path from "node:path";
import { NO_BASH_SUMMARY } from "../bin/gstack-gbrain-sync";
describe("gstack-gbrain-sync no-bash summary", () => {
test("names GSTACK_GIT_BASH first and GSTACK_BASH as the old alias", () => {
expect(NO_BASH_SUMMARY).toContain("GSTACK_GIT_BASH");
expect(NO_BASH_SUMMARY).toContain("GSTACK_BASH");
expect(NO_BASH_SUMMARY.indexOf("GSTACK_GIT_BASH")).toBeLessThan(NO_BASH_SUMMARY.indexOf("old name: GSTACK_BASH"));
});
test("gives the PowerShell user-variable and settings.json recipes", () => {
expect(NO_BASH_SUMMARY).toContain("[Environment]::SetEnvironmentVariable('GSTACK_GIT_BASH'");
expect(NO_BASH_SUMMARY).toContain("'User')");
expect(NO_BASH_SUMMARY).toContain("restart Claude Code");
expect(NO_BASH_SUMMARY).toContain('"env" block of ~/.claude/settings.json');
});
test("the brain-sync stage reports exactly this summary when bash is missing", () => {
const src = fs.readFileSync(path.join(import.meta.dir, "..", "bin", "gstack-gbrain-sync.ts"), "utf8");
const stage = src.slice(src.indexOf("function runBrainSyncPush("), src.indexOf("function runBrainSyncPush(") + 3000);
expect(stage).toMatch(/if \(!discover \|\| !once\) \{[\s\S]{0,200}summary: NO_BASH_SUMMARY/);
expect(src).not.toContain("set GSTACK_BASH to your Git bash.exe");
});
});
+27 -6
View File
@@ -45,10 +45,11 @@ function fixture(opts: { playwright?: boolean } = {}) {
'} };',
].join('\n'));
}
// `bunx playwright install chromium` "installs" by writing the marker and logging its argv.
write(path.join(stub, 'bunx'), `#!/usr/bin/env bash\necho "$*" >> "${base}/bunx-calls"\ncase "$*" in *"playwright install"*) touch "${marker}" ;; *) exit 9 ;; esac\n`, 0o755);
write(path.join(stub, 'bun'), '#!/usr/bin/env bash\n[ "$1" = --version ] && { echo 1.4.2; exit 0; }\nexit 0\n', 0o755);
const env: Record<string, string> = { PATH: `${stub}${path.delimiter}${process.env.PATH ?? ''}`, HOME: base, TMPDIR: base, GSTACK_PLAYWRIGHT_INSTALL_TIMEOUT: '20' };
// A winget-shaped Bun (#3131): `bun` and no `bunx` anywhere on PATH. `bun x playwright install chromium`
// "installs" by writing the marker and logging its argv.
write(path.join(stub, 'bun'), `#!/usr/bin/env bash\n[ "$1" = --version ] && { echo 1.4.2; exit 0; }\n[ "$1" = x ] || exit 0\nshift\necho "$*" >> "${base}/bunx-calls"\ncase "$*" in *"playwright install"*) touch "${marker}" ;; *) exit 9 ;; esac\n`, 0o755);
const rest = (process.env.PATH ?? '').split(path.delimiter).filter((d) => d && !fs.existsSync(path.join(d, 'bunx')));
const env: Record<string, string> = { PATH: [stub, ...rest].join(path.delimiter), HOME: base, TMPDIR: base, GSTACK_PLAYWRIGHT_INSTALL_TIMEOUT: '20' };
const run = (args: string[] = [], extra: Record<string, string> = {}) =>
spawnSync('bash', [path.join(root, 'bin/gstack-browser-ensure'), ...args], { encoding: 'utf8', env: { ...env, ...extra }, timeout: 60_000 });
return { base, root, marker, run, calls: () => fs.existsSync(path.join(base, 'bunx-calls')) ? fs.readFileSync(path.join(base, 'bunx-calls'), 'utf8') : '' };
@@ -104,10 +105,10 @@ describe('gstack-browser-ensure', () => {
test('an installer failure is BROWSER_UNAVAILABLE with the exit code; usage errors exit 2; --help exits 0', () => {
const f = fixture();
fs.writeFileSync(path.join(f.base, 'stub/bunx'), '#!/usr/bin/env bash\nexit 7\n');
fs.writeFileSync(path.join(f.base, 'stub/bun'), '#!/usr/bin/env bash\nexit 7\n');
const r = f.run();
expect(r.status).toBe(1);
expect(lastLine(r.stdout)).toBe('BROWSER_UNAVAILABLE bunx playwright install chromium exited 7 (offline, proxy, or blocked download?)');
expect(lastLine(r.stdout)).toBe(`BROWSER_UNAVAILABLE ${path.join(f.base, 'stub/bun')} x playwright install chromium exited 7 (offline, proxy, or blocked download?)`);
expect(f.run(['--bogus']).status).toBe(2);
const help = f.run(['--help']);
expect(help.status).toBe(0);
@@ -115,6 +116,26 @@ describe('gstack-browser-ensure', () => {
});
});
describe('gstack-browser-ensure with a winget-shaped Bun (#3131)', () => {
test('the install runs as `bun x` when no bunx exists, then re-probes to BROWSER_OK', () => {
const f = fixture();
const r = f.run();
expect(r.status, r.stdout + r.stderr).toBe(0);
expect(lastLine(r.stdout)).toBe('BROWSER_OK node 141.0.7390.37');
expect(f.calls().trim()).toBe('playwright install chromium');
});
test('exit 127 names the resolved bun and Bun from bun.sh, not the network', () => {
const f = fixture();
fs.writeFileSync(path.join(f.base, 'stub/bun'), '#!/usr/bin/env bash\nexit 127\n');
const r = f.run();
expect(r.status).toBe(1);
expect(lastLine(r.stdout)).toBe(`BROWSER_UNAVAILABLE ${path.join(f.base, 'stub/bun')} x playwright install chromium exited 127 (command not found)`);
expect(r.stderr).toContain('fix: install Bun from bun.sh (winget Bun ships no bunx), then re-run');
expect(r.stderr).not.toContain('Playwright CDN');
});
});
describe('browse preflight wiring (scripts/resolvers/browse.ts)', () => {
test('every browser skill\'s $B detection runs gstack-browser-ensure from the install root before READY', () => {
for (const host of ['claude', 'codex'] as const) {
+119
View File
@@ -0,0 +1,119 @@
import { afterEach, describe, expect, test } from 'bun:test';
import { execFileSync } from 'node:child_process';
import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
import { between } from './helpers/prompt-structure';
const ROOT = path.resolve(import.meta.dir, '..');
const BIN = path.join(ROOT, 'bin/gstack-ceo-plan-find');
const temps: string[] = [];
afterEach(() => {
for (const dir of temps.splice(0)) fs.rmSync(dir, { recursive: true, force: true });
});
function fixture() {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'ceo-plan-find-'));
temps.push(dir);
const home = path.join(dir, 'home');
fs.mkdirSync(home, { recursive: true });
const plans = path.join(home, '.gstack/projects/proj/ceo-plans');
const baseEnv = { PATH: process.env.PATH!, HOME: home };
// The header /plan-ceo-review writes (plan-ceo-review/SKILL.md.tmpl, 0H).
const write = (file: string, branch: string | null, ageSeconds: number) => {
fs.mkdirSync(path.dirname(file), { recursive: true });
const header = branch === null ? '' : `Branch: ${branch} | Mode: SELECTIVE EXPANSION\n`;
fs.writeFileSync(file, `---\nstatus: ACTIVE\n---\n# CEO Plan: Feature\nGenerated by /plan-ceo-review on 2026-10-12\n${header}Repo: acme/widgets\n`);
const t = Date.now() / 1000 - ageSeconds;
fs.utimesSync(file, t, t);
return file;
};
const find = (env: Record<string, string> = {}, args = ['proj', 'feat-x']) =>
execFileSync(BIN, args, { cwd: dir, env: { ...baseEnv, ...env }, encoding: 'utf8', timeout: 10_000 }).trim();
return { dir, home, plans, write, find };
}
describe('gstack-ceo-plan-find', () => {
test('default root is ~/.gstack and prints nothing when no plan exists', () => {
const f = fixture();
expect(f.find()).toBe('');
const plan = f.write(path.join(f.plans, '2026-10-01-feature.md'), 'feat/x', 100);
expect(f.find()).toBe(plan);
});
test('GSTACK_HOME moves the state root', () => {
const f = fixture();
f.write(path.join(f.plans, '2026-10-01-a.md'), 'feat/x', 10);
const custom = path.join(f.dir, 'custom-state');
const plan = f.write(path.join(custom, 'projects/proj/ceo-plans/2026-10-02-b.md'), 'feat/x', 100);
expect(f.find({ GSTACK_HOME: custom })).toBe(plan);
});
test('the plan for this branch wins over a newer plan for another branch', () => {
const f = fixture();
// gstack-slug reports feat/x as feat-x; the plan header keeps the slash.
const mine = f.write(path.join(f.plans, '2026-10-01-mine.md'), 'feat/x', 500);
const other = f.write(path.join(f.plans, '2026-10-03-other.md'), 'main', 10);
expect(f.find()).toBe(mine);
expect(f.find({}, ['proj', 'main'])).toBe(other);
expect(f.find({}, ['proj', 'unrelated'])).toBe(other);
});
test('the newest plan for the branch wins, and a plan without a Branch line is still a fallback', () => {
const f = fixture();
f.write(path.join(f.plans, '2026-10-01-old.md'), 'feat-x', 500);
const newer = f.write(path.join(f.plans, '2026-10-02-new.md'), 'feat-x', 100);
const headerless = f.write(path.join(f.plans, '2026-10-03-headerless.md'), null, 10);
expect(f.find()).toBe(newer);
expect(f.find({}, ['proj', 'other'])).toBe(headerless);
});
test('only top-level plans count', () => {
const f = fixture();
const plan = f.write(path.join(f.plans, '2026-10-01-live.md'), 'feat/x', 500);
f.write(path.join(f.plans, 'archive/2026-10-02-old.md'), 'feat/x', 10);
expect(f.find()).toBe(plan);
});
test('usage errors exit 2', () => {
const f = fixture();
for (const args of [[], ['proj'], ['', 'feat-x']]) {
let status: number | null = null;
try { f.find({}, args); } catch (err) { status = (err as { status: number | null }).status; }
expect(status).toBe(2);
}
});
});
describe('rendered plan-eng-review Design Doc Check (#280)', () => {
const rendered = fs.readFileSync(path.join(ROOT, 'plan-eng-review/SKILL.md'), 'utf8');
const check = between(rendered, '### Design Doc Check', '### Step 0');
const at = check.indexOf('CEO_PLAN=$(~/.claude/skills/gstack/bin/gstack-ceo-plan-find');
const block = check.slice(Math.max(at, 0)).split('\n').slice(0, 2).join('\n');
test('the check renders one CEO-plan helper invocation before Step 0', () => {
expect(at).toBeGreaterThanOrEqual(0);
expect(block).toContain('gstack-ceo-plan-find "$SLUG" "$BRANCH"');
expect(block).toContain('echo "CEO plan found: $CEO_PLAN"');
expect(block).toContain('echo "No CEO plan found"');
});
test('finds the plan for this branch under a custom GSTACK_HOME and reports none elsewhere', () => {
expect(at).toBeGreaterThanOrEqual(0);
const f = fixture();
const installed = path.join(f.home, '.claude/skills/gstack/bin');
fs.mkdirSync(installed, { recursive: true });
for (const bin of ['gstack-ceo-plan-find', 'gstack-paths', 'gstack-state-root.sh']) {
fs.copyFileSync(path.join(ROOT, 'bin', bin), path.join(installed, bin));
fs.chmodSync(path.join(installed, bin), 0o755);
}
const run = (env: Record<string, string>) => execFileSync('bash', ['-c', `SLUG=proj; BRANCH=feat-x; ${block}`],
{ cwd: f.dir, env: { PATH: process.env.PATH!, HOME: f.home, ...env }, encoding: 'utf8', timeout: 10_000 }).trim();
const custom = path.join(f.dir, 'custom-state');
const mine = f.write(path.join(custom, 'projects/proj/ceo-plans/2026-10-01-mine.md'), 'feat/x', 500);
f.write(path.join(custom, 'projects/proj/ceo-plans/2026-10-03-other.md'), 'main', 10);
expect(run({ GSTACK_HOME: custom })).toBe(`CEO plan found: ${mine}`);
expect(run({})).toBe('No CEO plan found');
});
});
+441
View File
@@ -0,0 +1,441 @@
/**
* bin/gstack-ff-update moves a gstack install's tree: the session-start
* updater, /gstack-upgrade Step 4 and the held-install recovery commands call
* it. Edits that ride over the update stay in place; an edit that conflicts,
* a staged change or an unmerged file is shelved in refs/gstack/rescue/<oid>
* (first parent the pre-update HEAD, second the staged state) and the install
* lands clean on the target. Nothing is ever left as conflict markers, and a
* refusal changes nothing.
*/
import { afterEach, describe, expect, test } from 'bun:test';
import { execFileSync, spawn, spawnSync } from 'node:child_process';
import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
const ROOT = path.resolve(import.meta.dir, '..');
const FF = path.join(ROOT, 'bin', 'gstack-ff-update');
const UPDATER = path.join(ROOT, 'bin', 'gstack-session-update');
const bases: string[] = [];
afterEach(() => { for (const b of bases.splice(0)) fs.rmSync(b, { recursive: true, force: true }); });
function git(cwd: string, ...args: string[]): string {
return execFileSync('git', args, { cwd, encoding: 'utf8', timeout: 30_000 }).trim();
}
function gitStatus(cwd: string, ...args: string[]) {
return spawnSync('git', args, { cwd, encoding: 'utf8', timeout: 30_000 });
}
const FIXED_DATES = { GIT_AUTHOR_DATE: '2026-10-15T12:00:00Z', GIT_COMMITTER_DATE: '2026-10-15T12:00:00Z' };
/** A bare origin, a seed that publishes releases, and an install cloned from it. */
function makeFixture(dirName = 'install') {
const base = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-ff-')));
bases.push(base);
const origin = path.join(base, 'origin.git');
const seed = path.join(base, 'seed');
const install = path.join(base, dirName);
execFileSync('git', ['init', '-q', '--bare', '-b', 'main', origin], { timeout: 30_000 });
fs.mkdirSync(path.join(seed, 'qa', 'sections'), { recursive: true });
fs.writeFileSync(path.join(seed, 'VERSION'), '1.0.0\n');
fs.writeFileSync(path.join(seed, 'notes.txt'), 'top\nmiddle\nbottom\n');
fs.writeFileSync(path.join(seed, 'other.txt'), 'other\n');
fs.writeFileSync(path.join(seed, 'fix.txt'), 'bug\n');
fs.writeFileSync(path.join(seed, 'SKILL.md'), 'name: gstack\nbody\n');
fs.writeFileSync(path.join(seed, 'qa', 'SKILL.md'), 'name: qa\nbody\n');
fs.writeFileSync(path.join(seed, 'qa', 'sections', 'one.md'), 'one\n');
git(seed, 'init', '-q', '-b', 'main');
git(seed, 'add', '-A');
git(seed, '-c', 'user.name=t', '-c', 'user.email=t@t', 'commit', '-q', '-m', 'seed');
git(seed, 'remote', 'add', 'origin', origin);
git(seed, 'push', '-q', 'origin', 'main');
execFileSync('git', ['clone', '-q', origin, install], { timeout: 30_000 });
return { base, origin, seed, install };
}
type Fx = ReturnType<typeof makeFixture>;
function release(fx: Fx, files: Record<string, string>, version = '1.1.0'): string {
for (const [f, body] of Object.entries(files)) fs.writeFileSync(path.join(fx.seed, f), body);
fs.writeFileSync(path.join(fx.seed, 'VERSION'), `${version}\n`);
git(fx.seed, 'add', '-A');
git(fx.seed, '-c', 'user.name=t', '-c', 'user.email=t@t', 'commit', '-q', '-m', `release ${version}`);
git(fx.seed, 'push', '-q', 'origin', 'main');
git(fx.install, 'fetch', '-q');
return git(fx.seed, 'rev-parse', 'HEAD');
}
/** An environment with no user identity, no global or system git config. */
function isolatedEnv(base: string, extra: Record<string, string> = {}) {
const home = path.join(base, 'home');
fs.mkdirSync(home, { recursive: true });
return { PATH: process.env.PATH!, HOME: home, XDG_CONFIG_HOME: path.join(home, '.config'), GIT_CONFIG_NOSYSTEM: '1', TMPDIR: base, ...extra };
}
function ff(fx: Fx, rev = 'origin/main', extra: Record<string, string> = {}, bin = FF, cwd = fx.base) {
return spawnSync('bash', [bin, fx.install, rev], { cwd, encoding: 'utf8', env: isolatedEnv(fx.base, extra), timeout: 60_000 });
}
const read = (fx: Fx, f: string) => fs.readFileSync(path.join(fx.install, f), 'utf8');
const write = (fx: Fx, f: string, body: string) => fs.writeFileSync(path.join(fx.install, f), body);
const rescueRef = (out: string) => out.match(/^rescued [0-9a-f]+ [0-9a-f]+ (refs\/gstack\/rescue\/[0-9a-f]{40}) unmerged=([01])$/m);
function makeUnmerged(fx: Fx, file: string) {
const blob = (body: string) => execFileSync('git', ['hash-object', '-w', '--stdin'], { cwd: fx.install, input: body, encoding: 'utf8', timeout: 30_000 }).trim();
const stages = [blob('top\nmiddle\nbottom\n'), blob('top OURS\nmiddle\nbottom\n'), blob('top THEIRS\nmiddle\nbottom\n')];
git(fx.install, 'update-index', '--force-remove', file);
execFileSync('git', ['update-index', '--index-info'], { cwd: fx.install, timeout: 30_000, input: stages.map((s, i) => `100644 ${s} ${i + 1}\t${file}\n`).join('') });
write(fx, file, '<<<<<<< ours\ntop OURS\n=======\ntop THEIRS\n>>>>>>> theirs\n');
}
describe.skipIf(process.platform === 'win32')('gstack-ff-update: moving the tree', () => {
test('a clean install fast-forwards; the real index matches the target', () => {
const fx = makeFixture();
const target = release(fx, { 'notes.txt': 'top UPSTREAM\nmiddle\nbottom\n' });
const old = git(fx.install, 'rev-parse', 'HEAD');
const r = ff(fx);
expect(r.status, r.stdout + r.stderr).toBe(0);
expect(r.stdout).toBe(`ok ${old} ${target}\n`);
expect(git(fx.install, 'rev-parse', 'HEAD')).toBe(target);
expect(git(fx.install, 'status', '--porcelain')).toBe('');
expect(ff(fx).stdout).toBe(`already ${target}\n`);
});
test('edits that merge cleanly ride over the update unstaged, and nothing is shelved', () => {
const fx = makeFixture();
write(fx, 'notes.txt', 'top\nmiddle\nbottom LOCAL\n');
write(fx, 'other.txt', 'other LOCAL\n');
release(fx, { 'notes.txt': 'top UPSTREAM\nmiddle\nbottom\n' });
const r = ff(fx);
expect(r.stdout).toMatch(/^ok /);
expect(read(fx, 'notes.txt')).toBe('top UPSTREAM\nmiddle\nbottom LOCAL\n');
expect(read(fx, 'other.txt')).toBe('other LOCAL\n');
expect(git(fx.install, 'diff', '--cached', '--name-only')).toBe('');
expect(git(fx.install, 'diff', '--name-only').split('\n').sort()).toEqual(['notes.txt', 'other.txt']);
expect(git(fx.install, 'for-each-ref', 'refs/gstack/rescue')).toBe('');
});
test('a conflicting edit is shelved: no markers, the patch holds only the person\'s delta, and an upstream fix survives restoring it', () => {
const fx = makeFixture();
write(fx, 'notes.txt', 'top LOCAL\nmiddle\nbottom\n');
const target = release(fx, { 'notes.txt': 'top UPSTREAM\nmiddle\nbottom\n', 'fix.txt': 'fixed\n' });
const r = ff(fx);
expect(r.status).toBe(0);
const m = rescueRef(r.stdout);
expect(m, r.stdout).not.toBeNull();
expect(m![2]).toBe('0');
expect(git(fx.install, 'rev-parse', 'HEAD')).toBe(target);
expect(git(fx.install, 'status', '--porcelain')).toBe('');
expect(read(fx, 'notes.txt')).toBe('top UPSTREAM\nmiddle\nbottom\n');
const ref = m![1];
expect(git(fx.install, 'diff', '--name-only', `${ref}^`, ref)).toBe('notes.txt');
// Restore the person's edit in a scratch checkout of the target, as the banner says.
const patch = execFileSync('git', ['diff', `${ref}^`, ref], { cwd: fx.install, encoding: 'utf8', timeout: 30_000 });
const scratch = path.join(fx.base, 'scratch');
execFileSync('git', ['clone', '-q', fx.origin, scratch], { timeout: 30_000 });
const applied = spawnSync('git', ['apply', '-3'], { cwd: scratch, input: patch, encoding: 'utf8', timeout: 30_000 });
expect(fs.readFileSync(path.join(scratch, 'fix.txt'), 'utf8')).toBe('fixed\n');
expect(applied.status === 0 || fs.readFileSync(path.join(scratch, 'notes.txt'), 'utf8').includes('top LOCAL')).toBe(true);
expect(fs.readFileSync(path.join(scratch, 'notes.txt'), 'utf8')).toContain('top LOCAL');
// stderr gives the inspect, export and delete commands.
expect(r.stderr).toContain(`show --stat '${ref}'`);
expect(r.stderr).toContain(`diff '${ref}^' '${ref}' > ~/gstack-local-edits.patch`);
expect(r.stderr).toContain(`update-ref -d '${ref}'`);
});
test('staged-only changes and differing staged and unstaged versions of one file are both kept', () => {
const fx = makeFixture();
write(fx, 'other.txt', 'other STAGED\n');
git(fx.install, 'add', 'other.txt');
write(fx, 'notes.txt', 'top STAGED\nmiddle\nbottom\n');
git(fx.install, 'add', 'notes.txt');
write(fx, 'notes.txt', 'top WORKTREE\nmiddle\nbottom\n');
const indexBefore = git(fx.install, 'ls-files', '-s');
release(fx, { 'fix.txt': 'fixed\n' });
const r = ff(fx);
const m = rescueRef(r.stdout);
expect(m, r.stdout + r.stderr).not.toBeNull();
const ref = m![1];
expect(git(fx.install, 'show', `${ref}:notes.txt`)).toBe('top WORKTREE\nmiddle\nbottom');
expect(git(fx.install, 'show', `${ref}^2:notes.txt`)).toBe('top STAGED\nmiddle\nbottom');
expect(git(fx.install, 'show', `${ref}^2:other.txt`)).toBe('other STAGED');
expect(git(fx.install, 'show', `${ref}:other.txt`)).toBe('other STAGED');
expect(git(fx.install, 'rev-parse', `${ref}^2^`)).toBe(git(fx.install, 'rev-parse', `${ref}^`));
expect(git(fx.install, 'status', '--porcelain')).toBe('');
expect(indexBefore).not.toBe(git(fx.install, 'ls-files', '-s'));
});
test('an already-unmerged install is rescued, labelled as needing manual resolution, and lands clean', () => {
const fx = makeFixture();
makeUnmerged(fx, 'notes.txt');
const target = release(fx, { 'notes.txt': 'top UPSTREAM\nmiddle\nbottom\n' });
const r = ff(fx);
const m = rescueRef(r.stdout);
expect(m, r.stdout + r.stderr).not.toBeNull();
expect(m![2]).toBe('1');
expect(r.stderr).toContain('needs manual resolution');
expect(git(fx.install, 'log', '-1', '--format=%B', m![1])).toContain('Needs manual resolution');
expect(git(fx.install, 'show', `${m![1]}:notes.txt`)).toContain('<<<<<<< ours');
expect(git(fx.install, 'ls-files', '-u')).toBe('');
expect(git(fx.install, 'rev-parse', 'HEAD')).toBe(target);
expect(read(fx, 'notes.txt')).toBe('top UPSTREAM\nmiddle\nbottom\n');
});
test('the regenerable footprint rides over when it merges and takes the target otherwise; it is never rescued', () => {
const fx = makeFixture();
write(fx, 'SKILL.md', 'name: gstack-prefixed\nbody\n');
write(fx, 'qa/SKILL.md', 'name: gstack-qa\nbody\n');
release(fx, { 'qa/SKILL.md': 'name: qa-renamed\nbody\n' });
const r = ff(fx);
expect(r.stdout).toMatch(/^ok /);
expect(read(fx, 'SKILL.md')).toBe('name: gstack-prefixed\nbody\n');
expect(read(fx, 'qa/SKILL.md')).toBe('name: qa-renamed\nbody\n');
expect(git(fx.install, 'for-each-ref', 'refs/gstack/rescue')).toBe('');
});
test('an untracked file in the way refuses with autostash-unrecoverable and changes nothing', () => {
const fx = makeFixture();
write(fx, 'notes.txt', 'top LOCAL\nmiddle\nbottom\n');
release(fx, { 'new.txt': 'upstream new\n' });
write(fx, 'new.txt', 'mine\n');
const head = git(fx.install, 'rev-parse', 'HEAD');
const r = ff(fx);
expect(r.status).toBe(3);
expect(r.stdout).toMatch(/^autostash-unrecoverable: git refused to update /);
expect(git(fx.install, 'rev-parse', 'HEAD')).toBe(head);
expect(read(fx, 'new.txt')).toBe('mine\n');
expect(read(fx, 'notes.txt')).toBe('top LOCAL\nmiddle\nbottom\n');
expect(git(fx.install, 'for-each-ref', 'refs/gstack/rescue')).toBe('');
expect(fs.existsSync(path.join(fx.install, '.git', 'index.lock'))).toBe(false);
});
test('an edit written between the capture and the move is refused and kept (barrier)', () => {
const fx = makeFixture();
write(fx, 'notes.txt', 'top LOCAL\nmiddle\nbottom\n');
release(fx, { 'notes.txt': 'top UPSTREAM\nmiddle\nbottom\n' });
const head = git(fx.install, 'rev-parse', 'HEAD');
// The first commit-tree (the rescue's staged-state commit) runs after the
// capture and before the move: the shim writes a late edit right then.
const shimDir = path.join(fx.base, 'barrier');
fs.mkdirSync(shimDir);
const real = path.join(execFileSync('git', ['--exec-path'], { encoding: 'utf8', timeout: 30_000 }).trim(), 'git');
fs.writeFileSync(path.join(shimDir, 'git'), `#!/bin/bash\ncase " $* " in *" commit-tree "*) [ -e "${fx.base}/barrier.done" ] || { echo LATE >> "${fx.install}/other.txt"; : > "${fx.base}/barrier.done"; } ;; esac\nexec "${real}" "$@"\n`, { mode: 0o755 });
const r = ff(fx, 'origin/main', { PATH: `${shimDir}:${process.env.PATH}` });
expect(r.status, r.stdout).toBe(3);
expect(r.stdout).toContain('changed while the update ran');
expect(git(fx.install, 'rev-parse', 'HEAD')).toBe(head);
expect(read(fx, 'other.txt')).toBe('other\nLATE\n');
expect(read(fx, 'notes.txt')).toBe('top LOCAL\nmiddle\nbottom\n');
expect(git(fx.install, 'for-each-ref', 'refs/gstack/rescue')).toBe('');
});
test('rescue refs are compare-and-create: same-second recoveries, an identical rescue, and a pre-existing ref', () => {
const fx = makeFixture();
write(fx, 'notes.txt', 'top LOCAL\nmiddle\nbottom\n');
release(fx, { 'notes.txt': 'top UPSTREAM\nmiddle\nbottom\n' });
const head = git(fx.install, 'rev-parse', 'HEAD');
const copies = ['a', 'b', 'c'].map((n) => { const d = path.join(fx.base, `copy-${n}`); fs.cpSync(fx.install, d, { recursive: true }); return d; });
// Same second, same content: the same oid, and a second run reuses the ref.
const first = ff({ ...fx, install: copies[0] }, 'origin/main', FIXED_DATES);
const ref = rescueRef(first.stdout)![1];
fs.writeFileSync(path.join(copies[1], 'notes.txt'), 'top OTHER\nmiddle\nbottom\n');
const second = ff({ ...fx, install: copies[1] }, 'origin/main', FIXED_DATES);
expect(rescueRef(second.stdout)![1]).not.toBe(ref);
// A pre-existing ref with this rescue's name and another commit: refused.
git(copies[2], 'update-ref', ref, head);
const third = ff({ ...fx, install: copies[2] }, 'origin/main', FIXED_DATES);
expect(third.status).toBe(3);
expect(third.stdout).toContain(`rescue ref ${ref} already exists and names another commit`);
expect(git(copies[2], 'rev-parse', ref)).toBe(head);
expect(git(copies[2], 'rev-parse', 'HEAD')).toBe(head);
// The same ref already naming this very rescue is accepted.
git(fx.install, 'fetch', '-q', copies[0], `${ref}:${ref}`);
const again = ff(fx, 'origin/main', FIXED_DATES);
expect(again.status, again.stdout).toBe(0);
expect(rescueRef(again.stdout)![1]).toBe(ref);
});
test('rescue commits carry gstack\'s own identity with no user config at all', () => {
const fx = makeFixture();
write(fx, 'notes.txt', 'top LOCAL\nmiddle\nbottom\n');
release(fx, { 'notes.txt': 'top UPSTREAM\nmiddle\nbottom\n' });
// The real git binary first on PATH: a host wrapper that injects its own
// identity must not stand in for what the bin asks for.
const realDir = path.join(fx.base, 'real-git');
fs.mkdirSync(realDir);
fs.symlinkSync(path.join(execFileSync('git', ['--exec-path'], { encoding: 'utf8', timeout: 30_000 }).trim(), 'git'), path.join(realDir, 'git'));
const r = ff(fx, 'origin/main', { PATH: `${realDir}:${process.env.PATH}` });
const ref = rescueRef(r.stdout)![1];
expect(git(fx.install, 'log', '-1', '--format=%an <%ae>|%cn <%ce>', ref)).toBe('gstack rescue <gstack@localhost>|gstack rescue <gstack@localhost>');
});
test('refusals: not a fast-forward, an unresolvable target, and a missing checkout', () => {
const fx = makeFixture();
write(fx, 'VERSION', 'local\n');
git(fx.install, '-c', 'user.name=t', '-c', 'user.email=t@t', 'commit', '-qam', 'local');
release(fx, { 'notes.txt': 'x\n' });
const head = git(fx.install, 'rev-parse', 'HEAD');
const nf = ff(fx);
expect(nf.status).toBe(4);
expect(nf.stdout).toMatch(/^not-fast-forward: /);
expect(git(fx.install, 'rev-parse', 'HEAD')).toBe(head);
expect(ff(fx, 'no-such-rev').status).toBe(2);
expect(spawnSync('bash', [FF, path.join(fx.base, 'missing'), 'HEAD'], { encoding: 'utf8', timeout: 30_000 }).stdout).toMatch(/^not-a-checkout: /);
});
});
describe.skipIf(process.platform === 'win32')('gstack-ff-update: the install-scoped lock', () => {
test('lives in the absolute git common dir, shared by a linked worktree, never in the caller\'s project', () => {
const fx = makeFixture();
release(fx, { 'notes.txt': 'top UPSTREAM\nmiddle\nbottom\n' });
const wt = path.join(fx.base, 'linked');
git(fx.install, 'worktree', 'add', '-q', '--detach', wt, 'HEAD');
const project = path.join(fx.base, 'project');
fs.mkdirSync(project);
// A live holder in the common dir blocks an update started from the linked worktree.
const holder = spawn('sleep', ['30']);
try {
const lock = path.join(fx.install, '.git', 'gstack-ff.lock');
fs.mkdirSync(lock);
fs.writeFileSync(path.join(lock, 'pid'), `${holder.pid}\n`);
const r = spawnSync('bash', [FF, wt, 'origin/main'], { cwd: project, encoding: 'utf8', env: isolatedEnv(fx.base, { GSTACK_FF_LOCK_WAIT: '0' }), timeout: 30_000 });
expect(r.status).toBe(75);
expect(r.stdout).toContain(`ff-busy: another gstack update is moving ${wt} (lock ${lock} held by pid ${holder.pid})`);
expect(fs.readdirSync(project)).toEqual([]);
expect(fs.existsSync(path.join(wt, 'gstack-ff.lock'))).toBe(false);
// A dead holder is reclaimed.
fs.writeFileSync(path.join(lock, 'pid'), '999999\n');
const ok = spawnSync('bash', [FF, wt, 'origin/main'], { cwd: project, encoding: 'utf8', env: isolatedEnv(fx.base, { GSTACK_FF_LOCK_WAIT: '0' }), timeout: 30_000 });
expect(ok.status, ok.stdout).toBe(0);
expect(fs.existsSync(lock)).toBe(false);
expect(fs.readdirSync(project)).toEqual([]);
} finally {
holder.kill();
}
});
test('a live holder that outlasts the TTL keeps its lock through the heartbeat', async () => {
const fx = makeFixture();
write(fx, 'notes.txt', 'top LOCAL\nmiddle\nbottom\n');
release(fx, { 'notes.txt': 'top UPSTREAM\nmiddle\nbottom\n' });
const shimDir = path.join(fx.base, 'slow');
fs.mkdirSync(shimDir);
const real = path.join(execFileSync('git', ['--exec-path'], { encoding: 'utf8', timeout: 30_000 }).trim(), 'git');
fs.writeFileSync(path.join(shimDir, 'git'), `#!/bin/bash\ncase " $* " in *" commit-tree "*) : > "${fx.base}/slow.started"; sleep 4 ;; esac\nexec "${real}" "$@"\n`, { mode: 0o755 });
const lock = path.join(fx.install, '.git', 'gstack-ff.lock');
const holder = spawn('bash', [FF, fx.install, 'origin/main'], { env: isolatedEnv(fx.base, { PATH: `${shimDir}:${process.env.PATH}`, GSTACK_FF_HEARTBEAT_SECONDS: '1' }) });
const done = new Promise<number | null>((resolve) => holder.on('exit', resolve));
const deadline = Date.now() + 20_000;
while (!fs.existsSync(path.join(fx.base, 'slow.started')) && Date.now() < deadline) await new Promise((r) => setTimeout(r, 50));
// The pidfile looks 40 minutes old; the holder's next beat freshens it.
const past = new Date(Date.now() - 40 * 60 * 1000);
fs.utimesSync(path.join(lock, 'pid'), past, past);
await new Promise((r) => setTimeout(r, 1600));
const contender = spawnSync('bash', [FF, fx.install, 'origin/main'], { encoding: 'utf8', env: isolatedEnv(fx.base, { GSTACK_FF_LOCK_WAIT: '0' }), timeout: 30_000 });
expect(contender.status, contender.stdout).toBe(75);
expect(await done).toBe(0);
expect(fs.existsSync(lock)).toBe(false);
expect(git(fx.install, 'ls-files', '-u')).toBe('');
}, 30_000);
test('the heartbeat and its sleeper are reaped when the bin exits', () => {
const fx = makeFixture();
release(fx, { 'notes.txt': 'top UPSTREAM\nmiddle\nbottom\n' });
const before = execFileSync('bash', ['-c', 'pgrep -f "^sleep 300$" | wc -l'], { encoding: 'utf8', timeout: 30_000 }).trim();
expect(ff(fx).status).toBe(0);
const after = execFileSync('bash', ['-c', 'sleep 0.3; pgrep -f "^sleep 300$" | wc -l'], { encoding: 'utf8', timeout: 30_000 }).trim();
expect(after).toBe(before);
});
});
describe.skipIf(process.platform === 'win32')('gstack-ff-update: callers', () => {
test('/gstack-upgrade Step 4 racing a background updater (two state roots) leaves one clean result and no lost edit', async () => {
const fx = makeFixture();
fs.mkdirSync(path.join(fx.seed, 'bin'), { recursive: true });
fs.writeFileSync(path.join(fx.seed, 'bin', 'gstack-config'), '#!/usr/bin/env bash\n[ "$1" = get ] && [ "$2" = auto_upgrade ] && echo true\nexit 0\n', { mode: 0o755 });
fs.writeFileSync(path.join(fx.seed, 'bin', 'gstack-patch-names'), '#!/usr/bin/env bash\nexit 0\n', { mode: 0o755 });
fs.writeFileSync(path.join(fx.seed, 'setup'), '#!/usr/bin/env bash\nexit 0\n', { mode: 0o755 });
const target = release(fx, { 'notes.txt': 'top\nmiddle\nbottom\n' }, '1.0.1');
git(fx.install, 'merge', '-q', '--ff-only', 'origin/main');
write(fx, 'notes.txt', 'top LOCAL\nmiddle\nbottom\n');
const incoming = release(fx, { 'notes.txt': 'top UPSTREAM\nmiddle\nbottom\n' });
expect(incoming).not.toBe(target);
const stateA = path.join(fx.base, 'state-a');
const stateB = path.join(fx.base, 'state-b');
fs.mkdirSync(stateA); fs.mkdirSync(stateB);
const env = (state: string) => ({ ...isolatedEnv(fx.base), PATH: `${path.dirname(process.execPath)}:${process.env.PATH}`, GSTACK_DIR: fx.install, GSTACK_STATE_ROOT: state });
const bg = spawnSync('bash', [UPDATER], { encoding: 'utf8', env: env(stateA), timeout: 30_000 });
expect(bg.status).toBe(0);
const step4 = spawnSync('bash', [FF, fx.install, 'origin/main'], { encoding: 'utf8', env: env(stateB), timeout: 60_000 });
const log = path.join(stateA, 'analytics', 'session-update.log');
const deadline = Date.now() + 30_000;
while (Date.now() < deadline && !/UPDATED|UP_TO_DATE|SKIP ff_busy|PULL_FAILED|HELD/.test(fs.existsSync(log) ? fs.readFileSync(log, 'utf8') : '')) await new Promise((r) => setTimeout(r, 100));
while (fs.existsSync(path.join(stateA, '.setup-lock')) && Date.now() < deadline) await new Promise((r) => setTimeout(r, 100));
expect([0, 75]).toContain(step4.status ?? -1);
expect(git(fx.install, 'rev-parse', 'HEAD')).toBe(incoming);
expect(git(fx.install, 'ls-files', '-u')).toBe('');
expect(read(fx, 'notes.txt')).toBe('top UPSTREAM\nmiddle\nbottom\n');
const refs = git(fx.install, 'for-each-ref', '--format=%(refname)', 'refs/gstack/rescue').split('\n').filter(Boolean);
expect(refs).toHaveLength(1);
expect(git(fx.install, 'show', `${refs[0]}:notes.txt`)).toBe('top LOCAL\nmiddle\nbottom');
}, 60_000);
test('/gstack-upgrade Step 4\'s git block leaves no conflict markers: FF_OK with the edit in a rescue ref', () => {
const fx = makeFixture();
for (const f of ['setup', 'bin/gstack-config']) {
fs.mkdirSync(path.join(fx.seed, path.dirname(f)), { recursive: true });
fs.writeFileSync(path.join(fx.seed, f), '#!/bin/sh\nexit 0\n', { mode: 0o755 });
}
fs.copyFileSync(FF, path.join(fx.seed, 'bin', 'gstack-ff-update'));
const base = release(fx, {}, '1.0.1');
git(fx.install, 'merge', '-q', '--ff-only', base);
write(fx, 'notes.txt', 'top LOCAL\nmiddle\nbottom\n');
const target = release(fx, { 'notes.txt': 'top UPSTREAM\nmiddle\nbottom\n' });
const tmpl = fs.readFileSync(path.join(ROOT, 'gstack-upgrade', 'SKILL.md.tmpl'), 'utf8');
const block = tmpl.slice(tmpl.indexOf('**For git installs**')).match(/```bash\n([\s\S]*?)\n```/)![1]!.replaceAll('{{SETUP_COMMAND}}', './setup');
const r = spawnSync('bash', ['-c', block], { cwd: fx.base, encoding: 'utf8', env: { ...isolatedEnv(fx.base), INSTALL_DIR: fx.install }, timeout: 60_000 });
expect(r.status, r.stdout + r.stderr).toBe(0);
expect(r.stdout).toContain('FF_OK');
expect(git(fx.install, 'rev-parse', 'HEAD')).toBe(target);
expect(git(fx.install, 'ls-files', '-u')).toBe('');
expect(read(fx, 'notes.txt')).toBe('top UPSTREAM\nmiddle\nbottom\n');
const ref = rescueRef(r.stdout)![1];
expect(git(fx.install, 'show', `${ref}:notes.txt`)).toBe('top LOCAL\nmiddle\nbottom');
});
test('the bin copied outside any checkout recovers an install that has no gstack-ff-update', () => {
const fx = makeFixture();
write(fx, 'notes.txt', 'top LOCAL\nmiddle\nbottom\n');
const target = release(fx, { 'notes.txt': 'top UPSTREAM\nmiddle\nbottom\n' });
const outside = path.join(fx.base, 'outside');
fs.mkdirSync(outside);
fs.copyFileSync(FF, path.join(outside, 'gstack-ff-update'));
const r = spawnSync('bash', [path.join(outside, 'gstack-ff-update'), '.', 'origin/main'], { cwd: fx.install, encoding: 'utf8', env: isolatedEnv(fx.base), timeout: 60_000 });
expect(r.status, r.stdout + r.stderr).toBe(0);
expect(rescueRef(r.stdout)).not.toBeNull();
expect(git(fx.install, 'rev-parse', 'HEAD')).toBe(target);
});
});
describe('gstack-ff-update: self-contained, with twins pinned', () => {
const ffSrc = fs.readFileSync(FF, 'utf8');
const updSrc = fs.readFileSync(UPDATER, 'utf8');
const fn = (src: string, name: string) => src.match(new RegExp(`\\n( *)${name}\\(\\) \\{\\n[\\s\\S]*?\\n\\1\\}\\n`))?.[0].replace(/^\n/, '').replace(/^ +/gm, '').replace(/^#.*\n/gm, '');
test('sources nothing', () => {
expect(ffSrc).not.toMatch(/^\s*(\.|source)\s/m);
});
test('ff_flatten is byte-identical to the updater\'s', () => {
expect(fn(ffSrc, 'ff_flatten')).toBeDefined();
expect(fn(ffSrc, 'ff_flatten')).toBe(fn(updSrc, 'ff_flatten'));
});
test('the lock keeps the updater\'s TTL check, atomic mv-aside reap and heartbeat reaping', () => {
expect(fn(ffSrc, 'lock_is_expired')).toBe(fn(updSrc, 'lock_is_expired'));
expect(fn(ffSrc, 'cleanup_heartbeat')).toBe(fn(updSrc, 'cleanup_heartbeat'));
expect(ffSrc).toContain('mv "$LOCK_DIR" "$LOCK_DIR.reap.$$" 2>/dev/null || return 1');
expect(updSrc).toContain('mv "$LOCK_DIR" "$LOCK_DIR.reap.$$" 2>/dev/null ||');
expect(ffSrc).toContain('[ "$(cat "$LOCK_DIR/pid" 2>/dev/null)" = "$MYPID" ] && rm -rf "$LOCK_DIR" 2>/dev/null');
});
test.skipIf(process.platform === 'win32')('ff_flatten flattens newlines and strips control characters and escape sequences', () => {
const r = spawnSync('bash', ['-c', `eval "$(sed -n '/^ff_flatten() {/,/^}/p' "${FF}")"; ff_flatten "$(printf 'bad\\nstages=x \\033[31mred\\033[0m\\001end')" 200`], { encoding: 'utf8', timeout: 30_000 });
expect(r.stdout).toBe('bad stages=x redend');
});
});
+11
View File
@@ -79,6 +79,17 @@ describe('enable', () => {
}
});
test('a per-session CLAUDE_CONFIG_DIR linking back to ~/.claude registers the $HOME path, which outlives the session (#3180)', () => {
const session = path.join(home, 'session-1234');
fs.mkdirSync(session);
fs.symlinkSync(path.join(home, '.claude', 'skills'), path.join(session, 'skills'));
const r = run(['enable'], { CLAUDE_CONFIG_DIR: session });
expect(r.status).toBe(0);
expect(commands()).toEqual([`${canonical}/${HOOK_REL}`]);
fs.rmSync(session, { recursive: true, force: true });
expect(fs.existsSync(commands()[0])).toBe(true);
});
test('twice: unchanged, one entry; over a stale worktree path: re-pointed', () => {
expect(run(['enable']).stdout).toContain('registered');
const again = run(['enable']);
+3 -2
View File
@@ -50,6 +50,7 @@ function makeGstackLike(dir: string, git: boolean) {
writeFileSync(join(dir, 'setup'), '#!/bin/sh\necho SETUP_RAN "$@"\n', { mode: 0o755 });
writeFileSync(join(dir, 'bin', 'gstack-config'), '#!/bin/sh\necho false\n', { mode: 0o755 });
writeFileSync(join(dir, 'bin', 'gstack-autoplan'), '#!/bin/sh\necho "## Coordinator contract (fixture)"\n', { mode: 0o755 });
writeFileSync(join(dir, 'bin', 'gstack-ff-update'), readFileSync(join(import.meta.dir, '..', 'bin', 'gstack-ff-update')), { mode: 0o755 });
if (git) mustSh(dir, 'git init -q -b main && git add -A && git commit -q -m init');
}
@@ -181,7 +182,7 @@ describe.skipIf(IS_WINDOWS)('C9: destructive upgrade/spec fences refuse bad path
type Kind = typeof BAD_VALUES[number];
const UNUSABLE: Kind[] = ['unset', 'empty', 'nonexistent', 'unreadable'];
const cases: Array<{ name: string; doc: 'upgrade' | 'spec'; marker: string; target: string; kinds?: Kind[]; others: (wd: ReturnType<typeof world>, h: HostRender) => Record<string, string> }> = [
{ name: 'ff-only upgrade', doc: 'upgrade', marker: 'git pull --ff-only', target: 'INSTALL_DIR', others: () => ({}) },
{ name: 'ff-only upgrade', doc: 'upgrade', marker: 'bash bin/gstack-ff-update', target: 'INSTALL_DIR', others: () => ({}) },
{ name: 'reset fallback', doc: 'upgrade', marker: 'git reset --hard origin/main', target: 'INSTALL_DIR', others: () => ({}) },
{ name: 'vendored swap', doc: 'upgrade', marker: 'git clone --depth 1', target: 'INSTALL_DIR', others: () => ({}) },
{ name: 'local copy detection', doc: 'upgrade', marker: '_RESOLVED_PRIMARY=', target: 'INSTALL_DIR', kinds: UNUSABLE, others: () => ({}) },
@@ -220,7 +221,7 @@ describe.skipIf(IS_WINDOWS)('C9: destructive upgrade/spec fences refuse bad path
async function controls(h: HostRender): Promise<string[]> {
const wd = world(h);
const problems: string[] = [];
const ff = await run(wd, fence(h.upgrade, 'git pull --ff-only'), { INSTALL_DIR: wd.gstack });
const ff = await run(wd, fence(h.upgrade, 'bash bin/gstack-ff-update'), { INSTALL_DIR: wd.gstack });
if (!ff.stdout.includes('FF_OK') || !ff.gitCalls.some(c => c.startsWith('fetch'))) problems.push(`${h.host}: ff-only upgrade did not run: ${ff.stderr}`);
const local = join(wd.project, h.localDir);
const team = await run(wd, fence(h.upgrade, 'git rm -r --cached'), { LOCAL_GSTACK: local });
+192
View File
@@ -0,0 +1,192 @@
/**
* The held-install recovery commands published in docs/troubleshooting.md
* (#auto-update-held-install-recovery). An install held by #3184 runs its own
* old updater and old /gstack-upgrade, so the recovery fetches the new
* bin/gstack-ff-update from the new revision into a private `mktemp -d`
* directory and runs it there. The Git Bash forms run here verbatim against a
* real gstack tree in three states (clean, dirty-conflicting,
* already-unmerged), all in prefix mode; the PowerShell forms run under
* powershell.exe in .github/workflows/windows-setup-e2e.yml.
*/
import { afterEach, describe, expect, test } from 'bun:test';
import { execFileSync, spawn, spawnSync } from 'node:child_process';
import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
const ROOT = path.resolve(import.meta.dir, '..');
const DOC = fs.readFileSync(path.join(ROOT, 'docs', 'troubleshooting.md'), 'utf8');
const SETUP_TAIL = '[ "$s" = 0 ] && ./setup';
const bases: string[] = [];
afterEach(() => { for (const b of bases.splice(0)) fs.rmSync(b, { recursive: true, force: true }); });
function form(name: string): string {
const m = DOC.match(new RegExp(`<!-- form:${name} -->\\n\`\`\`(?:bash|powershell)\\n(.+)\\n\`\`\``));
expect(m, name).not.toBeNull();
return m![1]!;
}
function git(cwd: string, ...args: string[]): string {
return execFileSync('git', ['-c', 'user.name=t', '-c', 'user.email=t@t', ...args], { cwd, encoding: 'utf8', timeout: 60_000 }).trim();
}
const EDITED = 'bin/gstack-session-update';
const CONFLICT_LINE = 'THROTTLE_SECONDS=3600 # 1 hour';
/**
* origin/main: this tree with an upstream edit to one line of EDITED. Each
* install sits one commit behind it, at the same tree without
* bin/gstack-ff-update (an install that predates it), with VERSION 1.91.101.0.
*/
function makeFixture() {
const base = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-held-')));
bases.push(base);
const origin = path.join(base, 'origin.git');
const work = path.join(base, 'work');
execFileSync('git', ['clone', '-q', '--shared', ROOT, work], { timeout: 60_000 });
// A root commit of this tree: the checkout may be shallow, and a bare
// origin refuses a shallow push.
git(work, 'checkout', '-q', '--orphan', 'main');
fs.writeFileSync(path.join(work, 'VERSION'), '1.91.101.0\n');
fs.rmSync(path.join(work, 'bin', 'gstack-ff-update'), { force: true });
git(work, 'add', '-A');
git(work, 'commit', '-q', '--allow-empty', '-m', 'v1.91.101.0-shaped install');
const held = git(work, 'rev-parse', 'HEAD');
fs.copyFileSync(path.join(ROOT, 'bin', 'gstack-ff-update'), path.join(work, 'bin', 'gstack-ff-update'));
const src = fs.readFileSync(path.join(work, EDITED), 'utf8');
expect(src).toContain(CONFLICT_LINE);
fs.writeFileSync(path.join(work, EDITED), src.replace(CONFLICT_LINE, 'THROTTLE_SECONDS=3600 # 1 hour (upstream)'));
fs.writeFileSync(path.join(work, 'VERSION'), '1.91.102.0\n');
git(work, 'add', '-A');
git(work, 'commit', '-q', '-m', 'the fixed release');
const fixed = git(work, 'rev-parse', 'HEAD');
execFileSync('git', ['init', '-q', '--bare', '-b', 'main', origin], { timeout: 60_000 });
git(work, 'push', '-q', origin, 'main');
return { base, origin, held, fixed };
}
type Fx = ReturnType<typeof makeFixture>;
/** An install at ~/.claude/skills/gstack under its own HOME (with a space), in prefix mode. */
function makeInstall(fx: Fx, name: string, state: 'clean' | 'dirty' | 'unmerged') {
const home = path.join(fx.base, `home ${name}`);
const install = path.join(home, '.claude', 'skills', 'gstack');
fs.mkdirSync(path.dirname(install), { recursive: true });
execFileSync('git', ['clone', '-q', fx.origin, install], { timeout: 60_000 });
git(install, 'reset', '-q', '--hard', fx.held);
for (const f of git(install, 'ls-files', 'SKILL.md', '*/SKILL.md').split('\n').slice(0, 12)) {
const p = path.join(install, f);
fs.writeFileSync(p, fs.readFileSync(p, 'utf8').replace(/^name: (?!gstack-)/m, 'name: gstack-'));
}
const p = path.join(install, EDITED);
if (state === 'dirty') fs.writeFileSync(p, fs.readFileSync(p, 'utf8').replace(CONFLICT_LINE, 'THROTTLE_SECONDS=60 # LOCAL-EDIT'));
if (state === 'unmerged') {
const blob = (body: string) => execFileSync('git', ['hash-object', '-w', '--stdin'], { cwd: install, input: body, encoding: 'utf8', timeout: 30_000 }).trim();
const stages = [blob('base\n'), blob('ours LOCAL-EDIT\n'), blob('theirs\n')];
git(install, 'update-index', '--force-remove', 'README.md');
execFileSync('git', ['update-index', '--index-info'], { cwd: install, timeout: 30_000, input: stages.map((s, i) => `100644 ${s} ${i + 1}\tREADME.md\n`).join('') });
fs.writeFileSync(path.join(install, 'README.md'), '<<<<<<< ours\nours LOCAL-EDIT\n=======\ntheirs\n>>>>>>> theirs\n');
}
return { home, install };
}
/** The Git Bash recovery form, verbatim up to its setup step, which prints a marker here. */
function recovery(home: string, tmp: string) {
const cmd = form('recovery-gitbash');
expect(cmd.endsWith(SETUP_TAIL)).toBe(true);
return spawn('bash', ['-c', `${cmd.slice(0, -'./setup'.length)}echo SETUP_RAN`], {
cwd: os.tmpdir(), env: { PATH: process.env.PATH!, HOME: home, TMPDIR: tmp, GIT_CONFIG_NOSYSTEM: '1' },
});
}
function finish(child: ReturnType<typeof spawn>): Promise<{ code: number | null; out: string }> {
let out = '';
child.stdout!.on('data', (d) => { out += d; });
child.stderr!.on('data', (d) => { out += d; });
return new Promise((resolve) => child.on('exit', (code) => resolve({ code, out })));
}
function trap(fx: Fx) {
const tmp = path.join(fx.base, 'tmp');
fs.mkdirSync(tmp, { recursive: true });
const victim = path.join(fx.base, 'victim');
fs.writeFileSync(victim, 'victim\n');
fs.symlinkSync(victim, path.join(tmp, 'gstack-ff-update'));
return { tmp, victim };
}
describe.skipIf(process.platform === 'win32')('held-install recovery (Git Bash form)', () => {
test('the published forms are labelled by shell and the PowerShell ones carry no double quotes inside bash', () => {
for (const shell of ['recovery', 'trial', 'goback']) {
expect(form(`${shell}-gitbash`)).toStartWith('cd ~/.claude/skills/gstack && ');
const ps = form(`${shell}-powershell`);
expect(ps).toStartWith('Set-Location -LiteralPath "$HOME\\.claude\\skills\\gstack" -ErrorAction Stop; $gb = Join-Path (git --exec-path) ');
expect(ps).toEndWith('; if ($LASTEXITCODE -eq 0) { .\\setup.ps1 }');
expect(ps).not.toContain('&& ');
const inner = ps.match(/& \$gb -c '([^']*)'/)![1]!;
expect(inner).not.toContain('"');
expect(ps.replace(/'[^']*'/g, '')).not.toContain('&&');
}
expect(form('recovery-gitbash')).toContain('d=$(mktemp -d)');
expect(form('recovery-powershell')).toContain('d=$(mktemp -d)');
});
for (const state of ['clean', 'dirty', 'unmerged'] as const) {
test(`a ${state} prefix-mode install reaches the fixed release; a planted symlink is never followed`, async () => {
const fx = makeFixture();
const { install, home } = makeInstall(fx, state, state);
const { tmp, victim } = trap(fx);
const { code, out } = await finish(recovery(home, tmp));
expect(code, out).toBe(0);
expect(out).toContain('SETUP_RAN');
expect(git(install, 'rev-parse', 'HEAD')).toBe(fx.fixed);
expect(git(install, 'ls-files', '-u')).toBe('');
expect(fs.existsSync(path.join(install, 'bin', 'gstack-ff-update'))).toBe(true);
expect(fs.readFileSync(path.join(install, 'SKILL.md'), 'utf8')).toMatch(/^name: gstack-/m);
const refs = git(install, 'for-each-ref', '--format=%(refname)', 'refs/gstack/rescue').split('\n').filter(Boolean);
if (state === 'clean') {
expect(refs).toEqual([]);
expect(out).toMatch(/^ok [0-9a-f]+ [0-9a-f]+$/m);
} else {
expect(refs).toHaveLength(1);
const file = state === 'dirty' ? EDITED : 'README.md';
expect(git(install, 'show', `${refs[0]}:${file}`)).toContain('LOCAL-EDIT');
expect(git(install, 'diff', '--name-only', `${refs[0]}^`, refs[0])).toBe(file);
expect(out).toContain(`unmerged=${state === 'unmerged' ? 1 : 0}`);
}
expect(fs.readFileSync(victim, 'utf8')).toBe('victim\n');
expect(fs.readdirSync(tmp)).toEqual(['gstack-ff-update']);
}, 60_000);
}
test('two recoveries at once share no script and clobber nothing', async () => {
const fx = makeFixture();
const a = makeInstall(fx, 'a', 'dirty');
const b = makeInstall(fx, 'b', 'clean');
const { tmp, victim } = trap(fx);
const [ra, rb] = await Promise.all([finish(recovery(a.home, tmp)), finish(recovery(b.home, tmp))]);
expect(ra.code, ra.out).toBe(0);
expect(rb.code, rb.out).toBe(0);
expect(git(a.install, 'rev-parse', 'HEAD')).toBe(fx.fixed);
expect(git(b.install, 'rev-parse', 'HEAD')).toBe(fx.fixed);
expect(fs.readFileSync(victim, 'utf8')).toBe('victim\n');
expect(fs.readdirSync(tmp)).toEqual(['gstack-ff-update']);
}, 60_000);
test('trying a fix branch detaches with the footprint discarded, and going back returns to main', () => {
const fx = makeFixture();
const { install, home } = makeInstall(fx, 'trial', 'clean');
git(install, 'reset', '-q', '--hard', fx.fixed);
git(fx.origin, 'update-ref', 'refs/heads/fix-branch', fx.held);
const run = (cmd: string) => spawnSync('bash', ['-c', cmd.replace(/ && \.\/setup$/, ' && echo SETUP_RAN')], {
cwd: os.tmpdir(), encoding: 'utf8', env: { PATH: process.env.PATH!, HOME: home, GIT_CONFIG_NOSYSTEM: '1' }, timeout: 60_000,
});
fs.writeFileSync(path.join(install, 'SKILL.md'), fs.readFileSync(path.join(install, 'SKILL.md'), 'utf8').replace(/^name: (?!gstack-)/m, 'name: gstack-'));
const trial = run(form('trial-gitbash').replace('<branch>', 'fix-branch'));
expect(trial.status, trial.stdout + trial.stderr).toBe(0);
expect(trial.stdout).toContain('SETUP_RAN');
expect(git(install, 'rev-parse', 'HEAD')).toBe(fx.held);
expect(spawnSync('git', ['symbolic-ref', '-q', 'HEAD'], { cwd: install, timeout: 30_000 }).status).not.toBe(0);
fs.writeFileSync(path.join(install, 'SKILL.md'), fs.readFileSync(path.join(install, 'SKILL.md'), 'utf8').replace(/^name: (?!gstack-)/m, 'name: gstack-'));
const back = run(form('goback-gitbash'));
expect(back.status, back.stdout + back.stderr).toBe(0);
expect(git(install, 'symbolic-ref', '--short', 'HEAD')).toBe('main');
expect(git(install, 'rev-parse', 'HEAD')).toBe(fx.fixed);
expect(git(install, 'status', '--porcelain')).toBe('');
}, 60_000);
});
+2 -1
View File
@@ -251,7 +251,8 @@ export function detectSectionReads(toolCalls: SkillTestResult['toolCalls'], sect
while (overlap > 0 && !text.endsWith(next.slice(0, overlap))) overlap--;
return text + next.slice(overlap);
}, '');
if (lines.length && lines.every(line => printed.has(line) || joined.includes(line))) readSections.add(name);
const abutted = outputs.join('');
if (lines.length && lines.every(line => printed.has(line) || joined.includes(line) || abutted.includes(line))) readSections.add(name);
}
return readSections;
}
+1 -1
View File
@@ -223,7 +223,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.2170, // + clarity rules for saved decisions/setup gates + the Aside probe's failure reason; measured 1.1504. + test value bar and Tests to Retire in the lazy Test review section (~2.6KB); measured 1.168 + W1 guarded state-root resolution (`eval gstack-paths; : "${GSTACK_STATE_ROOT:?…}"`) in the Context Recovery preamble, the eureka log and each state-writing bash block; measured 1.173 (2026-09-30). + v1.91.12.0 merge of #2999 (headless rule: a disallowed question tool never qualifies) with #3002; measured 1.1741 (2026-10-01). + Oct 6 fix wave A3/CEO-12: free text reaches commands only through agent-written mktemp files (mktemp block, write rule, path rebuild and refusal at each posting, prompt and brief site); measured 146,905 / 124,597 = 1.1790 (2026-10-06). Combined Oct 6 wave head (A and B): measured 147,524 / 124,597 = 1.1840 (2026-10-06). + Oct 7 wave B3: the Codex probe runs as a command (select-model capture lines, check-sandbox/probe-model/run-with-timeout subcommands) instead of being sourced; measured 147,693 / 124,597 = 1.1854 (2026-10-07). + Oct 7 wave CEO-28/DX-11: review prompts ask for a severity per finding and design proposals use the proposal gate; measured 147,752 / 124,597 = 1.1858 (2026-10-07). + fix wave PR D: the prerequisite offer is skipped in spawned/headless sessions (#1958); measured 147,864 / 124,597 = 1.1867 (2026-10-07). + Oct 10 multi-agent wave PR D1 (reality rows): the Scope Challenge reality-rows block, the deep incident table (18 rows, each tied to the incident that earned it), the Completion summary line and the checklist row; measured 151,423 / 124,597 = 1.2153 (2026-10-10).
maxSizeRatio: 1.2196, // + clarity rules for saved decisions/setup gates + the Aside probe's failure reason; measured 1.1504. + test value bar and Tests to Retire in the lazy Test review section (~2.6KB); measured 1.168 + W1 guarded state-root resolution (`eval gstack-paths; : "${GSTACK_STATE_ROOT:?…}"`) in the Context Recovery preamble, the eureka log and each state-writing bash block; measured 1.173 (2026-09-30). + v1.91.12.0 merge of #2999 (headless rule: a disallowed question tool never qualifies) with #3002; measured 1.1741 (2026-10-01). + Oct 6 fix wave A3/CEO-12: free text reaches commands only through agent-written mktemp files (mktemp block, write rule, path rebuild and refusal at each posting, prompt and brief site); measured 146,905 / 124,597 = 1.1790 (2026-10-06). Combined Oct 6 wave head (A and B): measured 147,524 / 124,597 = 1.1840 (2026-10-06). + Oct 7 wave B3: the Codex probe runs as a command (select-model capture lines, check-sandbox/probe-model/run-with-timeout subcommands) instead of being sourced; measured 147,693 / 124,597 = 1.1854 (2026-10-07). + Oct 7 wave CEO-28/DX-11: review prompts ask for a severity per finding and design proposals use the proposal gate; measured 147,752 / 124,597 = 1.1858 (2026-10-07). + fix wave PR D: the prerequisite offer is skipped in spawned/headless sessions (#1958); measured 147,864 / 124,597 = 1.1867 (2026-10-07). + Oct 10 multi-agent wave PR D1 (reality rows): the Scope Challenge reality-rows block, the deep incident table (18 rows, each tied to the incident that earned it), the Completion summary line and the checklist row; measured 151,423 / 124,597 = 1.2153 (2026-10-10). + #280: the Design Doc Check finds the CEO plan (`gstack-ceo-plan-find`) and names it in the data rule, +325 bytes on main's 151,630; measured 151,955 / 124,597 = 1.2196 (2026-10-12). Fix wave PR 4 (owner-approved raise 1.2170 → 1.2196): #3182's timer-bounded native fallback (net −17 bytes) plus #280's cross-branch rule, offset by tightening the Design Doc Check; measured 151,950 / 124,597 = 1.2195 (2026-10-15).
},
'plan-design-review': {
skill: 'plan-design-review',
+2
View File
@@ -154,6 +154,7 @@ export const FREE_FIXTURES: Readonly<Record<string, readonly string[]>> = {
'test/fixtures/redact-diagram/**': ['test/redact-context-exemptions.test.ts'],
'test/fixtures/remote-identity-vectors.json': ['test/bin-context-windows-slug.test.ts', 'test/gstack-slug-parity.test.ts', 'test/remote-identity-vectors.test.ts'],
'test/fixtures/review-design-lite-reports-ci-36633323521.json': ['test/review-finalization-budget.test.ts'],
'test/fixtures/session-update-heartbeat.sh': ['test/session-update-heartbeat.test.ts'],
'test/fixtures/shard-cli-parity/**': ['test/shard-cli-parity.test.ts'],
'test/fixtures/shard-equivalence/**': ['test/shard-engine-equivalence.test.ts'],
'test/fixtures/shared-libs-no-change-ci-public.json': ['test/shared-libs-fixture.test.ts'],
@@ -174,5 +175,6 @@ export const FREE_FIXTURES: Readonly<Record<string, readonly string[]>> = {
'test/fixtures/trial-cause/replays.json': ['test/trial-cause.test.ts'],
'test/fixtures/trial-cause/thinking-captures-37198445662.json': ['test/trial-cause.test.ts'],
'test/fixtures/trial-record-v1-reader.ts': ['test/helpers/eval-store.test.ts'],
'test/fixtures/windows-bash-resolution.json': ['test/script-invocation.test.ts'],
'test/fixtures/workflow-required-steps.json': ['test/workflow-required-steps.test.ts'],
};
+1 -1
View File
@@ -888,7 +888,7 @@ export const E2E_TOUCHFILES: Record<string, string[]> = {
'test/fixtures/outside-async-task-m-events.json',
'test/fixtures/autoplan-amend-input-77.json',
'test/fixtures/autoplan-phase-handoff-6714.json','scripts/resolvers/learnings.ts', 'scripts/resolvers/preamble/generate-completion-status.ts', 'scripts/resolvers/preamble/generate-preamble-bash.ts', 'test/fixtures/plan-scope-recovery-av.json', 'test/fixtures/design-scope-checkpoint-at.json', 'scripts/resolvers/composition.ts', 'autoplan/**', 'lib/claude-journal-records.ts', 'lib/claude-owned-journal.ts', 'codex/**', 'bin/gstack-codex-probe', 'scripts/resolvers/review-dashboard.ts', 'scripts/resolvers/plan-gates.ts', 'scripts/resolvers/spec-review.ts', 'scripts/resolvers/outside-voice-steps.ts', 'scripts/resolvers/review-scope.ts', 'scripts/resolvers/outside-voice.ts', 'scripts/resolvers/design.ts', 'test/skill-e2e-autoplan-dual-voice.test.ts', 'bin/gstack-autoplan-snapshot.ts', 'test/fixtures/autoplan/t-ceo-omitted-obligations.json', 'test/fixtures/autoplan/u-ceo-original-loss.json', 'test/fixtures/autoplan/v-ceo-dangling-references.json',
'scripts/resolvers/design-doc-discovery.ts', 'bin/gstack-design-doc-find', 'plan-ceo-review/**', 'plan-eng-review/**', 'plan-design-review/**', 'plan-devex-review/**', 'scripts/resolvers/testing.ts', 'scripts/resolvers/preamble/generate-ask-user-format.ts', 'scripts/resolvers/tasks-section.ts', 'test/helpers/autoplan-phase-observer.ts', 'scripts/resolve-codex-generation-model.ts', 'scripts/resolvers/constants.ts'],
'scripts/resolvers/design-doc-discovery.ts', 'bin/gstack-design-doc-find', 'bin/gstack-ceo-plan-find', 'plan-ceo-review/**', 'plan-eng-review/**', 'plan-design-review/**', 'plan-devex-review/**', 'scripts/resolvers/testing.ts', 'scripts/resolvers/preamble/generate-ask-user-format.ts', 'scripts/resolvers/tasks-section.ts', 'test/helpers/autoplan-phase-observer.ts', 'scripts/resolve-codex-generation-model.ts', 'scripts/resolvers/constants.ts'],
// Multi-provider benchmark adapters — live API smoke against real claude/codex/gemini CLIs
'benchmark-providers-live': ['bin/gstack-model-benchmark', 'test/helpers/providers/**', 'test/helpers/benchmark-runner.ts', 'test/helpers/pricing.ts', 'test/skill-e2e-benchmark-providers.test.ts'],
+8 -1
View File
@@ -539,9 +539,16 @@ describe('weekly/manual workflow contract', () => {
expect(text).toContain('if: always()');
expect(text).toContain('bun-version: 1.4.2');
expect(text).toContain('persist-credentials: false');
expect(text).toContain('actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a');
expect(text).toContain('actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9');
expect(text.match(/secrets\.[A-Z_]+/g)).toEqual(['secrets.GITHUB_TOKEN']);
expect(text).not.toMatch(/pull_request|ANTHROPIC_API_KEY|OPENAI_API_KEY|codex exec|claude -p|gh issue|eval:bg|gstack-config set/);
expect(text.match(/uses: [^\n]+/g)?.every(line => /@[a-f0-9]{40}$/.test(line))).toBe(true);
});
test('its upload-artifact pin is the one the eval workflows use, so a Dependabot group bump keeps them together', () => {
const pin = (file: string) => [...readFileSync(new URL(`../.github/workflows/${file}`, import.meta.url), 'utf8').matchAll(/actions\/upload-artifact@([0-9a-f]{40})/g)].map(m => m[1]);
const own = pin('model-policy-freshness.yml');
expect(own).toHaveLength(1);
for (const file of ['evals.yml', 'evals-periodic.yml', 'windows-free-tests.yml']) expect(new Set(pin(file))).toEqual(new Set(own));
});
});
+15
View File
@@ -57,4 +57,19 @@ describe('OSV suppression expiry', () => {
expect(report.steps[0].env.SCAN_RESULT).toBe('${{ needs.scan.result }}');
for (const text of ['"$SCAN_RESULT" = "failure"', 'gh issue create', 'gh issue comment', 'gh issue close']) expect(run).toContain(text);
});
test('the image-size entries name the fixed release and the pin that blocks it (#2753)', () => {
const toml = fs.readFileSync(path.join(import.meta.dir, '..', '.osv-scanner.toml'), 'utf8');
const entries = toml.split('[[IgnoredVulns]]').slice(1).filter(e => /^id = "GHSA-(?:5p2g-fcmc-qvqq|w3rx-r6r6-pgpr)"/m.test(e));
expect(entries).toHaveLength(2);
for (const entry of entries) {
expect(entry).not.toContain('No fixed version exists');
expect(entry).toMatch(/^reason = ".*image-size 2\.0\.3.*\^1\.0\.0.*"$/m);
expect(entry).toContain('ignoreUntil = 2026-11-30T00:00:00Z');
}
// The stated blocker is the lockfile's: html-to-docx asks for image-size ^1.0.0 and resolves a 1.x.
const lock = fs.readFileSync(path.join(ROOT, 'bun.lock'), 'utf8');
expect(lock).toMatch(/"html-to-docx": \["html-to-docx@[^"]+", "", \{ "dependencies": \{[^}]*"image-size": "\^1\.0\.0"/);
expect(lock).toMatch(/"image-size": \["image-size@1\.\d+\.\d+"/);
});
});
@@ -0,0 +1,84 @@
import { describe, test, expect } from 'bun:test';
import * as fs from 'fs';
import * as path from 'path';
import { generateCodexPlanReview } from '../scripts/resolvers/outside-voice-steps';
import { HOST_PATHS, type TemplateContext } from '../scripts/resolvers/types';
import { ALL_HOST_CONFIGS } from '../hosts';
import { RESULT_CODES } from '../lib/result-codes';
// #3182: Claude Code 2.1.277 removed TaskOutput. The plan-review native
// fallback must bound its reviewer with primitives the host still has: a
// background timer whose exit re-invokes the parent, the background agent's
// completion notification, and TaskStop. These checks pin the generated
// instructions, not a model's compliance with them.
const ROOT = path.resolve(import.meta.dir, '..');
const SKILLS = ['plan-ceo-review', 'plan-eng-review', 'plan-devex-review'] as const;
const flat = (text: string) => text.replace(/\s+/g, ' ');
function bounded(content: string): string {
return content.match(/\*\*Bounded outside-voice wait[\s\S]*?(?=\*\*(?:Integrate reviewer findings|Cross-model tension):\*\*)/)?.[0] ?? '';
}
function renders(): Array<[string, string]> {
const out: Array<[string, string]> = [];
for (const skill of SKILLS) {
out.push([`${skill}/sections/review-sections.md`, fs.readFileSync(path.join(ROOT, skill, 'sections/review-sections.md'), 'utf8')]);
for (const host of ALL_HOST_CONFIGS) {
const ctx: TemplateContext = { host: host.name, skillName: skill, tmplPath: `${skill}/sections/review-sections.md.tmpl`, paths: HOST_PATHS[host.name] };
out.push([`${host.name}:${skill}`, generateCodexPlanReview(ctx)]);
}
}
return out;
}
describe('native outside-voice fallback without TaskOutput (#3182)', () => {
test('no rendered plan-review section requires the removed TaskOutput tool', () => {
for (const [name, content] of renders()) {
const section = bounded(content);
expect(section.length, name).toBeGreaterThan(0);
expect(section, name).not.toContain('TaskOutput');
expect(section, name).not.toContain('block: true');
}
});
test('the deadline is a host timer started before dispatch, and TaskStop ends the loser', () => {
for (const [name, section] of renders().map(([n, c]) => [n, bounded(c)] as const)) {
const timer = section.indexOf('`command: "sleep 300"`');
const dispatch = section.indexOf('`subagent_type: "Plan"`');
expect(timer, name).toBeGreaterThan(0);
expect(dispatch, name).toBeGreaterThan(timer);
expect(section.slice(timer, dispatch), name).toContain('`run_in_background: true`');
expect(flat(section), name).toContain('call TaskStop with the timer');
expect(flat(section), name).toContain('TaskStop with the same ID as the agent');
expect(flat(section), name).toContain('End your turn and wait for task notifications');
expect(flat(section), name).toContain('do not poll, sleep, Read either output file');
}
});
test('only the matching completed notification that beats the timer counts', () => {
for (const [name, section] of renders().map(([n, c]) => [n, bounded(c)] as const)) {
for (const guard of ['`<task-notification>`', 'arriving before the timer', '`<task-id>` must match the agent ID',
'`<status>` must be `completed`', 'is waiting on its own background work', 'turn limit', '[Subagent hand-back]',
'identifiable complete final reviewer report', 'Reject raw or in-progress transcripts',
'still give no late-result credit', 'cancellation is unconfirmed']) {
expect(flat(section), `${name}: ${guard}`).toContain(guard);
}
// A foreground run returns a report the host never bounded: no credit.
expect(flat(section), name).toMatch(/Agent returns a report directly: no enforced deadline, so no credit/);
}
});
test('the unavailable line names its cause and fix, in the output and the persisted row', () => {
for (const [name, content] of renders()) {
const unavailable = flat(content.slice(content.indexOf('**Unavailable path:**')));
expect(unavailable, name).toContain('Outside voice unavailable: <cause>. Fix: <fix>.');
for (const cause of ['Plan agent type not offered', 'TaskStop not offered', 'background tasks unavailable',
'no complete report within five minutes']) expect(unavailable, `${name}: ${cause}`).toContain(cause);
expect(unavailable, name).toContain('(OUTSIDE_VOICE_UNAVAILABLE)');
expect(unavailable, name).toContain('`"unavailable_reason":"<cause>"`');
if (name.startsWith('claude:')) expect(unavailable, name).toContain('Claude Code 2.1.277+, background tasks on');
}
expect(RESULT_CODES.OUTSIDE_VOICE_UNAVAILABLE.anchor).toBe('outside-voice-unavailable');
});
});
+1 -1
View File
@@ -70,7 +70,7 @@ function scaffoldFixture(workDir: string): { workDir: string; stateRoot: string;
// These imports are resolved relative to the copied install, not the source checkout.
const libDir = path.join(workDir, 'lib');
fs.mkdirSync(libDir, { recursive: true });
for (const file of ['jsonl-store.ts', 'is-conductor.ts', 'state-root.ts', 'bin-context.ts', 'remote-identity.ts']) {
for (const file of ['jsonl-store.ts', 'is-conductor.ts', 'state-root.ts', 'bin-context.ts', 'remote-identity.ts', 'script-invocation.ts', 'result-codes.ts']) {
fs.copyFileSync(path.join(ROOT, 'lib', file), path.join(libDir, file));
}
+163
View File
@@ -0,0 +1,163 @@
/**
* Lane mapping for paths a framework puts punctuation in, and for imports
* written through a tsconfig `paths` alias. Both were `no lane` false
* negatives in a Next.js App Router repo whose tests did name the files:
* - `app/(app)/recipes/page.tsx` named in a string (readFileSync) — the
* QUOTED literal pattern stopped at `(`, so the literal never matched;
* - `app/(app)/recipes/[id]/page.tsx` imported as `@/app/(app)/recipes/[id]/page`
* — `@/…` was resolved as a repo path, so it never matched a file.
*/
import { afterEach, describe, expect, test } from 'bun:test';
import { MAX_TSCONFIG_EXTENDS, buildGraph, testsFor } from '../lib/pregate/import-graph';
import { cleanup, commit, makeFixtureRepo, type FixtureRepo } from './helpers/pregate-fixture';
const repos: FixtureRepo[] = [];
const fixture = () => { const r = makeFixtureRepo(); repos.push(r); return r; };
afterEach(() => { while (repos.length) cleanup(repos.pop()!); });
describe('import graph: route-group / dynamic-segment paths and tsconfig path aliases', () => {
test('a repo-path literal containing ( ) [ ] maps to the file it names', () => {
const repo = fixture();
commit(repo, {
'app/(app)/recipes/page.tsx': 'export default function P() { return null }\n',
'app/(app)/recipes/[id]/page.tsx': 'export default function D() { return null }\n',
'app/[[...slug]]/page.tsx': 'export default function C() { return null }\n',
'test/pages.test.ts': "import { readFileSync } from 'node:fs';\nfor (const f of ['app/(app)/recipes/page.tsx', 'app/(app)/recipes/[id]/page.tsx', 'app/[[...slug]]/page.tsx']) readFileSync(f, 'utf8');\n",
});
const g = buildGraph(repo.work);
expect(testsFor(g, 'app/(app)/recipes/page.tsx').tests).toEqual(['test/pages.test.ts']);
expect(testsFor(g, 'app/(app)/recipes/[id]/page.tsx').tests).toEqual(['test/pages.test.ts']);
expect(testsFor(g, 'app/[[...slug]]/page.tsx').tests).toEqual(['test/pages.test.ts']);
});
test('a relative import of a bracketed path already maps (control: the import scanner is not the bug)', () => {
const repo = fixture();
commit(repo, {
'app/(app)/recipes/[id]/page.tsx': 'export default function D() { return null }\n',
'test/detail.test.tsx': "import D from '../app/(app)/recipes/[id]/page';\nD();\n",
});
expect(testsFor(buildGraph(repo.work), 'app/(app)/recipes/[id]/page.tsx').tests).toEqual(['test/detail.test.tsx']);
});
test('an import through a tsconfig paths alias (JSONC, with comments and a trailing comma) maps; so does a vi.mock of it', () => {
const repo = fixture();
commit(repo, {
'tsconfig.json': '{\n // Next.js default\n "compilerOptions": {\n "baseUrl": ".",\n "paths": { "@/*": ["./*"], "~lib/*": ["lib/*"], },\n },\n}\n',
'app/(app)/recipes/[id]/page.tsx': 'export default function D() { return null }\n',
'lib/plan.ts': 'export const plan = 1;\n',
'lib/mocked.ts': 'export const m = 1;\n',
'test/detail.test.tsx': "import D from '@/app/(app)/recipes/[id]/page';\nimport { plan } from '~lib/plan';\nvi.mock('@/lib/mocked', () => ({}));\nD(); plan;\n",
});
const g = buildGraph(repo.work);
expect(testsFor(g, 'app/(app)/recipes/[id]/page.tsx').tests).toEqual(['test/detail.test.tsx']);
expect(testsFor(g, 'lib/plan.ts').tests).toEqual(['test/detail.test.tsx']);
expect(testsFor(g, 'lib/mocked.ts').tests).toEqual(['test/detail.test.tsx']);
});
test('without a tsconfig an @scope/pkg import still resolves to nothing (no new false edges)', () => {
const repo = fixture();
commit(repo, {
'lib/plan.ts': 'export const plan = 1;\n',
'test/scoped.test.ts': "import { x } from '@scope/plan';\nx;\n",
});
expect(testsFor(buildGraph(repo.work), 'lib/plan.ts').tests).toEqual([]);
});
});
describe('import graph: alias precedence, extends and the no-lane explanation', () => {
const twoAliases = (specificFirst: boolean) => {
const specific = '"@/lib/*": ["src/lib/*"]';
const broad = '"@/*": ["./*"]';
return `{ "compilerOptions": { "paths": { ${specificFirst ? `${specific}, ${broad}` : `${broad}, ${specific}`} } } }\n`;
};
for (const specificFirst of [true, false]) {
test(`overlapping aliases pick the most specific pattern when both targets exist (${specificFirst ? 'specific' : 'broad'} key first)`, () => {
const repo = fixture();
commit(repo, {
'tsconfig.json': twoAliases(specificFirst),
'lib/x.ts': 'export const x = "root";\n',
'src/lib/x.ts': 'export const x = "src";\n',
'test/x.test.ts': "import { x } from '@/lib/x';\nx;\n",
});
const g = buildGraph(repo.work);
expect(testsFor(g, 'src/lib/x.ts').tests).toEqual(['test/x.test.ts']);
expect(testsFor(g, 'lib/x.ts').tests).toEqual([]);
});
}
test('an exact alias wins over a wildcard that also matches', () => {
const repo = fixture();
commit(repo, {
'tsconfig.json': '{ "compilerOptions": { "paths": { "@/*": ["./*"], "@/env": ["src/env.ts"] } } }\n',
'env.ts': 'export const env = 1;\n',
'src/env.ts': 'export const env = 2;\n',
'test/env.test.ts': "import { env } from '@/env';\nenv;\n",
});
const g = buildGraph(repo.work);
expect(testsFor(g, 'src/env.ts').tests).toEqual(['test/env.test.ts']);
expect(testsFor(g, 'env.ts').tests).toEqual([]);
});
test('a later target is the fallback when the first target does not exist', () => {
const repo = fixture();
commit(repo, {
'tsconfig.json': '{ "compilerOptions": { "paths": { "@/*": ["src/*", "generated/*"] } } }\n',
'generated/api.ts': 'export const api = 1;\n',
'test/api.test.ts': "import { api } from '@/api';\napi;\n",
});
expect(testsFor(buildGraph(repo.work), 'generated/api.ts').tests).toEqual(['test/api.test.ts']);
});
test('when the chosen alias resolves nothing, every plausible reading gains the edge (uncertainty selects more)', () => {
const repo = fixture();
commit(repo, {
'tsconfig.json': '{ "compilerOptions": { "paths": { "@/ui/*": ["packages/ui/*"], "@/*": ["src/*"] } } }\n',
'src/ui/button.ts': 'export const b = 1;\n',
'test/button.test.ts': "import { b } from '@/ui/button';\nb;\n",
});
expect(testsFor(buildGraph(repo.work), 'src/ui/button.ts').tests).toEqual(['test/button.test.ts']);
});
test('a relative extends chain supplies paths and baseUrl relative to the config that declares them', () => {
const repo = fixture();
commit(repo, {
'tsconfig.json': '{ "extends": "./config/tsconfig.base", "compilerOptions": { "strict": true } }\n',
'config/tsconfig.base.json': '{ "extends": "./tsconfig.paths.json" }\n',
'config/tsconfig.paths.json': '{ "compilerOptions": { "baseUrl": "..", "paths": { "#lib/*": ["lib/*"] } } }\n',
'lib/plan.ts': 'export const plan = 1;\n',
'test/plan.test.ts': "import { plan } from '#lib/plan';\nplan;\n",
});
expect(testsFor(buildGraph(repo.work), 'lib/plan.ts').tests).toEqual(['test/plan.test.ts']);
});
test('trailing commas are dropped by the tokenizer, never inside a string', () => {
const repo = fixture();
commit(repo, {
'tsconfig.json': '{ "compilerOptions": { "paths": { "~a,]/*": ["lib/*",], }, }, }\n',
'lib/plan.ts': 'export const plan = 1;\n',
'test/plan.test.ts': "import { plan } from '~a,]/plan';\nplan;\n",
});
expect(testsFor(buildGraph(repo.work), 'lib/plan.ts').tests).toEqual(['test/plan.test.ts']);
});
test('an extends chain past the depth limit is named in the no-lane explanation, with the unresolved specifiers', () => {
const repo = fixture();
const files: Record<string, string> = {
'tsconfig.json': '{ "extends": "./c1.json" }\n',
'lib/plan.ts': 'export const plan = 1;\n',
'test/plan.test.ts': "import { plan } from '#lib/plan';\nimport { gone } from '../lib/gone';\nimport { expect } from 'bun:test';\nimport React from 'react';\nplan; gone; expect; React;\n",
};
for (let i = 1; i <= MAX_TSCONFIG_EXTENDS; i++) files[`c${i}.json`] = `{ "extends": "./c${i + 1}.json" }\n`;
files[`c${MAX_TSCONFIG_EXTENDS + 1}.json`] = '{ "compilerOptions": { "paths": { "#lib/*": ["lib/*"] } } }\n';
commit(repo, files);
const m = testsFor(buildGraph(repo.work), 'lib/plan.ts');
expect(m.tests).toEqual([]);
const text = m.provenance.join('\n');
expect(text).toContain(`tsconfig extends depth limit ${MAX_TSCONFIG_EXTENDS}`);
expect(text).toContain("test/plan.test.ts: '#lib/plan' '../lib/gone'");
expect(text).not.toContain("'react'");
expect(text).not.toContain("'bun:test'");
expect(text).toContain('declare the file under dependencies in .gstack/pregate.json, or report the resolver gap');
});
});
+79
View File
@@ -0,0 +1,79 @@
/**
* Item 8 (manifest-parser half of #3176): a lane's selection manifest prints
* framework route paths (`app/(shop)/[id]/page.test.ts`, `@modal`, `$id`)
* and the parser keeps them whole. Cutting them down to `page.test.ts`
* dropped the test from its platform lane, so its remote receipt obligation
* vanished and the test ran locally instead.
*/
import { afterEach, describe, expect, test } from 'bun:test';
import * as fs from 'node:fs';
import * as path from 'node:path';
import { manifestTestPaths } from '../lib/pregate/lane-selection';
import { runScriptSync } from '../lib/script-invocation';
import { BASE_PREGATE, BIN, cleanup, commit, makeFixtureRepo, type FixtureRepo } from './helpers/pregate-fixture';
const repos: FixtureRepo[] = [];
afterEach(() => { while (repos.length) cleanup(repos.pop()!); });
describe('manifestTestPaths', () => {
test('framework route segments stay intact', () => {
const out = [
'app/(shop)/[id]/page.test.ts',
'app/@modal/(.)photo/[...slug]/page.spec.tsx',
'app/routes/$userId/route.test.ts',
'src/routes/[[lang]]/+page.test.ts',
' test/plain.test.ts ',
].join('\n');
expect(manifestTestPaths(out)).toEqual([
'app/(shop)/[id]/page.test.ts',
'app/@modal/(.)photo/[...slug]/page.spec.tsx',
'app/routes/$userId/route.test.ts',
'src/routes/[[lang]]/+page.test.ts',
'test/plain.test.ts',
]);
});
test('paths inside JSON, quotes, listings and grep-style lines are found; prose is not', () => {
const out = [
'Discovered 12 test files.',
'["app/(shop)/[id]/a.test.ts", "test/b.test.ts"]',
' ./test/c.test.ts:12',
'(test/d.test.ts)',
'shard 2: tests/test_e.py',
'app/(group)/f.test.ts,',
].join('\n');
expect(manifestTestPaths(out)).toEqual(['app/(shop)/[id]/a.test.ts', 'test/b.test.ts', 'test/c.test.ts', 'test/d.test.ts', 'tests/test_e.py', 'app/(group)/f.test.ts']);
});
test('the test-file rule is the import graph\'s own (one definition of a test file)', () => {
expect(manifestTestPaths('pkg/x_test.go\nlib/y_spec.rb\nlib/not-a-test.ts')).toEqual(['pkg/x_test.go', 'lib/y_spec.rb']);
});
});
describe('lanes: a bracketed route test in a platform-only lane keeps its remote receipt obligation', () => {
test('the manifest path selects the Windows lane, not a local run', () => {
const repo = makeFixtureRepo();
repos.push(repo);
const route = 'app/(shop)/[id]/page.test.js';
commit(repo, {
'scripts/windows-list.js': `console.log('test/windows-paths.test.js');\nconsole.log(${JSON.stringify(route)});\n`,
});
repo.git('push', '-q', 'origin', 'feature:main');
repo.git('fetch', '-q', 'origin');
commit(repo, { [route]: "const test = require('node:test');\ntest('route', () => {});\n" });
const run = runScriptSync(BIN('gstack-pregate'), ['--base', 'main', '--allow-repo-commands', '--stage', 'tests', '--explain'],
{ cwd: repo.work, encoding: 'utf8', timeout: 180_000, maxBuffer: 64 * 1024 * 1024, env: { ...process.env, ...repo.env } });
const r = { out: run.stdout ?? '', err: `${run.stderr ?? ''}${run.error ? `\n${run.error.message}` : ''}` };
expect(r.out, r.err).toContain('lane windows.yml/windows-shard: 2 files from manifest `node scripts/windows-list.js`');
const host = process.platform === 'win32' ? 'windows' : process.platform === 'darwin' ? 'macos' : 'linux';
const owed = [
{ lane: 'free-tests.yml/unit', platform: 'linux', workflow: 'free-tests.yml', job: 'unit', tests: [route], receipt: null },
{ lane: 'windows.yml/windows-shard', platform: 'windows', workflow: 'windows.yml', job: 'windows-shard', tests: [route], receipt: null },
].filter((o) => o.platform !== host);
const out = JSON.parse(fs.readFileSync(path.join(repo.work, '.gstack/tmp/pregate.json'), 'utf8'));
expect(out.requires_remote).toEqual(owed);
for (const o of owed) expect(r.out).toContain(`requires-remote ${o.lane} (${o.platform}): 1 test(s) — ${route}`);
if (host === 'windows') expect(r.out, r.err).toContain(`ran: node --test '${route}'`);
expect(BASE_PREGATE.selection['windows.yml/windows-shard']).toBe('node scripts/windows-list.js');
});
});
+6 -1
View File
@@ -135,7 +135,12 @@ test('CI native exploration Read does not stand in for completed method Reads',
try {
for (const variant of ['omitted methods', 'pending methods', 'completed methods']) {
const events = structuredClone(captured.omittedReadEvents);
if (variant !== 'omitted methods') events.push(...captured.completedMethodEvents.filter(event => variant === 'completed methods' || event.type === 'assistant'));
if (variant !== 'omitted methods') events.push(...structuredClone(captured.completedMethodEvents.filter(event => variant === 'completed methods' || event.type === 'assistant')));
for (const part of events.flatMap((event: any) => Array.isArray(event.message?.content) ? event.message.content : [])) {
if (part.type === 'tool_result' && typeof part.content === 'string' && part.content.includes('AUTO-GENERATED from system-functional.md.tmpl')) {
part.content = readFileSync(join(import.meta.dir, '../qa/sections/system-functional.md'), 'utf8').split('\n').map((line, i) => `${i + 1}\t${line}`).join('\n');
}
}
const parsed = parseNDJSON(events.map(event => JSON.stringify(event)));
expect(parsed.toolCalls.some(call => call.tool === 'Read' && call.input.file_path.endsWith('/qa-only/sections/exploratory.md') && call.output.includes('# Shared exploratory QA'))).toBe(true);
const errors = qaFunctionalVerdict(fixture, 'qa-only', {
+57
View File
@@ -0,0 +1,57 @@
/**
* #3169: README told users to paste a skill list into CLAUDE.md, and its two
* copies were stale and disagreed. Claude Code lists installed skills itself,
* so the docs keep only the /browse rule. If a comma-separated skill list
* comes back in README.md or CLAUDE.md, it must name exactly the skills that
* ship (the `name:` of every top-level SKILL.md).
*/
import { describe, expect, test } from 'bun:test';
import * as fs from 'node:fs';
import * as path from 'node:path';
const ROOT = path.resolve(import.meta.dir, '..');
const DOCS = ['README.md', 'CLAUDE.md'];
/** Every run of eight or more comma-separated `/skill` tokens, as a set of names. */
export function skillLists(text: string): string[][] {
const flat = text.replace(/\s+/g, ' ');
return [...flat.matchAll(/(?:\/[a-z0-9-]+, ?){7,}(?:and )?\/[a-z0-9-]+/g)].map(m => [...m[0].matchAll(/\/([a-z0-9-]+)/g)].map(n => n[1]!));
}
function shippedSkills(): string[] {
const names = new Set<string>();
for (const dir of fs.readdirSync(ROOT, { withFileTypes: true })) {
if (!dir.isDirectory() && !dir.isSymbolicLink()) continue;
const file = path.join(ROOT, dir.name, 'SKILL.md');
if (!fs.existsSync(file)) continue;
const name = /^name:\s*(\S+)/m.exec(fs.readFileSync(file, 'utf8'))?.[1];
if (name) names.add(name);
}
return [...names].sort();
}
describe('skill lists in README.md and CLAUDE.md (#3169)', () => {
test('the detector finds the kind of list README used to carry (negative control)', () => {
const old = 'lists the available skills: /office-hours, /plan-ceo-review, /plan-eng-review,\n/plan-design-review, /design-consultation, /review, /ship, /qa, /browse, /learn. Then ask';
expect(skillLists(old)).toEqual([['office-hours', 'plan-ceo-review', 'plan-eng-review', 'plan-design-review', 'design-consultation', 'review', 'ship', 'qa', 'browse', 'learn']]);
expect(skillLists('Use /browse for browsing; /qa or /qa-only for testing.')).toEqual([]);
});
test('any skill list present names exactly the shipped skills', () => {
const shipped = shippedSkills();
expect(shipped.length).toBeGreaterThan(40);
for (const doc of DOCS) {
for (const list of skillLists(fs.readFileSync(path.join(ROOT, doc), 'utf8'))) {
const listed = [...new Set(list)].sort();
expect({ doc, missing: shipped.filter(s => !listed.includes(s)), unknown: listed.filter(s => !shipped.includes(s)) })
.toEqual({ doc, missing: [], unknown: [] });
}
}
});
test('README keeps the /browse rule for the CLAUDE.md gstack section', () => {
const readme = fs.readFileSync(path.join(ROOT, 'README.md'), 'utf8');
expect(readme).toContain('mcp__claude-in-chrome__*');
expect(readme).toContain('Use /browse from gstack for all web browsing. Never use mcp__claude-in-chrome__* tools.');
});
});
+64 -2
View File
@@ -37,8 +37,19 @@ const PREPUSH = path.resolve(import.meta.dir, "..", "bin", "gstack-redact-prepus
let repo: string;
let remote: string;
// Same blanking as test/redact-prepush-scan-range.test.ts (#2967). A
// hooksPath written into the fixture repo still runs.
function gitEnv(): NodeJS.ProcessEnv {
const env: NodeJS.ProcessEnv = { ...process.env };
env.GIT_CONFIG_GLOBAL = "/dev/null";
env.GIT_CONFIG_NOSYSTEM = "1";
env.GIT_CONFIG_COUNT = "0";
delete env.GIT_CONFIG_PARAMETERS;
return env;
}
function git(args: string[], cwd = repo): string {
const r = spawnSync("git", args, { cwd, encoding: "utf8", timeout: 30_000 });
const r = spawnSync("git", args, { cwd, encoding: "utf8", timeout: 30_000, env: gitEnv() });
if (r.status !== 0) throw new Error(`git ${args.join(" ")}\n${r.stderr}`);
return r.stdout?.trim() ?? "";
}
@@ -116,7 +127,7 @@ describe("rebased force-push does not re-scan upstream commits (#2573)", () => {
// The rebased tip exists locally and is NOT an ancestor of HEAD — the
// exact condition #2573 identified as the untested third branch.
expect(git(["cat-file", "-t", preRebaseTip])).toBe("commit");
const isAncestor = spawnSync("git", ["merge-base", "--is-ancestor", preRebaseTip, "HEAD"], { cwd: repo, timeout: 30_000 });
const isAncestor = spawnSync("git", ["merge-base", "--is-ancestor", preRebaseTip, "HEAD"], { cwd: repo, timeout: 30_000, env: gitEnv() });
expect(isAncestor.status).not.toBe(0);
// What the OLD range would scan: upstream's published fixture included.
const oldDiff = git(["diff", "--unified=0", `${preRebaseTip}..HEAD`]);
@@ -153,3 +164,54 @@ describe("rebased force-push does not re-scan upstream commits (#2573)", () => {
expect(subject).toBe("my clean work");
});
});
describe("fixture git ignores inherited hook config (#2967)", () => {
test("global, system, and environment-injected hooksPath cannot reject the push", () => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), "prepush-rebase-inherited-"));
const hooks = path.join(root, "hooks");
fs.mkdirSync(hooks);
fs.writeFileSync(path.join(hooks, "pre-push"), "#!/bin/sh\necho inherited-hook >&2\nexit 1\n", { mode: 0o755 });
const config = path.join(root, "gitconfig");
fs.writeFileSync(config, `[core]\n\thooksPath = ${JSON.stringify(hooks)}\n`);
const prev = {
GIT_CONFIG_GLOBAL: process.env.GIT_CONFIG_GLOBAL,
GIT_CONFIG_SYSTEM: process.env.GIT_CONFIG_SYSTEM,
GIT_CONFIG_NOSYSTEM: process.env.GIT_CONFIG_NOSYSTEM,
GIT_CONFIG_COUNT: process.env.GIT_CONFIG_COUNT,
GIT_CONFIG_KEY_0: process.env.GIT_CONFIG_KEY_0,
GIT_CONFIG_VALUE_0: process.env.GIT_CONFIG_VALUE_0,
GIT_CONFIG_PARAMETERS: process.env.GIT_CONFIG_PARAMETERS,
};
try {
process.env.GIT_CONFIG_GLOBAL = config;
process.env.GIT_CONFIG_SYSTEM = config;
delete process.env.GIT_CONFIG_NOSYSTEM;
process.env.GIT_CONFIG_COUNT = "1";
process.env.GIT_CONFIG_KEY_0 = "core.hooksPath";
process.env.GIT_CONFIG_VALUE_0 = hooks;
process.env.GIT_CONFIG_PARAMETERS = `'core.hooksPath=${hooks}'`;
commit("again.txt", "again\n", "again");
git(["push", "-q", "origin", "main"]);
} finally {
for (const [key, value] of Object.entries(prev)) {
if (value === undefined) delete process.env[key];
else process.env[key] = value;
}
fs.rmSync(root, { recursive: true, force: true });
}
});
test("a repo-local hooksPath still rejects the fixture push", () => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), "prepush-rebase-local-hook-"));
const hooks = path.join(root, "hooks");
fs.mkdirSync(hooks);
fs.writeFileSync(path.join(hooks, "pre-push"), "#!/bin/sh\necho inherited-hook >&2\nexit 1\n", { mode: 0o755 });
try {
git(["config", "core.hooksPath", hooks]);
commit("local-hook.txt", "x\n", "local hook");
expect(() => git(["push", "-q", "origin", "main"])).toThrow(/inherited-hook/);
} finally {
fs.rmSync(root, { recursive: true, force: true });
}
});
});
+139 -2
View File
@@ -21,9 +21,24 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "fs";
import { tmpdir } from "os";
import { dirname, join } from "path";
// Fixture git was spawned with the parent environment. A global or system
// core.hooksPath, or the same key via GIT_CONFIG_COUNT /
// GIT_CONFIG_PARAMETERS, runs on these pushes and rejects the local remote
// (#2967). /dev/null drops the global file on every platform: Git for
// Windows rejects NUL (see EMPTY_GLOBAL_GIT_CONFIG in lib/cso/process.ts).
// Config written inside the fixture repo still applies.
function gitEnv(): NodeJS.ProcessEnv {
const env: NodeJS.ProcessEnv = { ...process.env };
env.GIT_CONFIG_GLOBAL = "/dev/null";
env.GIT_CONFIG_NOSYSTEM = "1";
env.GIT_CONFIG_COUNT = "0";
delete env.GIT_CONFIG_PARAMETERS;
return env;
}
let dir: string;
const run = (args: string[], cwd = dir): string => {
const r = spawnSync("git", args, { cwd, encoding: "utf8", timeout: 30_000 });
const r = spawnSync("git", args, { cwd, encoding: "utf8", timeout: 30_000, env: gitEnv() });
if (r.status !== 0) throw new Error(`git ${args.join(" ")}\n${r.stderr}`);
return r.stdout ?? "";
};
@@ -146,7 +161,7 @@ describe("narrowing the range does not narrow coverage", () => {
run(["push", "-q", "origin", "main"]);
run(["fetch", "-q", "origin"]);
run(["checkout", "-q", "feature"]);
spawnSync("git", ["merge", "--no-edit", "main"], { cwd: dir, encoding: "utf8", timeout: 30_000 }); // conflicts
spawnSync("git", ["merge", "--no-edit", "main"], { cwd: dir, encoding: "utf8", timeout: 30_000, env: gitEnv() }); // conflicts
writeFileSync(join(dir, "conflict.txt"), `resolved ${FAKE_AWS_RESOLV}\n`);
run(["add", "conflict.txt"]);
run(["commit", "-q", "--no-edit"]);
@@ -275,3 +290,125 @@ describe("S1: exclusion scoped to the push-target remote", () => {
expect(code).toBe(1);
});
});
// One channel per case. Blanking only the global file still loses to the
// system file, GIT_CONFIG_COUNT, GIT_CONFIG_PARAMETERS, or an init.templateDir
// copied in at git init (#2967).
const INHERITED_HOOK = "#!/bin/sh\necho inherited-hook >&2\nexit 1\n";
function writeHook(dir: string, name: string): void {
mkdirSync(dir, { recursive: true });
writeFileSync(join(dir, name), INHERITED_HOOK, { mode: 0o755 });
}
function withInheritedEnv(extra: Record<string, string | undefined>, body: () => void): void {
const prev = new Map(Object.keys(extra).map((key) => [key, process.env[key]]));
try {
for (const [key, value] of Object.entries(extra)) {
if (value === undefined) delete process.env[key];
else process.env[key] = value;
}
body();
} finally {
for (const [key, value] of prev) {
if (value === undefined) delete process.env[key];
else process.env[key] = value;
}
}
}
describe("fixture git ignores inherited hook config (#2967)", () => {
const roots: string[] = [];
afterEach(() => {
for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true });
});
function keep(path: string): string {
roots.push(path);
return path;
}
function hooksPathConfig(): { config: string; hooks: string } {
const root = keep(mkdtempSync(join(tmpdir(), "gstack prepush inherited-")));
const hooks = join(root, "hooks");
writeHook(hooks, "pre-push");
const config = join(root, "gitconfig");
writeFileSync(config, `[core]\n\thooksPath = ${JSON.stringify(hooks)}\n`);
return { config, hooks };
}
function pushSeed(): void {
const remote = keep(mkdtempSync(join(tmpdir(), "gstack-prepush-inherited-remote-")));
run(["init", "-q", "--bare", "-b", "main"], remote);
run(["remote", "add", "origin", remote]);
run(["push", "-q", "origin", "main"]);
}
test("an inherited global hooksPath cannot reject the fixture push", () => {
const { config } = hooksPathConfig();
withInheritedEnv({ GIT_CONFIG_GLOBAL: config }, () => pushSeed());
});
test("an inherited system hooksPath cannot reject the fixture push", () => {
const { config } = hooksPathConfig();
withInheritedEnv({ GIT_CONFIG_SYSTEM: config, GIT_CONFIG_NOSYSTEM: undefined }, () => pushSeed());
});
test("GIT_CONFIG_COUNT cannot inject a rejecting hooksPath", () => {
const { hooks } = hooksPathConfig();
withInheritedEnv({
GIT_CONFIG_COUNT: "1",
GIT_CONFIG_KEY_0: "core.hooksPath",
GIT_CONFIG_VALUE_0: hooks,
}, () => pushSeed());
});
test("GIT_CONFIG_PARAMETERS cannot inject a rejecting hooksPath", () => {
const { hooks } = hooksPathConfig();
withInheritedEnv({
GIT_CONFIG_PARAMETERS: `'core.hooksPath=${hooks}'`,
}, () => pushSeed());
});
test("an inherited init.templateDir cannot install a rejecting hook", () => {
const root = keep(mkdtempSync(join(tmpdir(), "gstack-prepush-template-")));
const template = join(root, "template");
writeHook(join(template, "hooks"), "pre-push");
writeHook(join(template, "hooks"), "pre-receive");
const config = join(root, "gitconfig");
writeFileSync(config, `[init]\n\ttemplateDir = ${JSON.stringify(template)}\n`);
const work = keep(mkdtempSync(join(tmpdir(), "gstack-prepush-template-work-")));
const remote = keep(mkdtempSync(join(tmpdir(), "gstack-prepush-template-remote-")));
withInheritedEnv({ GIT_CONFIG_GLOBAL: config }, () => {
run(["init", "-q", "-b", "main"], work);
run(["config", "user.email", "t@example.com"], work);
run(["config", "user.name", "T"], work);
writeFileSync(join(work, "README.md"), "seed\n");
run(["add", "README.md"], work);
run(["commit", "-q", "-m", "seed"], work);
run(["init", "-q", "--bare", "-b", "main"], remote);
run(["remote", "add", "origin", remote], work);
run(["push", "-q", "origin", "main"], work);
});
});
test("a hooksPath in the default global files under HOME or XDG_CONFIG_HOME cannot reject the fixture push", () => {
const { hooks } = hooksPathConfig();
const home = keep(mkdtempSync(join(tmpdir(), "gstack-prepush-home-")));
const xdg = join(home, "xdg");
mkdirSync(join(xdg, "git"), { recursive: true });
const body = `[core]\n\thooksPath = ${JSON.stringify(hooks)}\n`;
writeFileSync(join(home, ".gitconfig"), body);
writeFileSync(join(xdg, "git", "config"), body);
withInheritedEnv({ HOME: home, USERPROFILE: home, XDG_CONFIG_HOME: xdg, GIT_CONFIG_GLOBAL: undefined }, () => pushSeed());
});
test("a repo-local hooksPath still rejects the fixture push", () => {
const { hooks } = hooksPathConfig();
const remote = keep(mkdtempSync(join(tmpdir(), "gstack-prepush-local-remote-")));
run(["init", "-q", "--bare", "-b", "main"], remote);
run(["remote", "add", "origin", remote]);
run(["config", "core.hooksPath", hooks]);
expect(() => run(["push", "-q", "origin", "main"])).toThrow(/inherited-hook/);
});
});
+21 -16
View File
@@ -184,14 +184,17 @@ function boundedOutsideVoice(content: string): string {
return content.match(/\*\*Bounded outside-voice wait[\s\S]*?(?=\*\*(?:Integrate reviewer findings|Cross-model tension):\*\*)/)?.[0] ?? '';
}
function hasBoundedOutsideVoiceWait(content: string): boolean {
const fallback = boundedOutsideVoice(content);
return ['Bounded outside-voice wait', 'subagent_type: "Plan"', 'run_in_background: true',
'Immediately call TaskOutput', 'block: true', 'timeout: 300000', 'Make one wait only',
'`<retrieval_status>` must be `success`', '`<task_id>` must match', '`<task_type>` must be `local_agent`',
'`<status>`\n must be `completed`', '`<output>` must be nonempty', 'must be no outer\n `<error>`',
// #3182: Claude Code 2.1.277 removed TaskOutput. The deadline is a background
// timer the host reports when it exits; TaskStop ends whichever task lost.
const fallback = boundedOutsideVoice(content).replace(/\s+/g, ' ');
return ['Bounded outside-voice wait', '`command: "sleep 300"`', 'subagent_type: "Plan"', 'run_in_background: true',
'End your turn and wait for task notifications', 'Make one wait only',
'`<task-notification>`', '`<task-id>` must match the agent ID', '`<status>` must be `completed`',
'is waiting on its own background work', 'must be nonempty',
'identifiable complete', 'Reject raw or in-progress transcripts',
'call TaskStop with the same ID', 'Ignore partial or late results',
'call TaskStop with the timer', 'TaskStop with the same ID', 'Ignore partial or late results',
'STATUS = "unavailable", SOURCE = "none", OUTSIDE_STATUS = "unavailable"'].every(part => fallback.includes(part))
&& !fallback.includes('TaskOutput')
&& /Skip (?:Integrate reviewer findings and )?Cross-model tension\. Persist an unavailable result/.test(fallback);
}
@@ -230,22 +233,23 @@ describe('outside-voice dispatch contract', () => {
expect(prompt).toContain('explicit user approval');
});
test('fallback uses one exact-ID wait and explicit cancellation without a model override', () => {
test('fallback uses one host-timed wait and explicit cancellation without a model override', () => {
expect(hasBoundedOutsideVoiceWait(rendered)).toBe(true);
expectMentions(fallback, [['before', 'taskoutput', 'dispatch']], 'fallback');
expectMentions(fallback, [['before', 'taskstop', 'dispatch']], 'fallback');
expectMentions(fallback, [['without', 'unavailable', 'launching']], 'fallback');
expect(fallback).toContain('Do not set a model\noverride');
expectMentions(fallback, [['wait', 'dispatch/cancellation', 'five-minute']], 'fallback');
expectTokens(fallback, ['`agentId`'], 'fallback');
expectMentions(fallback, [['five-minute', 'host timer']], 'fallback');
expect(fallback).toContain('Keep the returned agent ID');
expectMentions(fallback, [['do not', 'returned', 'launch']], 'fallback');
expectMentions(fallback, [['does not', 'taskoutput', 'timeout']], 'fallback');
expectMentions(fallback, [['report directly', 'no enforced deadline', 'no credit']], 'fallback');
expect(fallback).not.toContain('TaskOutput');
expect(fallback).not.toContain('allowed_tools');
expect(fallback).not.toContain('run_in_background: false');
});
test('only the matching completed final report can enter agreement and persistence', () => {
for (const guard of ['<retrieval_status>', '<task_id>', '<task_type>', 'local_agent', '<status>', 'completed',
'<output>', 'nonempty', 'no outer', '<error>', 'identifiable complete',
for (const guard of ['<task-notification>', '<task-id>', 'must match the agent ID', '<status>', 'completed',
'<summary>', '<result>', 'nonempty', 'is waiting on its own background', 'turn limit', 'identifiable',
'Reject raw or in-progress transcripts', 'do not extract\n finding fragments from them']) expect(fallback).toContain(guard);
expectMentions(fallback, [['do not', 'completeness', 'establish']], 'fallback');
expect(fallback).not.toContain('isRawTranscript');
@@ -269,13 +273,14 @@ describe('outside-voice dispatch contract', () => {
test('the generated-carrier exception rejects missing wait, cancellation or result guards', () => {
expect(hasBoundedOutsideVoiceWait(rendered)).toBe(true);
for (const guard of ['subagent_type: "Plan"', 'timeout: 300000', 'call TaskStop with the same ID',
'<status>', '<output>', 'Reject raw or in-progress transcripts',
for (const guard of ['subagent_type: "Plan"', 'sleep 300', 'TaskStop with the same ID', 'call TaskStop with the timer',
'<status>', '<task-notification>', 'Reject raw or in-progress transcripts',
'Ignore partial or late results', 'Skip Cross-model tension. Persist an unavailable result',
'STATUS = "unavailable", SOURCE = "none", OUTSIDE_STATUS = "unavailable"']) {
expect(hasBoundedOutsideVoiceWait(rendered.replaceAll(guard, 'missing guard')), guard).toBe(false);
}
expect(hasBoundedOutsideVoiceWait('Dispatch via the Agent tool with run_in_background: true')).toBe(false);
expect(hasBoundedOutsideVoiceWait(rendered.replace('Make one wait only', 'Make one wait only with TaskOutput'))).toBe(false);
});
test('expanded Codex availability states preserve the same bounded dispatch guards', () => {
@@ -283,7 +288,7 @@ describe('outside-voice dispatch contract', () => {
expect(expanded).not.toBe(rendered);
for (const content of [rendered, expanded]) {
expect(hasBoundedOutsideVoiceWait(content)).toBe(true);
expect(hasBoundedOutsideVoiceWait(content.replace('call TaskStop with the same ID', 'missing cancellation'))).toBe(false);
expect(hasBoundedOutsideVoiceWait(content.replace('TaskStop with the same ID', 'missing cancellation'))).toBe(false);
}
});
+64
View File
@@ -0,0 +1,64 @@
import { describe, expect, test } from 'bun:test';
import { spawnSync } from 'node:child_process';
import * as path from 'node:path';
import { ECHO_LIMIT, sanitizeEcho } from '../lib/sanitize-echo';
// The one echo sanitizer: lib/sanitize-echo.ts and its Bash twin
// bin/gstack-sanitize-echo.sh must agree byte for byte on every row, in every
// shell that sources the twin (the Bun floor check runs in zsh tool shells).
const ROOT = path.resolve(import.meta.dir, '..');
const TWIN = path.join(ROOT, 'bin', 'gstack-sanitize-echo.sh');
const hasZsh = spawnSync('zsh', ['-c', 'true'], { timeout: 10_000 }).status === 0;
const SHELLS: Array<[string, string[]]> = [['bash', ['bash']], ['bash --posix', ['bash', '--posix']], ...(hasZsh ? [['zsh', ['zsh']] as [string, string[]]] : [])];
const TABLE: Array<[string, string, string]> = [
['plain text', 'Bun 1.4.2', 'Bun 1.4.2'],
['a newline cannot start a state-file key', 'tar: failed\nstages=setup\nreason=x', 'tar: failed stages=setup reason=x'],
['CR, LF and TAB flatten', 'a\r\nb\tc', 'a b c'],
['ESC and other control bytes are removed', '\x1b[31mred\x1b[0m \x07bell\x7f', '[31mred[0m bell'],
['runs of spaces collapse and ends are trimmed', ' a \n\n b ', 'a b'],
['empty', '', ''],
['only control bytes', '\x01\x02\x1b\x7f', ''],
['a path with spaces and non-ASCII letters is kept', "/Users/José Núñez/it's/.bun/bin/bun", "/Users/José Núñez/it's/.bun/bin/bun"],
['capped at 200 bytes', 'x'.repeat(300), 'x'.repeat(200)],
['a cap on a character boundary keeps the character', 'é'.repeat(150), 'é'.repeat(100)],
['a 2-byte character cut by the cap is dropped', `a${'é'.repeat(150)}`, `a${'é'.repeat(99)}`],
['a 3-byte character cut after 1 byte is dropped', `a${'€'.repeat(100)}`, `a${'€'.repeat(66)}`],
['a 3-byte character cut after 2 bytes is dropped', `${'€'.repeat(100)}`, `${'€'.repeat(66)}`],
['a 4-byte character cut after 3 bytes is dropped', `ab${'😀'.repeat(60)}`, `ab${'😀'.repeat(49)}`],
['a space before the cut is trimmed', `${'x'.repeat(199)} tail`, 'x'.repeat(199)],
];
function twin(shell: string[], text: string, viaStdin = false): string {
const script = viaStdin ? '. "$1"; gstack_sanitize_echo' : '. "$1"; gstack_sanitize_echo "$2"';
const r = spawnSync(shell[0]!, [...shell.slice(1), '-c', script, '_', TWIN, ...(viaStdin ? [] : [text])], {
input: viaStdin ? text : undefined, encoding: 'utf8', timeout: 10_000,
});
expect(r.status).toBe(0);
expect(r.stdout.endsWith('\n')).toBe(true);
return r.stdout.slice(0, -1);
}
describe('sanitizeEcho (TypeScript)', () => {
for (const [name, input, expected] of TABLE) test(name, () => expect(sanitizeEcho(input)).toBe(expected));
test('output never exceeds the limit and is always valid UTF-8', () => {
for (const [, input] of TABLE) {
const out = sanitizeEcho(input);
expect(Buffer.byteLength(out)).toBeLessThanOrEqual(ECHO_LIMIT);
expect(out).not.toContain('\uFFFD');
}
});
});
describe.skipIf(process.platform === 'win32')('gstack_sanitize_echo (Bash twin)', () => {
for (const [label, shell] of SHELLS) {
test(`${label}: every row matches the TypeScript twin`, () => {
expect(TABLE.map(([, input]) => twin(shell, input))).toEqual(TABLE.map(([, , expected]) => expected));
});
}
test('stdin form strips NUL bytes too', () => {
expect(twin(['bash'], 'a\0b\nc', true)).toBe(sanitizeEcho('a\0b\nc'));
expect(sanitizeEcho('a\0b\nc')).toBe('ab c');
});
});
+129
View File
@@ -0,0 +1,129 @@
/**
* #3197 tripwire: production TypeScript never spawns a gstack shebang bin by
* path and never spawns a bare `bash`. Windows cannot execute either (no
* shebangs; a PATH `bash` is often WSL's launcher). Both go through
* lib/script-invocation.ts (runScriptSync, runBashSync, wtreeFingerprint).
*
* KNOWN_SITES lists the call sites outside this fix's ownership, each with
* the change that removes it. It may only shrink.
*
* Second rule: the compiled binaries (`bun build --compile` entries) never
* reach lib/script-invocation.ts. Inside a compiled binary process.execPath
* is the binary itself and import.meta.url is a virtual path, so a bin path
* computed there points at nothing.
*/
import { describe, expect, test } from 'bun:test';
import * as fs from 'node:fs';
import * as path from 'node:path';
const ROOT = path.resolve(import.meta.dir, '..');
const SPAWN_BIN_BY_PATH = /\b(?:spawn|spawnSync|execFile|execFileSync)\(\s*(?:path\.)?join\(\s*(?:BIN_DIR|binDir|BIN|bin|binRoot|BIN_ROOT)\b/;
const SPAWN_BARE_BASH = /\b(?:spawn|spawnSync|execFile|execFileSync|execSync)\(\s*['"]bash['"]|Bun\.spawn(?:Sync)?\(\s*\[\s*['"]bash['"]|\[\s*['"]bash['"]\s*,\s*['"]-l?c['"]/;
const COMMENT = /^\s*(?:\/\/|\*|\/\*)/;
const KNOWN_SITES: Record<string, string> = {
'lib/pregate/checks/guards.ts': 'PR 5 (a #3190 file): repo guard commands move to runBashSync',
'lib/pregate/checks/lanes.ts': 'PR 5 (a #3190 file): the lane runner moves to runBashSync',
'lib/evidence-bundle.ts': 'outside this wave: bundle replay commands (bash -lc) move to runBashSync',
'bin/gstack-brain-context-load.ts': 'outside this wave: the brain context loader moves to runBashSync',
'bin/gstack-issue-links': 'outside this wave: the gstack-issue-guard spawn moves to runScriptSync',
};
function productionFiles(): string[] {
const out: string[] = [];
const walk = (dir: string) => {
for (const e of fs.readdirSync(path.join(ROOT, dir), { withFileTypes: true })) {
const rel = path.posix.join(dir, e.name);
if (e.isDirectory()) { if (e.name !== 'node_modules' && e.name !== 'dist') walk(rel); continue; }
if (rel.endsWith('.ts') && !rel.endsWith('.d.ts')) out.push(rel);
}
};
walk('lib');
walk('hosts');
for (const e of fs.readdirSync(path.join(ROOT, 'bin'), { withFileTypes: true })) {
if (!e.isFile()) continue;
const rel = `bin/${e.name}`;
if (rel.endsWith('.ts') || /^#!.*\bbun\b/.test(fs.readFileSync(path.join(ROOT, rel), 'utf8').split('\n')[0] ?? '')) out.push(rel);
}
return out.sort();
}
function offendingSites(): Record<string, string[]> {
const hits: Record<string, string[]> = {};
for (const rel of productionFiles()) {
if (rel === 'lib/script-invocation.ts') continue;
fs.readFileSync(path.join(ROOT, rel), 'utf8').split('\n').forEach((line, i) => {
if (COMMENT.test(line)) return;
if (SPAWN_BIN_BY_PATH.test(line) || SPAWN_BARE_BASH.test(line)) (hits[rel] ??= []).push(`${rel}:${i + 1}: ${line.trim().slice(0, 120)}`);
});
}
return hits;
}
describe('#3197: shebang bins and bash go through lib/script-invocation.ts', () => {
test('no production file spawns a gstack bin by path or a bare bash, outside the known sites', () => {
const hits = offendingSites();
const unexpected = Object.entries(hits).filter(([file]) => !(file in KNOWN_SITES)).flatMap(([, lines]) => lines);
if (unexpected.length) {
throw new Error(`spawn through lib/script-invocation.ts instead (runScriptSync for a bin, runBashSync for bash -c, wtreeFingerprint for gstack-wtree):\n${unexpected.join('\n')}`);
}
});
test('KNOWN_SITES only shrinks: every entry still has a site to remove', () => {
const hits = offendingSites();
const stale = Object.keys(KNOWN_SITES).filter(file => !hits[file]);
expect(stale).toEqual([]);
});
test('the scanner catches both shapes', () => {
expect(SPAWN_BIN_BY_PATH.test("spawnSync(path.join(BIN_DIR, 'gstack-wtree'), [], { timeout: 1 })")).toBe(true);
expect(SPAWN_BIN_BY_PATH.test('spawnSync(join(BIN_DIR, "gstack-slug"), { timeout: 1 })')).toBe(true);
expect(SPAWN_BARE_BASH.test("spawnSync('bash', ['-c', cmd], { timeout: 1 })")).toBe(true);
expect(SPAWN_BARE_BASH.test('const argv = ["bash", "-c", command];')).toBe(true);
expect(SPAWN_BARE_BASH.test("spawnSync(process.execPath, [script], { timeout: 1 })")).toBe(false);
});
});
describe('#3197: compiled binaries never import lib/script-invocation.ts', () => {
const IMPORT = /(?:^|\n)\s*(?:import|export)\s[^'"]*?from\s*['"](\.{1,2}\/[^'"]+)['"]|import\(\s*['"](\.{1,2}\/[^'"]+)['"]\s*\)/g;
function compiledEntries(): string[] {
const scripts = JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8')).scripts as Record<string, string>;
const entries = new Set<string>();
for (const cmd of Object.values(scripts)) for (const m of cmd.matchAll(/bun build --compile\s+(\S+\.ts)/g)) entries.add(m[1]!);
return [...entries].sort();
}
function reaches(entry: string, target: string): string[] | null {
const seen = new Set<string>();
const stack: Array<{ file: string; trail: string[] }> = [{ file: path.join(ROOT, entry), trail: [entry] }];
while (stack.length) {
const { file, trail } = stack.pop()!;
if (seen.has(file)) continue;
seen.add(file);
let src: string;
try { src = fs.readFileSync(file, 'utf8'); } catch { continue; }
for (const m of src.matchAll(IMPORT)) {
const spec = m[1] ?? m[2]!;
const base = path.resolve(path.dirname(file), spec);
const resolved = [base, `${base}.ts`, `${base}.tsx`, path.join(base, 'index.ts')].find(p => fs.existsSync(p) && fs.statSync(p).isFile());
if (!resolved) continue;
const rel = path.relative(ROOT, resolved).split(path.sep).join('/');
if (rel === target) return [...trail, rel];
stack.push({ file: resolved, trail: [...trail, rel] });
}
}
return null;
}
test('package.json declares compiled entries', () => {
expect(compiledEntries().length).toBeGreaterThan(0);
});
for (const entry of compiledEntries()) {
test(`${entry} does not reach lib/script-invocation.ts`, () => {
expect(reaches(entry, 'lib/script-invocation.ts')).toBeNull();
});
}
});
+229
View File
@@ -0,0 +1,229 @@
/**
* #3197: lib/script-invocation.ts is the one way TypeScript runs gstack's
* shebang bins and `bash -c` strings. Windows is simulated with an injected
* platform and filesystem; the fixture table is the shared contract for
* Windows bash discovery.
*/
import { describe, expect, test } from 'bun:test';
import { spawnSync } from 'node:child_process';
import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
import {
bashCommandInvocation, resolveWindowsBash, resolveWindowsBashCached, runBashSync, runScriptSync, scriptInvocation, wtreeFingerprint,
type BashProbe,
} from '../lib/script-invocation';
import { wtreeFingerprint as regenWtreeFingerprint } from '../lib/regen';
const ROOT = path.resolve(import.meta.dir, '..');
const BIN = path.join(ROOT, 'bin');
const table = JSON.parse(fs.readFileSync(path.join(ROOT, 'test/fixtures/windows-bash-resolution.json'), 'utf8')) as {
rows: Array<{ name: string; env?: Record<string, string>; exists: string[]; gitExecPath?: string; which?: Record<string, string>; uname?: string;
expect: { bash: string; source: string } | { refused: true; mentions: string[] }; warning?: string | null }>;
};
const WIN_GIT_BASH = 'C:/Program Files/Git/bin/bash.exe';
const noBash: BashProbe = { platform: 'win32', env: {}, exists: () => false, gitExecPath: () => null, which: () => null };
function probeFor(row: (typeof table.rows)[number]): BashProbe {
return {
platform: 'win32',
env: row.env ?? {},
exists: p => row.exists.includes(p),
gitExecPath: () => row.gitExecPath ?? null,
which: c => row.which?.[c] ?? null,
uname: () => row.uname ?? null,
};
}
describe('Windows bash resolution (fixture table)', () => {
for (const row of table.rows) {
test(row.name, () => {
const res = resolveWindowsBash(probeFor(row));
if ('bash' in row.expect) {
expect(res.ok).toBe(true);
if (!res.ok) return;
expect({ bash: res.bash, source: res.source }).toEqual(row.expect);
} else {
expect(res.ok).toBe(false);
if (res.ok) return;
for (const m of row.expect.mentions) expect(res.message).toContain(m);
expect(res.message).toContain('GSTACK_GIT_BASH');
}
if (row.warning !== undefined) expect(res.warning ?? null).toBe(row.warning === null ? null : `gstack: ${row.warning}`);
});
}
test('WSL launchers are rejected without being probed', () => {
let probed = false;
const res = resolveWindowsBash({ ...noBash, which: () => 'C:\\Windows\\System32\\bash.exe', uname: () => { probed = true; return 'MINGW64_NT'; } });
expect(res.ok).toBe(false);
expect(probed).toBe(false);
});
});
describe('scriptInvocation', () => {
const win: BashProbe = { platform: 'win32', env: {}, exists: p => p === WIN_GIT_BASH, gitExecPath: () => null, which: () => null };
test('a bash-shebang bin on Windows runs through Git Bash with a forward-slashed script path', () => {
const inv = scriptInvocation(path.join(BIN, 'gstack-wtree'), ['--x'], win);
expect(inv).toEqual({ ok: true, cmd: WIN_GIT_BASH, argv: [path.join(BIN, 'gstack-wtree').replace(/\\/g, '/'), '--x'] });
});
test('a bash-shebang bin on POSIX execs directly', () => {
expect(scriptInvocation(path.join(BIN, 'gstack-slug'), [], { platform: 'linux' })).toEqual({ ok: true, cmd: path.join(BIN, 'gstack-slug'), argv: [] });
});
test('a bun-shebang bin runs under Bun on every platform', () => {
for (const platform of ['win32', 'linux', 'darwin']) {
const inv = scriptInvocation(path.join(BIN, 'gstack-redact'), ['--json'], { ...win, platform });
expect(inv).toEqual({ ok: true, cmd: process.execPath, argv: [path.join(BIN, 'gstack-redact'), '--json'] });
}
});
test('no bash on Windows: an actionable refusal, not a spawn error', () => {
const inv = scriptInvocation(path.join(BIN, 'gstack-wtree'), [], noBash);
expect(inv.ok).toBe(false);
if (inv.ok) return;
expect(inv.error).toContain('(BASH_UNAVAILABLE)');
expect(inv.error).toContain('GSTACK_GIT_BASH');
});
test('bash -c goes through the same resolver', () => {
expect(bashCommandInvocation('echo hi', win)).toEqual({ ok: true, cmd: WIN_GIT_BASH, argv: ['-c', 'echo hi'] });
expect(bashCommandInvocation('echo hi', { platform: 'linux' })).toEqual({ ok: true, cmd: 'bash', argv: ['-c', 'echo hi'] });
expect(bashCommandInvocation('echo hi', noBash).ok).toBe(false);
});
test('runScriptSync and runBashSync return a spawnSync-shaped failure the callers already handle', () => {
const r = runScriptSync(path.join(BIN, 'gstack-wtree'), [], { encoding: 'utf8', timeout: 5_000 }, noBash);
expect(r.status).toBeNull();
expect(r.stdout).toBe('');
expect((r.error as NodeJS.ErrnoException).code).toBe('BASH_UNAVAILABLE');
expect(r.error?.message).toContain('GSTACK_GIT_BASH');
const b = runBashSync('true', { encoding: 'utf8', timeout: 5_000 }, noBash);
expect((b.error as NodeJS.ErrnoException).code).toBe('BASH_UNAVAILABLE');
expect(runBashSync('echo ok', { encoding: 'utf8', timeout: 5_000 }).stdout.trim()).toBe('ok');
});
});
describe('resolveWindowsBashCached (the hooks hot path)', () => {
const tmp = () => fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-bash-cache-'));
const base = (calls: { n: number }, mtime = { v: 1 }, live = new Set([WIN_GIT_BASH])): Parameters<typeof resolveWindowsBashCached>[1] => ({
platform: 'win32', env: {},
exists: p => live.has(p),
gitExecPath: () => { calls.n++; return 'C:/Program Files/Git/mingw64/libexec/git-core'; },
which: c => (c === 'git' ? 'C:/Program Files/Git/cmd/git.exe' : null),
stat: () => ({ mtimeMs: mtime.v }),
});
test('second resolution is served from the cache without asking git', () => {
const dir = tmp();
try {
const file = path.join(dir, 'windows-bash.json');
const calls = { n: 0 };
const first = resolveWindowsBashCached(file, base(calls));
expect(first.ok && first.bash).toBe(WIN_GIT_BASH);
expect(calls.n).toBe(1);
const second = resolveWindowsBashCached(file, base(calls));
expect(second.ok && second.bash).toBe(WIN_GIT_BASH);
expect(second.ok && second.source).toBe('git --exec-path (cached)');
expect(calls.n).toBe(1);
expect(fs.readdirSync(dir)).toEqual(['windows-bash.json']);
} finally { fs.rmSync(dir, { recursive: true, force: true }); }
});
test('a new git.exe mtime or a vanished cached bash re-resolves', () => {
const dir = tmp();
try {
const file = path.join(dir, 'windows-bash.json');
const calls = { n: 0 };
const mtime = { v: 1 };
resolveWindowsBashCached(file, base(calls, mtime));
mtime.v = 2;
resolveWindowsBashCached(file, base(calls, mtime));
expect(calls.n).toBe(2);
const live = new Set(['C:/Program Files/Git/usr/bin/bash.exe']);
const moved = resolveWindowsBashCached(file, base(calls, mtime, live));
expect(moved.ok && moved.bash).toBe('C:/Program Files/Git/usr/bin/bash.exe');
expect(calls.n).toBe(3);
} finally { fs.rmSync(dir, { recursive: true, force: true }); }
});
test('the override bypasses the cache and is never written to it', () => {
const dir = tmp();
try {
const file = path.join(dir, 'windows-bash.json');
const calls = { n: 0 };
const res = resolveWindowsBashCached(file, { ...base(calls), env: { GSTACK_GIT_BASH: 'D:/x/bash.exe' }, exists: p => p === 'D:/x/bash.exe' });
expect(res.ok && res.source).toBe('GSTACK_GIT_BASH');
expect(fs.existsSync(file)).toBe(false);
expect(calls.n).toBe(0);
} finally { fs.rmSync(dir, { recursive: true, force: true }); }
});
test('a refusal is not cached', () => {
const dir = tmp();
try {
const file = path.join(dir, 'windows-bash.json');
const res = resolveWindowsBashCached(file, { ...base({ n: 0 }), exists: () => false });
expect(res.ok).toBe(false);
expect(fs.existsSync(file)).toBe(false);
} finally { fs.rmSync(dir, { recursive: true, force: true }); }
});
});
describe('wtreeFingerprint', () => {
const repo = (extra: string[] = []) => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-wtree-fp-'));
const git = (...a: string[]) => spawnSync('git', a, { cwd: dir, encoding: 'utf8', timeout: 30_000 });
git('init', '-q', ...extra);
fs.writeFileSync(path.join(dir, 'a.txt'), 'a\n');
git('add', '.');
git('-c', 'user.name=t', '-c', 'user.email=t@t', '-c', 'commit.gpgsign=false', 'commit', '-q', '-m', 'init');
return dir;
};
test('a SHA-1 repository yields a 40-hex tree, and the regen compatibility wrapper returns the same string', () => {
const dir = repo();
try {
const r = wtreeFingerprint({ cwd: dir });
expect('tree' in r && r.tree).toMatch(/^[0-9a-f]{40}$/);
expect(regenWtreeFingerprint(dir)).toBe('tree' in r ? r.tree : 'missing');
} finally { fs.rmSync(dir, { recursive: true, force: true }); }
});
test('a SHA-256 repository yields a 64-hex tree', () => {
const dir = repo(['--object-format=sha256']);
try {
const r = wtreeFingerprint({ cwd: dir });
expect('tree' in r && r.tree).toMatch(/^[0-9a-f]{64}$/);
} finally { fs.rmSync(dir, { recursive: true, force: true }); }
});
test('a launch failure (no bash on Windows) is distinguished from a helper exit', () => {
const dir = repo();
try {
const launch = wtreeFingerprint({ cwd: dir, invocation: noBash });
expect(launch).toMatchObject({ kind: 'launch' });
expect('error' in launch && launch.error).toContain('GSTACK_GIT_BASH');
const exit = wtreeFingerprint({ cwd: dir, env: { ...process.env, TMPDIR: path.join(dir, 'no-such-dir') } });
expect(exit).toMatchObject({ kind: 'exit' });
expect('error' in exit && exit.error).toMatch(/^gstack-wtree exited 1: .*set TMPDIR to a writable directory/);
expect(regenWtreeFingerprint(path.join(os.tmpdir()))).toBeNull();
} finally { fs.rmSync(dir, { recursive: true, force: true }); }
});
test('always runs with GIT_OPTIONAL_LOCKS=0', () => {
const dir = repo();
const shim = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-wtree-shim-'));
try {
const realGit = Bun.which('git')!;
const log = path.join(shim, 'locks.log');
fs.writeFileSync(path.join(shim, 'git'), `#!/bin/sh\necho "\${GIT_OPTIONAL_LOCKS:-unset}" >> '${log}'\nexec '${realGit}' "$@"\n`, { mode: 0o755 });
const r = wtreeFingerprint({ cwd: dir, env: { ...process.env, PATH: `${shim}${path.delimiter}${process.env.PATH}`, GIT_OPTIONAL_LOCKS: '1' } });
expect('tree' in r).toBe(true);
const seen = new Set(fs.readFileSync(log, 'utf8').trim().split('\n'));
expect([...seen]).toEqual(['0']);
} finally { fs.rmSync(dir, { recursive: true, force: true }); fs.rmSync(shim, { recursive: true, force: true }); }
});
});
@@ -520,3 +520,11 @@ test('section detection credits complete byte-range prints and still refuses a g
expect(read(calls.filter((_, i) => i !== 2))).toEqual([]);
expect(read(calls.slice(0, -1))).toEqual([]);
});
test('section detection credits abutting chunks whose edge bytes repeat by chance', async () => {
const { detectSectionReads } = await import('./helpers/auq-sdk-capture');
const sections = new Map([['s.md', 'alpha\nrecurrent line\nomega\n']]);
const chunk = (output: string) => ({ tool: 'Bash', input: { command: 'head -c 11 x/sections/s.md' }, output });
expect([...detectSectionReads([chunk('alpha\nrecur'), chunk('rent line\nomega\n')], sections)]).toEqual(['s.md']);
expect([...detectSectionReads([chunk('alpha\nrecur'), chunk('line\nomega\n')], sections)]).toEqual([]);
});
+294 -9
View File
@@ -1,4 +1,4 @@
import { describe, test, expect } from 'bun:test';
import { afterEach, describe, test, expect } from 'bun:test';
import { execFileSync, spawnSync } from 'child_process';
import * as fs from 'fs';
import * as os from 'os';
@@ -249,9 +249,8 @@ describe('gstack-session-update lock identity + TTL (#2613)', () => {
// even that one is ownership-checked (see the static pin below).
const bareRms = src.match(/rm -rf "\$LOCK_DIR"(?!\.)/g) || [];
expect(bareRms.length).toBe(1);
expect(src).toContain(
`trap 'kill "$HB_PID" 2>/dev/null; [ "$(cat "$LOCK_DIR/pid" 2>/dev/null)" = "$MYPID" ] && rm -rf "$LOCK_DIR" 2>/dev/null' EXIT`,
);
expect(src).toContain('[ "$(cat "$LOCK_DIR/pid" 2>/dev/null)" = "$MYPID" ] && rm -rf "$LOCK_DIR" 2>/dev/null');
expect(src).toContain('trap cleanup_session_update EXIT');
});
test('EXIT trap is ownership-checked and a heartbeat runs during pull/setup (static pins)', () => {
@@ -259,9 +258,10 @@ describe('gstack-session-update lock identity + TTL (#2613)', () => {
// (a) After a TTL reclaim by another updater, $LOCK_DIR belongs to the
// NEW holder — the old holder's trap must remove the lock ONLY while the
// pidfile still contains ITS pid (MYPID captured at write time).
const trapLine = src.split('\n').find((l) => l.includes("trap '") && l.includes('rm -rf "$LOCK_DIR"'));
expect(trapLine).toBeDefined();
expect(trapLine!).toContain('[ "$(cat "$LOCK_DIR/pid" 2>/dev/null)" = "$MYPID" ] && rm -rf "$LOCK_DIR"');
const cleanup = src.match(/\n cleanup_session_update\(\) \{\n[\s\S]*?\n \}\n/)?.[0];
expect(cleanup).toBeDefined();
expect(src).toContain('trap cleanup_session_update EXIT');
expect(cleanup!).toContain('[ "$(cat "$LOCK_DIR/pid" 2>/dev/null)" = "$MYPID" ] && rm -rf "$LOCK_DIR"');
// MYPID is written to the pidfile (the identity the trap compares against).
expect(src).toContain('MYPID="${BASHPID:-$(sh -c \'echo $PPID\')}"');
expect(src).toContain('echo "$MYPID" > "$LOCK_DIR/pid"');
@@ -270,11 +270,12 @@ describe('gstack-session-update lock identity + TTL (#2613)', () => {
// got reclaimed while ALIVE. The loop re-checks ownership each beat and
// exits instead of touching a reclaimed holder's pidfile.
expect(src).toMatch(
/while :; do sleep 300; \[ "\$\(cat "\$LOCK_DIR\/pid" 2>\/dev\/null\)" = "\$MYPID" \] \|\| exit 0; touch "\$LOCK_DIR\/pid" 2>\/dev\/null; done/,
/while :; do\n\s+sleep 300 &\n\s+wait "\$!" \|\| exit 0\n\s+\[ "\$\(cat "\$LOCK_DIR\/pid" 2>\/dev\/null\)" = "\$MYPID" \] \|\| exit 0\n\s+touch "\$LOCK_DIR\/pid" 2>\/dev\/null\n\s+done/,
);
expect(src).toContain('HB_PID=$!');
// The trap stops the heartbeat so it can never outlive the holder.
expect(trapLine!).toContain('kill "$HB_PID"');
expect(cleanup!).toContain('kill "$heartbeat"');
expect(cleanup!).toContain('${HB_PID:-$(jobs -p)}');
});
test('an expired-TTL lock is reclaimed even when its pid is alive (PID reuse)', async () => {
@@ -300,3 +301,287 @@ describe('gstack-session-update lock identity + TTL (#2613)', () => {
}
}, 30000);
});
// ── A conflicting autostash pop: judged by unmerged files, never by exit code ──
//
// When the carried-over edits conflict with the incoming revision, git (2.56
// at least) still exits 0 from `merge --ff-only --autostash` and leaves
// conflict markers in the live checkout, where Claude Code runs hooks from.
// The updater reads the unmerged files instead: it puts the checked revision
// back and keeps the edits. It never drops a stash entry, because refs/stash is
// shared with every worktree and its top entry may not be the autostash.
describe.skipIf(process.platform === 'win32')('gstack-session-update: a conflicting autostash pop', () => {
const bases: string[] = [];
afterEach(() => { for (const b of bases.splice(0)) fs.rmSync(b, { recursive: true, force: true }); });
function makeConflictFixture() {
const base = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-supd-pop-')));
bases.push(base);
const origin = path.join(base, 'origin.git');
const seed = path.join(base, 'seed');
const install = path.join(base, 'install');
const state = path.join(base, 'state');
const home = path.join(base, 'home');
fs.mkdirSync(state, { recursive: true });
fs.mkdirSync(path.join(home, '.claude'), { recursive: true });
execFileSync('git', ['init', '-q', '--bare', '-b', 'main', origin], { timeout: 30_000 });
fs.mkdirSync(path.join(seed, 'bin'), { recursive: true });
fs.writeFileSync(path.join(seed, 'VERSION'), '1.0.0\n');
fs.writeFileSync(path.join(seed, 'notes.txt'), 'top\nmiddle\nbottom\n');
fs.writeFileSync(path.join(seed, 'bin', 'gstack-config'),
'#!/usr/bin/env bash\nif [ "$1" = "get" ]; then case "$2" in auto_upgrade) echo true;; skill_prefix) echo false;; *) echo "";; esac; fi\nexit 0\n', { mode: 0o755 });
fs.writeFileSync(path.join(seed, 'bin', 'gstack-patch-names'), '#!/usr/bin/env bash\nexit 0\n', { mode: 0o755 });
fs.writeFileSync(path.join(seed, 'setup'), '#!/usr/bin/env bash\necho "$*" >> "$SETUP_CALLS"\nexit 0\n', { mode: 0o755 });
git(seed, 'init', '-q');
git(seed, 'add', '-A');
git(seed, 'commit', '-q', '-m', 'seed');
git(seed, 'branch', '-M', 'main');
git(seed, 'remote', 'add', 'origin', origin);
git(seed, 'push', '-q', 'origin', 'main');
execFileSync('git', ['clone', '-q', origin, install], { timeout: 30_000 });
return { base, seed, install, state, home, calls: path.join(base, 'calls') };
}
type Fx = ReturnType<typeof makeConflictFixture>;
function release(fx: Fx, version: string, notes: string): string {
fs.writeFileSync(path.join(fx.seed, 'notes.txt'), notes);
fs.writeFileSync(path.join(fx.seed, 'VERSION'), `${version}\n`);
git(fx.seed, 'add', '-A');
git(fx.seed, 'commit', '-qm', `release ${version}`);
git(fx.seed, 'push', '-q', 'origin', 'main');
return git(fx.seed, 'rev-parse', 'HEAD');
}
function runHook(fx: Fx, pathPrefix = '', extraEnv: Record<string, string> = {}) {
return spawnSync('bash', [SCRIPT], {
encoding: 'utf8',
env: { PATH: `${pathPrefix}${path.dirname(process.execPath)}:${process.env.PATH}`, HOME: fx.home, GSTACK_DIR: fx.install, GSTACK_STATE_ROOT: fx.state, SETUP_CALLS: fx.calls, TMPDIR: fx.base, ...extraEnv },
timeout: 20_000,
});
}
// The real git binary, pinned once: `git --exec-path` runs through any PATH
// wrapper (a guard that resolves "the next git on PATH" would loop back
// into a shim) and names the directory of the binary itself.
function realGit(): string {
const dir = execFileSync('git', ['--exec-path'], { encoding: 'utf8', timeout: 30_000 }).trim();
const bin = path.join(dir, process.platform === 'win32' ? 'git.exe' : 'git');
try { fs.accessSync(bin, fs.constants.X_OK); } catch { throw new Error(`cannot pin the real git binary: ${bin} (from git --exec-path) is not executable`); }
return bin;
}
// shim(fx, name, tool, body): a PATH prefix whose <tool> runs <body> first
// and otherwise execs the real one ("$REAL").
function shim(fx: Fx, name: string, tool: string, body: string): string {
const dir = path.join(fx.base, name);
fs.mkdirSync(dir, { recursive: true });
const real = tool === 'git' ? realGit() : execFileSync('bash', ['-c', `command -v ${tool}`], { encoding: 'utf8', timeout: 30_000 }).trim();
fs.writeFileSync(path.join(dir, tool), `#!/bin/bash\nREAL="${real}"\n${body}\nexec "$REAL" "$@"\n`, { mode: 0o755 });
return `${dir}:`;
}
const FIXED_DATES = { GIT_AUTHOR_DATE: '2026-10-15T12:00:00Z', GIT_COMMITTER_DATE: '2026-10-15T12:00:00Z' };
/** The rescue commit id gstack-ff-update makes for this install, from a copy of it. */
function predictRescue(fx: Fx): string {
const copy = path.join(fx.base, 'predict');
fs.cpSync(fx.install, copy, { recursive: true });
const r = spawnSync('bash', [path.join(ROOT, 'bin', 'gstack-ff-update'), copy, 'origin/main'], { encoding: 'utf8', env: { ...process.env, ...FIXED_DATES }, timeout: 30_000 });
const m = r.stdout.match(/^rescued \S+ \S+ refs\/gstack\/rescue\/([0-9a-f]{40}) /);
if (!m) throw new Error(`no rescue predicted: ${r.stdout}${r.stderr}`);
fs.rmSync(copy, { recursive: true, force: true });
return m[1];
}
// A git whose `ls-files -u` fails with empty output from call <from> on.
const unreadableIndexGit = (fx: Fx, from: number) =>
shim(fx, 'unreadable-index-git', 'git', [
'case " $* " in *" ls-files -u "*)',
` n=$(( $(cat "${fx.base}/ls-files-calls" 2>/dev/null || echo 0) + 1 )); echo "$n" > "${fx.base}/ls-files-calls"`,
` [ "$n" -ge ${from} ] && { echo "fatal: index file corrupt" >&2; exit 128; } ;;`,
'esac',
].join('\n'));
async function waitFor(fx: Fx, pattern: RegExp, ms = 30_000): Promise<string> {
const logFile = path.join(fx.state, 'analytics', 'session-update.log');
const deadline = Date.now() + ms;
let content = '';
while (Date.now() < deadline) {
content = fs.existsSync(logFile) ? fs.readFileSync(logFile, 'utf8') : '';
if (pattern.test(content) && !fs.existsSync(path.join(fx.state, '.setup-lock'))) return content;
await new Promise((r) => setTimeout(r, 100));
}
throw new Error(`timed out waiting for ${pattern}; log:\n${content}`);
}
const unmerged = (fx: Fx) => git(fx.install, 'ls-files', '-u');
const notes = (fx: Fx) => fs.readFileSync(path.join(fx.install, 'notes.txt'), 'utf8');
test('leaves no conflict markers, keeps the edits, and still sets up', async () => {
const fx = makeConflictFixture();
fs.writeFileSync(path.join(fx.install, 'notes.txt'), 'top LOCAL\nmiddle\nbottom\n');
const incoming = release(fx, '1.1.0', 'top UPSTREAM\nmiddle\nbottom\n');
runHook(fx);
const log = await waitFor(fx, /Z UPDATED from=1\.0\.0 to=1\.1\.0/);
expect(git(fx.install, 'rev-parse', 'HEAD')).toBe(incoming);
expect(unmerged(fx)).toBe('');
expect(notes(fx)).toBe('top UPSTREAM\nmiddle\nbottom\n');
const kept = log.match(/AUTOSTASH_CONFLICT_RECOVERED tree_reset=1 kept_stash=([0-9a-f]{40}) kept_ref=refs\/gstack\/rescue\/([0-9a-f]{40}) unmerged=0/);
expect(kept, log).not.toBeNull();
expect(kept![2]).toBe(kept![1]);
expect(git(fx.install, 'stash', 'show', '-p', kept![1])).toContain('+top LOCAL');
expect(spawnSync('git', ['rev-parse', '-q', '--verify', 'refs/stash'], { cwd: fx.install, timeout: 30_000 }).status).not.toBe(0);
expect(fs.readFileSync(fx.calls, 'utf8')).toContain('--refresh-registered');
}, 60_000);
test('never drops a stash entry it did not make', async () => {
const fx = makeConflictFixture();
fs.writeFileSync(path.join(fx.install, 'notes.txt'), 'top\nmiddle\nbottom MINE\n');
git(fx.install, 'stash', 'push', '-q', '-m', 'keep me');
const mine = git(fx.install, 'rev-parse', 'refs/stash');
fs.writeFileSync(path.join(fx.install, 'notes.txt'), 'top LOCAL\nmiddle\nbottom\n');
release(fx, '1.1.0', 'top UPSTREAM\nmiddle\nbottom\n');
runHook(fx);
const log = await waitFor(fx, /Z UPDATED /);
const kept = log.match(/kept_stash=([0-9a-f]{40})/);
expect(kept, log).not.toBeNull();
expect(git(fx.install, 'stash', 'list', '--format=%H').split('\n')).toEqual([mine]);
expect(git(fx.install, 'rev-parse', 'refs/stash')).toBe(mine);
expect(git(fx.install, 'rev-parse', `refs/gstack/rescue/${kept![1]}`)).toBe(kept![1]);
}, 60_000);
test('a held refs/stash.lock does not matter: the edits are anchored outside refs/stash', async () => {
const fx = makeConflictFixture();
fs.writeFileSync(path.join(fx.install, 'notes.txt'), 'top LOCAL\nmiddle\nbottom\n');
release(fx, '1.1.0', 'top UPSTREAM\nmiddle\nbottom\n');
// A held lock: git prints "cannot store <id>" and nothing references the
// autostash commit.
const lock = path.join(fx.install, '.git', 'refs', 'stash.lock');
fs.writeFileSync(lock, '');
runHook(fx);
const log = await waitFor(fx, /Z UPDATED /);
fs.rmSync(lock);
expect(unmerged(fx)).toBe('');
const kept = log.match(/kept_stash=([0-9a-f]{40}) kept_ref=(refs\/gstack\/rescue\/[0-9a-f]{40})/);
expect(kept, log).not.toBeNull();
expect(git(fx.install, 'rev-parse', kept![2])).toBe(kept![1]);
expect(git(fx.install, 'stash', 'show', '-p', kept![1])).toContain('+top LOCAL');
}, 60_000);
test('a rescue ref that already names another commit is never overwritten, and nothing moves', async () => {
const fx = makeConflictFixture();
const oldHead = git(fx.install, 'rev-parse', 'HEAD');
fs.writeFileSync(path.join(fx.install, 'notes.txt'), 'top LOCAL\nmiddle\nbottom\n');
release(fx, '1.1.0', 'top UPSTREAM\nmiddle\nbottom\n');
git(fx.install, 'fetch', '-q');
const oid = predictRescue(fx);
git(fx.install, 'update-ref', `refs/gstack/rescue/${oid}`, oldHead);
runHook(fx, '', FIXED_DATES);
const log = await waitFor(fx, /Z HELD /);
expect(log).toContain(`HELD autostash-unrecoverable: rescue ref refs/gstack/rescue/${oid} already exists and names another commit`);
expect(log).not.toContain('AUTOSTASH_CONFLICT_RECOVERED');
expect(git(fx.install, 'rev-parse', 'HEAD')).toBe(oldHead);
expect(git(fx.install, 'rev-parse', `refs/gstack/rescue/${oid}`)).toBe(oldHead);
expect(notes(fx)).toBe('top LOCAL\nmiddle\nbottom\n');
expect(fs.existsSync(fx.calls)).toBe(false);
}, 60_000);
test('a held update clears once its cause is gone, and setup runs', async () => {
const fx = makeConflictFixture();
const oldHead = git(fx.install, 'rev-parse', 'HEAD');
fs.writeFileSync(path.join(fx.install, 'notes.txt'), 'top LOCAL\nmiddle\nbottom\n');
const incoming = release(fx, '1.1.0', 'top UPSTREAM\nmiddle\nbottom\n');
git(fx.install, 'fetch', '-q');
const oid = predictRescue(fx);
git(fx.install, 'update-ref', `refs/gstack/rescue/${oid}`, oldHead);
runHook(fx, '', FIXED_DATES);
await waitFor(fx, /Z HELD autostash-unrecoverable/);
expect(runHook(fx, '', FIXED_DATES).stdout).toContain('update held (autostash-unrecoverable: ');
// The person deletes the unrelated ref; the next check (past the throttle) updates.
git(fx.install, 'update-ref', '-d', `refs/gstack/rescue/${oid}`);
fs.rmSync(path.join(fx.state, '.last-session-update'), { force: true });
runHook(fx, '', FIXED_DATES);
const after = await waitFor(fx, /Z UPDATED from=1\.0\.0 to=1\.1\.0/);
expect(after).toContain(`kept_ref=refs/gstack/rescue/${oid}`);
expect(git(fx.install, 'rev-parse', 'HEAD')).toBe(incoming);
expect(notes(fx)).toBe('top UPSTREAM\nmiddle\nbottom\n');
expect(fs.readFileSync(fx.calls, 'utf8')).toContain('--refresh-registered');
}, 90_000);
test('an index that cannot be read before the merge holds the checkout where it is', async () => {
const fx = makeConflictFixture();
const oldHead = git(fx.install, 'rev-parse', 'HEAD');
fs.writeFileSync(path.join(fx.install, 'notes.txt'), 'top LOCAL\nmiddle\nbottom\n');
release(fx, '1.1.0', 'top UPSTREAM\nmiddle\nbottom\n');
runHook(fx, unreadableIndexGit(fx, 1));
const log = await waitFor(fx, /Z PULL_FAILED /);
expect(log).toContain('cannot read the index');
expect(git(fx.install, 'rev-parse', 'HEAD')).toBe(oldHead);
expect(notes(fx)).toBe('top LOCAL\nmiddle\nbottom\n');
expect(fs.existsSync(fx.calls)).toBe(false);
}, 60_000);
test('an index that cannot be read after the merge is never taken as clean', async () => {
const fx = makeConflictFixture();
fs.writeFileSync(path.join(fx.install, 'notes.txt'), 'top LOCAL\nmiddle\nbottom\n');
release(fx, '1.1.0', 'top UPSTREAM\nmiddle\nbottom\n');
runHook(fx, unreadableIndexGit(fx, 2));
const log = await waitFor(fx, /Z PULL_FAILED /);
expect(log).toContain('cannot read the index');
expect(log).not.toContain('UPDATED');
expect(fs.existsSync(fx.calls)).toBe(false);
}, 60_000);
test('without a file for git\'s messages, the update is held before the merge', async () => {
const fx = makeConflictFixture();
const oldHead = git(fx.install, 'rev-parse', 'HEAD');
fs.writeFileSync(path.join(fx.install, 'notes.txt'), 'top LOCAL\nmiddle\nbottom\n');
release(fx, '1.1.0', 'top UPSTREAM\nmiddle\nbottom\n');
runHook(fx, shim(fx, 'no-pull-tmp', 'mktemp', 'case " $* " in *gstack-session-pull*) exit 1 ;; esac'));
const log = await waitFor(fx, /Z HELD /);
expect(log).toContain('HELD temp-file-unavailable');
expect(git(fx.install, 'rev-parse', 'HEAD')).toBe(oldHead);
expect(notes(fx)).toBe('top LOCAL\nmiddle\nbottom\n');
expect(fs.existsSync(fx.calls)).toBe(false);
}, 60_000);
test('files left unmerged before the update hold the checkout where it is', async () => {
const fx = makeConflictFixture();
const oldHead = git(fx.install, 'rev-parse', 'HEAD');
// Someone's own merge or stash pop left a conflict: three index stages.
const blob = (body: string) => execFileSync('git', ['hash-object', '-w', '--stdin'], { cwd: fx.install, input: body, encoding: 'utf8', timeout: 30_000 }).trim();
const stages = [blob('top\nmiddle\nbottom\n'), blob('top OURS\nmiddle\nbottom\n'), blob('top THEIRS\nmiddle\nbottom\n')];
git(fx.install, 'update-index', '--force-remove', 'notes.txt');
execFileSync('git', ['update-index', '--index-info'], {
cwd: fx.install, timeout: 30_000,
input: stages.map((sha, i) => `100644 ${sha} ${i + 1}\tnotes.txt\n`).join(''),
});
fs.writeFileSync(path.join(fx.install, 'notes.txt'), '<<<<<<< ours\ntop OURS\n=======\ntop THEIRS\n>>>>>>> theirs\n');
release(fx, '1.1.0', 'top UPSTREAM\nmiddle\nbottom\n');
runHook(fx);
const log = await waitFor(fx, /Z HELD /);
expect(log).toContain('HELD unmerged-files: 1 unmerged file(s) in the install (first: notes.txt)');
expect(log).not.toContain('AUTOSTASH_CONFLICT_RECOVERED');
expect(git(fx.install, 'rev-parse', 'HEAD')).toBe(oldHead);
expect(unmerged(fx).split('\n')).toHaveLength(3);
expect(notes(fx)).toContain('top THEIRS');
expect(fs.existsSync(fx.calls)).toBe(false);
}, 60_000);
test('a local edit that does not conflict rides over the update (control)', async () => {
const fx = makeConflictFixture();
fs.writeFileSync(path.join(fx.install, 'notes.txt'), 'top\nmiddle\nbottom LOCAL\n');
release(fx, '1.1.0', 'top UPSTREAM\nmiddle\nbottom\n');
runHook(fx);
const log = await waitFor(fx, /Z UPDATED /);
expect(log).not.toContain('AUTOSTASH_CONFLICT_RECOVERED');
expect(notes(fx)).toBe('top UPSTREAM\nmiddle\nbottom LOCAL\n');
}, 60_000);
});
+31
View File
@@ -0,0 +1,31 @@
import { describe, expect, test } from 'bun:test';
import { spawnSync } from 'node:child_process';
import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
const ROOT = path.resolve(import.meta.dir, '..');
// Test-only base control; neither source is run as an account updater.
const SCRIPT = process.env.GSTACK_HEARTBEAT_TEST_SCRIPT ?? path.join(ROOT, 'bin/gstack-session-update');
const FIXTURE = path.join(ROOT, 'test/fixtures/session-update-heartbeat.sh');
describe.skipIf(process.platform === 'win32')('session updater heartbeat lifecycle', () => {
for (const mode of ['normal', 'failure', 'TERM', 'HUP', 'reclaimed'] as const) {
test(`${mode}: reap owned heartbeat and sleeper; preserve unrelated process and lock owner`, () => {
const base = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-heartbeat-'));
try {
fs.chmodSync(base, 0o700);
const result = spawnSync('bash', [FIXTURE, SCRIPT, mode, base], {
encoding: 'utf8', timeout: 5_000,
env: { PATH: '/usr/bin:/bin' },
});
expect(result.error, result.stderr).toBeUndefined();
expect(result.status, result.stderr).toBe(0);
const status = mode === 'failure' ? 7 : mode === 'TERM' ? 143 : mode === 'HUP' ? 129 : 0;
expect(result.stdout).toBe(`closed status=${status} sentinel=alive heartbeat=absent sleeper=absent\n`);
} finally {
fs.rmSync(base, { recursive: true, force: true });
}
}, 7_000);
}
});
+213
View File
@@ -0,0 +1,213 @@
/**
* The session-start lines for a held update, a stage that did not finish and
* edits a recovery shelved. Each hold reason has its own line naming the exact
* command and a troubleshooting anchor; the hold prints before the stage line;
* no setup fix prints while the install has unmerged files; every path is
* shell-quoted. The emitted commands are executed here against an install
* whose path holds a space and an apostrophe.
*/
import { afterEach, describe, expect, test } from 'bun:test';
import { execFileSync, spawnSync } from 'node:child_process';
import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
const ROOT = path.resolve(import.meta.dir, '..');
const SCRIPT = path.join(ROOT, 'bin', 'gstack-session-update');
const DOC = fs.readFileSync(path.join(ROOT, 'docs', 'troubleshooting.md'), 'utf8');
const bases: string[] = [];
afterEach(() => { for (const b of bases.splice(0)) fs.rmSync(b, { recursive: true, force: true }); });
function git(cwd: string, ...args: string[]): string {
return execFileSync('git', args, { cwd, encoding: 'utf8', timeout: 30_000 }).trim();
}
function makeFixture() {
const base = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-banner-')));
bases.push(base);
const origin = path.join(base, 'origin.git');
const seed = path.join(base, 'seed');
const install = path.join(base, "it's an install");
const state = path.join(base, 'state');
const home = path.join(base, 'home');
fs.mkdirSync(state, { recursive: true });
fs.mkdirSync(path.join(home, '.claude'), { recursive: true });
execFileSync('git', ['init', '-q', '--bare', '-b', 'main', origin], { timeout: 30_000 });
fs.mkdirSync(path.join(seed, 'bin'), { recursive: true });
fs.writeFileSync(path.join(seed, 'VERSION'), '1.0.0\n');
fs.writeFileSync(path.join(seed, 'notes.txt'), 'top\nmiddle\nbottom\n');
fs.writeFileSync(path.join(seed, 'bin', 'gstack-config'),
'#!/usr/bin/env bash\nif [ "$1" = "get" ]; then case "$2" in auto_upgrade) echo true;; skill_prefix) echo false;; *) echo "";; esac; fi\nexit 0\n', { mode: 0o755 });
fs.writeFileSync(path.join(seed, 'bin', 'gstack-patch-names'), '#!/usr/bin/env bash\nexit 0\n', { mode: 0o755 });
fs.copyFileSync(path.join(ROOT, 'bin', 'gstack-ff-update'), path.join(seed, 'bin', 'gstack-ff-update'));
fs.writeFileSync(path.join(seed, 'setup'), '#!/usr/bin/env bash\necho "$*" >> "$SETUP_CALLS"\nexit 0\n', { mode: 0o755 });
git(seed, 'init', '-q', '-b', 'main');
git(seed, 'add', '-A');
git(seed, '-c', 'user.name=t', '-c', 'user.email=t@t', 'commit', '-q', '-m', 'seed');
git(seed, 'remote', 'add', 'origin', origin);
git(seed, 'push', '-q', 'origin', 'main');
execFileSync('git', ['clone', '-q', origin, install], { timeout: 30_000 });
return { base, seed, install, state, home, calls: path.join(base, 'calls') };
}
type Fx = ReturnType<typeof makeFixture>;
function release(fx: Fx, notes: string, version = '1.1.0'): string {
fs.writeFileSync(path.join(fx.seed, 'notes.txt'), notes);
fs.writeFileSync(path.join(fx.seed, 'VERSION'), `${version}\n`);
git(fx.seed, 'add', '-A');
git(fx.seed, '-c', 'user.name=t', '-c', 'user.email=t@t', 'commit', '-qm', `release ${version}`);
git(fx.seed, 'push', '-q', 'origin', 'main');
return git(fx.seed, 'rev-parse', 'HEAD');
}
const env = (fx: Fx, extra: Record<string, string> = {}) => ({
PATH: `${path.dirname(process.execPath)}:${process.env.PATH}`, HOME: fx.home, GSTACK_DIR: fx.install, GSTACK_STATE_ROOT: fx.state, SETUP_CALLS: fx.calls, TMPDIR: fx.base, ...extra,
});
/** One session start in the foreground only (the throttle keeps the background check off). */
function banner(fx: Fx): string {
fs.writeFileSync(path.join(fx.state, '.last-session-update'), `${Math.floor(Date.now() / 1000)}\n`);
return spawnSync('bash', [SCRIPT], { encoding: 'utf8', env: env(fx), timeout: 20_000 }).stdout;
}
function pending(fx: Fx, fields: Record<string, string>) {
const all = { stages: '', from: '', failures: '0', next: '0', reason: '', pull: '', ...fields };
fs.writeFileSync(path.join(fx.state, 'session-update-pending'), Object.entries(all).map(([k, v]) => `${k}=${v}\n`).join(''));
}
/** The command after "Fix now (…):", up to the closing `./setup`. */
function fixCommand(line: string): string {
const m = line.match(/Fix now \(in a terminal; Git Bash on Windows\): (.*?&& \.\/setup)/);
expect(m, line).not.toBeNull();
return m![1];
}
function run(fx: Fx, command: string, extra: Record<string, string> = {}) {
return spawnSync('bash', ['-c', command], { cwd: fx.base, encoding: 'utf8', env: env(fx, extra), timeout: 60_000 });
}
async function waitFor(fx: Fx, pattern: RegExp, ms = 30_000): Promise<string> {
const logFile = path.join(fx.state, 'analytics', 'session-update.log');
const deadline = Date.now() + ms;
let content = '';
while (Date.now() < deadline) {
content = fs.existsSync(logFile) ? fs.readFileSync(logFile, 'utf8') : '';
if (pattern.test(content) && !fs.existsSync(path.join(fx.state, '.setup-lock'))) return content;
await new Promise((r) => setTimeout(r, 100));
}
throw new Error(`timed out waiting for ${pattern}; log:\n${content}`);
}
const quoted = (p: string) => `'${p.replace(/'/g, `'\\''`)}'`;
describe.skipIf(process.platform === 'win32')('gstack-session-update: held-update lines', () => {
test('hook-check-unavailable: the hold prints before the stage line, and its command updates the install', () => {
const fx = makeFixture();
const target = release(fx, 'top UPSTREAM\nmiddle\nbottom\n');
fs.writeFileSync(path.join(fx.install, 'notes.txt'), 'top\nmiddle\nbottom LOCAL\n');
pending(fx, { stages: 'setup', reason: 'bun not found on PATH', pull: 'hook-check-unavailable: cannot extract the incoming revision: tar: x' });
const lines = banner(fx).trim().split('\n');
expect(lines).toHaveLength(2);
expect(lines[0]).toStartWith('gstack auto-update: update held (hook-check-unavailable: cannot extract the incoming revision: tar: x)');
expect(lines[0]).toContain('troubleshooting.md#auto-update-hook-check-unavailable');
expect(lines[1]).toContain(`setup did not finish (bun not found on PATH)`);
expect(lines[1]).toContain(`then cd ${quoted(fx.install)} && ./setup`);
const cmd = fixCommand(lines[0]);
expect(cmd).toBe(`cd ${quoted(fx.install)} && git fetch origin && bash bin/gstack-ff-update . '@{upstream}' && ./setup`);
const r = run(fx, cmd);
expect(r.status, r.stdout + r.stderr).toBe(0);
expect(git(fx.install, 'rev-parse', 'HEAD')).toBe(target);
expect(fs.readFileSync(path.join(fx.install, 'notes.txt'), 'utf8')).toBe('top UPSTREAM\nmiddle\nbottom LOCAL\n');
expect(fs.readFileSync(fx.calls, 'utf8')).toBe('\n');
});
test('unmerged files: no stage fix prints, and the command rescues them before it updates', () => {
const fx = makeFixture();
const target = release(fx, 'top UPSTREAM\nmiddle\nbottom\n');
const blob = (body: string) => execFileSync('git', ['hash-object', '-w', '--stdin'], { cwd: fx.install, input: body, encoding: 'utf8', timeout: 30_000 }).trim();
const stages = [blob('top\nmiddle\nbottom\n'), blob('top OURS\nmiddle\nbottom\n'), blob('top THEIRS\nmiddle\nbottom\n')];
git(fx.install, 'update-index', '--force-remove', 'notes.txt');
execFileSync('git', ['update-index', '--index-info'], { cwd: fx.install, timeout: 30_000, input: stages.map((s, i) => `100644 ${s} ${i + 1}\tnotes.txt\n`).join('') });
fs.writeFileSync(path.join(fx.install, 'notes.txt'), '<<<<<<< ours\ntop OURS\n=======\ntop THEIRS\n>>>>>>> theirs\n');
pending(fx, { stages: 'setup', reason: './setup exited 1', pull: '' });
const out = banner(fx);
const lines = out.trim().split('\n');
expect(lines).toHaveLength(1);
expect(out).not.toContain('did not finish');
expect(lines[0]).toContain('update held (unmerged-files: the install has unmerged files (first: notes.txt))');
expect(lines[0]).toContain('troubleshooting.md#auto-update-unmerged-files');
const r = run(fx, fixCommand(lines[0]));
expect(r.status, r.stdout + r.stderr).toBe(0);
expect(git(fx.install, 'ls-files', '-u')).toBe('');
expect(git(fx.install, 'rev-parse', 'HEAD')).toBe(target);
const ref = git(fx.install, 'for-each-ref', '--format=%(refname)', 'refs/gstack/rescue');
expect(git(fx.install, 'show', `${ref}:notes.txt`)).toContain('<<<<<<< ours');
});
test('autostash-unrecoverable: inspection first, then the command once the cause is gone', () => {
const fx = makeFixture();
const target = release(fx, 'top UPSTREAM\nmiddle\nbottom\n');
pending(fx, { pull: 'autostash-unrecoverable: git refused to update x: untracked new.txt would be overwritten' });
const out = banner(fx).trim();
expect(out).toContain(`Look first: git -C ${quoted(fx.install)} status --short.`);
expect(out).toContain('troubleshooting.md#auto-update-autostash-unrecoverable');
expect(run(fx, `git -C ${quoted(fx.install)} status --short`).status).toBe(0);
const r = run(fx, fixCommand(out));
expect(r.status, r.stdout + r.stderr).toBe(0);
expect(git(fx.install, 'rev-parse', 'HEAD')).toBe(target);
});
test('bun-too-old: Bun is upgraded first, then the same command', () => {
const fx = makeFixture();
const target = release(fx, 'top UPSTREAM\nmiddle\nbottom\n');
pending(fx, { pull: 'bun-too-old: found Bun 1.3.2 at /x/bun; gstack 1.1.0 needs 1.3.3 or newer' });
const out = banner(fx).trim();
const m = out.match(/Fix now \(in a terminal; Git Bash on Windows\): (bun upgrade && .*&& \.\/setup)$/);
expect(m, out).not.toBeNull();
const stub = path.join(fx.base, 'bun-stub');
fs.mkdirSync(stub);
fs.writeFileSync(path.join(stub, 'bun'), `#!/usr/bin/env bash\necho "$*" >> "${fx.base}/bun-calls"\n`, { mode: 0o755 });
const r = run(fx, m![1], { PATH: `${stub}:${process.env.PATH}` });
expect(r.status, r.stdout + r.stderr).toBe(0);
expect(fs.readFileSync(path.join(fx.base, 'bun-calls'), 'utf8')).toBe('upgrade\n');
expect(git(fx.install, 'rev-parse', 'HEAD')).toBe(target);
});
test('every anchor the lines link to exists', () => {
const src = fs.readFileSync(SCRIPT, 'utf8');
const anchors = [...src.matchAll(/troubleshooting\.md#([a-z0-9-]+)/g)].map((m) => m[1]!);
for (const a of ['auto-update-unmerged-files', 'auto-update-autostash-unrecoverable', 'auto-update-rescued-edits']) expect(anchors).toContain(a);
for (const a of anchors) expect(DOC, a).toContain(`<a id="${a}"></a>`);
});
});
describe.skipIf(process.platform === 'win32')('gstack-session-update: shelved edits are never silent', () => {
test('background rescue, then a daily line naming the files and the ref; its commands inspect, export only the delta, and delete', async () => {
const fx = makeFixture();
fs.writeFileSync(path.join(fx.install, 'notes.txt'), 'top LOCAL\nmiddle\nbottom\n');
const target = release(fx, 'top UPSTREAM\nmiddle\nbottom\n');
spawnSync('bash', [SCRIPT], { encoding: 'utf8', env: env(fx), timeout: 20_000 });
const log = await waitFor(fx, /Z UPDATED /);
const ref = log.match(/kept_ref=(refs\/gstack\/rescue\/[0-9a-f]{40})/)![1];
expect(git(fx.install, 'rev-parse', 'HEAD')).toBe(target);
// Background → foreground: the next session start names it.
const first = banner(fx).trim();
expect(first).toContain(`your local edits in the install (notes.txt) conflicted with an update, so they were saved in ${ref}`);
expect(first).toContain('troubleshooting.md#auto-update-rescued-edits');
// Once a day: the next session start the same day is quiet.
expect(banner(fx)).toBe('');
const show = first.match(/Inspect \(in a terminal; Git Bash on Windows\): (git -C .*? show --stat '[^']+')\./)![1];
expect(run(fx, show).stdout).toContain('notes.txt');
const exp = first.match(/not in the install: (git -C .*? diff '[^']+\^' '[^']+' > ~\/gstack-local-edits\.patch)/)![1];
expect(run(fx, exp).status).toBe(0);
const patch = fs.readFileSync(path.join(fx.home, 'gstack-local-edits.patch'), 'utf8');
expect(patch).toContain('+top LOCAL');
expect([...patch.matchAll(/^diff --git a\/(\S+)/gm)].map((m) => m[1])).toEqual(['notes.txt']);
// The next day it repeats.
const notes = path.join(fx.state, 'session-update-rescues');
fs.writeFileSync(notes, fs.readFileSync(notes, 'utf8').replace(/ \d{4}-\d{2}-\d{2}$/m, ' 2000-01-01'));
expect(banner(fx)).toContain(ref);
const del = first.match(/Delete when done: (git -C .*? update-ref -d '[^']+')\./)![1];
expect(run(fx, del).status).toBe(0);
expect(git(fx.install, 'for-each-ref', 'refs/gstack/rescue')).toBe('');
expect(banner(fx)).toBe('');
expect(fs.existsSync(notes)).toBe(false);
}, 60_000);
});
+107 -3
View File
@@ -153,7 +153,7 @@ describe.skipIf(process.platform === 'win32')('gstack-session-update: incoming h
const src = fs.readFileSync(SCRIPT, 'utf8');
const bun = src.indexOf('HELD=$(gstack_bun_incoming_hold');
const hooks = src.indexOf('HELD=$(hook_incoming_hold');
const ff = src.indexOf('merge --ff-only');
const ff = src.indexOf('bash "$FF_UPDATE"');
expect(bun).toBeGreaterThan(-1);
expect(hooks).toBeGreaterThan(bun);
expect(ff).toBeGreaterThan(hooks);
@@ -172,7 +172,7 @@ describe.skipIf(process.platform === 'win32')('gstack-session-update: the incomi
function installedUpdater(fx: Fx, checker: string): string {
const bin = path.join(fx.base, 'installed-bin');
fs.mkdirSync(bin, { recursive: true });
for (const f of ['gstack-session-update', 'gstack-state-root.sh', 'gstack-egress-lib.sh', 'gstack-egress-receipt', 'gstack-bun-version.sh', 'gstack-path-spelling.sh']) {
for (const f of ['gstack-session-update', 'gstack-state-root.sh', 'gstack-egress-lib.sh', 'gstack-egress-receipt', 'gstack-bun-version.sh', 'gstack-path-spelling.sh', 'gstack-ff-update']) {
fs.copyFileSync(path.join(ROOT, 'bin', f), path.join(bin, f));
}
fs.writeFileSync(path.join(bin, 'gstack-hook-check'), `#!/usr/bin/env bash\n${checker}\n`, { mode: 0o755 });
@@ -268,7 +268,111 @@ describe.skipIf(process.platform === 'win32')('gstack-session-update: the incomi
await expectHeld(fx, script, /HELD hook-check-unavailable: the installed bin\/gstack-hook-check gave no verified report either \(exited 139/);
const next = runHook(fx, script).stdout;
expect(next).toContain('gstack auto-update: update held (hook-check-unavailable: ');
expect(next).toContain(`Fix now: cd ${fx.install} && git pull --ff-only --autostash && ./setup`);
expect(next).toContain(`Fix now (in a terminal; Git Bash on Windows): cd '${fx.install}' && git fetch origin && bash bin/gstack-ff-update . '@{upstream}' && ./setup`);
expect(next).toContain('https://github.com/garrytan/gstack/blob/main/docs/troubleshooting.md#auto-update-hook-check-unavailable');
});
});
// #3184: MSYS tar cannot create a symlink whose target it has not extracted
// yet (connect-chrome sorts before open-gstack-browser), so `git archive | tar`
// held every Windows release as hook-check-unavailable. The incoming revision
// is extracted through a private index with checkout-index instead, symlinks
// as plain files; tar is never run.
describe.skipIf(process.platform === 'win32')('gstack-session-update: extraction without tar or symlinks (#3184)', () => {
/** A PATH whose tar fails like MSYS tar on any symlink member. */
function msysTar(fx: Fx): string {
const dir = path.join(fx.base, 'msys-tar');
fs.mkdirSync(dir, { recursive: true });
const real = execFileSync('bash', ['-c', 'command -v tar'], { encoding: 'utf8', timeout: 30_000 }).trim();
fs.writeFileSync(path.join(dir, 'tar'), [
'#!/usr/bin/env bash',
`buf=$(mktemp "${fx.base}/tarbuf-XXXXXX"); cat > "$buf"`,
`if "${real}" -tvf "$buf" 2>/dev/null | grep -q '^l'; then`,
` link=$("${real}" -tvf "$buf" | awk '/^l/ { print $6; exit }')`,
' echo "tar: $link: Cannot create symlink: No such file or directory" >&2; echo "tar: Exiting with failure status due to previous errors" >&2; rm -f "$buf"; exit 2',
'fi',
`"${real}" "$@" < "$buf"; rc=$?; rm -f "$buf"; exit $rc`,
].join('\n') + '\n', { mode: 0o755 });
return dir;
}
function runWith(fx: Fx, extraPath: string, script = SCRIPT) {
return spawnSync('bash', [script], {
encoding: 'utf8',
env: { PATH: `${extraPath}:${path.dirname(process.execPath)}:${process.env.PATH}`, HOME: fx.home, GSTACK_DIR: fx.install, GSTACK_STATE_ROOT: fx.state, SETUP_CALLS: fx.calls, TMPDIR: fx.base },
timeout: 20_000,
});
}
/** A release whose tree has a symlink sorted before its target, like connect-chrome. */
const withLink = (fx: Fx, extra: () => void = () => {}) => release(fx, '1.1.0', () => {
fs.mkdirSync(path.join(fx.seed, 'zz-target'), { recursive: true });
fs.writeFileSync(path.join(fx.seed, 'zz-target', 'SKILL.md'), 'name: zz\n');
fs.symlinkSync('zz-target', path.join(fx.seed, 'aa-link'));
extra();
});
test('a release with a symlink before its target fast-forwards under MSYS tar; the real index is untouched by the check', async () => {
const fx = makeFixture();
withLink(fx, () => fs.writeFileSync(path.join(fx.seed, path.dirname(HOOK), 'note.ts'), "export const note = 'new hook ran';\n"));
runWith(fx, msysTar(fx));
const log = await waitFor(fx, /Z (UPDATED|HELD)/);
expect(log).not.toContain('HELD');
expect(log).toContain('UPDATED from=1.0.0 to=1.1.0');
expect(fs.readlinkSync(path.join(fx.install, 'aa-link'))).toBe('zz-target');
expect(runRegisteredHook(fx).stdout).toContain('new hook ran');
});
test('the incoming bytes are what is checked: a valid installed hook against an invalid incoming one holds, and the index stays byte-identical', async () => {
const fx = makeFixture();
withLink(fx, () => fs.writeFileSync(path.join(fx.seed, path.dirname(HOOK), 'note.ts'), 'export const note = ;\n'));
const indexBefore = fs.readFileSync(path.join(fx.install, '.git', 'index'));
runWith(fx, msysTar(fx));
const log = await waitFor(fx, /Z HELD /);
expect(log).toContain(`HELD hook-does-not-parse: ${path.dirname(HOOK)}/note.ts:1:`);
expect(fs.readFileSync(path.join(fx.install, '.git', 'index')).equals(indexBefore)).toBe(true);
expect(runRegisteredHook(fx).stdout).toContain('old hook ran');
expect(fs.readdirSync(fx.base).filter((f) => f.startsWith('gstack-session-hooks-'))).toEqual([]);
});
test('an extraction failure holds with its own stderr, flattened and stripped of control characters', async () => {
const fx = makeFixture();
release(fx, '1.1.0', () => fs.writeFileSync(path.join(fx.seed, 'extra.txt'), 'x\n'));
const dir = path.join(fx.base, 'bad-read-tree');
fs.mkdirSync(dir);
const real = path.join(execFileSync('git', ['--exec-path'], { encoding: 'utf8', timeout: 30_000 }).trim(), 'git');
fs.writeFileSync(path.join(dir, 'git'), `#!/bin/bash\ncase " $* " in *" read-tree "*) [ -n "$GIT_INDEX_FILE" ] && { printf 'fatal: broken\\nstages=x \\033[31mred\\033[0m\\n' >&2; exit 128; } ;; esac\nexec "${real}" "$@"\n`, { mode: 0o755 });
runWith(fx, dir);
const log = await waitFor(fx, /Z HELD /);
expect(log).toContain('HELD hook-check-unavailable: cannot extract the incoming revision: fatal: broken stages=x red incoming=');
const pending = fs.readFileSync(path.join(fx.state, 'session-update-pending'), 'utf8');
expect(pending).not.toMatch(/^stages=x/m);
expect(pending).not.toContain('\x1b');
expect(pending).toMatch(/^stages=$/m);
});
test('tripwire: no hooked path or module a hook imports or sources is a symlink', () => {
const links = new Set(execFileSync('git', ['ls-files', '-s'], { cwd: ROOT, encoding: 'utf8', timeout: 30_000 })
.split('\n').filter((l) => l.startsWith('120000 ')).map((l) => l.split('\t')[1]));
const hooks = execFileSync('bash', [path.join(ROOT, 'bin', 'gstack-hook-check'), '--list', ROOT], { encoding: 'utf8', timeout: 30_000 }).split('\n').filter(Boolean);
expect(hooks.length).toBeGreaterThan(3);
const seen = new Set<string>();
const queue = [...hooks, ...hooks.map((h) => `${h}.ts`)].filter((f) => fs.existsSync(path.join(ROOT, f)));
while (queue.length) {
const f = queue.shift()!;
if (seen.has(f)) continue;
seen.add(f);
const src = fs.readFileSync(path.join(ROOT, f), 'utf8');
const deps = [
...[...src.matchAll(/(?:from|import)\s*\(?\s*['"](\.{1,2}\/[^'"]+)['"]/g)].map((m) => m[1]!),
...[...src.matchAll(/^\s*\. "\$\(cd "\$\(dirname "\$0"\)" && pwd\)\/([^"]+)"/gm)].map((m) => `./${m[1]}`),
];
for (const d of deps) {
const base = path.posix.normalize(path.posix.join(path.posix.dirname(f), d));
const hit = [base, `${base}.ts`, `${base}/index.ts`].find((c) => fs.existsSync(path.join(ROOT, c)) && fs.statSync(path.join(ROOT, c)).isFile());
if (hit) queue.push(hit);
}
}
expect(seen.size).toBeGreaterThan(hooks.length);
expect([...seen].filter((f) => links.has(f))).toEqual([]);
expect(links.has('connect-chrome')).toBe(true);
});
});
+35 -13
View File
@@ -48,6 +48,8 @@ function makeFixture() {
fs.writeFileSync(path.join(seed, 'bin', 'gstack-config'),
'#!/usr/bin/env bash\nif [ "$1" = "get" ]; then case "$2" in auto_upgrade) echo true;; skill_prefix) echo false;; *) echo "";; esac; fi\nexit 0\n', { mode: 0o755 });
fs.writeFileSync(path.join(seed, 'bin', 'gstack-patch-names'), '#!/usr/bin/env bash\nexit 0\n', { mode: 0o755 });
// Installed beside the Bun floor helper, which sources it for held reasons.
fs.copyFileSync(path.join(ROOT, 'bin', 'gstack-sanitize-echo.sh'), path.join(seed, 'bin', 'gstack-sanitize-echo.sh'));
// Stub setup: records each run; $SETUP_CONTROL selects the outcome.
fs.writeFileSync(path.join(seed, 'setup'), [
'#!/usr/bin/env bash',
@@ -146,7 +148,7 @@ describe.skipIf(process.platform === 'win32')('gstack-session-update stages (B11
expireThrottle(fx);
const second = runHook(fx);
expect(second.stdout.trim().split('\n')).toEqual([
`gstack auto-update: setup did not finish (./setup exited 1: error: could not build browse); installed skills may be out of date. gstack retries automatically. Fix now: cd ${fx.install} && ./setup`,
`gstack auto-update: setup did not finish (./setup exited 1: error: could not build browse); installed skills may be out of date. gstack retries automatically. Fix now: cd '${fx.install}' && ./setup`,
]);
await waitFor(fx, /PENDING_BACKOFF stages=setup/);
expect(setupRuns(fx)).toBe(1);
@@ -192,7 +194,7 @@ describe.skipIf(process.platform === 'win32')('gstack-session-update stages (B11
expect(fs.existsSync(marker(fx))).toBe(false);
expect(setupRuns(fx)).toBe(0);
expireThrottle(fx);
expect(runHook(fx, { noBun: true }).stdout).toContain(`(bun not found on PATH); installed skills may be out of date. gstack retries automatically. Fix now: install Bun (https://bun.sh), then cd ${fx.install} && ./setup`);
expect(runHook(fx, { noBun: true }).stdout).toContain(`(bun not found on PATH); installed skills may be out of date. gstack retries automatically. Fix now: install Bun (https://bun.sh), then cd '${fx.install}' && ./setup`);
});
test('a failed migration is its own stage', async () => {
@@ -240,7 +242,7 @@ describe.skipIf(process.platform === 'win32')('gstack-session-update Bun floor (
expireThrottle(fx);
expect(runHook(fx, { bun: '1.3.2' }).stdout.trim()).toBe(
`gstack auto-update: update held (bun-too-old: found Bun 1.3.2 at ${stub}; gstack 1.1.0 needs 1.3.3 or newer); nothing was installed or changed. Fix now: bun upgrade && cd ${fx.install} && git pull --ff-only && ./setup`,
`gstack auto-update: update held (bun-too-old: found Bun 1.3.2 at ${stub}; gstack 1.1.0 needs 1.3.3 or newer); nothing was installed or changed. Fix now (in a terminal; Git Bash on Windows): bun upgrade && cd '${fx.install}' && git fetch origin && bash bin/gstack-ff-update . '@{upstream}' && ./setup`,
);
await waitFor(fx, /HELD bun-too-old/, 2);
expect(head(fx)).toBe(before);
@@ -254,14 +256,34 @@ describe.skipIf(process.platform === 'win32')('gstack-session-update Bun floor (
expect(fs.existsSync(pending(fx))).toBe(false);
});
for (const version of ['1.3.14', 'bun-dev (local build)']) {
test(`supported or unparseable Bun (${version}) proceeds: setup decides`, async () => {
const fx = makeFixture();
upstreamReleaseWithFloor(fx, '1.1.0', '1.3.3');
runHook(fx, { bun: version });
const log = await waitFor(fx, /UPDATED from=1\.0\.0 to=1\.1\.0/);
expect(log).not.toContain('HELD');
expect(head(fx)).toBe(git(fx.seed, 'rev-parse', 'HEAD'));
});
}
test('supported Bun (1.3.14) proceeds: setup decides', async () => {
const fx = makeFixture();
upstreamReleaseWithFloor(fx, '1.1.0', '1.3.3');
runHook(fx, { bun: '1.3.14' });
const log = await waitFor(fx, /UPDATED from=1\.0\.0 to=1\.1\.0/);
expect(log).not.toContain('HELD');
expect(head(fx)).toBe(git(fx.seed, 'rev-parse', 'HEAD'));
});
test('unparseable Bun (bun-dev (local build)) holds with BUN_VERSION_UNREADABLE and names the reinstall fix (#3195)', async () => {
const fx = makeFixture();
const before = head(fx);
upstreamReleaseWithFloor(fx, '1.1.0', '1.3.3');
const stub = path.join(fx.base, 'bun-stub', 'bun');
const reason = `bun-version-unreadable: could not read the version of Bun at ${stub} (bun --version printed 'bun-dev (local build)'); gstack 1.1.0 needs 1.3.3 or newer (BUN_VERSION_UNREADABLE)`;
expect(runHook(fx, { bun: 'bun-dev (local build)' }).stdout).toBe('');
const log = await waitFor(fx, /HELD bun-version-unreadable/);
expect(log).toContain(`HELD ${reason}`);
expect(log).not.toContain('UPDATED');
expect(head(fx)).toBe(before);
expect(setupRuns(fx)).toBe(0);
expect(fs.readFileSync(pending(fx), 'utf8')).toContain(`pull=${reason}\n`);
expireThrottle(fx);
const banner = runHook(fx, { bun: 'bun-dev (local build)' }).stdout.trim();
expect(banner).toBe(
`gstack auto-update: update held (${reason}); nothing was installed or changed. Fix now: reinstall Bun (curl -fsSL https://bun.sh/install | bash), check that bun --version prints a version, then cd ${fx.install} && git pull --ff-only && ./setup. https://github.com/garrytan/gstack/blob/main/docs/troubleshooting.md#bun-version-unreadable`,
);
expect(banner).not.toContain('git pull did not finish');
});
});
+1 -1
View File
@@ -30,7 +30,7 @@ function fixture(copy: boolean) {
put(path.join(root, 'VERSION'), '2.0.0.0\n');
put(path.join(root, 'ETHOS.md'), 'Fixture ethos\n');
put(path.join(root, 'package.json'), JSON.stringify({ type: 'module', scripts: { 'gen:skill-docs': 'bun run scripts/gen-skill-docs.ts' } }));
for (const bin of ['gstack-config', 'gstack-patch-names', 'gstack-relink', 'gstack-migrate-claude-code', 'gstack-claude-code', 'gstack-models', 'gstack-state-root.sh', 'gstack-bun-version.sh', 'gstack-path-spelling.sh', 'gstack-install-registry.sh', 'gstack-render-claude.sh', 'gstack-host-renders.sh']) {
for (const bin of ['gstack-config', 'gstack-patch-names', 'gstack-relink', 'gstack-migrate-claude-code', 'gstack-claude-code', 'gstack-models', 'gstack-state-root.sh', 'gstack-bun-version.sh', 'gstack-path-spelling.sh', 'gstack-claude-root.sh', 'gstack-install-registry.sh', 'gstack-render-claude.sh', 'gstack-host-renders.sh']) {
const target = path.join(root, 'bin', bin);
fs.mkdirSync(path.dirname(target), { recursive: true });
fs.copyFileSync(path.join(ROOT, 'bin', bin), target);
+94
View File
@@ -0,0 +1,94 @@
/**
* #3133: a 1.31 setup run from a checkout under ~/.cursor/skills set up
* unprefixed <skill>/ folders there, each holding a SKILL.md symlink into the
* checkout. Current setup links gstack-<skill>/ folders and its retired-skill
* prune looks only at gstack-* names, so the old folders stayed: Cursor loaded
* every skill twice, or held dangling links once the checkout moved.
* `./setup --host cursor` now removes them with the Claude flat-name cleanup,
* which deletes only entries proven to link into gstack (#2119). Controls:
* user-owned folders stay byte-identical, and an install that fails before
* its new links exist keeps the old folders.
*/
import { afterAll, afterEach, describe, expect, test } from 'bun:test';
import { existsSync, lstatSync, readFileSync, symlinkSync } from 'node:fs';
import { join } from 'node:path';
import { cleanupFixtures, cleanupSeed, fixtureMkdirSync, makeFixture, makeSource, put, runSetup, tree } from './helpers/install-fixture';
afterEach(cleanupFixtures);
afterAll(cleanupSeed);
describe.skipIf(process.platform === 'win32')('setup --host cursor removes 1.31-era unprefixed skill folders (#3133)', () => {
/** A 1.31 folder: a real directory holding only a SKILL.md symlink to `target`. */
function legacy(skills: string, name: string, target: string) {
fixtureMkdirSync(join(skills, name), { recursive: true });
symlinkSync(target, join(skills, name, 'SKILL.md'));
}
test('legacy folders that link into gstack go; user-owned folders stay byte-identical', () => {
const f = makeFixture();
const src = makeSource(f, join(f.home, '.claude/skills/gstack'));
const skills = join(f.home, '.cursor/skills');
// Resolves into the checkout, so Cursor loads it next to gstack-autoplan/.
legacy(skills, 'autoplan', join(src, 'autoplan/SKILL.md'));
// The reporter's shape once the checkout left ~/.cursor/skills/gstack.
legacy(skills, 'review', join(skills, 'gstack/review/SKILL.md'));
// 1.31's /connect-chrome alias, a relative directory link.
symlinkSync('gstack/open-gstack-browser', join(skills, 'connect-chrome'));
// The user's own: a hand-written skill, one named like a gstack skill, and
// one whose SKILL.md links outside any gstack path.
put(join(skills, 'my-skill/SKILL.md'), '---\nname: my-skill\n---\nMine.\n');
put(join(skills, 'qa/SKILL.md'), '---\nname: qa\n---\nMy own QA checklist.\n');
put(join(f.dir, 'dotfiles/notes/SKILL.md'), '---\nname: notes\n---\n');
legacy(skills, 'notes', join(f.dir, 'dotfiles/notes/SKILL.md'));
const kept = Object.fromEntries(['my-skill', 'qa', 'notes'].map(name => [name, tree(join(skills, name))]));
const r = runSetup(f, join(src, 'setup'), ['--host', 'cursor']);
expect(r.status, r.stdout + r.stderr).toBe(0);
expect(['autoplan', 'review', 'connect-chrome'].filter(name => lstatSync(join(skills, name), { throwIfNoEntry: false }))).toEqual([]);
for (const [name, before] of Object.entries(kept)) expect(tree(join(skills, name)), name).toEqual(before);
expect(existsSync(join(skills, 'gstack-autoplan/SKILL.md'))).toBe(true);
expect(existsSync(join(skills, 'gstack/SKILL.md'))).toBe(true);
}, 120_000);
test('reviewer: only gstack-proven folders go and setup names them; user links outside any gstack checkout stay', () => {
const f = makeFixture();
const src = makeSource(f, join(f.home, '.claude/skills/gstack'));
const skills = join(f.home, '.cursor/skills');
legacy(skills, 'autoplan', join(src, 'autoplan/SKILL.md'));
// A real dir whose SKILL.md links into gstack, next to the user's own notes: only gstack's link goes.
legacy(skills, 'ship', join(src, 'ship/SKILL.md'));
put(join(skills, 'ship/my-notes.md'), 'mine\n');
// A sibling repo whose name only starts with gstack, a relative link, and a dangling link: none is gstack's.
put(join(f.home, 'tools/gstack-fork/fork-skill/SKILL.md'), '---\nname: fork-skill\n---\n');
legacy(skills, 'fork-skill', join(f.home, 'tools/gstack-fork/fork-skill/SKILL.md'));
put(join(f.home, 'dotfiles/rel/SKILL.md'), '---\nname: rel\n---\n');
legacy(skills, 'rel', '../../../dotfiles/rel/SKILL.md');
legacy(skills, 'gone', join(f.home, 'old-skills/gone/SKILL.md'));
const kept = Object.fromEntries(['fork-skill', 'rel', 'gone'].map(name => [name, tree(join(skills, name))]));
const r = runSetup(f, join(src, 'setup'), ['--host', 'cursor']);
expect(r.status, r.stdout + r.stderr).toBe(0);
expect(lstatSync(join(skills, 'autoplan'), { throwIfNoEntry: false })).toBeUndefined();
expect(lstatSync(join(skills, 'ship/SKILL.md'), { throwIfNoEntry: false })).toBeUndefined();
expect(readFileSync(join(skills, 'ship/my-notes.md'), 'utf8')).toBe('mine\n');
for (const [name, before] of Object.entries(kept)) expect(tree(join(skills, name)), name).toEqual(before);
expect(r.stdout).toContain(`cleaned up old entries: autoplan ship (removed from ${skills})`);
}, 120_000);
test('control: an install that fails before its new links exist keeps the legacy folders', () => {
const f = makeFixture();
const src = makeSource(f, join(f.home, '.claude/skills/gstack'));
const skills = join(f.home, '.cursor/skills');
legacy(skills, 'autoplan', join(src, 'autoplan/SKILL.md'));
// #3084's failure: the Cursor render step exits 0 but renders nothing, so
// linking fails after the runtime root is in place.
const bun = join(f.commands, 'bun');
put(bun, readFileSync(bun, 'utf8').replace('case "$*" in\n', `case "$*" in\n 'run gen:skill-docs --host cursor') exit 0 ;;\n`), 0o755);
const before = tree(join(skills, 'autoplan'));
const r = runSetup(f, join(src, 'setup'), ['--host', 'cursor']);
expect(r.status, r.stdout + r.stderr).toBe(1);
expect(r.stderr).toContain('.cursor/skills/ generation failed');
expect(tree(join(skills, 'autoplan'))).toEqual(before);
}, 120_000);
});
+86 -3
View File
@@ -23,17 +23,100 @@
import { describe, test, expect } from 'bun:test';
import * as fs from 'fs';
import * as path from 'path';
import * as os from 'os';
import { spawnSync } from 'child_process';
const ROOT = path.resolve(import.meta.dir, '..');
const setupSrc = fs.readFileSync(path.join(ROOT, 'setup'), 'utf-8');
const ROOT_HELPER = path.join(ROOT, 'bin', 'gstack-claude-root.sh');
const rootHelperSrc = fs.readFileSync(ROOT_HELPER, 'utf-8');
const memorableSrc = fs.readFileSync(path.join(ROOT, 'bin', 'gstack-memorable'), 'utf-8');
const hookBinSrc = fs.readFileSync(path.join(ROOT, 'bin', 'gstack-settings-hook'), 'utf-8');
const uninstallSrc = fs.readFileSync(path.join(ROOT, 'bin', 'gstack-uninstall'), 'utf-8');
describe('setup: canonical-only hook paths', () => {
test('CANONICAL_GSTACK_ROOT honors CLAUDE_CONFIG_DIR with ~/.claude fallback', () => {
expect(setupSrc).toContain(
'CANONICAL_GSTACK_ROOT="${CLAUDE_CONFIG_DIR:-$HOME/.claude}/skills/gstack"',
);
expect(rootHelperSrc).toContain('"${CLAUDE_CONFIG_DIR:-$HOME/.claude}/skills/gstack"');
});
test('setup and gstack-memorable take the root from the one sourced helper', () => {
for (const [src, sourceLine] of [
[setupSrc, '. "$SOURCE_GSTACK_DIR/bin/gstack-claude-root.sh" ||'],
[memorableSrc, '. "$(dirname "$0")/gstack-claude-root.sh" ||'],
]) {
expect(src).toContain(sourceLine);
expect(src).toContain('CANONICAL_GSTACK_ROOT="$(gstack_canonical_claude_root)"');
expect(src).not.toContain('CANONICAL_GSTACK_ROOT="${CLAUDE_CONFIG_DIR');
}
});
describe('gstack_canonical_claude_root', () => {
function installAt(root: string) {
const bin = path.join(root, 'bin');
fs.mkdirSync(bin, { recursive: true });
fs.writeFileSync(path.join(bin, 'gstack-session-update'), '#!/bin/sh\n', { mode: 0o755 });
}
function resolve(home: string, configDir?: string): string {
const env: Record<string, string> = { PATH: process.env.PATH ?? '/usr/bin:/bin', HOME: home };
if (configDir !== undefined) env.CLAUDE_CONFIG_DIR = configDir;
const r = spawnSync('bash', ['-c', 'set -u; . "$1" && gstack_canonical_claude_root', '_', ROOT_HELPER.replace(/\\/g, '/')],
{ env, encoding: 'utf-8', timeout: 10_000 });
expect(r.status).toBe(0);
return r.stdout.replace(/\n$/, '');
}
function withHome(fn: (home: string) => void) {
const home = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-canon-'));
try {
installAt(path.join(home, '.claude', 'skills', 'gstack'));
fn(home);
} finally {
fs.rmSync(home, { recursive: true, force: true });
}
}
test('no CLAUDE_CONFIG_DIR resolves to the $HOME install', () => {
withHome((home) => {
expect(resolve(home)).toBe(path.join(home, '.claude', 'skills', 'gstack'));
});
});
test('a per-session config dir linking back to the $HOME install resolves to the $HOME spelling', () => {
withHome((home) => {
const session = path.join(home, 'session-1234');
fs.mkdirSync(session);
fs.symlinkSync(path.join(home, '.claude', 'skills'), path.join(session, 'skills'));
expect(resolve(home, session)).toBe(path.join(home, '.claude', 'skills', 'gstack'));
});
});
test('a config dir with its own install keeps that install', () => {
withHome((home) => {
const other = path.join(home, 'other-config');
installAt(path.join(other, 'skills', 'gstack'));
expect(resolve(home, other)).toBe(path.join(other, 'skills', 'gstack'));
});
});
test('a config dir with no install falls back to the $HOME install', () => {
withHome((home) => {
const empty = path.join(home, 'empty-config');
fs.mkdirSync(empty);
expect(resolve(home, empty)).toBe(path.join(home, '.claude', 'skills', 'gstack'));
});
});
test('with no $HOME install the config-dir spelling stands, even when it is empty', () => {
const home = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-canon-'));
try {
const empty = path.join(home, 'empty-config');
fs.mkdirSync(empty);
expect(resolve(home, empty)).toBe(path.join(empty, 'skills', 'gstack'));
} finally {
fs.rmSync(home, { recursive: true, force: true });
}
});
});
test('_hook_command_path body never references the running tree', () => {
+2 -1
View File
@@ -36,7 +36,7 @@ function slice(from: string, to: string | null): string {
}
const HOOK_SECTIONS = [
slice('CANONICAL_GSTACK_ROOT="${CLAUDE_CONFIG_DIR', '# ─── GBrain detection'),
slice('CANONICAL_GSTACK_ROOT="$(gstack_canonical_claude_root)"', '# ─── GBrain detection'),
slice('# 11. Plan-tune cathedral hook install', '# ─── Redact pre-push guard consent'),
slice('if [ -n "${_HOOK_REFUSED:-}" ]; then', null),
].join('\n');
@@ -282,6 +282,7 @@ describe('setup: registers the hooks that parse, refuses the rest, exits non-zer
`SETTINGS_HOOK='${posix(ROOT)}/bin/gstack-settings-hook'`,
`GSTACK_CONFIG='${posix(ROOT)}/bin/gstack-config'`,
'TEAM_MODE=1 NO_TEAM_MODE=0 IS_WINDOWS=0 QUIET=1 PLAN_TUNE_HOOKS_MODE="" TIMELINE_STOP_HOOK_MODE=""',
'. "$SOURCE_GSTACK_DIR/bin/gstack-claude-root.sh"',
HOOK_SECTIONS,
'echo SETUP_HOOKS_DONE',
].join('\n');
+56 -11
View File
@@ -106,13 +106,15 @@ describe('setup: Chromium bootstrap static invariants', () => {
/**
* Integration harness: the real block + the real deadline helpers, with the
* probe and installer stubbed. `bunx` is a shell function, so the block's
* subshell inherits the stub. Emits REASON=... and REACHED_END=1 so the test
* can prove setup continued past the block.
* probe and installer stubbed. The installer runs through setup's `bun_cmd`,
* a shell function, so the block's subshell inherits the stub. Emits
* REASON=... and REACHED_END=1 so the test can prove setup continued past
* the block.
*/
function runBlock(opts: {
probe: 'ok' | 'fail' | 'fail-then-ok'; // fail-then-ok = fresh install: probe fails, install runs, probe passes
bunx: string; // body of the bunx stub
bunx?: string; // body of the bun_cmd stub (the installer); omitted = setup's real bun_cmd runs $BUN_CMD
bunCmd?: string; // BUN_CMD for the real bun_cmd (default: bun)
env?: Record<string, string>;
preLockPid?: string; // pre-create the install lock held by this pid
preLockNoPidAgeMin?: number; // pre-create a lock dir with NO pid file, this many minutes old
@@ -160,7 +162,10 @@ function runBlock(opts: {
'_clear_playwright_quarantine() { :; }',
probeFn,
opts.prelude ?? '',
`bunx() { echo "bunx-called override=${'$'}{PLAYWRIGHT_HOST_PLATFORM_OVERRIDE:-unset}" >> "$MARK"; ${opts.bunx}; }`,
`BUN_CMD='${opts.bunCmd ?? 'bun'}'`,
opts.bunx === undefined
? extractFn('bun_cmd')
: `bun_cmd() { echo "bun-x-called args=$* override=${'$'}{PLAYWRIGHT_HOST_PLATFORM_OVERRIDE:-unset}" >> "$MARK"; ${opts.bunx}; }`,
killTree,
extractFn('_wait_with_deadline'),
// The block opens with the /etc/os-release probe that RESETS the override
@@ -287,14 +292,14 @@ describe('setup: Chromium bootstrap block executes best-effort', () => {
const r = runBlock({ probe: 'fail', bunx: 'exit 0', preLockPid: '4194305' /* above Linux's largest pid_max: never a live pid */ });
expect(r.status).toBe(0);
expect(r.stderr).toContain('reclaiming stale Chromium-install lock');
expect(fs.readFileSync(path.join(r.tmp, 'mark'), 'utf-8')).toContain('bunx-called');
expect(fs.readFileSync(path.join(r.tmp, 'mark'), 'utf-8')).toContain('bun-x-called');
});
test('a lock whose pid file is garbage (-1, abc, 0) is stale, not "locked": kill -0 -1 would signal everything and "succeed"', () => {
for (const pid of ['-1', 'abc', '0']) {
const r = runBlock({ probe: 'fail', bunx: 'exit 0', preLockPid: pid });
expect(r.status).toBe(0);
expect(fs.readFileSync(path.join(r.tmp, 'mark'), 'utf-8')).toContain('bunx-called');
expect(fs.readFileSync(path.join(r.tmp, 'mark'), 'utf-8')).toContain('bun-x-called');
expect(r.stdout).not.toContain('chromium-install-locked');
}
}, 15_000);
@@ -302,7 +307,7 @@ describe('setup: Chromium bootstrap block executes best-effort', () => {
test('a lock held by a LIVE pid but older than the install bound is reclaimed (holder past its deadline, or a recycled pid)', () => {
const r = runBlock({ probe: 'fail', bunx: 'exit 0', preLockPid: String(process.pid), preLockAgeMin: 30, env: { GSTACK_PLAYWRIGHT_INSTALL_TIMEOUT: '60' } });
expect(r.status).toBe(0);
expect(fs.readFileSync(path.join(r.tmp, 'mark'), 'utf-8')).toContain('bunx-called');
expect(fs.readFileSync(path.join(r.tmp, 'mark'), 'utf-8')).toContain('bun-x-called');
expect(r.stdout).not.toContain('chromium-install-locked');
expect(r.stderr).toContain('past the install bound');
}, 15_000);
@@ -310,7 +315,7 @@ describe('setup: Chromium bootstrap block executes best-effort', () => {
test('a lock dir with NO pid file is reclaimed once older than the install bound, and honored while fresh', () => {
const old = runBlock({ probe: 'fail', bunx: 'exit 0', preLockNoPidAgeMin: 30, env: { GSTACK_PLAYWRIGHT_INSTALL_TIMEOUT: '60' } });
expect(old.status).toBe(0);
expect(fs.readFileSync(path.join(old.tmp, 'mark'), 'utf-8')).toContain('bunx-called');
expect(fs.readFileSync(path.join(old.tmp, 'mark'), 'utf-8')).toContain('bun-x-called');
expect(old.stdout).not.toContain('chromium-install-locked');
const fresh = runBlock({ probe: 'fail', bunx: 'exit 0', preLockNoPidAgeMin: 0, env: { GSTACK_PLAYWRIGHT_INSTALL_TIMEOUT: '600' } });
expect(fresh.status).toBe(0);
@@ -363,6 +368,46 @@ function pathWithoutNode(): { bin: string; cleanup: () => void } {
}
describe('setup: Chromium bootstrap block — fresh install, lock hygiene, override, Windows arms', () => {
/** A winget-shaped Bun (#3131): `bun` on PATH, no `bunx` anywhere on it. */
function wingetBun(body: string): { dir: string; env: Record<string, string>; cleanup: () => void } {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-winget-bun-'));
fs.writeFileSync(path.join(dir, 'bun'), `#!/bin/sh\nprintf '%s\\n' "$*" >> "${dir}/calls"\n${body}\n`, { mode: 0o755 });
const rest = (process.env.PATH ?? '').split(path.delimiter)
.filter((d) => d && !fs.existsSync(path.join(d, 'bunx')) && !fs.existsSync(path.join(d, 'bunx.exe')));
return { dir, env: { PATH: [dir, ...rest].join(path.delimiter) }, cleanup: () => fs.rmSync(dir, { recursive: true, force: true }) };
}
test('winget-shaped Bun with no bunx: the install runs as `bun x` through setup\'s resolver and succeeds', () => {
const bun = wingetBun('exit 0');
try {
const r = runBlock({ probe: 'fail-then-ok', env: bun.env });
expect(r.status).toBe(0);
expect(r.stdout).toContain('REASON=\n');
expect(r.stdout).toContain('REACHED_END=1');
expect(fs.readFileSync(path.join(bun.dir, 'calls'), 'utf-8')).toBe('x playwright install chromium\n');
} finally {
bun.cleanup();
}
});
test('exit 127 from the installer names the resolved bun and both skip commands, not the network', () => {
const bun = wingetBun('exit 127');
try {
const r = runBlock({ probe: 'fail', env: bun.env });
expect(r.status).toBe(0);
expect(r.stdout).toContain('REASON=chromium-install\n');
expect(r.stderr).toContain(`${path.join(bun.dir, 'bun')} x playwright install chromium exited 127 (command not found); install Bun from bun.sh (winget Bun ships no bunx), or skip with ./setup --no-browser (Git Bash) or .\\setup.ps1 --no-browser (PowerShell)`);
expect(r.stderr).not.toContain('offline, proxy');
} finally {
bun.cleanup();
}
});
test('the installer stub sees `x playwright install chromium`', () => {
const r = runBlock({ probe: 'fail-then-ok', bunx: 'exit 0' });
expect(fs.readFileSync(path.join(r.tmp, 'mark'), 'utf-8')).toContain('bun-x-called args=x playwright install chromium override=unset');
});
test('fresh install happy path: probe fails, install succeeds, re-probe passes → no reason, lock released, EXIT trap restored', () => {
const r = runBlock({ probe: 'fail-then-ok', bunx: 'exit 0' });
expect(r.status).toBe(0);
@@ -370,7 +415,7 @@ describe('setup: Chromium bootstrap block — fresh install, lock hygiene, overr
expect(r.stdout).toContain('REACHED_END=1');
// Installer ran exactly once (no override on a non-26.04 path).
const mark = fs.readFileSync(path.join(r.tmp, 'mark'), 'utf-8');
expect(mark.split('\n').filter((l) => l.startsWith('bunx-called')).length).toBe(1);
expect(mark.split('\n').filter((l) => l.startsWith('bun-x-called')).length).toBe(1);
expect(mark).toContain('override=unset');
// The mkdir-mutex is released for the next setup...
expect(fs.existsSync(path.join(r.tmp, 'gstack-playwright-install.lock'))).toBe(false);
@@ -402,7 +447,7 @@ describe('setup: Chromium bootstrap block — fresh install, lock hygiene, overr
expect(r.stdout).toContain('REACHED_END=1');
expect(r.stderr).toContain('nodejs.org');
// The install itself ran; only the Node verification failed.
expect(fs.readFileSync(path.join(r.tmp, 'mark'), 'utf-8')).toContain('bunx-called');
expect(fs.readFileSync(path.join(r.tmp, 'mark'), 'utf-8')).toContain('bun-x-called');
} finally {
cleanup();
}
+174 -2
View File
@@ -2,7 +2,11 @@
* setup.ps1: the Windows entry point checks Git for Windows, Bun and Node.js,
* then runs ./setup in Git Bash with every argument passed as its own argv
* entry, never pasted into shell source. The behavioral cases copy the script
* next to a stub ./setup that prints its argv and run it under pwsh.
* next to a stub ./setup that prints its argv and run it under pwsh, and
* under Windows PowerShell 5.1's legacy native-argument passing: pwsh with
* $PSNativeCommandArgumentPassing = 'Legacy' here, powershell.exe on Windows
* (#3130: the 5.1 legacy mode stripped the double quotes inside the bash -c
* script, and bash failed with "unexpected EOF").
*/
import { describe, test, expect, afterEach } from 'bun:test';
import * as fs from 'fs';
@@ -28,6 +32,28 @@ function stubCheckout(): string {
return dir;
}
const IS_WIN = process.platform === 'win32';
/** Windows PowerShell 5.1 itself on Windows; elsewhere pwsh in Legacy argument mode. */
function runPs1Legacy(dir: string, args: string[], env: Record<string, string | undefined> = {}) {
let cmd: string;
let argv: string[];
if (IS_WIN) {
cmd = 'powershell.exe';
argv = ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', path.join(dir, 'setup.ps1'), ...args];
} else {
fs.writeFileSync(path.join(dir, 'legacy.ps1'), "$PSNativeCommandArgumentPassing = 'Legacy'\n& (Join-Path $PSScriptRoot 'setup.ps1') @args\nexit $LASTEXITCODE\n");
cmd = PWSH!;
argv = ['-NoProfile', '-NonInteractive', '-File', path.join(dir, 'legacy.ps1'), ...args];
}
const r = spawnSync(cmd, argv, {
cwd: os.tmpdir(),
encoding: 'utf-8',
env: { ...process.env, ...(IS_WIN ? {} : { GSTACK_GIT_BASH: BASH! }), ...env },
timeout: 60_000,
});
return { code: r.status, out: (r.stdout || '') + (r.stderr || '') };
}
function runPs1(dir: string, args: string[], env: Record<string, string | undefined> = {}) {
const r = spawnSync(PWSH!, ['-NoProfile', '-NonInteractive', '-File', path.join(dir, 'setup.ps1'), ...args], {
cwd: os.tmpdir(),
@@ -40,7 +66,9 @@ function runPs1(dir: string, args: string[], env: Record<string, string | undefi
describe('setup.ps1', () => {
test('passes arguments NUL-separated through a private file to a constant bash script', () => {
expect(SOURCE).toContain(`& $bash -c 'mapfile -d "" -t argv < "$1"; rm -f "$1"; exec ./setup "\${argv[@]}"' setup $argFile`);
expect(SOURCE).toContain(`& $bash -c 'set -f; IFS=; mapfile -d '''' -t argv < $1; rm -f -- $1; exec ./setup \${argv[@]}' setup $argFile`);
const script = SOURCE.match(/& \$bash -c '((?:[^']|'')*)' setup \$argFile/)![1]!;
expect(script).not.toContain('"');
expect(SOURCE).toContain('foreach ($arg in $args) { $writer.Write([string]$arg); $writer.Write([char]0) }');
expect(SOURCE).not.toMatch(/-join|Invoke-Expression|\biex\b|git-bash\.exe/);
expect([...SOURCE].every((c) => c.charCodeAt(0) < 128)).toBe(true);
@@ -73,4 +101,148 @@ describe('setup.ps1', () => {
expect(out).not.toContain('Git for Windows:');
expect(out).not.toContain('arg=[');
});
// Arguments Node cannot hand to powershell.exe intact are left out on Windows:
// there the command line is parsed before setup.ps1 sees it.
const ADVERSARIAL = ['--host', 'codex', 'two words', '$(touch PWNED)', "it's", ';echo injected', '`whoami`', '*',
...(IS_WIN ? [] : ['"quoted"', 'a\\"b\\'])];
test.skipIf((!PWSH && !IS_WIN) || !BASH)('Windows PowerShell 5.1 (legacy argument passing): forwards every argument literally, with a space in TMPDIR', () => {
const dir = stubCheckout();
const tmp = path.join(dir, 'temp with space');
fs.mkdirSync(tmp);
const { code, out } = runPs1Legacy(dir, ADVERSARIAL, { TMPDIR: tmp, TEMP: tmp, TMP: tmp });
expect(out).not.toContain('unexpected EOF');
expect(code, out).toBe(7);
expect(out.split(/\r?\n/).filter((l) => l.startsWith('arg=['))).toEqual(ADVERSARIAL.map((a) => `arg=[${a}]`));
expect(out).not.toContain('injected\n');
expect(fs.existsSync(path.join(dir, 'PWNED'))).toBe(false);
expect(fs.existsSync(path.join(os.tmpdir(), 'PWNED'))).toBe(false);
expect(fs.readdirSync(tmp)).toEqual([]);
});
test.skipIf((!PWSH && !IS_WIN) || !BASH)('an empty argument is refused before anything runs', () => {
const dir = stubCheckout();
for (const run of [runPs1Legacy, ...(PWSH ? [runPs1] : [])]) {
const { code, out } = run(dir, ['--host', '', 'codex']);
expect(code, out).toBe(2);
expect(out).toContain('setup.ps1: argument 2 is empty; setup takes no empty arguments. Nothing was installed or changed. (SETUP_PS1_EMPTY_ARGUMENT; https://github.com/garrytan/gstack/blob/main/docs/troubleshooting.md#setup-ps1-empty-argument)');
expect(out).not.toContain('arg=[');
}
});
});
/**
* Git Bash resolution: setup.ps1's own refusal and warning text, then every
* row of lib/script-invocation.ts's table (test/fixtures/windows-bash-resolution.json)
* so the two resolvers cannot drift. The override and its deprecated alias,
* both set, a missing override, a scoop shim, per-user, portable and
* machine-wide Git, an MSYS bash on PATH, and the WSL and non-MSYS
* rejections. pwsh on Linux with every location injected: PATH,
* git --exec-path, LOCALAPPDATA, ProgramFiles and SystemRoot. A shared row's
* C:/... path lives under <root>/C/..., with its separators kept as written.
*/
describe.skipIf(!PWSH || IS_WIN)('setup.ps1: Git Bash resolution', () => {
type Row = {
name: string;
git?: string; // where the fake git lives (default bin/git)
execPath?: string; // what git --exec-path prints (relative to the root); none when absent
gitBash?: string[]; // fake Git Bash files
pathBash?: Record<string, string>; // bash on PATH -> what its uname -s prints
env?: Record<string, string>; // values may start with @ for a root-relative path
used?: string; // the bash that ran setup
refused?: string[]; // the refusal lines that must appear
warnings?: number; // how many differ-warnings print
};
const ROWS: Row[] = [
{ name: 'override', gitBash: ['custom/bash.exe', 'Program Files/Git/bin/bash.exe'], env: { GSTACK_GIT_BASH: '@custom/bash.exe', ProgramFiles: '@Program Files' }, used: 'custom/bash.exe' },
{ name: 'alias', gitBash: ['custom/bash.exe'], env: { GSTACK_BASH: '@custom/bash.exe' }, used: 'custom/bash.exe' },
{ name: 'both set and differ: GSTACK_GIT_BASH wins, one warning', gitBash: ['a/bash.exe', 'b/bash.exe'], env: { GSTACK_GIT_BASH: '@a/bash.exe', GSTACK_BASH: '@b/bash.exe' }, used: 'a/bash.exe', warnings: 1 },
{ name: 'both set to the same path: no warning', gitBash: ['a/bash.exe'], env: { GSTACK_GIT_BASH: '@a/bash.exe', GSTACK_BASH: '@a/bash.exe' }, used: 'a/bash.exe', warnings: 0 },
{ name: 'a missing override is refused, never skipped', gitBash: ['Program Files/Git/bin/bash.exe'], env: { GSTACK_GIT_BASH: '@nope/bash.exe', ProgramFiles: '@Program Files' }, refused: ['setup.ps1: GSTACK_GIT_BASH names @nope/bash.exe, which does not exist.'] },
{ name: 'a missing alias is refused by its own name', env: { GSTACK_BASH: '@nope/bash.exe' }, refused: ['setup.ps1: GSTACK_BASH names @nope/bash.exe, which does not exist.'] },
{ name: 'scoop shim: git --exec-path finds the real install', git: 'scoop/shims/git', execPath: 'scoop/apps/git/current/mingw64/libexec/git-core', gitBash: ['scoop/apps/git/current/bin/bash.exe'], used: 'scoop/apps/git/current/bin/bash.exe' },
{ name: 'per-user Git', execPath: 'nowhere/mingw64/libexec/git-core', gitBash: ['AppData/Local/Programs/Git/bin/bash.exe'], env: { LOCALAPPDATA: '@AppData/Local' }, used: 'AppData/Local/Programs/Git/bin/bash.exe' },
{ name: 'portable Git: the folders around git.exe', git: 'PortableGit/cmd/git', gitBash: ['PortableGit/bin/bash.exe'], used: 'PortableGit/bin/bash.exe' },
{ name: 'machine-wide Git', gitBash: ['Program Files/Git/bin/bash.exe'], env: { ProgramFiles: '@Program Files' }, used: 'Program Files/Git/bin/bash.exe' },
{ name: 'an MSYS bash on PATH', pathBash: { 'msys64/usr/bin/bash': 'MINGW64_NT-10.0-19045' }, used: 'msys64/usr/bin/bash' },
{ name: 'WSL rejection (System32 and WindowsApps)', pathBash: { 'Windows/System32/bash': 'Linux', 'Users/u/AppData/Local/Microsoft/WindowsApps/bash': 'Linux' }, env: { SystemRoot: '@Windows' },
refused: [" @Windows/System32/bash: WSL's bash, not Git Bash", " @Users/u/AppData/Local/Microsoft/WindowsApps/bash: WSL's bash, not Git Bash"] },
{ name: 'a PATH bash that is not MSYS', pathBash: { 'usr/bin/bash': 'Linux' }, refused: [" @usr/bin/bash: not Git Bash (uname -s printed 'Linux')"] },
{ name: 'missing: every candidate and why, then both recipes', execPath: 'Git/mingw64/libexec/git-core', env: { LOCALAPPDATA: '@AppData/Local', ProgramFiles: '@Program Files' },
refused: ['setup.ps1: Git Bash (bash.exe) was not found. Tried:', ' @Git/bin/bash.exe: not found', ' @bin/bin/bash.exe: not found', ' @AppData/Local/Programs/Git/bin/bash.exe: not found', ' @Program Files/Git/bin/bash.exe: not found'] },
];
type SharedRow = {
name: string;
env?: Record<string, string>;
exists?: string[];
gitExecPath?: string;
which?: { git?: string; bash?: string };
uname?: string;
expect: { bash?: string; source?: string; refused?: boolean };
warning?: string | null;
};
const SHARED: SharedRow[] = JSON.parse(fs.readFileSync(path.resolve(import.meta.dir, 'fixtures', 'windows-bash-resolution.json'), 'utf-8')).rows;
const underRoot = (p: string) => p.replace(/^([A-Za-z]):(?=[\\/])/, '$1');
const fwd = (p: string) => underRoot(p).replace(/\\/g, '/');
const command = (p: string) => fwd(p).replace(/\.exe$/i, '');
for (const s of SHARED) {
const pathBash = s.which?.bash ? command(s.which.bash) : undefined;
const env: Record<string, string> = { ProgramFiles: '@C/Program Files', SystemRoot: '@C/Windows' };
for (const [k, v] of Object.entries(s.env ?? {})) env[k] = `@${underRoot(v)}`;
ROWS.push({
name: `shared table: ${s.name}`,
git: s.which?.git ? command(s.which.git) : undefined,
execPath: s.gitExecPath ? fwd(s.gitExecPath) : undefined,
gitBash: (s.exists ?? []).map(fwd).filter((f) => f.replace(/\.exe$/i, '') !== pathBash),
pathBash: pathBash ? { [pathBash]: s.uname ?? '' } : undefined,
env,
used: s.expect.bash ? (s.expect.source === 'PATH' ? pathBash : fwd(s.expect.bash)) : undefined,
refused: s.expect.refused ? [] : undefined,
warnings: s.warning === undefined ? undefined : s.warning ? 1 : 0,
});
}
const RECIPE = [
" PowerShell (new windows; restart Claude Code after): [Environment]::SetEnvironmentVariable('GSTACK_GIT_BASH', 'C:\\Program Files\\Git\\bin\\bash.exe', 'User')",
' Claude Code: add "GSTACK_GIT_BASH": "C:\\\\Program Files\\\\Git\\\\bin\\\\bash.exe" to the "env" block of ~/.claude/settings.json',
'Nothing was installed or changed. (BASH_UNAVAILABLE; https://github.com/garrytan/gstack/blob/main/docs/troubleshooting.md#bash-unavailable)',
];
const WARNING = 'GSTACK_BASH is a deprecated alias: unset it.';
function put(file: string, body: string) {
fs.mkdirSync(path.dirname(file), { recursive: true });
fs.writeFileSync(file, body, { mode: 0o755 });
}
for (const row of ROWS) {
test(row.name, () => {
const root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'setup-ps1-bash-')));
dirs.push(root);
const at = (v: string) => v.replace(/@/g, `${root}/`);
fs.copyFileSync(SCRIPT, path.join(root, 'setup.ps1'));
put(path.join(root, row.git ?? 'bin/git'), `#!/bin/sh\n[ "$1" = --exec-path ] && ${row.execPath ? `echo '${root}/${row.execPath}'` : ':'}\nexit 0\n`);
for (const tool of ['bun', 'node']) put(path.join(root, 'bin', tool), '#!/bin/sh\nexit 0\n');
for (const f of row.gitBash ?? []) put(path.join(root, f), '#!/bin/sh\necho "BASH_USED=$0"\n');
for (const [f, kernel] of Object.entries(row.pathBash ?? {})) {
put(path.join(root, f), `#!/bin/sh\n[ "$2" = 'uname -s' ] && { echo '${kernel}'; exit 0; }\necho "BASH_USED=$0"\n`);
}
const PATH = [...new Set([path.join(root, 'bin'), path.dirname(path.join(root, row.git ?? 'bin/git')),
...Object.keys(row.pathBash ?? {}).map((f) => path.dirname(path.join(root, f)))])].join(':');
const env: Record<string, string> = { PATH, HOME: root, TMPDIR: root };
for (const [k, v] of Object.entries(row.env ?? {})) env[k] = at(v);
const r = spawnSync(PWSH!, ['-NoProfile', '-NonInteractive', '-File', path.join(root, 'setup.ps1'), '--host', 'codex'],
{ cwd: root, encoding: 'utf-8', env, timeout: 60_000 });
const out = (r.stdout || '') + (r.stderr || '');
const lines = out.split(/\r?\n/);
if (row.used) {
expect(r.status, out).toBe(0);
expect(lines.filter((l) => l.startsWith('BASH_USED=')).map((l) => l.replace(/\\/g, '/'))).toEqual([`BASH_USED=${path.join(root, row.used)}`]);
} else {
expect(r.status, out).toBe(1);
expect(out).not.toContain('BASH_USED=');
for (const l of [...row.refused!.map(at), ...RECIPE]) expect(lines, out).toContain(l);
}
if (row.warnings !== undefined) expect(lines.filter((l) => l.includes(WARNING)), out).toHaveLength(row.warnings);
});
}
});
+30 -3
View File
@@ -166,9 +166,12 @@ describe('ship-measure sweep CLI ($0)', () => {
fs.writeFileSync(path.join(dir, 'trial-outcomes.jsonl'), `${history().map(r => JSON.stringify(r)).join('\n')}\n`);
return dir;
};
const cli = (cwd: string, ...args: string[]) => spawnSync(process.execPath, ['run', path.join(ROOT, 'scripts/ship-measure.ts'), 'sweep', ...args], {
cwd, encoding: 'utf8', timeout: 120_000, env: { ...process.env, GSTACK_STATE_ROOT: tmp('sweep-cli-state-'), GITHUB_STEP_SUMMARY: '' },
});
const cli = (cwd: string, ...args: string[]) => {
const state = tmp('sweep-cli-state-');
return spawnSync(process.execPath, ['run', path.join(ROOT, 'scripts/ship-measure.ts'), 'sweep', ...args], {
cwd, encoding: 'utf8', timeout: 120_000, env: { ...process.env, HOME: state, USERPROFILE: state, GSTACK_STATE_ROOT: state, GITHUB_STEP_SUMMARY: '' },
});
};
test('--dry-run reads local history, prints the plan and the before probability, and spends nothing', () => {
const cwd = tmp('sweep-cli-');
@@ -191,6 +194,30 @@ describe('ship-measure sweep CLI ($0)', () => {
expect(r.stdout).toMatch(new RegExp(`\\| 1 \\| ${A} \\| rule \\| [^|]+ \\| 9/10 \\| MEETS \\|`));
});
test('the CLI never writes eval dirs under the parent HOME (#3162)', () => {
const home = tmp('sweep-cli-parent-home-');
const slug = path.join(home, '.claude', 'skills', 'gstack', 'bin', 'gstack-slug');
fs.mkdirSync(path.dirname(slug), { recursive: true });
fs.writeFileSync(slug, '#!/usr/bin/env bash\necho SLUG=leaked-slug\n', { mode: 0o755 });
const saved = { HOME: process.env.HOME, USERPROFILE: process.env.USERPROFILE };
process.env.HOME = home;
process.env.USERPROFILE = home;
try {
const cwd = tmp('sweep-cli-home-');
const script = path.join(cwd, 'fake-trial.ts');
fs.writeFileSync(script, 'console.log("cost_usd: 0");\nconsole.log(`PASS ${process.argv[2]}`);\n');
const bun = /\s/.test(process.execPath) ? 'bun' : process.execPath;
const r = cli(cwd, '--history-dir', historyDir(), '--k', '1', '--cap-usd', '1', '--command', `${bun} ${script} {case}`, '--jobs', '5', '--out', path.join(cwd, 'out'));
expect(r.status).toBe(0);
} finally {
for (const [key, value] of Object.entries(saved)) {
if (value === undefined) delete process.env[key];
else process.env[key] = value;
}
}
expect(fs.existsSync(path.join(home, '.gstack'))).toBe(false);
});
test('history that cannot be read fails closed with nothing measured', () => {
const cwd = tmp('sweep-cli-nohistory-');
const r = spawnSync(process.execPath, ['run', path.join(ROOT, 'scripts/ship-measure.ts'), 'sweep', '--dry-run', '--repo', 'garrytan/no-such-repo-xyz', '--out', path.join(cwd, 'out')], {
+1 -1
View File
@@ -234,7 +234,7 @@ echo "cost_usd: 0.10"
if [ "$GSTACK_SHIP_MEASURE_TRIAL" = 2 ]; then echo "failure_cause: assertion"; echo "failure_detail: order.js:3 unsorted"; exit 1; fi
`, { mode: 0o755 });
const cli = (...args: string[]) => spawnSync(process.execPath, ['run', path.join(ROOT, 'scripts/ship-measure.ts'), ...args], {
cwd: project, encoding: 'utf8', timeout: 60_000, env: { ...process.env, GSTACK_HOME: state, GSTACK_STATE_ROOT: state },
cwd: project, encoding: 'utf8', timeout: 60_000, env: { ...process.env, HOME: state, USERPROFILE: state, GSTACK_HOME: state, GSTACK_STATE_ROOT: state },
});
const out = path.join(project, '.context', 'ship-measure');
const red = cli('measure', '--case', 'flaky-sort', '--command', './evals.sh case {case}', '--cost-per-trial', '0.1', '--jobs', '3');
@@ -0,0 +1,153 @@
/** Completion durability and privacy at the real skill-end boundary.
* All Git writes stay in disposable local fixtures; no live remote/API. */
import { afterEach, beforeEach, 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';
const BIN = path.resolve(import.meta.dir, '../bin');
const TIMELINE = 'projects/completion-order/timeline.jsonl';
let fixture: string, state: string, remote: string;
let env: Record<string, string>;
function run(bin: string, args: string[] = [], extra: Record<string, string> = {}) {
const r = spawnSync(path.join(BIN, bin), args, {
cwd: fixture, env: { ...env, ...extra }, encoding: 'utf-8', timeout: 30_000,
});
expect(r.error).toBeUndefined();
expect(r.status).toBe(0);
return r;
}
function git(args: string[], dir = state): string {
const r = spawnSync('git', args, { cwd: dir, env, encoding: 'utf-8', timeout: 30_000 });
expect(r.status).toBe(0);
return r.stdout.trim();
}
function write(rel: string, text: string) {
fs.mkdirSync(path.dirname(path.join(state, rel)), { recursive: true });
fs.writeFileSync(path.join(state, rel), text);
}
function remoteText(rel: string): string { return git(['show', `main:${rel}`], remote); }
function remotePaths(): string { return git(['ls-tree', '-r', '--name-only', 'main'], remote); }
function queue(): string {
const dir = path.join(state, '.brain-queue.d');
return fs.existsSync(dir) ? fs.readdirSync(dir).filter(x => x.endsWith('.json')).map(x => fs.readFileSync(path.join(dir, x), 'utf8')).join('') : '';
}
function seedTrackedTimeline() {
run('gstack-timeline-log', [JSON.stringify({ skill: 'qa', event: 'started' })]);
run('gstack-brain-sync', ['--discover-new']);
run('gstack-brain-sync', ['--once']);
expect(remoteText(TIMELINE)).toContain('started');
}
function end(extra: Record<string, string> = {}) {
return run('gstack-skill-end', ['--skill', 'qa', '--outcome', 'success', '--session-id', 'completion-fixture'], extra);
}
beforeEach(() => {
fixture = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-completion-'));
state = path.join(fixture, 'state'); remote = path.join(fixture, 'remote.git');
fs.mkdirSync(state);
// Do not inherit live state-root overrides, git configuration or API keys.
const config = path.join(fixture, 'gitconfig');
fs.writeFileSync(config, '[user]\n name = Fixture\n email = fixture@example.invalid\n');
env = { PATH: process.env.PATH!, HOME: fixture, GSTACK_HOME: state, GSTACK_STATE_ROOT: state,
GSTACK_PROJECT_SLUG: 'completion-order', GIT_CONFIG_GLOBAL: config, GIT_CONFIG_NOSYSTEM: '1',
GIT_TERMINAL_PROMPT: '0', GSTACK_SESSION_KIND: 'interactive' };
git(['init', '--bare', '-q', '-b', 'main', remote], fixture);
run('gstack-artifacts-init', ['--remote', remote]);
run('gstack-config', ['set', 'artifacts_sync_mode', 'full']);
run('gstack-config', ['set', 'telemetry', 'off']);
run('gstack-config', ['set', 'transcript_ingest_mode', 'off']);
});
afterEach(() => { fs.rmSync(fixture, { recursive: true, force: true }); });
describe('skill-end completion durability', () => {
test('full: the same final drain pushes a completion into an already tracked timeline', () => {
seedTrackedTimeline();
end();
expect(remoteText(TIMELINE)).toContain('completed');
expect(git(['status', '--porcelain'])).toBe('');
expect(queue()).toBe('');
}, 30_000);
test('full: a new completion timeline reaches the remote at its first end boundary', () => {
end();
expect(remotePaths()).toContain(TIMELINE);
expect(remoteText(TIMELINE)).toContain('completed');
expect(queue()).toBe('');
}, 30_000);
test('artifacts-only: a formerly tracked behavioral timeline stays local and privacy-held', () => {
seedTrackedTimeline();
const before = remoteText(TIMELINE);
run('gstack-config', ['set', 'artifacts_sync_mode', 'artifacts-only']);
end();
expect(remoteText(TIMELINE)).toBe(before);
expect(fs.readFileSync(path.join(state, TIMELINE), 'utf8')).toContain('completed');
expect(queue()).toContain(TIMELINE);
expect(JSON.parse(fs.readFileSync(path.join(state, '.brain-sync-status.json'), 'utf8')).message).toContain('privacy-held');
// Privacy does not promise a clean old full-tier checkout after downgrade.
expect(git(['diff', '--name-only'])).toBe(TIMELINE);
}, 30_000);
test('full: secret and unconsented transcript holds survive while completion metadata pushes', () => {
const held = 'projects/completion-order/learnings.jsonl';
const transcript = 'transcripts/run-fixture-1/session.md';
const synthetic = ['ghp', 'abcdefghij1234567890abcdef1234567890'].join('_');
write(held, JSON.stringify({ insight: synthetic }) + '\n');
write(transcript, '# Synthetic private fixture\n');
run('gstack-brain-enqueue', [held]); run('gstack-brain-enqueue', [transcript]);
end();
expect(remoteText(TIMELINE)).toContain('completed');
expect(remotePaths()).not.toContain(held); expect(remotePaths()).not.toContain(transcript);
expect(queue()).toContain(held); expect(queue()).toContain(transcript);
expect(fs.readFileSync(path.join(state, transcript), 'utf8')).toContain('Synthetic');
expect(JSON.parse(fs.readFileSync(path.join(state, '.brain-sync-status.json'), 'utf8')).status).toBe('held');
}, 30_000);
test('unattended: completion remains local; no drain, push or new queue entry', () => {
const rel = 'projects/completion-order/ceo-plans/fixture.md';
write(rel, '# Fixture\n'); run('gstack-brain-enqueue', [rel]);
const beforeQueue = queue(), head = git(['rev-parse', 'main'], remote);
expect(end({ GSTACK_SESSION_KIND: 'unattended' }).stdout).toContain('ARTIFACTS_SYNC: skipped');
expect(git(['rev-parse', 'main'], remote)).toBe(head); expect(queue()).toBe(beforeQueue);
expect(fs.readFileSync(path.join(state, TIMELINE), 'utf8')).toContain('completed');
expect(fs.existsSync(path.join(state, 'analytics/skill-usage.jsonl'))).toBe(false);
}, 30_000);
test('concurrent drain owner: completion remains queued and a later drain publishes it', async () => {
const holder = Bun.spawn(['bash', '-c', '. "$1"; gstack_brain_lock_acquire "$2" try || exit 9; echo locked; read -r release; gstack_brain_lock_release', '_', path.join(BIN, 'gstack-brain-lock.sh'), state],
{ env, cwd: fixture, stdin: 'pipe', stdout: 'pipe', stderr: 'pipe' });
try {
const reader = holder.stdout.getReader();
expect(new TextDecoder().decode((await reader.read()).value)).toContain('locked');
end();
expect(queue()).toContain(TIMELINE); expect(remotePaths()).not.toContain(TIMELINE);
} finally { holder.stdin.write('release\n'); holder.stdin.end(); expect(await holder.exited).toBe(0); }
run('gstack-brain-sync', ['--once']);
expect(remoteText(TIMELINE)).toContain('completed'); expect(queue()).toBe('');
}, 30_000);
test('sync off: completion is written locally with no queue entry and no push', () => {
seedTrackedTimeline();
const head = git(['rev-parse', 'main'], remote);
run('gstack-config', ['set', 'artifacts_sync_mode', 'off']);
end();
expect(fs.readFileSync(path.join(state, TIMELINE), 'utf8')).toContain('completed');
expect(git(['rev-parse', 'main'], remote)).toBe(head);
expect(queue()).toBe('');
}, 30_000);
test('logger returns only after a delayed enqueue makes its spool record durable', () => {
const shadow = path.join(fixture, 'bin'); fs.mkdirSync(shadow);
for (const f of fs.readdirSync(BIN)) { fs.symlinkSync(path.join(BIN, f), path.join(shadow, f)); }
for (const f of ['gstack-timeline-log', 'gstack-brain-enqueue']) { fs.unlinkSync(path.join(shadow, f)); }
fs.copyFileSync(path.join(BIN, 'gstack-timeline-log'), path.join(shadow, 'gstack-timeline-log'));
const marker = path.join(fixture, 'enqueue-done');
fs.writeFileSync(path.join(shadow, 'gstack-brain-enqueue'), '#!/bin/sh\nsleep 0.4\n' + 'printf done > "$ENQUEUE_MARKER"\n', { mode: 0o755 });
const r = spawnSync(path.join(shadow, 'gstack-timeline-log'), [JSON.stringify({ skill: 'qa', event: 'completed' })],
{ cwd: fixture, env: { ...env, ENQUEUE_MARKER: marker }, stdio: 'ignore', timeout: 30_000 });
expect(r.status).toBe(0); expect(fs.existsSync(marker)).toBe(true);
}, 30_000);
});
+19 -2
View File
@@ -20,7 +20,7 @@ const POLICY = path.join(ROOT, 'bin', 'gstack-gbrain-repo-policy');
let tmp: string, home: string, legacy: string, resolved: string, env: Record<string, string>;
beforeEach(() => {
tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-merge-'));
tmp = fs.mkdtempSync(path.join(os.tmpdir(), "gstack merge's-"));
home = path.join(tmp, 'home');
legacy = path.join(home, '.gstack');
resolved = path.join(tmp, 'custom');
@@ -70,12 +70,27 @@ describe('merged config keys', () => {
expect(r.stderr).toContain(`gstack-config: set codex_reviews in ${resolved}/config.yaml, but codex_reviews is still 'disabled': ${legacy}/config.yaml sets that more restrictive value`);
expect(r.stderr).toContain('docs/state-root.md');
const fix = r.stderr.split('\n').find((l) => l.startsWith('fix: '))!;
expect(fix).toContain(`GSTACK_STATE_ROOT='${legacy}'`);
const quoted = (v: string) => spawnSync('bash', ['-c', 'printf %q "$1"', '_', v], { encoding: 'utf-8', timeout: 20_000 }).stdout;
expect(fix).toContain(`GSTACK_STATE_ROOT=${quoted(legacy)} `);
const command = fix.slice('fix: '.length).replace(/ \(https:.*\)$/, '');
expect(spawnSync('bash', ['-c', command], { env, encoding: 'utf-8', timeout: 20_000 }).status).toBe(0);
expect(config(['get', 'codex_reviews']).stdout).toBe('enabled');
});
test('the printed recovery command runs from an install path containing a space and an apostrophe', () => {
const install = path.join(tmp, "inst all's", 'bin');
fs.cpSync(path.join(ROOT, 'bin'), install, { recursive: true });
fs.writeFileSync(path.join(legacy, 'config.yaml'), 'codex_reviews: disabled\n');
const r = spawnSync('bash', [path.join(install, 'gstack-config'), 'set', 'codex_reviews', 'enabled'], { env, encoding: 'utf-8', timeout: 20_000 });
expect(r.status).toBe(0);
const fix = r.stderr.split('\n').find((l) => l.startsWith('fix: '))!;
const command = fix.slice('fix: '.length).replace(/ \(https:.*\)$/, '');
const ran = spawnSync('bash', ['-c', command], { env, encoding: 'utf-8', timeout: 20_000 });
expect(ran.stderr).toBe('');
expect(ran.status).toBe(0);
expect(config(['get', 'codex_reviews']).stdout).toBe('enabled');
});
test('a set with no overriding root stays silent', () => {
fs.writeFileSync(path.join(legacy, 'config.yaml'), 'telemetry: anonymous\n');
const r = config(['set', 'telemetry', 'off']);
@@ -90,6 +105,8 @@ describe('merged config keys', () => {
expect(plain).toContain(`telemetry: off (set, ${legacy})`);
expect(plain).toContain('proactive: false (set)');
expect(plain).not.toContain('root-selecting variables disagree');
// Two variables naming the same directory agree, even when the path contains spaces.
expect(config(['list'], { GSTACK_STATE_ROOT: resolved }).stdout).not.toContain('root-selecting variables disagree');
const other = path.join(tmp, 'other');
const disagree = config(['list'], { GSTACK_STATE_DIR: other }).stdout;
expect(disagree).toContain(`# note: root-selecting variables disagree: GSTACK_HOME=${resolved} GSTACK_STATE_DIR=${other}; using ${resolved} (GSTACK_HOME wins).`);
+1 -1
View File
@@ -455,7 +455,7 @@ describe('setup --team / --no-team / -q', () => {
try {
for (const rel of [
'setup', 'VERSION', 'SKILL.md', 'qa/SKILL.md', 'bin/gstack-config', 'bin/gstack-patch-names',
'bin/gstack-state-root.sh', 'bin/gstack-bun-version.sh', 'bin/gstack-path-spelling.sh', 'bin/gstack-install-registry.sh', 'bin/gstack-render-claude.sh', 'bin/gstack-host-renders.sh',
'bin/gstack-state-root.sh', 'bin/gstack-bun-version.sh', 'bin/gstack-path-spelling.sh', 'bin/gstack-claude-root.sh', 'bin/gstack-install-registry.sh', 'bin/gstack-render-claude.sh', 'bin/gstack-host-renders.sh',
'scripts/resolve-codex-generation-model.ts', 'scripts/models.ts', 'scripts/preflight-codex-overlap.ts',
'scripts/discover-skills.ts', 'scripts/external-skill-names.ts', 'scripts/host-config.ts',
'lib/claude-code-migration.ts', 'lib/model-policy.ts', 'lib/model-catalog.ts',
+1 -2
View File
@@ -270,7 +270,6 @@ describe('docs and registration', () => {
const lists: [string, string][] = [
['AGENTS.md', '| `/test-audit` |'],
['README.md', '| `/test-audit` | **Test Auditor** |'],
['README.md', '/deslop-shared-libs, /test-audit, /ship'],
['docs/skills.md', '| [`/test-audit`](#test-audit) |'],
['docs/skills.md', '## `/test-audit`'],
['gstack/llms.txt', '[/test-audit](test-audit/SKILL.md)'],
@@ -280,7 +279,7 @@ describe('docs and registration', () => {
['test/helpers/touchfiles-data.ts', "'test-audit-report-only': ['test-audit/**'"],
];
expect(lists.filter(([file, text]) => !read(file).includes(text)).map(([file, text]) => `${file}: ${text}`)).toEqual([]);
expect(read('README.md').split('/deslop-shared-libs, /test-audit, /ship').length - 1).toBe(2);
expect(read('README.md').split('/deslop-shared-libs, /test-audit, /ship').length - 1).toBe(0);
});
});
+2
View File
@@ -27,6 +27,8 @@ const HOOK_FILES = [
'lib/state-root.ts',
'lib/bin-context.ts',
'lib/remote-identity.ts',
'lib/script-invocation.ts',
'lib/result-codes.ts',
];
const SLUG = 'stop-hook-slug-test';
const BUDGET_MS = 2000;
+2
View File
@@ -55,6 +55,7 @@ describe.skipIf(process.platform === 'win32')('upgrade setup recovery (real shel
// C9: the git fence verifies it is inside gstack's own checkout first.
writeFileSync(join(root, 'VERSION'), '1.0.0.0\n');
writeFileSync(join(root, 'bin', 'gstack-config'), '#!/bin/sh\n', { mode: 0o755 });
writeFileSync(join(root, 'bin', 'gstack-ff-update'), '#!/bin/sh\necho "ok old-commit new-commit"\n', { mode: 0o755 });
const result = spawnSync('bash', ['-c', blockAfter('**For git installs**')], {
cwd: root, encoding: 'utf8', timeout: 10_000,
env: { ...process.env, PATH: `${bin}:${process.env.PATH}`, INSTALL_DIR: root },
@@ -85,6 +86,7 @@ describe.skipIf(process.platform === 'win32')('upgrade Bun floor (real git)', ()
spawnSync('git', ['init', '-q', '--bare', '-b', 'main', origin], { timeout: 30_000 });
const helper = readFileSync(join(import.meta.dir, '../bin/gstack-bun-version.sh'), 'utf8');
writeFileSync(join(seed, 'bin', 'gstack-bun-version.sh'), helper);
writeFileSync(join(seed, 'bin', 'gstack-ff-update'), readFileSync(join(import.meta.dir, '../bin/gstack-ff-update'), 'utf8'), { mode: 0o755 });
writeFileSync(join(seed, 'bin', 'gstack-config'), '#!/bin/sh\n', { mode: 0o755 });
writeFileSync(join(seed, 'VERSION'), '1.0.0\n');
writeFileSync(join(seed, 'setup'), '#!/bin/sh\necho ran >> "$SETUP_LOG"\n', { mode: 0o755 });
+2 -2
View File
@@ -13,8 +13,8 @@ const read = (p: string) => fs.readFileSync(path.join(ROOT, p), 'utf-8');
describe('gstack-upgrade template: ff-only precedes the gated reset (#2517)', () => {
const tmpl = read('gstack-upgrade/SKILL.md.tmpl');
test('git pull --ff-only runs before any reset --hard', () => {
const ff = tmpl.indexOf('git pull --ff-only --autostash');
test('the fast-forward (gstack-ff-update) runs before any reset --hard', () => {
const ff = tmpl.indexOf('bash bin/gstack-ff-update . origin/main');
const reset = tmpl.indexOf('git reset --hard origin/main');
expect(ff).toBeGreaterThan(-1);
expect(reset).toBeGreaterThan(-1);
+11
View File
@@ -102,4 +102,15 @@ describe('workflow action pins', () => {
const config = Bun.YAML.parse(fs.readFileSync(path.join(GITHUB_DIR, 'dependabot.yml'), 'utf-8')) as any;
expect((config.updates ?? []).map((update: any) => update['package-ecosystem'])).toContain('github-actions');
});
test('Dependabot holds Playwright minor and major bumps behind the windowsHide patch; patch updates still flow', () => {
const config = Bun.YAML.parse(fs.readFileSync(path.join(__dirname, '..', '.github', 'dependabot.yml'), 'utf-8')) as any;
const bun = (config.updates ?? []).find((update: any) => update['package-ecosystem'] === 'bun');
const ignored = Object.fromEntries((bun?.ignore ?? []).map((rule: any) => [rule['dependency-name'], rule]));
const pkg = JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf-8'));
expect(Object.keys(pkg.patchedDependencies ?? {}).some(key => key.startsWith('playwright-core@'))).toBe(true);
for (const name of ['playwright', 'playwright-core']) {
expect(ignored[name]).toEqual({ 'dependency-name': name, 'update-types': ['version-update:semver-minor', 'version-update:semver-major'] });
}
});
});
+106
View File
@@ -0,0 +1,106 @@
/**
* #3197: every consumer of the working-tree fingerprint goes through
* lib/script-invocation.ts's wtreeFingerprint and keeps its own fail
* direction when the fingerprint is unavailable, now saying why:
* gstack-regen check refuses the scratch run (incomplete)
* gstack-regen write completes; the run id falls back to the registry label
* gstack-gate-diff records the candidate as `+nowtree`
* gstack-restamp refuses (RESTAMP_CONFLICT), nothing written
* gstack-evidence records without a fingerprint (grades STALE)
* The failure is induced with an unwritable TMPDIR, which gstack-wtree
* reports with its own repair hint.
*/
import { afterEach, 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 { cleanup as cleanupPregate, commit, makeFixtureRepo as makePregateRepo, runBin as runPregateBin, type FixtureRepo } from './helpers/pregate-fixture';
import { cleanup as cleanupRestamp, makeFixtureRepo as makeRestampRepo, makePr, restamp } from './helpers/restamp-fixture';
import { runBin } from './helpers/run-bin';
import { gitIn, findFilesBySuffix } from './helpers/scratch-repo';
const ROOT = path.resolve(import.meta.dir, '..');
const cleanups: Array<() => void> = [];
afterEach(() => { while (cleanups.length) cleanups.pop()!(); });
const badTmp = (root: string) => ({ TMPDIR: path.join(root, 'no-such-tmp') });
const WTREE_FAILED = /gstack-wtree exited 1: gstack-wtree: cannot create a temp index under .*no-such-tmp; set TMPDIR to a writable directory/;
function pregateRepo(): FixtureRepo {
const repo = makePregateRepo();
cleanups.push(() => cleanupPregate(repo));
return repo;
}
describe('gstack-regen', () => {
test('check: an unavailable fingerprint is an incomplete run that names the cause', () => {
const repo = pregateRepo();
commit(repo, { 'src/version.js': "module.exports = { VERSION: '1.1.0' };\n" });
const r = runPregateBin(repo, 'gstack-regen', ['check', '--allow-repo-commands'], badTmp(repo.root));
expect(r.status).not.toBe(0);
expect(r.err).toMatch(WTREE_FAILED);
expect(r.err).toContain('cannot fingerprint the working tree (gstack-wtree exited 1:');
expect(r.out).toContain('status=incomplete');
});
test('write: the no-scratch path completes and reports the registry label as its run id', () => {
const repo = pregateRepo();
const r = runPregateBin(repo, 'gstack-regen', ['write', '--allow-repo-commands'], badTmp(repo.root));
expect(r.status).toBe(0);
expect(r.out).toMatch(/GSTACK_RESULT: skill=regen status=complete run=origin\/main@/);
});
});
describe('gstack-gate-diff', () => {
test('records the candidate without a fingerprint and prints why', () => {
const repo = pregateRepo();
commit(repo, { 'lib/util.js': 'exports.add = (a, b) => a + b + 0;\n' });
const r = runPregateBin(repo, 'gstack-gate-diff', ['main'], badTmp(repo.root));
expect(r.status).toBe(0);
expect(r.err).toMatch(/gstack-gate-diff: working-tree fingerprint unavailable \(gstack-wtree exited 1: .*set TMPDIR.*\); candidate recorded without it/);
expect(r.out + r.err).toContain('+nowtree');
});
});
describe('gstack-restamp', () => {
test('refuses with the fingerprint failure in its detail and writes nothing', () => {
const repo = makeRestampRepo();
cleanups.push(() => cleanupRestamp(repo));
makePr(repo, 'pr-a');
const r = restamp(repo, ['--next', '--dry-run'], badTmp(repo.root));
expect(r.status).not.toBe(0);
expect(r.out + r.err).toMatch(/cannot fingerprint the working tree \(gstack-wtree exited 1: .*set TMPDIR to a writable directory\); nothing written/);
expect(r.out + r.err).toContain('RESTAMP_CONFLICT');
expect(repo.git('status', '--porcelain')).toBe('');
});
});
describe('gstack-evidence', () => {
function evidenceRepo(extra: string[] = []) {
const home = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-evidence-wtree-home-'));
const repo = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-evidence-wtree-repo-'));
cleanups.push(() => { fs.rmSync(home, { recursive: true, force: true }); fs.rmSync(repo, { recursive: true, force: true }); });
gitIn(repo, `init -q -b main ${extra.join(' ')}`);
fs.writeFileSync(path.join(repo, 'src.txt'), 'v1\n');
gitIn(repo, 'add src.txt');
gitIn(repo, 'commit -q -m init');
const run = (env: Record<string, string> = {}) => runBin(path.join(ROOT, 'bin', 'gstack-evidence'), ['run', '--label', 'tests', '--', 'echo ok'], { cwd: repo, env: { GSTACK_HOME: home, ...env } });
const record = () => JSON.parse(fs.readFileSync(findFilesBySuffix(path.join(home, 'projects'), '-evidence.jsonl')[0]!, 'utf8').trim().split('\n').pop()!);
return { home, repo, run, record };
}
test('a SHA-256 repository gets a 64-hex content fingerprint', () => {
const e = evidenceRepo(['--object-format=sha256']);
expect(e.run().status).toBe(0);
expect(e.record().wtree).toMatch(/^[0-9a-f]{64}$/);
});
test('an unavailable fingerprint records without it and says why once', () => {
const e = evidenceRepo();
const r = e.run(badTmp(e.home));
expect(r.status).toBe(0);
expect(e.record().wtree).toBeUndefined();
const warnings = r.stderr.split('\n').filter(l => l.includes('working-tree fingerprint unavailable'));
expect(warnings.length).toBe(1);
expect(warnings[0]).toMatch(WTREE_FAILED);
});
});