From 6b327148e37134e2628d2d20cd98f33dcbeef51c Mon Sep 17 00:00:00 2001 From: Garry Tan Date: Tue, 10 Nov 2026 01:34:35 -0800 Subject: [PATCH 01/31] Stop gstack-uninstall deleting unpushed or kept work under any folder it removes (GST-2303) (#4282) * Stop gstack-uninstall deleting unpushed or kept work under any folder it removes (GST-2303) Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * Keep repos behind a symlinked .gstack-worktrees, remove stable-channel installs, and read worktrees on git before 2.36 in gstack-uninstall (GST-2303) Review-Finding: p1/red-team#1 reader=red-team Review-Finding: p1/red-team#2 reader=red-team Review-Finding: p1/red-team#3 reader=red-team Review-Finding: p1/specialist-batched#1 reader=testing Review-Finding: p1/specialist-batched#2 reader=testing Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * Count a FETCH_HEAD commit as pushed only when it came from one of the checkout's remotes in gstack-uninstall (GST-2303) Review-Finding: p2/specialist-batched#1 reader=security Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * Read remote URLs with git remote get-url so url.insteadOf rewrites match FETCH_HEAD in gstack-uninstall (GST-2303) Review-Finding: fc/fix-check#1 reader=fix-check Review-Finding: fc/fix-check#2 reader=fix-check Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * Refuse to uninstall on git older than 2.36 instead of reading worktrees without -z (GST-2303) Review-Finding: v11/outside-voice#1 reader=outside-voice Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * List the git 2.36 uninstall refusal in troubleshooting (GST-2303) Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --------- Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- bin/gstack-uninstall | 343 +++++++++++------ ...checks-every-folder-it-deletes-gst-2303.md | 6 + docs/troubleshooting.md | 14 + docs/uninstall.md | 63 +++- test/uninstall.test.ts | 344 ++++++++++++++++++ 5 files changed, 651 insertions(+), 119 deletions(-) create mode 100644 changelog.d/uninstall-checks-every-folder-it-deletes-gst-2303.md diff --git a/bin/gstack-uninstall b/bin/gstack-uninstall index 7b35678d4bb..f88e66e00bc 100755 --- a/bin/gstack-uninstall +++ b/bin/gstack-uninstall @@ -156,17 +156,39 @@ _project_worktrees() { printf '%s\0' "${_dotgit%/.git}" done } -# Real paths of the worktrees this repository registered (all, or with -# "locked" only the locked ones). -_registered_worktrees() { - git -C "$_GIT_ROOT" worktree list --porcelain 2>/dev/null | awk -v only="${1:-}" ' - /^worktree / { if (path != "" && (only == "" || locked)) print path; path = substr($0, 10); locked = 0 } - /^locked( |$)/ { locked = 1 } - END { if (path != "" && (only == "" || locked)) print path }' | while IFS= read -r _wt; do - _real "$_wt" - done +# Fills _REGISTERED_WORKTREES with the real paths of the worktrees this +# repository registered and _LOCKED_WORKTREES with the locked ones. The list is +# read NUL-separated, so a path holding a newline stays one unquoted path. +_read_registered_worktrees() { + local _field _path="" _locked=0 + _REGISTERED_WORKTREES=() + _LOCKED_WORKTREES=() + while IFS= read -r -d '' _field; do + case "$_field" in + "worktree "*) _path="$(_real "${_field#worktree }")"; _locked=0 ;; + locked|"locked "*) _locked=1 ;; + "") + [ -n "$_path" ] || continue + _REGISTERED_WORKTREES+=("$_path") + [ "$_locked" -eq 0 ] || _LOCKED_WORKTREES+=("$_path") + _path="" + ;; + esac + done < <(_worktree_list git -C "$_GIT_ROOT") } -# git inside a registered checkout, with no config able to run a command. +# "$@" worktree list --porcelain, NUL-separated. git before 2.36 has no -z and +# fails here, so the uninstall refuses instead of reading a list it cannot split. +_worktree_list() { + "$@" worktree list --porcelain -z 2>/dev/null +} +# _in_list VALUE ITEM... — VALUE equals one of the ITEMs. +_in_list() { + local _want="$1" _item + shift + for _item in "$@"; do [ "$_item" = "$_want" ] && return 0; done + return 1 +} +# git inside a checkout, with its hooks and fsmonitor turned off. _wt_git() { local _dir="$1" shift @@ -183,7 +205,7 @@ _worktree_risk() { ""|*" "*) echo "it is not a registered worktree of this repository"; return 0 ;; esac - if ! printf '%s\n' "$_REGISTERED_WORKTREES" | grep -Fxq -- "$_dir"; then + if ! _in_list "$_dir" ${_REGISTERED_WORKTREES[@]+"${_REGISTERED_WORKTREES[@]}"}; then _is_registered_submodule "$_dir" || { echo "it is not a registered worktree of this repository"; return 0; } _local="$(_wt_git "$_dir" rev-list -n 1 --all --not --remotes 2>/dev/null)" || { echo "git cannot read its history"; return 0; } [ -z "$_local" ] || echo "it is a submodule with commits no remote-tracking branch contains" @@ -195,20 +217,18 @@ _worktree_risk() { _head="$(_wt_git "$1" rev-parse -q --verify HEAD 2>/dev/null)" || return 0 [ -n "$(git -C "$_GIT_ROOT" for-each-ref --contains "$_head" --count=1 --format=x 2>/dev/null)" ] || echo "it has commits no branch or tag contains" } -# Succeeds when checkout $1 is a submodule of the registered worktree under -# .gstack-worktrees that holds it: that worktree's index records exactly this -# path as a gitlink, so its status reports the submodule's changes. Commits only -# the submodule's own refs hold are checked by the caller. +# Succeeds when checkout $1 is a submodule of the closest checkout under +# .gstack-worktrees that holds it, and that checkout is a registered worktree or +# (for a nested submodule) itself such a submodule: its index records exactly +# this path as a gitlink, so its status reports the submodule's changes. Commits +# only the submodule's own refs hold are checked by the caller. _is_registered_submodule() { - local _wt _parent="" _base _rel _entry - _base="$(_real "$_GIT_ROOT/.gstack-worktrees")" - while IFS= read -r _wt; do - case "$_wt" in "$_base"/*) ;; *) continue ;; esac + local _wt _parent="" _rel _entry + for _wt in ${_CHECKOUTS_ON_DISK[@]+"${_CHECKOUTS_ON_DISK[@]}"}; do case "$1" in "$_wt"/*) [ ${#_wt} -gt ${#_parent} ] && _parent="$_wt" ;; esac - done </dev/null | tr '\0' '\n')" case "$_entry" in 160000\ *) ;; *) return 1 ;; esac @@ -219,15 +239,18 @@ EOF # is kept even with --force-worktrees. _worktree_refusals() { local _wt _risk - if ! git -C "$_GIT_ROOT" worktree list --porcelain >/dev/null 2>&1; then + if ! _worktree_list git -C "$_GIT_ROOT" >/dev/null; then echo "gstack-uninstall: refusing to delete $_GIT_ROOT/.gstack-worktrees/: git cannot list this repository's worktrees" return 0 fi - _REGISTERED_WORKTREES="$(_registered_worktrees)" - _LOCKED_WORKTREES="$(_registered_worktrees locked)" + _read_registered_worktrees + _CHECKOUTS_ON_DISK=() + while IFS= read -r -d '' _wt; do + _CHECKOUTS_ON_DISK+=("$(_real "$_wt")") + done < <(_project_worktrees) while IFS= read -r -d '' _wt; do [ -n "$_wt" ] || continue - if [ -n "$_LOCKED_WORKTREES" ] && printf '%s\n' "$_LOCKED_WORKTREES" | grep -Fxq -- "$(_real "$_wt")"; then + if _in_list "$(_real "$_wt")" ${_LOCKED_WORKTREES[@]+"${_LOCKED_WORKTREES[@]}"}; then _risk="it is locked (git worktree lock)" elif [ "$FORCE_WORKTREES" -eq 1 ]; then continue @@ -272,7 +295,190 @@ _check_project_keep() { exit 2 fi } +# ─── Deletion inventory ────────────────────────────────────── +CLAUDE_SKILLS="$HOME/.claude/skills" + +# Skill-name inventory (#2563 gate a): every name setup could have installed — +# each source skill's directory name, its frontmatter name, their gstack- +# prefixed variants, and the alias dirs. Built BEFORE the install root is +# removed. A real directory in ~/.claude/skills is only deletable when its +# name is in this inventory AND its SKILL.md carries the generated banner. +# The seed names below are the alias dirs setup's _install_alias_skill_md +# creates (setup: link_claude_root_skill_alias + the connect-chrome call +# sites) — keep in sync with setup if an alias is added or renamed there. +_INVENTORY=" _gstack-command connect-chrome gstack-connect-chrome " +if [ -d "$GSTACK_DIR" ]; then + for _SRC in "$GSTACK_DIR"/*/; do + [ -f "$_SRC/SKILL.md" ] || continue + _SRC_NAME=${_SRC%/}; _SRC_NAME=${_SRC_NAME##*/} + gstack_skill_md_name "$_SRC/SKILL.md"; _FM_NAME=$GSTACK_SKILL_NAME + for _N in "$_SRC_NAME" "$_FM_NAME"; do + [ -n "$_N" ] || continue + case "$_INVENTORY" in *" $_N "*) ;; *) _INVENTORY="$_INVENTORY$_N gstack-$_N " ;; esac + done + done +fi +_in_skill_inventory() { case "$_INVENTORY" in *" $1 "*) return 0 ;; *) return 1 ;; esac; } + +# Prints what the removal step does with ~/.claude/skills entry $1: unlink, +# delete, keep (listed, not provably gstack-managed), or nothing. Per-skill +# entries created by setup come in three shapes: +# 1. symlink entry (oldest installs) +# 2. real dir + SYMLINKED SKILL.md (standard Unix install) +# 3. real dir + REAL-FILE SKILL.md (Windows copy install, #2563) +# Shape 3 was skipped entirely — gstack-uninstall exited 0 and reported +# success while leaving ~52 gstack-* directories behind on Windows. +_claude_entry_action() { + local _name="${1##*/}" _target + [ "$_name" = "gstack" ] && return 0 + if [ -L "$1" ]; then + _target="$(readlink "$1" 2>/dev/null || true)" + case "$_target" in gstack/*|*/gstack/*) echo unlink ;; esac + elif [ -d "$1" ] && { [ -f "$1/SKILL.md" ] || [ -L "$1/SKILL.md" ]; }; then + if [ -L "$1/SKILL.md" ]; then + # Shape 2: provenance readable from the symlink target itself. + # Gate 1: the name must be in gstack's skill inventory (parity with + # shape 3). Gate 2: the target must contain "gstack" as an ANCHORED + # path segment (gstack/*|*/gstack/*, same pattern as shape 1) — a + # bare *gstack* substring match would wipe a user's own skill whose + # SKILL.md merely lives under e.g. ~/tools/gstack-fork/. + _target="$(readlink "$1/SKILL.md" 2>/dev/null || true)" + if _in_skill_inventory "$_name"; then + case "$_target" in gstack/*|*/gstack/*) echo delete ;; *) echo keep ;; esac + else + echo keep + fi + elif _in_skill_inventory "$_name" && grep -q '\n'); + fs.writeFileSync(path.join(skill, 'SKILL.md'), '\nmy edit\n'); + const r = uninstall(['--force']); + expect(r.status).toBe(2); + expect(r.stderr).toContain(`refusing to delete ${skill}: ${skill} has uncommitted changes`); + expect(fs.readFileSync(path.join(skill, 'SKILL.md'), 'utf-8')).toContain('my edit'); + }); + + test('a repository with unpushed commits under ~/.gstack stops the uninstall', () => { + const notes = pushedRepo(path.join(home, '.gstack', 'projects', 'notes'), 'README.md'); + unpushedCommit(notes); + const r = uninstall(['--force']); + expect(r.status).toBe(2); + expect(r.stderr).toContain(`refusing to delete ${path.join(home, '.gstack')}: ${notes} has commits no remote-tracking branch contains`); + expect(fs.existsSync(path.join(notes, 'notes.md'))).toBe(true); + expect(fs.existsSync(install)).toBe(true); + }); + + test('a locked worktree of the install clone stops the uninstall, even outside the install', () => { + const lane = path.join(tmp, 'lane'); + git(['worktree', 'add', '-q', '--detach', lane, 'HEAD'], install); + git(['worktree', 'lock', lane], install); + const r = uninstall(['--force']); + expect(r.status).toBe(2); + expect(r.stderr).toContain(`refusing to delete ${install}: ${install} registers the locked worktree ${lane}`); + expect(fs.existsSync(path.join(install, '.git'))).toBe(true); + }); + + test('a dirty repo behind a .gstack-worktrees symlink into ~/.gstack stops the uninstall', () => { + const lane = pushedRepo(path.join(home, '.gstack', 'lanes', 'lane1')); + fs.writeFileSync(path.join(lane, 'SKILL.md'), 'my edit\n'); + fs.symlinkSync(path.join(home, '.gstack', 'lanes'), path.join(proj, '.gstack-worktrees')); + const r = uninstall(['--force']); + expect(r.status).toBe(2); + expect(r.stderr).toContain(`refusing to delete ${path.join(home, '.gstack')}: ${lane} has uncommitted changes`); + expect(fs.readFileSync(path.join(lane, 'SKILL.md'), 'utf-8')).toBe('my edit\n'); + }); + + test('a shallow stable-channel install advanced by git fetch origin stable is removed', () => { + fs.rmSync(install, { recursive: true, force: true }); + const origin = path.join(tmp, 'channel-origin.git'); + const seed = pushedRepo(path.join(tmp, 'channel-seed')); + git(['remote', 'set-url', 'origin', origin], seed); + git(['init', '-q', '--bare', '-b', 'main', origin], tmp); + git(['push', '-q', 'origin', 'main'], seed); + git(['clone', '-q', '--single-branch', '--depth', '1', `file://${origin}`, install], tmp); + fs.writeFileSync(path.join(seed, 'SKILL.md'), 'release\n'); + git(['commit', '-q', '-am', 'release'], seed); + git(['push', '-q', 'origin', 'main', 'main:stable'], seed); + git(['fetch', '-q', 'origin', 'stable'], install); + git(['merge', '-q', '--ff-only', 'FETCH_HEAD'], install); + const r = uninstall(['--force']); + expect(r.stderr).toBe(''); + expect(r.status).toBe(0); + expect(fs.existsSync(install)).toBe(false); + }); + + test('a stable-channel install whose remote URL goes through url.insteadOf is removed', () => { + fs.rmSync(install, { recursive: true, force: true }); + const origin = path.join(tmp, 'channel-origin.git'); + const seed = pushedRepo(path.join(tmp, 'channel-seed')); + git(['remote', 'set-url', 'origin', origin], seed); + git(['init', '-q', '--bare', '-b', 'main', origin], tmp); + git(['push', '-q', 'origin', 'main'], seed); + fs.writeFileSync(path.join(tmp, 'gitconfig'), `[url "file://${tmp}/"]\n\tinsteadOf = alias:\n`); + git(['clone', '-q', '--single-branch', '--depth', '1', 'alias:channel-origin.git', install], tmp); + fs.writeFileSync(path.join(seed, 'SKILL.md'), 'release\n'); + git(['commit', '-q', '-am', 'release'], seed); + git(['push', '-q', 'origin', 'main', 'main:stable'], seed); + git(['fetch', '-q', 'origin', 'stable'], install); + git(['merge', '-q', '--ff-only', 'FETCH_HEAD'], install); + const r = uninstall(['--force']); + expect(r.stderr).toBe(''); + expect(r.status).toBe(0); + expect(fs.existsSync(install)).toBe(false); + }); + + test('a local-only commit that git fetch . HEAD wrote into FETCH_HEAD still stops the uninstall', () => { + unpushedCommit(install); + git(['fetch', '-q', '.', 'HEAD'], install); + const r = uninstall(['--force']); + expect(r.status).toBe(2); + expect(r.stderr).toContain(`refusing to delete ${install}: ${install} has commits no remote-tracking branch contains`); + expect(fs.existsSync(path.join(install, 'notes.md'))).toBe(true); + }); + + test('on a git older than 2.36 (no worktree list -z) the uninstall refuses and keeps the install', () => { + const lane = path.join(tmp, 'lane'); + git(['worktree', 'add', '-q', '--detach', lane, 'HEAD'], install); + git(['worktree', 'lock', lane], install); + const shim = path.join(tmp, 'oldgit'); + fs.mkdirSync(shim); + fs.writeFileSync(path.join(shim, 'git'), `#!/bin/bash\ncase " $* " in *" worktree list "*" -z "*) echo "error: unknown switch z" >&2; exit 129 ;; esac\nexec ${JSON.stringify(Bun.which('git'))} "$@"\n`, { mode: 0o755 }); + const r = spawnSync('bash', [UNINSTALL, '--force'], { + cwd: proj, encoding: 'utf-8', timeout: 30_000, + env: { ...gitEnv, PATH: `${shim}:${gitEnv.PATH}`, HOME: home, GSTACK_DIR: install, GSTACK_SETTINGS_FILE: path.join(home, 'settings.json'), + GSTACK_HOME: '', GSTACK_STATE_ROOT: path.join(home, '.gstack'), GSTACK_STATE_DIR: '', CLAUDE_PLUGIN_DATA: '' }, + }); + expect(r.status).toBe(2); + expect(r.stderr).toContain(`refusing to delete ${install}: ${install} has worktrees git cannot list (gstack-uninstall needs git 2.36 or later)`); + expect(fs.existsSync(path.join(install, '.git'))).toBe(true); + }, 30_000); +}); + +describe('locked worktrees are found by NUL-separated paths (GST-2303)', () => { + let tmp: string, home: string, repo: string, gitEnv: Record; + const git = (args: string[], cwd = repo) => { + const r = spawnSync('git', ['-c', 'user.name=fixture', '-c', 'user.email=fixture@example.com', '-c', 'commit.gpgsign=false', '-c', 'protocol.file.allow=always', ...args], { cwd, encoding: 'utf-8', timeout: 30_000, env: gitEnv }); + expect(r.status).toBe(0); + return r.stdout; + }; + const uninstall = (args: string[]) => spawnSync('bash', [UNINSTALL, ...args], { + cwd: repo, encoding: 'utf-8', timeout: 30_000, + env: { ...gitEnv, HOME: home, GSTACK_DIR: path.join(home, '.claude', 'skills', 'gstack'), + GSTACK_SETTINGS_FILE: path.join(home, 'settings.json'), + GSTACK_HOME: '', GSTACK_STATE_ROOT: path.join(home, '.gstack'), GSTACK_STATE_DIR: '', CLAUDE_PLUGIN_DATA: '' }, + }); + beforeEach(() => { + tmp = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-uninstall-lock-'))); + home = path.join(tmp, 'home'); + repo = path.join(tmp, 'proj'); + fs.writeFileSync(path.join(tmp, 'gitconfig'), ''); + gitEnv = { ...process.env, GIT_CONFIG_GLOBAL: path.join(tmp, 'gitconfig'), GIT_CONFIG_NOSYSTEM: '1' } as Record; + fs.mkdirSync(path.join(home, '.claude', 'skills', 'gstack'), { recursive: true }); + fs.writeFileSync(path.join(home, '.claude', 'skills', 'gstack', 'SKILL.md'), 'test'); + fs.mkdirSync(repo, { recursive: true }); + git(['init', '-q', '-b', 'main']); + fs.writeFileSync(path.join(repo, '.git', 'info', 'exclude'), '.gstack-worktrees/\n'); + fs.writeFileSync(path.join(repo, 'README.md'), 'x\n'); + git(['add', 'README.md']); + git(['commit', '-q', '-m', 'seed']); + }); + afterEach(() => fs.rmSync(tmp, { recursive: true, force: true })); + + test('a locked worktree whose path holds a newline survives --force --force-worktrees', () => { + const lane = path.join(repo, '.gstack-worktrees', 'run', 'lane\nx'); + git(['worktree', 'add', '-q', '--detach', lane, 'HEAD']); + git(['worktree', 'lock', lane]); + const r = uninstall(['--force', '--force-worktrees']); + expect(r.status).toBe(2); + expect(r.stderr).toContain('it is locked (git worktree lock)'); + expect(fs.existsSync(path.join(lane, 'README.md'))).toBe(true); + }); + + test('a clean submodule nested inside a clean submodule of a clean lane does not stop the uninstall', () => { + const inner = path.join(tmp, 'inner'); + fs.mkdirSync(inner); + git(['init', '-q', '-b', 'main'], inner); + fs.writeFileSync(path.join(inner, 'a.txt'), 'a\n'); + git(['add', 'a.txt'], inner); + git(['commit', '-q', '-m', 'inner'], inner); + const lib = path.join(tmp, 'lib'); + fs.mkdirSync(lib); + git(['init', '-q', '-b', 'main'], lib); + git(['submodule', 'add', '-q', inner, 'deps/inner'], lib); + git(['commit', '-q', '-m', 'lib'], lib); + git(['submodule', 'add', '-q', lib, 'vendor/lib']); + git(['commit', '-q', '-m', 'submodule']); + const lane = path.join(repo, '.gstack-worktrees', 'run', 'lane'); + git(['worktree', 'add', '-q', '--detach', lane, 'HEAD']); + git(['submodule', 'update', '-q', '--init', '--recursive'], lane); + expect(fs.existsSync(path.join(lane, 'vendor', 'lib', 'deps', 'inner', 'a.txt'))).toBe(true); + const r = uninstall(['--force']); + expect(r.stderr).toBe(''); + expect(r.status).toBe(0); + expect(fs.existsSync(lane)).toBe(false); + }); +}); + +describe('the manual removal in docs/uninstall.md checks each folder before deleting it (GST-2303)', () => { + let tmp: string, gitEnv: Record; + const git = (args: string[], cwd: string) => { + const r = spawnSync('git', ['-c', 'user.name=fixture', '-c', 'user.email=fixture@example.com', '-c', 'commit.gpgsign=false', ...args], { cwd, encoding: 'utf-8', timeout: 30_000, env: gitEnv }); + expect(r.status).toBe(0); + }; + const checkedDelete = (dirs: string[]) => { + const doc = fs.readFileSync(path.join(ROOT, 'docs', 'uninstall.md'), 'utf-8'); + const start = doc.indexOf('# 0. A delete that stops for unsaved git work'); + expect(start).toBeGreaterThan(-1); + const helper = doc.slice(start, doc.indexOf('# 1. Stop browse daemons', start)); + return spawnSync('bash', ['-c', `${helper}\ngstack_rm_checked "$@"`, 'doc', ...dirs], { cwd: tmp, encoding: 'utf-8', timeout: 30_000, env: gitEnv }); + }; + beforeEach(() => { + tmp = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-uninstall-doc-'))); + fs.writeFileSync(path.join(tmp, 'gitconfig'), ''); + gitEnv = { ...process.env, GIT_CONFIG_GLOBAL: path.join(tmp, 'gitconfig'), GIT_CONFIG_NOSYSTEM: '1' } as Record; + }); + afterEach(() => fs.rmSync(tmp, { recursive: true, force: true })); + + test('a folder holding a repo with an unpushed commit is kept, and a plain folder goes', () => { + const install = path.join(tmp, 'install'); + const notes = path.join(install, '.gstack'); + fs.mkdirSync(notes, { recursive: true }); + fs.writeFileSync(path.join(install, 'SKILL.md'), 'test\n'); + git(['init', '-q', '-b', 'main'], notes); + fs.writeFileSync(path.join(notes, 'notes.md'), 'mine\n'); + git(['add', 'notes.md'], notes); + git(['commit', '-q', '-m', 'unpushed notes'], notes); + const plain = path.join(tmp, 'plain'); + fs.mkdirSync(plain); + fs.writeFileSync(path.join(plain, 'SKILL.md'), 'test\n'); + const r = checkedDelete([install, plain]); + expect(r.status).toBe(0); + expect(r.stderr).toContain(`kept ${install}: ${notes} has uncommitted changes, unpushed commits or a locked worktree`); + expect(fs.existsSync(path.join(notes, 'notes.md'))).toBe(true); + expect(fs.existsSync(plain)).toBe(false); + }); + + test('a local-only commit that git fetch . HEAD wrote into FETCH_HEAD keeps its folder', () => { + const repo = path.join(tmp, 'repo'); + fs.mkdirSync(repo); + git(['init', '-q', '-b', 'main'], repo); + fs.writeFileSync(path.join(repo, 'notes.md'), 'mine\n'); + git(['add', 'notes.md'], repo); + git(['commit', '-q', '-m', 'local notes'], repo); + git(['fetch', '-q', '.', 'HEAD'], repo); + const r = checkedDelete([repo]); + expect(r.stderr).toContain(`kept ${repo}: ${repo} has uncommitted changes, unpushed commits or a locked worktree`); + expect(fs.existsSync(path.join(repo, 'notes.md'))).toBe(true); + }); +}); + From dbb4b5064c3757354231f8dbb65de5b476949e2a Mon Sep 17 00:00:00 2001 From: Garry Tan Date: Tue, 10 Nov 2026 07:55:42 -0800 Subject: [PATCH 02/31] Fix six test and eval checks that misread correct work or raced their own fixtures (GST-2338) (#4284) * Fix six test and eval checks that misread correct work or raced their own fixtures (GST-2338) Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * Credit a one-sentence defer offer again and limit the /dev/null goto credit to file:// targets with no || before it Review-Finding: p1/red-team#1 reader=red-team Review-Finding: p1/specialist-batched#1 reader=specialist-batched Review-Finding: p1/red-team#3 reader=red-team Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * Refuse the /dev/null goto credit only when || sits directly before the goto's pipeline Review-Finding: p2/red-team#3 reader=red-team Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --------- Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- changelog.d/fix-flaky-checks-2026-11-10.md | 1 + .../test/helpers/session-runner.ts.json | 2 +- test/cso-registry-socket.test.ts | 4 +- test/cso-snapshot-state.test.ts | 2 +- test/docsync-command-grammar.test.ts | 23 ++++++++++ test/helpers/docsync-interface.ts | 2 +- test/helpers/docsync-observer.ts | 4 +- test/helpers/session-runner.test.ts | 34 +++++++++++++++ test/helpers/session-runner.ts | 42 ++++++++++++++++--- test/helpers/third-party-actions.ts | 22 ++++++++-- test/skill-e2e-skillify.test.ts | 2 +- test/third-party-actions.test.ts | 21 +++++++++- 12 files changed, 143 insertions(+), 16 deletions(-) create mode 100644 changelog.d/fix-flaky-checks-2026-11-10.md diff --git a/changelog.d/fix-flaky-checks-2026-11-10.md b/changelog.d/fix-flaky-checks-2026-11-10.md new file mode 100644 index 00000000000..6ba4b653418 --- /dev/null +++ b/changelog.d/fix-flaky-checks-2026-11-10.md @@ -0,0 +1 @@ +- **Six test and eval checks that misread correct work, or raced their own fixtures, now read it right (2026-11-10 daily flaky pass, GST-2338).** ship-docsync-store's fixture interface now declares the `gstack-docs-candidate attempt --state ` call that /ship's documentation step has asked for since #4192, so a model that follows the step is no longer stopped by the fixture (census 42748129558). tpa-absent-darwin no longer counts a gstack-browser option as an Aside drive just because it says Aside isn't available. tpa-present's defer check counts a "the step stays blocked on you" status line only when the option puts the step off ("later", "not yet", "not now"), so a status line after another instruction no longer passes as a defer offer. scrape-prototype-path also credits `$B goto >/dev/null && $B html` when the call proves the goto exited 0. Two free tests stop racing themselves: the CSO lease contender publishes its result file by rename, so the test never reads it empty, and the registry-socket deadline test sets a deadline that expires after the watchdog's startup handshake instead of inside it. No threshold, trial count, case kind or retry changed. diff --git a/scripts/harness-pins/test/helpers/session-runner.ts.json b/scripts/harness-pins/test/helpers/session-runner.ts.json index b1dc4ddd3e0..c81f216e3d3 100644 --- a/scripts/harness-pins/test/helpers/session-runner.ts.json +++ b/scripts/harness-pins/test/helpers/session-runner.ts.json @@ -1 +1 @@ -{"blob":"0d5f36f91c31bf32d4997cde0c267f96caf57c7a","since":6,"nonBehavioral":"adds helpers called only by the changed scrape-prototype-path, codex-review and ship-coverage-value case files and turns off git auto-maintenance in the AUQ capture fixture; no existing caller's behavior changes (GST-2131)"} +{"blob":"6a0fad8792221a97dd27c01837af368be81d5bf5","since":6,"nonBehavioral":"widens browseNavigatedTo, whose only caller is the changed scrape-prototype-path case file, to credit a goto with stdout sent to /dev/null when the call proves it exited 0 (a file:// target, no || directly before the goto's pipeline, only && after it); no other caller or case changes (GST-2338)"} diff --git a/test/cso-registry-socket.test.ts b/test/cso-registry-socket.test.ts index 02352e3a049..a311d644122 100644 --- a/test/cso-registry-socket.test.ts +++ b/test/cso-registry-socket.test.ts @@ -80,7 +80,9 @@ posixDescribe('short supervised CSO registry sockets', () => { }, 15_000); test('deadline cleanup removes the whole per-call socket root without a global temp sweep', async () => { - const doomed = await superviseRegistrySocket({ watchdogPath, ownerPid: process.pid, deadline: Date.now() + 150 }); + // The watchdog takes whole seconds and cleans as soon as the deadline passes, so a deadline inside the ~1 s startup + // handshake fails it on a slow start (Free Tests 42772387147): expire it after the handshake instead. + const doomed = await superviseRegistrySocket({ watchdogPath, ownerPid: process.pid, deadline: Date.now() + 2_000 }); const survivor = await superviseRegistrySocket({ watchdogPath, ownerPid: process.pid, deadline: Date.now() + 10_000 }); const broker = new RegistryEgressBroker(doomed.socketPath, ['registry.npmjs.org'], Date.now() + 10_000, 1024 * 1024); try { diff --git a/test/cso-snapshot-state.test.ts b/test/cso-snapshot-state.test.ts index a18799a73fb..3357e8b5407 100644 --- a/test/cso-snapshot-state.test.ts +++ b/test/cso-snapshot-state.test.ts @@ -17,7 +17,7 @@ const read=fs.readdirSync.bind(fs);spyOn(fsModule,'readdirSync').mockImplementat spyOn(fsModule,'writeFileSync').mockImplementation(((target,data,...args)=>{const name=path.basename(String(target));if(name.includes('.decision.tmp.')){let decision;try{decision=JSON.parse(String(data));}catch{}if(decision?.kind==='ticket'&&decision.token===token){try{mark('choice-'+id,decision.ticket);}catch{}if(mode==='pause-before-decision'&&!triggered){triggered=true;mark('paused-'+id);process.kill(process.pid,'SIGSTOP');}}if(decision?.kind==='withdraw'&&mode==='pause-before-withdraw'&&!triggered){triggered=true;mark('paused-'+id);process.kill(process.pid,'SIGSTOP');}}return write(target,data,...args);}) as typeof fs.writeFileSync); const link=fs.linkSync.bind(fs);spyOn(fsModule,'linkSync').mockImplementation(((source,target)=>{const name=path.basename(String(target));if(mode==='wait-active'&&!triggered&&name.includes('.active.')){triggered=true;mark('doorway-'+id);waitFor('paused-H');}return link(source,target);}) as typeof fs.linkSync); const unlink=fs.unlinkSync.bind(fs);spyOn(fsModule,'unlinkSync').mockImplementation(((target)=>{const result=unlink(target),name=path.basename(String(target)),candidateToken=name.endsWith('.json')?name.slice(0,-5):'';if((mode==='pause-decision'||mode==='pause-ticket')&&!triggered&&name.includes('.decision.tmp.')&&(!token||name.startsWith(token+'.decision.tmp.'))){triggered=true;mark('paused-'+id);process.kill(process.pid,'SIGSTOP');}if((mode==='pause-after-candidate-cleanup'||mode==='pause-withdraw-cleanup')&&!triggered&&/^[a-f0-9]{32}$/.test(candidateToken)&&(!token||candidateToken===token)&&fs.existsSync(path.join(leases,candidateToken+'.decision'))){triggered=true;mark('paused-'+id);process.kill(process.pid,'SIGSTOP');}return result;}) as typeof fs.unlinkSync); -const {withLock}=await import(${JSON.stringify(path.resolve(import.meta.dir,'../lib/cso/state.ts'))});let outcome='success';try{withLock(dir,()=>{const active=path.join(barrier,'work-active');try{write(active,id,{flag:'wx'});}catch{fs.appendFileSync(path.join(barrier,'overlap'),'overlap\\n');}mark('entered-'+id);if(process.env.RACE_HOLD==='1')waitFor('release-'+id);try{if(fs.readFileSync(active,'utf8')===id)fs.unlinkSync(active);}catch{}});}catch(error){outcome=String(error?.code??error);}write(path.join(barrier,'result-'+id),outcome);`;} +const {withLock}=await import(${JSON.stringify(path.resolve(import.meta.dir,'../lib/cso/state.ts'))});let outcome='success';try{withLock(dir,()=>{const active=path.join(barrier,'work-active');try{write(active,id,{flag:'wx'});}catch{fs.appendFileSync(path.join(barrier,'overlap'),'overlap\\n');}mark('entered-'+id);if(process.env.RACE_HOLD==='1')waitFor('release-'+id);try{if(fs.readFileSync(active,'utf8')===id)fs.unlinkSync(active);}catch{}});}catch(error){outcome=String(error?.code??error);}const result=path.join(barrier,'result-'+id);write(result+'.tmp',outcome);fs.renameSync(result+'.tmp',result);`;} describe('CSO dirty snapshot boundary',()=>{ test('captures tracked modifications and nonignored untracked source without changing Git state',async()=>{const p=repo();fs.writeFileSync(path.join(p,'tracked.txt'),'dirty\n');fs.writeFileSync(path.join(p,'new.txt'),'untracked\n');fs.writeFileSync(path.join(p,'.gitignore'),'ignored.txt\n');fs.writeFileSync(path.join(p,'ignored.txt'),'ignored\n');const before=git(p,'status','--porcelain=v1','-z'),run=newRun(p),m=await capture(p,run.dir,'HEAD');expect(fs.readFileSync(path.join(run.dir,'snapshot','tracked.txt'),'utf8')).toBe('dirty\n');expect(fs.readFileSync(path.join(run.dir,'snapshot','new.txt'),'utf8')).toBe('untracked\n');expect(fs.existsSync(path.join(run.dir,'snapshot','ignored.txt'))).toBe(false);expect(git(p,'status','--porcelain=v1','-z')).toBe(before);expect(m.changedPaths).toContain('new.txt');}); test('records an untracked nested repository as one boundary entry instead of failing the run',async()=>{const p=repo(),inner=path.join(p,'inner');fs.mkdirSync(inner);git(inner,'init','-q');git(inner,'config','user.email','fixture@example.test');git(inner,'config','user.name','Fixture');fs.writeFileSync(path.join(inner,'f.txt'),'x\n');git(inner,'add','.');git(inner,'commit','-qm','inner');const run=newRun(p),manifest=await capture(p,run.dir,'HEAD');assertSnapshot(run.dir,manifest);const entry=manifest.entries.find(e=>e.path==='inner');expect(entry?.transformation).toBe(NESTED_REPOSITORY);expect(entry?.originalHash).toBe('not-read');expect(manifest.entries.map(e=>e.path).filter(p=>p==='tracked.txt'||p.startsWith('inner'))).toEqual(['inner','tracked.txt']);expect(manifest.changedPaths).toContain('inner');expect(fs.existsSync(path.join(run.dir,'snapshot','inner'))).toBe(false);expect(fs.existsSync(path.join(run.dir,'readable','inner'))).toBe(false);}); diff --git a/test/docsync-command-grammar.test.ts b/test/docsync-command-grammar.test.ts index 0a26c7266a7..ad9743cff87 100644 --- a/test/docsync-command-grammar.test.ts +++ b/test/docsync-command-grammar.test.ts @@ -258,6 +258,29 @@ test('the docs-candidate result command is admitted only with a private output f expect(docsNativeInterface(fixture)).toContain(`${fixture.skills.split(path.sep).join('/')}/bin/gstack-docs-candidate result --audit-id --out-dir <`); }); +// Census 42748129558 (ship-docsync-store): Step 14.5 counts each launch with `gstack-docs-candidate attempt` (#4192), which +// this interface did not declare, so the parent correctly stopped before launching any audit. +test('the docs-candidate attempt command is admitted only with a private child output and a private --state .json', () => { + const helper = path.join(fixture.skills, 'bin/gstack-docs-candidate'); + const output = path.join(fixture.home, 'audit-1-output.md'); + const state = path.join(fixture.home, 'docs-attempts.json'); + for (const command of [`${helper} attempt ${output} --state ${state}`, `${helper} attempt --help`]) + expect(docsCommandAllowed(command, fixture), command).toBe(true); + for (const command of [ + `${helper} attempt ${output} --state ${path.join(fixture.repo, '.gstack/tmp/docs-attempts.json')}`, + `${helper} attempt ${output} --state ${path.join(fixture.home, 'docs-attempts.md')}`, + `${helper} attempt ${output} --state ${path.join(fixture.skills, 'bin/docs-attempts.json')}`, + `${helper} attempt ${path.join(fixture.repo, 'out.md')} --state ${state}`, + `${helper} attempt ${output}`, + `${helper} attempt --state ${state} ${output}`, + `${helper} attempt ${output} --state ${state} --exec rm`, + `${helper} attempt ${output} --out ${state}`, + `${helper} attempt --help extra`, + `~/.claude/skills/gstack/bin/gstack-docs-candidate attempt ${output} --state ${state}`, + ]) expect(docsCommandAllowed(command, fixture), command).toBe(false); + expect(docsNativeInterface(fixture)).toContain(`${fixture.skills.split(path.sep).join('/')}/bin/gstack-docs-candidate attempt --state and attempt --help`); +}); + // Train gate 39904966815 and GSTA-63's focused run joined the candidate's --help onto a line of reads; v1.91.185.0 moved the // own-call rule into the sentence naming --help and the slip came back four times (JOINED_READ_LINES below). The --help only // prints usage, so it now joins a line of reads like a Git read; every other own-call command stays alone. diff --git a/test/helpers/docsync-interface.ts b/test/helpers/docsync-interface.ts index 90113471f26..485fa3becd6 100644 --- a/test/helpers/docsync-interface.ts +++ b/test/helpers/docsync-interface.ts @@ -15,7 +15,7 @@ export const docsCapsCommand = (skills: string) => `${skills}/bin/gstack-ship-re export function docsNativeInterface(fixture: Pick, 'home' | 'repo' | 'skills'> & Partial, 'env'>>, scripts: string[] = [], transport = false, insert = false, file?: string): string { const skills = fixture.skills.split(path.sep).join('/'); const state = fixture.env?.GSTACK_HOME ?? path.join(fixture.home, 'state'); - return `Fixture observation interface (applies to parent and every child; ${file ? `saved at ${file}: each child prompt tells the child to Read that file first instead of copying this text` : 'include this interface in child prompts'}): Bash may execute only separate literal pwd, ls, cat, stat, sha256sum and Git read commands (status, diff, show, log, ls-files, ls-tree, check-ignore, rev-parse, merge-base, hash-object without -w, branch listings with no operand and only --show-current, -a/--all, -r/--remotes, -v/--verbose, -l/--list, --no-color or --no-abbrev (no --merged, --sort, --format or --contains), tag listings with no operand and only -l/--list, describe with only --tags, --always, --abbrev= or --exact-match and at most one revision). Bash may also run each of the following as its own Bash call, with nothing joined before or after it by ;, &&, || or a pipe (one exception follows the read grammar below): the exact generated Preamble block with its spawned prefix, literal installed gstack-skill-start/gstack-skill-end commands for document-release (start requires GSTACK_SESSION_KIND=spawned) or their own --help, or the literal installed ${skills}/bin/gstack-docs-candidate snapshot (its --out a private .json under ${fixture.home}), compare and --help commands, the literal installed ${skills}/bin/gstack-docs-candidate result --audit-id --out-dir <${fixture.home} or a new directory directly under it> and result --help, and /ship Step 14.5's three own-tree housekeeping commands exactly as written, each on its own line: the shared .gstack/tmp exclude line (the one &&-joined housekeeping line this interface admits) + return `Fixture observation interface (applies to parent and every child; ${file ? `saved at ${file}: each child prompt tells the child to Read that file first instead of copying this text` : 'include this interface in child prompts'}): Bash may execute only separate literal pwd, ls, cat, stat, sha256sum and Git read commands (status, diff, show, log, ls-files, ls-tree, check-ignore, rev-parse, merge-base, hash-object without -w, branch listings with no operand and only --show-current, -a/--all, -r/--remotes, -v/--verbose, -l/--list, --no-color or --no-abbrev (no --merged, --sort, --format or --contains), tag listings with no operand and only -l/--list, describe with only --tags, --always, --abbrev= or --exact-match and at most one revision). Bash may also run each of the following as its own Bash call, with nothing joined before or after it by ;, &&, || or a pipe (one exception follows the read grammar below): the exact generated Preamble block with its spawned prefix, literal installed gstack-skill-start/gstack-skill-end commands for document-release (start requires GSTACK_SESSION_KIND=spawned) or their own --help, or the literal installed ${skills}/bin/gstack-docs-candidate snapshot (its --out a private .json under ${fixture.home}), compare and --help commands, the literal installed ${skills}/bin/gstack-docs-candidate result --audit-id --out-dir <${fixture.home} or a new directory directly under it> and result --help, the literal installed ${skills}/bin/gstack-docs-candidate attempt --state and attempt --help, and /ship Step 14.5's three own-tree housekeeping commands exactly as written, each on its own line: the shared .gstack/tmp exclude line (the one &&-joined housekeeping line this interface admits) ${DOCS_TMP_EXCLUDE} then ${DOCS_AUDIT_RESET} diff --git a/test/helpers/docsync-observer.ts b/test/helpers/docsync-observer.ts index 0630b1facf2..00ac6a56a74 100644 --- a/test/helpers/docsync-observer.ts +++ b/test/helpers/docsync-observer.ts @@ -414,8 +414,10 @@ function literalDocsCommandAllowed(text: string, fixture: ReturnType !!file && path.isAbsolute(file) && /\.json$/i.test(file) && docsPrivateArtifact(file, fixture, scripts); if (rest.length === 1 && rest[0] === '--help') return true; - if (rest.length === 2 && (rest[0] === 'snapshot' || rest[0] === 'compare' || rest[0] === 'result') && rest[1] === '--help') return true; + if (rest.length === 2 && ['snapshot', 'compare', 'result', 'attempt'].includes(rest[0]) && rest[1] === '--help') return true; if (rest[0] === 'compare') return rest.length === 2 && privateJson(rest[1]); + if (rest[0] === 'attempt') return rest.length === 4 && path.isAbsolute(rest[1]) && docsPrivateArtifact(rest[1], fixture, scripts) && + rest[2] === '--state' && privateJson(rest[3]); if (rest[0] === 'result') { if (rest.length !== 6 || !path.isAbsolute(rest[1]) || !docsPrivateArtifact(rest[1], fixture, scripts)) return false; const flags = [rest[2], rest[4]]; diff --git a/test/helpers/session-runner.test.ts b/test/helpers/session-runner.test.ts index 2c67252e64c..dd24d7bfd79 100644 --- a/test/helpers/session-runner.test.ts +++ b/test/helpers/session-runner.test.ts @@ -282,4 +282,38 @@ describe('browseNavigatedTo', () => { expect(browseNavigatedTo(bash(`$B goto ${url}`, `Error: page.goto: net::ERR_FILE_NOT_FOUND at ${url}`), url)).toBe(false); expect(browseNavigatedTo(bash(`$B goto ${url}`, `Navigated to ${url} (404)`), url)).toBe(false); }); + + test('a goto with its stdout sent to /dev/null is credited only when the call proves it exited 0 (PR #4223 outside-voice#1)', () => { + const { url } = trials[0]!; + const cwd = url.replace(/^file:\/\//, '').replace(/\/fixture\.html$/, ''); + const html = '
  • Alpha 12
'; + const credited = (command: string, output = html) => browseNavigatedTo(bash(command, output), url, cwd); + for (const command of ['B=/x/browse; $B goto "file://$PWD/fixture.html" >/dev/null && $B html', + `$B goto ${url} >/dev/null 2>&1 && $B text`, `"$B" goto '${url}' > /dev/null &&\n $B html`, + '/x/browse/dist/browse goto "file://${PWD}/fixture.html" &>/dev/null && /x/browse/dist/browse html']) + expect(credited(command), command).toBe(true); + expect(browseNavigatedTo(bash(`cd ${cwd} && $B goto file://$PWD/fixture.html >/dev/null && $B html`, html), url)).toBe(true); + expect(browseNavigatedTo([...bash(`cd ${cwd}`, ''), ...bash('$B goto "file://$PWD/fixture.html" >/dev/null && $B html', html)], url)) + .toBe(true); + for (const command of ['$B goto "file://$PWD/fixture.html" >/dev/null; $B html', + '$B goto "file://$PWD/fixture.html" >/dev/null || $B html', '$B goto "file://$PWD/fixture.html" >/dev/null & $B html', + '$B goto "file://$PWD/fixture.html" >/dev/null && $B html; echo done', '$B goto "file://$PWD/fixture.html" && $B html', + "$B goto 'file://$PWD/fixture.html' >/dev/null && $B html", '$B goto "file://$PWD/other.html" >/dev/null && $B html', + 'cd /tmp/elsewhere && $B goto "file://$PWD/fixture.html" >/dev/null && $B html', + 'cd "$HOME" && $B goto "file://$PWD/fixture.html" >/dev/null && $B html', + `echo "$B goto ${url}" >/dev/null && $B html`, `$B text goto ${url} >/dev/null && $B html`, + '$B status >/dev/null || $B goto "file://$PWD/fixture.html" >/dev/null && $B html', + `cd ${cwd} && $B status || $B goto "file://$PWD/fixture.html" >/dev/null && $B html`, + 'true || echo | $B goto "file://$PWD/fixture.html" >/dev/null && $B html']) + expect(credited(command), command).toBe(false); + for (const command of [`test -d ${cwd} || exit 1; $B goto "file://$PWD/fixture.html" >/dev/null && $B html`, + '[ -x "$B" ] || B=/x/browse && $B goto "file://$PWD/fixture.html" >/dev/null && $B html']) + expect(credited(command), command).toBe(true); + const http = 'http://127.0.0.1:9/missing'; + expect(browseNavigatedTo(bash(`$B goto ${http} >/dev/null && $B html`, 'Not Found'), http)).toBe(false); + const goto = '$B goto "file://$PWD/fixture.html" >/dev/null && $B html'; + expect(browseNavigatedTo(bash(goto, html), url)).toBe(false); + for (const output of [`Exit code 1\n${html}`, `Error: page.goto: net::ERR_FILE_NOT_FOUND at ${url}`, 'denied']) + expect(credited(goto, output), output).toBe(false); + }); }); diff --git a/test/helpers/session-runner.ts b/test/helpers/session-runner.ts index 0d5f36f91c3..6a0fad87922 100644 --- a/test/helpers/session-runner.ts +++ b/test/helpers/session-runner.ts @@ -92,13 +92,45 @@ export function scanBrowseErrors(text: string): string[] { }); } -/** True when a Bash `goto` printed browse's success line for exactly this URL with a 2xx status. */ -export function browseNavigatedTo(toolCalls: Array<{ tool: string; input: any; output: string }>, url: string): boolean { - return toolCalls.some(call => call.tool === 'Bash' && /\bgoto\b/.test(String(call.input?.command ?? '')) - && String(call.output ?? '').split('\n').some(line => { +/** + * True when a Bash `goto` reached exactly this URL: it printed browse's success line for the URL with a 2xx status, or + * it sent its stdout to /dev/null (`$B goto "" >/dev/null && $B html`) and the call proves it exited 0. That proof + * is a call that did not fail (no leading `Exit code N` or tool error, no `Error` or `net::ERR_` line) where no `||` + * directly before the goto's pipeline could skip it and every command after the goto is joined by `&&`, so none of them ran + * unless it succeeded. Only a file:// URL qualifies: goto exits 0 on any HTTP status, so exit 0 proves no 2xx load of + * an http URL. The goto's target must be the URL + * itself, or `$PWD`/`${PWD}` under a known working directory (`cwd`, followed through literal `cd ` commands in + * call order; any other `cd` makes it unknown). The goto must be the segment's own browse command (`$B goto`, + * `${B} goto` or `/browse goto`), not text inside another command. + */ +export function browseNavigatedTo(toolCalls: Array<{ tool: string; input: any; output: string }>, url: string, cwd?: string): boolean { + let pwd = cwd; + for (const call of toolCalls) { + if (call.tool !== 'Bash') continue; + const command = String(call.input?.command ?? ''); + const output = String(call.output ?? ''); + if (/\bgoto\b/.test(command) && output.split('\n').some(line => { const match = line.trim().match(/^Navigated to (\S+) \((\d+)\)$/); return match?.[1] === url && match[2]!.startsWith('2'); - })); + })) return true; + const failed = /^\s*(?:Exit code [1-9]|)/.test(output) || /^\s*Error\b|net::ERR_/m.test(output); + const parts = command.replace(/\\\n/g, ' ').replace(/(&&|\|\|)\s*\n/g, '$1 ').trim().split(/(&&|\|\||(?&])&(?![>&])|[;|\n])/); + for (let i = 0; i < parts.length; i += 2) { + const segment = parts[i]!.trim(); + const cd = segment.match(/^cd\s+(\S+)$/); + if (cd) pwd = /^\/[^$`'"]*$/.test(cd[1]!) ? cd[1] : undefined; + const goto = segment.match(/^(?:\w+=\S*\s+)*(?:"?\$\{?B\}?"?|\S*\bbrowse)\s+goto\s+("[^"]*"|'[^']*'|[^\s'"]+)(.*)$/); + if (failed || !goto || !url.startsWith('file://') || !/(?:^|\s)(?:1?>|&>)\s*\/dev\/null(?:\s|$)/.test(goto[2]!)) continue; + if (parts.slice(i + 1).some((separator, j) => j % 2 === 0 && separator !== '&&')) continue; + const before = parts.slice(0, i).filter((_, j) => j % 2 === 1); + if (before[before.findLastIndex(separator => separator !== '|')] === '||') continue; + const raw = goto[1]!; + const target = raw.startsWith("'") ? raw.slice(1, -1) + : (raw.startsWith('"') ? raw.slice(1, -1) : raw).replace(/\$\{PWD\}|\$PWD\b/g, () => pwd ?? '\u0000'); + if (target === url) return true; + } + } + return false; } // --- Testable NDJSON parser --- diff --git a/test/helpers/third-party-actions.ts b/test/helpers/third-party-actions.ts index 8220e897cf7..426c6020287 100644 --- a/test/helpers/third-party-actions.ts +++ b/test/helpers/third-party-actions.ts @@ -34,6 +34,13 @@ export function letteredOptions(text: string): string[] { return options; } +/** + * A mention that says Aside is missing ("since Aside isn't available", "Aside was not detected", "with no Aside + * installed") names the browser the option does not use, so it never makes a drive option an Aside drive (gate + * 42748129558: "I drive it in gstack's own visible browser (recommended, since Aside isn't available)"). + */ +const ASIDE_UNAVAILABLE = /\bAside(?:['’]s)?(?:\s+(?:browser|app))?\s+(?:is|was)(?:n['’]t|\s+not)\b|\bAside(?:\s+(?:browser|app))?\s+(?:is|was)\s+(?:unavailable|missing|absent)\b|\b(?:no|without)\s+(?:the\s+|your\s+)?Aside\b/gi; + /** Inspect lettered consent options, not narration that quotes an unavailable option. */ export function asideDriveOptions(text: string): string[] { return letteredOptions(text).filter(option => { @@ -41,7 +48,7 @@ export function asideDriveOptions(text: string): string[] { /\b(?:I|we)(?:['’]ll| will) (?:re[- ]?ask|ask again)(?: (?:you|this question))? with (?:the )?(?:"[^"]+"|“[^”]+”|[\w -]+?) option(?: included)?\b/gi, '', ); - return /\bAside\b/.test(option) && (/\b(?:drive|driving|browse|browsing|navigate|click)\b/i.test(currentOffer) + return /\bAside\b/.test(option.replace(ASIDE_UNAVAILABLE, '')) && (/\b(?:drive|driving|browse|browsing|navigate|click)\b/i.test(currentOffer) || /\bI(?:['’]ll| will)? (?:do|handle|create|complete) (?:it|this)\b/i.test(currentOffer)); }); } @@ -65,13 +72,22 @@ export const offersDriveOption = (text: string): boolean => letteredOptions(text * waiting on you", "I refuse to mark this step as blocked on you", "otherwise I'll mark this step as blocked on you", * "if you skip it, I'll mark this step as blocked on you", "the step is not blocked on you" and "nothing stays blocked * on you" do not count, and neither does "waiting on you to approve it". + * + * Marking the step is what choosing the option does, so that clause counts on its own. The stays/remains/is predicate + * only describes the step's state, which any option can mention, so it counts only after an earlier part of the same + * option puts the step off ("later", "not yet", "not now"): "Later. This step remains waiting on you." counts, but "Sign + * in yourself. Until then the step stays blocked on you.", "Approve it in the dashboard. The step is waiting on you." + * and "Do it now, not later. The step stays blocked on you." do not. */ -const DEFER_OUTCOME = /(?:^|[.!?;:]\s+|\s-+\s+|[\u2013\u2014]\s*)(?:(?!\b(?:not|never|no|nothing|nobody|none|neither|nor|without|cannot|refus\w*|declin\w*|avoid\w*|rather|instead|if|unless|otherwise|else)\b|n['\u2019]t\b)[^.!?;:\u2013\u2014])*?\b(?:(?:I|we)(?:['\u2019]ll| will) |I |we )?(?:(?:mark|leave|keep)\w* (?:this|it|the)(?: [\w-]+)?(?: step)? (?:as )?|(?:stays|remains|is) )(?:blocked|waiting) on you(?=\s*(?:[.!?;:]|[-\u2013\u2014]|$))/i; +const DEFER_OUTCOME = /(?:^|[.!?;:]\s+|\s-+\s+|[\u2013\u2014]\s*)(?:(?!\b(?:not|never|no|nothing|nobody|none|neither|nor|without|cannot|refus\w*|declin\w*|avoid\w*|rather|instead|if|unless|otherwise|else)\b|n['\u2019]t\b)[^.!?;:\u2013\u2014])*?\b(?:(?:I|we)(?:['\u2019]ll| will) |I |we )?(?:(?:mark|leave|keep)\w* (?:this|it|the)(?: [\w-]+)?(?: step)? (?:as )?|(?(?:stays|remains|is) ))(?:blocked|waiting) on you(?=\s*(?:[.!?;:]|[-\u2013\u2014]|$))/gi; +const PUT_OFF = /(? [...option.matchAll(DEFER_OUTCOME)] + .some(match => !match.groups?.status || PUT_OFF.test(option.slice(0, match.index + match[0].lastIndexOf(match.groups.status)))); export const offersDefer = (text: string): boolean => letteredOptions(text).some(option => /\b(?:defer\w*|postpone\w*|put (?:this|it)(?: step)? off|skip (?:this|it)(?: step)? for now|come back to (?:this|it)(?: step)? later|leave (?:this|it)(?: step)? for (?:now|later))\b/i.test(option) || !/drive|browse|Aside/i.test(option) && (/(?:^|[.!?;:]\s+)(?:(?:we|I|let['\u2019]s) )?(?:wait|hold off)(?: on (?:this|it)(?: step)?)? for now\b(?=\s*(?:[.!?;:]|[-\u2013\u2014]|$))/i.test(option) - || !offersManualSteps(option) && DEFER_OUTCOME.test(option))); + || !offersManualSteps(option) && offersDeferOutcome(option))); /** The manual option: "manual", or one sentence offering instructions or steps the user follows themselves. */ export function offersManualSteps(text: string): boolean { diff --git a/test/skill-e2e-skillify.test.ts b/test/skill-e2e-skillify.test.ts index d5847f970bd..acdf4d64745 100644 --- a/test/skill-e2e-skillify.test.ts +++ b/test/skill-e2e-skillify.test.ts @@ -280,7 +280,7 @@ This run is non-interactive; AskUserQuestion is unavailable.`, logCost('scrape-prototype-path', result); const cmds = bashCommands(result); - const wentToFixture = browseNavigatedTo(result.toolCalls, fileUrl); + const wentToFixture = browseNavigatedTo(result.toolCalls, fileUrl, workDir); const fetchedHtml = cmds.some(c => /\bgoto\b|\bhtml\b|\btext\b/.test(c)); const surface = fullSurface(result); const mentionsSkillify = /skillify/i.test(surface); diff --git a/test/third-party-actions.test.ts b/test/third-party-actions.test.ts index c597fe4f1b4..50e68a4d9f3 100644 --- a/test/third-party-actions.test.ts +++ b/test/third-party-actions.test.ts @@ -72,6 +72,16 @@ D) Defer expect(asideDriveOptions('A) Open the Aside app; if READY, I drive the dashboard.')).toHaveLength(1); }); + test('a drive option that names Aside only as missing is not an Aside drive (gate 42748129558)', () => { + for (const option of ["B) I drive it in gstack's own visible browser (recommended, since Aside isn't available). I open the dashboard in a visible browser window and stop whenever you need to act.", + "B) Aside isn't available, so I drive it in gstack's own browser.", "B) Aside was not detected; I drive it in gstack's own browser.", + "B) Since the Aside browser is unavailable, I drive it in gstack's own browser.", "B) With no Aside installed, I drive it in gstack's browser."]) + expect(asideDriveOptions(option), option).toEqual([]); + for (const option of ["A) Aside isn't open yet, so I open Aside and drive the dashboard.", + 'A) I drive it in your Aside browser; Aside is not the only option.', "A) Aside wasn't running, but now I drive it in your Aside browser."]) + expect(asideDriveOptions(option), option).toHaveLength(1); + }); + test.each(recoveryFixture.responses)('native recovery response $attempt defers drive consent to a new question', ({ text }) => { expect(asideDriveOptions(text)).toEqual([]); expect(asideDriveOptions(text.replace('option included.', 'option included; then I drive in your Aside browser.'))).toHaveLength(1); @@ -577,8 +587,9 @@ describe('Opus consent renders (gate captures)', () => { test('the defer outcome counts in any words, and a refusal of it never does', () => { // Gate 42431616220 slice 15: the red tpa-present render's D) option, missed by the spelling list. for (const option of ["D) Do it later. I'll mark this step as waiting on you.", 'D) Not yet: the step stays blocked on you.', - 'D) Later. This step remains waiting on you.', "D) Do it later \u2014 I'll leave this step as blocked on you.", - "D) Do it later - I'll leave this step as blocked on you."]) + 'D) Later. This step remains waiting on you.', 'D) Later, so this step remains waiting on you.', "D) Do it later \u2014 I'll leave this step as blocked on you.", + "D) Do it later - I'll leave this step as blocked on you.", 'D) Not now. The step stays blocked on you.', + 'D) Sign in yourself later. The step is waiting on you.']) expect(offersDefer(option), option).toBe(true); for (const text of ['D) Continue now. I will not mark this step as blocked on you.', "D) Continue now. I won't mark this step as waiting on you.", 'D) Continue now. I never mark this step as blocked on you.', @@ -598,6 +609,12 @@ describe('Opus consent renders (gate captures)', () => { "B) I drive it in gstack's own browser and mark this step as waiting on you.", "C) Manual instructions; I'll mark this step as blocked on you.", 'C) I give you the steps to do it yourself. The step stays blocked on you.', + // /ship note at d98f9bb5 (PR #4223): a state line after a non-defer instruction is not a defer offer. + 'D) Sign in yourself. Until then the step stays blocked on you.', + 'D) Approve the token in the dashboard. The step is waiting on you.', + 'D) Continue now. The step is waiting on you.', + 'D) Do it now, not later. The step stays blocked on you.', + 'D) The step is waiting on you. Do it later.', "I'll mark this step as waiting on you.\nA) I drive it in your Aside browser\nB) Manual instructions"]) expect(offersDefer(text), text).toBe(false); }); From f0cd9f8c4b453c1eadd714e4149174ee01179eae Mon Sep 17 00:00:00 2001 From: Garry Tan Date: Tue, 10 Nov 2026 09:37:51 -0800 Subject: [PATCH 03/31] Keep /review and /ship working in copied Windows installs (GST-2347) (#4286) * Keep /review and /ship working in copied Windows installs (GST-2347) On Windows, setup copies bin/ and lib/ into each non-Claude host's runtime folder, but left out the scripts/ modules they import. gstack-review-plan, which /review and /ship run first, failed with "Cannot find module '../scripts/resolvers/fix-check'". Setup now also copies fix-check.ts, discover-skills.ts and lib/ci-history.ts, and the runtime-root test follows every static import of the commands each host's skills run. Co-authored-by: Satria Suria <57977752+SatriaSuriaAriffin@users.noreply.github.com> Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * Say the copied-install import check follows static imports only The changelog entry claimed the new test follows every import; it follows static imports. TODOS.md now lists the three deferred commands with one remedy and records what the check does not see: lazy import() and require() calls, modules a shell script launches, and bare package imports. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * Keep the production-dependency check's walk sentinel on a module setup does not name setup now names scripts/discover-skills.ts, so the check scans it as a root file and its import walk no longer reaches it. The walk's sentinel moves to scripts/gen-agents-digest.ts, which only gen-skill-docs imports, and discover-skills.ts stays asserted as scanned. Fixes the quick-bun-default failure in CI run 42857125482. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --------- Co-authored-by: Satria Suria <57977752+SatriaSuriaAriffin@users.noreply.github.com> Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- TODOS.md | 15 +++-- ...view-working-in-copied-windows-installs.md | 4 ++ setup | 9 ++- test/runtime-root-assets.test.ts | 66 +++++++++++++++++-- test/setup-production-deps.test.ts | 3 +- 5 files changed, 85 insertions(+), 12 deletions(-) create mode 100644 changelog.d/keep-review-working-in-copied-windows-installs.md diff --git a/TODOS.md b/TODOS.md index abc4c831cd5..12d02f317d2 100644 --- a/TODOS.md +++ b/TODOS.md @@ -425,10 +425,17 @@ From the approved 2026-10 test/eval/CI audit plan; the audit PR files these. - **`scripts/ship-measure.ts` on env-var hosts** — /ship's measure loop runs `$GSTACK_ROOT/scripts/ship-measure.ts`, which imports gstack's test helpers and eval harness, so a Codex/Factory/... runtime root would need most of the - development tree. It is the one `$GSTACK_ROOT` path - `test/runtime-root-assets.test.ts` defers. Either make ship-measure - self-contained or have the skill call it from the source checkout - (`.source-path`). **Effort:** M. **Priority:** P3. + development tree. `bin/gstack-model-benchmark` (/benchmark-models imports + the test tree's providers) and `bin/gstack-ship-queue` (the merge queue + imports the eval gate) have the same problem and fail to start from a + copied Windows root. `test/runtime-root-assets.test.ts` defers all three. + For each, either make it self-contained or have the skill call it from the + source checkout (`.source-path`). That test also follows static imports + only: lazy `import()` and `require()` calls (`bin/gstack-evidence` loads + `scripts/lib/shard-engine` with a fallback, and + `lib/pregate/flaky-exception.ts` requires it and a test helper), modules a + shell script launches, and bare package imports go unchecked. + **Effort:** M. **Priority:** P3. - **Rendered `SKILL.md` copies inside runtime roots are discoverable** — `office-hours/SKILL.md` (#2449) and now `plan-design-review/SKILL.md` sit in `~/.codex/skills/gstack//` because skills read them as diff --git a/changelog.d/keep-review-working-in-copied-windows-installs.md b/changelog.d/keep-review-working-in-copied-windows-installs.md new file mode 100644 index 00000000000..adfb5ae4a8c --- /dev/null +++ b/changelog.d/keep-review-working-in-copied-windows-installs.md @@ -0,0 +1,4 @@ +--- +important: blocker +--- +- **/review and /ship start again on Windows under Codex, Cursor and the other non-Claude hosts.** On Windows, setup copies gstack's `bin/` and `lib/` into each host's runtime folder instead of linking them, and it left out three `scripts/` files those commands import. The review planner that /review and /ship run first stopped with `Cannot find module '../scripts/resolvers/fix-check'`, and the commands behind /retro and /write-skill had the same gap. Setup now copies `scripts/resolvers/fix-check.ts`, `scripts/discover-skills.ts` and `scripts/lib/ci-history.ts` too, and a test follows the static imports of the commands each host's skills run, so a new static import outside the runtime folder fails CI. Thanks to @SatriaSuriaAriffin, who found and reported the fix-check gap (#4275). diff --git a/setup b/setup index 56fded0f84e..c969f3d7d94 100755 --- a/setup +++ b/setup @@ -790,9 +790,11 @@ _link_or_copy() { # residue): the preamble's jargon list, question registry and AskUserQuestion # docs, the review checklists and specialists, /plan-devex-review's Hall of # Fame, the test-value bar, design-html's vendored pretext.js and VERSION. -# And crew/lib, which bin and lib import (the crew/ move, GST-1833): a root -# whose bin and lib are copies (Windows) needs it beside them to start. -# Pinned by test/runtime-root-assets.test.ts. A destination that already exists +# And crew/lib, which bin and lib import (the crew/ move, GST-1833), plus the +# scripts/ modules they import: a root whose bin and lib are copies (Windows) +# needs them beside it to start (/review and /ship's review planner imports +# fix-check.ts). +# Pinned by test/runtime-root-assets.test.ts, which also follows those imports. A destination that already exists # as a real entry is left alone: in the repo-local sidecar review/ is a link to # the source, so its files already resolve and must never be linked over. _link_runtime_dists() { @@ -813,6 +815,7 @@ _link_runtime_dists() { fi done for f in VERSION scripts/jargon-list.json scripts/question-registry.ts \ + scripts/resolvers/fix-check.ts scripts/discover-skills.ts scripts/lib/ci-history.ts \ docs/askuserquestion-split.md docs/askuserquestion-cjk.md docs/test-value-bar.md \ review/checklist.md review/design-checklist.md review/greptile-triage.md review/TODOS-format.md \ plan-devex-review/dx-hall-of-fame.md; do diff --git a/test/runtime-root-assets.test.ts b/test/runtime-root-assets.test.ts index d18eed0beef..5e5cb3635e7 100644 --- a/test/runtime-root-assets.test.ts +++ b/test/runtime-root-assets.test.ts @@ -20,6 +20,7 @@ import * as fs from 'fs'; import * as os from 'os'; import * as path from 'path'; import { HOST_CONFIG_MAP } from '../hosts'; +import { bunIsolationArgs } from '../lib/bun-isolation'; import { runGeneration } from '../scripts/gen-skill-docs'; const ROOT = path.resolve(import.meta.dir, '..'); @@ -43,7 +44,9 @@ const ROOT_BUILDERS: Record = { // Deferred, with the reason recorded in TODOS.md: /ship's measure loop runs // scripts/ship-measure.ts, which imports gstack's test helpers and eval // harness; a runtime root would need the whole development tree. -const DEFERRED = new Set(['scripts/ship-measure.ts']); +// gstack-model-benchmark (/benchmark-models) and the merge queue's +// gstack-ship-queue are deferred the same way: both import that tree. +const DEFERRED = new Set(['scripts/ship-measure.ts', 'bin/gstack-model-benchmark', 'bin/gstack-ship-queue']); // Compiled outputs: the stub source carries placeholder binaries, so a fresh // checkout without a build still exercises the links to them. @@ -97,17 +100,52 @@ function makeSource(): void { } } -function buildRoot(host: string): { root: string; stderr: string; status: number | null } { - const root = path.join(tmp, 'home', host, 'skills', 'gstack'); +// windows: setup's IS_WINDOWS=1 arm, where bin/, lib/ and the runtime dists +// are real copies instead of links, so a module they import resolves only if +// setup copied it beside them. It copies from the checkout itself, because +// cp -R copies the stub source's top-level links as links. +function buildRoot(host: string, windows = false): { root: string; stderr: string; status: number | null } { + const root = path.join(tmp, windows ? 'home-windows' : 'home', host, 'skills', 'gstack'); fs.mkdirSync(path.dirname(root), { recursive: true }); const functions = ['_link_or_copy', '_link_runtime_dists', '_copy_runtime_skill_refs', '_copy_skill_md', '_sidecar_root_user_owned', '_gstack_generated_header', ROOT_BUILDERS[host]!] .filter(name => SETUP_SRC.includes(`\n${name}() {`)).map(extractFunction).join('\n'); - const r = spawnSync('bash', ['-c', `set -e\nIS_WINDOWS=0\n${functions}\n${ROOT_BUILDERS[host]} "${src}" "${root}"`], + const r = spawnSync('bash', ['-c', `set -e\nIS_WINDOWS=${windows ? 1 : 0}\n${functions}\n${ROOT_BUILDERS[host]} "${windows ? ROOT : src}" "${root}"`], { encoding: 'utf8', timeout: 30_000, env: { PATH: process.env.PATH ?? '/usr/bin:/bin', HOME: path.join(tmp, 'home') } }); return { root, stderr: r.stderr, status: r.status }; } +const transpiler = new Bun.Transpiler({ loader: 'ts' }); +function isBunSource(file: string): boolean { + if (!fs.existsSync(file) || !fs.statSync(file).isFile()) return false; + return /\.(ts|js|mjs)$/.test(file) || (!path.extname(file) && /^#!.*\bbun\b/.test(fs.readFileSync(file, 'utf8'))); +} + +/** + * Static imports reachable from the code a host's skills run that do not + * resolve inside its runtime root. Paths resolve from where the root holds + * each file, never through its links, which is how a copied root loads them. + */ +function importsOutsideRoot(host: string, root: string): string[] { + const queue = [...referencedPaths(host)].filter(rel => !DEFERRED.has(rel)).map(rel => path.join(root, rel)).filter(isBunSource); + const seen = new Set(); + const outside = new Set(); + while (queue.length) { + const file = queue.pop()!; + if (seen.has(file)) continue; + seen.add(file); + for (const { path: spec, kind } of transpiler.scanImports(fs.readFileSync(file, 'utf8').replace(/^#!.*/, ''))) { + if (kind !== 'import-statement' || !spec.startsWith('.')) continue; + const target = path.resolve(path.dirname(file), spec); + const found = [target, target.replace(/\.js$/, '.ts'), `${target}.ts`, `${target}.js`, path.join(target, 'index.ts')] + .find(c => c.startsWith(root + path.sep) && fs.existsSync(c) && fs.statSync(c).isFile()); + if (!found) outside.add(`${path.relative(root, file)} -> ${path.relative(root, target)}`); + else if (isBunSource(found)) queue.push(found); + } + } + return [...outside].sort(); +} + beforeAll(async () => { const result = await runGeneration({ host: 'all', outputRoot: renderDir }); if (result.exitCode !== 0) throw new Error(result.diagnostics.filter(d => d.kind === 'error').map(d => d.message).join('\n')); @@ -139,6 +177,26 @@ describe.skipIf(process.platform === 'win32')('runtime roots carry every $GSTACK }); } + for (const host of Object.keys(ROOT_BUILDERS)) { + test(`${host}: every module the skills' commands import is inside the runtime root`, () => { + const { root, status } = buildRoot(host); + expect(status).toBe(0); + expect(importsOutsideRoot(host, root)).toEqual([]); + }); + } + + test('the review planner starts from a copied (Windows) runtime root', () => { + const { root, stderr, status } = buildRoot('codex', true); + expect(stderr).toBe(''); + expect(status).toBe(0); + expect(fs.lstatSync(path.join(root, 'bin')).isSymbolicLink()).toBe(false); + const r = spawnSync(process.execPath, [...bunIsolationArgs(), path.join(root, 'bin', 'gstack-review-plan'), '--help'], + { cwd: tmp, encoding: 'utf8', timeout: 30_000, env: { PATH: process.env.PATH ?? '/usr/bin:/bin', HOME: path.join(tmp, 'home-windows') } }); + expect(r.stderr).not.toContain('Cannot find module'); + expect(r.status).toBe(0); + expect(r.stdout).toContain('--fix-check-prompt'); + }); + test('a runtime root never gains a whole skill directory beside the rendered copies', () => { const { root } = buildRoot('codex'); for (const dir of ['plan-design-review', 'office-hours']) { diff --git a/test/setup-production-deps.test.ts b/test/setup-production-deps.test.ts index 5289b4e1399..38b3e4d1033 100644 --- a/test/setup-production-deps.test.ts +++ b/test/setup-production-deps.test.ts @@ -572,7 +572,8 @@ describe('setup and runtime need only production dependencies', () => { queue.push(target); } } - expect(Object.keys(reached)).toContain('scripts/discover-skills.ts'); + expect(Object.keys(reached)).toContain('scripts/gen-agents-digest.ts'); + expect(Object.keys({ ...files, ...reached })).toContain('scripts/discover-skills.ts'); expect(Object.keys(reached)).toContain('test/helpers/providers/claude.ts'); expect(nonProductionImports(PKG, reached)).toEqual([]); }); From 554390da387d97c8b93dc2337c2ab41d4271e9f4 Mon Sep 17 00:00:00 2001 From: Garry Tan Date: Wed, 11 Nov 2026 06:37:58 -0800 Subject: [PATCH 04/31] Stop the doctor floor test failing on every release that adds no policy key (GST-2441) (#4293) Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- changelog.d/fix-policy-floor-test-on-release-stamps.md | 1 + test/policy-floor-stable.test.ts | 8 +++++--- 2 files changed, 6 insertions(+), 3 deletions(-) create mode 100644 changelog.d/fix-policy-floor-test-on-release-stamps.md diff --git a/changelog.d/fix-policy-floor-test-on-release-stamps.md b/changelog.d/fix-policy-floor-test-on-release-stamps.md new file mode 100644 index 00000000000..2ac5773d505 --- /dev/null +++ b/changelog.d/fix-policy-floor-test-on-release-stamps.md @@ -0,0 +1 @@ +- **The doctor floor-row test no longer fails every release that adds no policy key (GST-2441).** test/policy-floor-stable.test.ts now expects a lagging checkout to read policies as the newest policy key gstack knows, computed from the same key table validatePolicy reads, instead of the repo's own VERSION. Before this, any release stamp past the newest key (v1.99.1.0 in #4291) turned free-tests red. Test-only change; no product code moved. diff --git a/test/policy-floor-stable.test.ts b/test/policy-floor-stable.test.ts index b840f7c0f3c..b90af5d2908 100644 --- a/test/policy-floor-stable.test.ts +++ b/test/policy-floor-stable.test.ts @@ -10,7 +10,8 @@ import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; import { EXIT } from '../lib/headless-artifacts'; -import { runningGstackVersion, validatePolicy } from '../lib/ship-policy'; +import { BUMP_NEVER_KEY_VERSION, POLICY_KEY_INTRODUCED, runningGstackVersion, TRAIN_GATES_KEY_VERSION, validatePolicy } from '../lib/ship-policy'; +import { cmpVersion, parseVersion } from '../lib/version-source'; import { useDoctorCleanup, REPO, makeFixture, doctor, write as writeFile } from './helpers/doctor-fixture'; import { cleanup as cleanupPregate, commit, makeFixtureRepo as makePregateRepo, runBin as runPregateBin, type FixtureRepo as PregateRepo } from './helpers/pregate-fixture'; import { cleanup, makeFixtureRepo, runBin, type FixtureRepo } from './helpers/restamp-fixture'; @@ -187,12 +188,13 @@ describe('gstack-doctor --check floor row', () => { test('an unstamped main checkout gets the verdict validatePolicy gives: the newest policy key it knows counts', () => { const f = makeFixture(); fs.copyFileSync(path.join(REPO, 'lib/ship-policy-keys.ts'), path.join(f.root, 'lib/ship-policy-keys.ts')); - const known = runningGstackVersion(); + const newer = (a: string, b: string) => cmpVersion(parseVersion(a)!, parseVersion(b)!) > 0; + const known = [...Object.values(POLICY_KEY_INTRODUCED), BUMP_NEVER_KEY_VERSION, TRAIN_GATES_KEY_VERSION].reduce((a, b) => (newer(b, a) ? b : a)); const dir = project(f, known); const at = floorRow(f, dir); expect(validatePolicy({ min_gstack_version: known })).toEqual([]); expect(at.status, at.line).toBe('PASS'); - expect(at.line).toBe(known === VERSION ? `PASS floor ${known} declared by ${dir}/.gstack/ship-policy.json (installed ${VERSION})` : `PASS floor ${known} declared by ${dir}/.gstack/ship-policy.json (installed ${VERSION}, reads policies as ${known})`); + expect(at.line).toBe(!newer(known, VERSION) ? `PASS floor ${known} declared by ${dir}/.gstack/ship-policy.json (installed ${VERSION})` : `PASS floor ${known} declared by ${dir}/.gstack/ship-policy.json (installed ${VERSION}, reads policies as ${known})`); // A checkout whose VERSION lags a key it carries reads the key's floor (validatePolicy agrees), so the row passes. writeFile(path.join(f.root, 'VERSION'), '1.0.0.0\n'); const lagging = floorRow(f, project(f, known)); From 2cca89628ce0d94b266e383ffcda9da600a3d0a4 Mon Sep 17 00:00:00 2001 From: Garry Tan Date: Wed, 11 Nov 2026 09:53:14 -0800 Subject: [PATCH 05/31] v1.99.1.0 release (#4291) Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- CHANGELOG.md | 40 +++++++++++++++++++ VERSION | 2 +- agents-digest/gstack-AGENTS.md | 2 +- ...follow-up-review-after-docs-only-commit.md | 4 -- ...ry-files-and-split-authorization-values.md | 4 -- .../capy-catch-secrets-split-across.md | 4 -- changelog.d/capy-fix-ship-queue-ready.md | 1 - changelog.d/capy-make-ship-queue-ready.md | 4 -- .../ci-carry-accepts-unrelated-job-rerun.md | 4 -- changelog.d/drop-review-from-qm-edition.md | 1 - ...nc-scan-escaped-secrets-and-added-lines.md | 4 -- changelog.d/fix-flaky-checks-2026-11-10.md | 1 - ...fix-policy-floor-test-on-release-stamps.md | 1 - ...view-working-in-copied-windows-installs.md | 4 -- ...rulings-close-a-fix-checks-own-blockers.md | 4 -- .../pregate-verify-refuses-partial-run.md | 4 -- .../ship-queue-ready-fetches-base-gst-2232.md | 4 -- ...ll-deleting-nested-and-locked-worktrees.md | 4 -- ...checks-every-folder-it-deletes-gst-2303.md | 6 --- ...uperseded-ci-refuse-unpushed-ready-note.md | 6 --- package.json | 2 +- 21 files changed, 43 insertions(+), 63 deletions(-) delete mode 100644 changelog.d/accept-follow-up-review-after-docs-only-commit.md delete mode 100644 changelog.d/brain-sync-scans-binary-files-and-split-authorization-values.md delete mode 100644 changelog.d/capy-catch-secrets-split-across.md delete mode 100644 changelog.d/capy-fix-ship-queue-ready.md delete mode 100644 changelog.d/capy-make-ship-queue-ready.md delete mode 100644 changelog.d/ci-carry-accepts-unrelated-job-rerun.md delete mode 100644 changelog.d/drop-review-from-qm-edition.md delete mode 100644 changelog.d/fix-brain-sync-scan-escaped-secrets-and-added-lines.md delete mode 100644 changelog.d/fix-flaky-checks-2026-11-10.md delete mode 100644 changelog.d/fix-policy-floor-test-on-release-stamps.md delete mode 100644 changelog.d/keep-review-working-in-copied-windows-installs.md delete mode 100644 changelog.d/let-owner-rulings-close-a-fix-checks-own-blockers.md delete mode 100644 changelog.d/pregate-verify-refuses-partial-run.md delete mode 100644 changelog.d/ship-queue-ready-fetches-base-gst-2232.md delete mode 100644 changelog.d/stop-uninstall-deleting-nested-and-locked-worktrees.md delete mode 100644 changelog.d/uninstall-checks-every-folder-it-deletes-gst-2303.md delete mode 100644 changelog.d/warn-superseded-ci-refuse-unpushed-ready-note.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 89bb3ce23b6..bef44d81dc5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,45 @@ # Changelog +## [1.99.1.0] - 2026-11-11 + +- **/ship now accepts a granted follow-up review that starts after a docs-only commit.** When the docs commit /ship writes after its review landed before the owner granted one more scoped review of a fix, that review's range started at the docs commit, and `gstack-ship-release finish` refused it with `FIX_CHECK: not counted (range_base does not hold the reviewed tree)`, so the reviewed fix counted as unreviewed code. finish now accepts the range when every commit between the reviewed commit and the range start changes only docs or release metadata, and prints a `FIX_CHECK_DOCS_BRIDGE:` line naming those commits. The docs still get their usual recheck. A code or test commit in between, a merge, a range that starts before the reviewed commit, and a range that starts on another branch still refuse. + +- **Brain sync now scans binary files and catches an auth value added under an existing key.** Git shows a file with a NUL byte (or UTF-16 text) as "Binary files differ" instead of its contents, so the push-time secret scan never saw it and an AWS key inside such a note was pushed. The scan now diffs every file as text and also reads lines and edited blocks that hold NUL bytes as UTF-16 and with the NULs removed; if git still reports a file as binary instead of showing its bytes, the file is held as `binary-not-scanned`. A Bearer value added on the line under an unchanged `"authorization":` key also slipped through, because the diff's `+` marker broke the match; each edited block is now also scanned as the new file text, in UTF-16 files too, and a second reading of the diff always shows three unchanged lines around each edit so a `diff.context` setting of 0 cannot hide the key. The diff git normally shows, with your `diff.context` and any textconv driver, is still scanned too, so nothing the old scan held is lost. The pre-commit hook that `gstack-artifacts-init` and `gstack-brain-restore` install gets the same fix; rerun `gstack-artifacts-init` (or `gstack-brain-restore` on a machine you restored) to refresh it. docs/gbrain-sync.md now says plainly that a secret already committed in `~/.gstack` stays held after you delete it, and only `--skip-file` clears it. + +- **A secret split across two lines of UTF-16 text is now caught, and deleting a large binary no longer blocks a push.** The secret check and the pre-push hook read a file git calls binary three ways (as bytes and as little- and big-endian UTF-16), but they kept all three readings on one line. So in a UTF-16 file, an AWS secret key on the line under its `aws_secret_access_key:` key passed both guards, because the keyword line ended with another reading. Each reading is now scanned as its own text with the file's line numbers, so that pair fails in UTF-16LE and UTF-16BE as it does in plain text. The pre-push hook also leaves deleted files out of the diff it scans (`--irreversible-delete`). A delete cannot add a secret, and the old bytes of a deleted 70 MiB binary used to fill the hook's 64 MiB buffer and block the push with `git diff failed (status=killed/overflow)`. Adding a binary that large still blocks, and a replaced binary's old bytes still count toward the limit. + +- **The free test suite is green on main again.** Two `gstack-ship-queue ready` tests still wrote a pre-merge check record with a single check, which `ready` has refused since the pre-merge check started requiring every registered check (GST-2194). Their fixtures now record every check, so the tests exercise what they were written for. No product behavior changed (GST-2282). + +- **Under a merge-train policy, `gstack-ship-queue ready` no longer reports READY when its note never reached origin.** `land --pin` reads the READY note from origin's `refs/notes/gstack-trains`, but `ready` exited 0 even when it couldn't push that note, so a lane sent READY and the land was refused with `QUEUE_NOT_READY` (#4245 lost a land round this way). After pushing, `ready` now fetches origin's notes ref back and prints `notes pushed` only when origin holds the note. If three tries fail, or the push exits 0 and origin still lacks the note, it refuses with `QUEUE_READY_NOTE_UNPUSHED` and keeps the local receipt, so rerunning the same `ready` command once the push works records it (GST-2242). + +- **The CI carry now accepts a run where only an unrelated job was rerun.** Rerunning one job of a green run (a flaky `public-export`, say) made GitHub number the run's newest attempt 2 while the checks job, which wasn't rerun, still carried its attempt-1 `tree.json`, so `accept` refused with `artifact_mismatch`; rerunning the checks job too left two same-named artifacts and refused with `artifact_missing`. Run verification now works out which attempt each profile job actually ran in (GitHub relists a job it didn't rerun with its old start and finish times) and checks `tree.json` against that attempt, and with one artifact per attempt it reads the one from the uploading job's newest attempt. Every other field (head, merge commit, tree, event, job conclusion) is still compared exactly, and an older attempt's artifact is never read in place of the newest. The 24-hour freshness check now dates a run by its own test jobs, so rerunning an unrelated job never makes days-old results look fresh. When the pregate's skipped-tests command fails because the checkout has no installed dependencies, the refusal now says so (GST-2284, harness-evals HARN-56). + +- **The QM edition no longer includes `gstack-review`.** QM's default gstack skills are now just `gstack-plan`. A benchmark of the edition inside QM found that `gstack-review` flagged too many problems without making the reviewed work any better, so it was cut. To update a QM deployment, delete its `sandbox/skills/gstack-review/` folder and run `qm up`. gstack's own `/review` skill is unchanged. + +- **Brain sync now catches secrets hidden behind JSON escapes, and its pre-commit hook checks every family the sync does.** A hand-written learnings or timeline row could slip a Stripe key past the push-time scan by writing it with `\u` escapes, or slip an auth header past it inside an escaped JSON string. The scan now decodes each added line's JSON strings and scans them as well as the raw diff, so both are held. The pre-commit hook that `gstack-artifacts-init` and `gstack-brain-restore` install, which catches a manual `git commit` in `~/.gstack`, checked only the original six families; it now runs the same scanner as brain sync (`bin/gstack-brain-secret-scan.py`), so it also refuses Stripe live keys, Slack and npm tokens and database URLs with a password. Rerun `gstack-artifacts-init` to refresh a hook written by an older gstack. + +- **Six test and eval checks that misread correct work, or raced their own fixtures, now read it right (2026-11-10 daily flaky pass, GST-2338).** ship-docsync-store's fixture interface now declares the `gstack-docs-candidate attempt --state ` call that /ship's documentation step has asked for since #4192, so a model that follows the step is no longer stopped by the fixture (census 42748129558). tpa-absent-darwin no longer counts a gstack-browser option as an Aside drive just because it says Aside isn't available. tpa-present's defer check counts a "the step stays blocked on you" status line only when the option puts the step off ("later", "not yet", "not now"), so a status line after another instruction no longer passes as a defer offer. scrape-prototype-path also credits `$B goto >/dev/null && $B html` when the call proves the goto exited 0. Two free tests stop racing themselves: the CSO lease contender publishes its result file by rename, so the test never reads it empty, and the registry-socket deadline test sets a deadline that expires after the watchdog's startup handshake instead of inside it. No threshold, trial count, case kind or retry changed. + +- **The doctor floor-row test no longer fails every release that adds no policy key (GST-2441).** test/policy-floor-stable.test.ts now expects a lagging checkout to read policies as the newest policy key gstack knows, computed from the same key table validatePolicy reads, instead of the repo's own VERSION. Before this, any release stamp past the newest key (v1.99.1.0 in #4291) turned free-tests red. Test-only change; no product code moved. + +- **/review and /ship start again on Windows under Codex, Cursor and the other non-Claude hosts.** On Windows, setup copies gstack's `bin/` and `lib/` into each host's runtime folder instead of linking them, and it left out three `scripts/` files those commands import. The review planner that /review and /ship run first stopped with `Cannot find module '../scripts/resolvers/fix-check'`, and the commands behind /retro and /write-skill had the same gap. Setup now copies `scripts/resolvers/fix-check.ts`, `scripts/discover-skills.ts` and `scripts/lib/ci-history.ts` too, and a test follows the static imports of the commands each host's skills run, so a new static import outside the runtime folder fails CI. Thanks to @SatriaSuriaAriffin, who found and reported the fix-check gap (#4275). + +- **An owner's ruling now clears the new blockers a granted fix-check found, so /ship can finish with them listed as open notes.** When a granted fix-check finds a new CRITICAL, it logs the finding `open` and stops for the owner. The owner can rule it a disclosed note with `gstack-approvals rule`, but `gstack-ship-release finish` rejected the fix-check as unfinished before it looked at any ruling. It also ignored rulings on `open` findings, so the stop could only end with another fix-check (harness-evals#361, GST-2251). Now, once an approved ruling covers every finding that still holds it open, the fix-check counts at the tree it read, and each ruling is printed and listed in the PR body and receipt. A fix-check with a finding still unruled prints `FIX_CHECK_OPEN:`, which names every finding that still holds it open, including below-floor ones, and the full `gstack-approvals rule` command to run. A finding the lane only marks as accepted in its own review-log row still stays open, and so does a ruling at a head outside the fix-check's range. Edits made after the fix-check still route as post-review changes. + +- **`gstack-pregate verify` no longer passes a record from a partial run.** A `--only ` or `--stage preflight|tests` run used to replace `.gstack/tmp/pregate.json` with only the checks it ran, and `verify` (so also `gstack-ship-queue ready` and `gstack-ship-receipt write`) accepted it as a full pass. So following pregate's own "rerun `--stage tests`" hint after a red full run could clear a secrets failure while the token was still in HEAD, and `--only strays` alone verified as green. Now `verify` refuses with `PREGATE_INCOMPLETE` unless the record holds every registered check, and it names what is missing. The PREGATE line prints `checks=N of M`. A staged or `--only` rerun at the same head, tree, base and policy keeps the checks it skipped from the record it replaces (it prints `PREGATE_MERGED: kept …`), so rerunning one stage keeps an earlier failure and an earlier pass. Any other partial run needs a full `gstack-pregate --allow-repo-commands` at that tree (GST-2194). + +- **`gstack-ship-queue ready` no longer refuses a good receipt because the lane's copy of the base was old.** `ready` read `origin/` as the clone last fetched it, so a lane a few landings behind measured the PR from an older merge base, counted files from PRs that had already landed, and refused with a false `RECEIPT_INVALID field=review_exclude` (gbrain #8991). `ready` now fetches the base before it reads the policy or checks any receipt field, and refuses with the new `QUEUE_BASE_UNFETCHED` when the fetch fails; the stamp path of `land` refuses the same way instead of carrying on with the old ref. The selection itself was already measured from the merge base (the PR's own files), and a new test pins that (GST-2232). + +- **`gstack-uninstall` no longer deletes a worktree nested inside another checkout, a locked worktree, a `.gstack/` that is its own git repo, or a worktree you edit while it asks to continue.** Since #4241 a plain uninstall stops when a `.gstack-worktrees/` checkout holds unsaved work, but it only looked at the top-level checkouts, so a worktree created inside a lane (as gstack does when it runs from inside one) was deleted with its uncommitted edits and exit 0. Now every checkout on disk is checked, nested ones included; a submodule inside a clean lane goes with it only when every commit it holds is on a remote-tracking branch, and otherwise stops the uninstall. A locked worktree (`git worktree lock`) stops the uninstall even with `--force-worktrees`, and the fix line says to `git worktree unlock` it. A `.gstack/` that is its own git repository, and that the project tracks nothing in, is kept with a message saying why, where before it was deleted with any commits it held. The worktree check now runs a second time after you confirm, before anything is removed, so work saved while the confirmation prompt waited is kept. Uninstall exits 2 and removes nothing, even when run from inside the gstack install. A `git worktree list` that fails stops the uninstall instead of letting `--force-worktrees` delete blind. The manual steps in docs/uninstall.md no longer tell you to `rm -rf .gstack .gstack-worktrees`; they remove only what git ignores and only worktrees that pass the same checks (GST-2268). + +- **`gstack-uninstall` now checks every folder it deletes for unsaved git work, not only the repo you run it from.** Each host's install (global and project-local), the gstack-made Claude per-skill folders and `~/.gstack` are searched for git checkouts before anything is removed. One with uncommitted changes, commits no remote-tracking branch holds, or a locked worktree stops the uninstall with exit 2, naming the checkout. Before, an unpushed `.gstack` repo inside `~/.claude/skills/gstack`, an edited project-local install or a notes repo under `.agents/skills/gstack-*` was deleted without a check (GST-2303). +- **`--keep-state` no longer deletes the state it keeps.** Run from inside the gstack checkout, `--keep-state` skipped the worktree check and then deleted the whole install, taking the kept `.gstack-worktrees` lanes and tracked `.gstack` files with it. An install that holds kept state is now refused instead (GST-2303). +- **A locked worktree whose path contains a newline is kept under `--force --force-worktrees`.** The worktree list is now read NUL-separated, so the lock check sees the real path. A clean submodule nested inside another submodule of a clean lane no longer stops the uninstall as unregistered (GST-2303). + +- **`gstack-ship-queue ready` and `land` now say when a red check counted as green only because a run from another check suite replaced it.** A lane that dispatches `free-tests.yml` on its branch after a red `pull_request` run gets a green verdict from the branch-only run, which never tested the merge with main. Both commands now print `CI_SUPERSEDED: red run replaced by (suite
→ )` for each such run. It is a warning only and changes no verdict; a rerun in the same suite prints nothing (GST-2205). +- **Without a train policy, `gstack-ship-queue ready` no longer reports READY when its note never reached origin.** Under `changelog_fragments` it exited 0 even when the READY note push failed, so `land --pin` then refused `QUEUE_NOT_READY` because origin had no note. It now refuses with `QUEUE_READY_NOTE_UNPUSHED`, as the train path does, and rerunning the same `ready` command once the push works records it (GST-2205). +- **`gstack-ship-queue ready` now fetches the base before it picks the train or plain path.** It read the base policy first and fetched only inside plain `ready`, so a clone with no `origin/main` ref, or a stale one, ran plain `ready` under a train policy and skipped the train-only screen, conflict and READY-receipt steps. It now fetches first, and refuses `QUEUE_BASE_UNFETCHED` when it can't (GST-2205). + ## [1.99.0.0] - 2026-11-09 - **The pre-archive check no longer passes a thread whose PR state it can't read.** `gstack-archive-check` treated any PR state other than `OPEN` as closed, so an empty or unknown state from `gh pr view` let a thread with a possibly open PR archive clean. It now accepts only `OPEN`, `CLOSED` and `MERGED` and exits 3 with `ARCHIVE_PR_STATE_UNKNOWN` on anything else, on both `thread` and `landed`. An issue row cut short (no assignee, title or age) is now unreadable instead of a complete row. A failed CI read shows as `ci=unknown (CI read failed: )` on the ORPHAN line, and the open PR still refuses. `landed` with a missing, invalid or empty `.gstack/plain-titles.json` now exits 3 with `ARCHIVE_POLICY_UNREADABLE` instead of treating every code-shaped ref as an issue to close (R91, GST-2241). diff --git a/VERSION b/VERSION index 55dbc3502aa..42588f71a87 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -1.99.0.0 +1.99.1.0 diff --git a/agents-digest/gstack-AGENTS.md b/agents-digest/gstack-AGENTS.md index dd4df1f0e2b..1004c797f85 100644 --- a/agents-digest/gstack-AGENTS.md +++ b/agents-digest/gstack-AGENTS.md @@ -1,4 +1,4 @@ -# gstack digest v1.99.0.0 — regenerate/re-copy after upgrading gstack +# gstack digest v1.99.1.0 — regenerate/re-copy after upgrading gstack Behavioral rules from gstack (https://github.com/garrytan/gstack), compressed for agent hosts without a full skill install. The full skills add workflows, diff --git a/changelog.d/accept-follow-up-review-after-docs-only-commit.md b/changelog.d/accept-follow-up-review-after-docs-only-commit.md deleted file mode 100644 index abcbd8af0cd..00000000000 --- a/changelog.d/accept-follow-up-review-after-docs-only-commit.md +++ /dev/null @@ -1,4 +0,0 @@ ---- -important: blocker ---- -- **/ship now accepts a granted follow-up review that starts after a docs-only commit.** When the docs commit /ship writes after its review landed before the owner granted one more scoped review of a fix, that review's range started at the docs commit, and `gstack-ship-release finish` refused it with `FIX_CHECK: not counted (range_base does not hold the reviewed tree)`, so the reviewed fix counted as unreviewed code. finish now accepts the range when every commit between the reviewed commit and the range start changes only docs or release metadata, and prints a `FIX_CHECK_DOCS_BRIDGE:` line naming those commits. The docs still get their usual recheck. A code or test commit in between, a merge, a range that starts before the reviewed commit, and a range that starts on another branch still refuse. diff --git a/changelog.d/brain-sync-scans-binary-files-and-split-authorization-values.md b/changelog.d/brain-sync-scans-binary-files-and-split-authorization-values.md deleted file mode 100644 index 912149f8782..00000000000 --- a/changelog.d/brain-sync-scans-binary-files-and-split-authorization-values.md +++ /dev/null @@ -1,4 +0,0 @@ ---- -important: security ---- -- **Brain sync now scans binary files and catches an auth value added under an existing key.** Git shows a file with a NUL byte (or UTF-16 text) as "Binary files differ" instead of its contents, so the push-time secret scan never saw it and an AWS key inside such a note was pushed. The scan now diffs every file as text and also reads lines and edited blocks that hold NUL bytes as UTF-16 and with the NULs removed; if git still reports a file as binary instead of showing its bytes, the file is held as `binary-not-scanned`. A Bearer value added on the line under an unchanged `"authorization":` key also slipped through, because the diff's `+` marker broke the match; each edited block is now also scanned as the new file text, in UTF-16 files too, and a second reading of the diff always shows three unchanged lines around each edit so a `diff.context` setting of 0 cannot hide the key. The diff git normally shows, with your `diff.context` and any textconv driver, is still scanned too, so nothing the old scan held is lost. The pre-commit hook that `gstack-artifacts-init` and `gstack-brain-restore` install gets the same fix; rerun `gstack-artifacts-init` (or `gstack-brain-restore` on a machine you restored) to refresh it. docs/gbrain-sync.md now says plainly that a secret already committed in `~/.gstack` stays held after you delete it, and only `--skip-file` clears it. diff --git a/changelog.d/capy-catch-secrets-split-across.md b/changelog.d/capy-catch-secrets-split-across.md deleted file mode 100644 index 2ae07efcf2a..00000000000 --- a/changelog.d/capy-catch-secrets-split-across.md +++ /dev/null @@ -1,4 +0,0 @@ ---- -important: security ---- -- **A secret split across two lines of UTF-16 text is now caught, and deleting a large binary no longer blocks a push.** The secret check and the pre-push hook read a file git calls binary three ways (as bytes and as little- and big-endian UTF-16), but they kept all three readings on one line. So in a UTF-16 file, an AWS secret key on the line under its `aws_secret_access_key:` key passed both guards, because the keyword line ended with another reading. Each reading is now scanned as its own text with the file's line numbers, so that pair fails in UTF-16LE and UTF-16BE as it does in plain text. The pre-push hook also leaves deleted files out of the diff it scans (`--irreversible-delete`). A delete cannot add a secret, and the old bytes of a deleted 70 MiB binary used to fill the hook's 64 MiB buffer and block the push with `git diff failed (status=killed/overflow)`. Adding a binary that large still blocks, and a replaced binary's old bytes still count toward the limit. diff --git a/changelog.d/capy-fix-ship-queue-ready.md b/changelog.d/capy-fix-ship-queue-ready.md deleted file mode 100644 index c4834741794..00000000000 --- a/changelog.d/capy-fix-ship-queue-ready.md +++ /dev/null @@ -1 +0,0 @@ -- **The free test suite is green on main again.** Two `gstack-ship-queue ready` tests still wrote a pre-merge check record with a single check, which `ready` has refused since the pre-merge check started requiring every registered check (GST-2194). Their fixtures now record every check, so the tests exercise what they were written for. No product behavior changed (GST-2282). diff --git a/changelog.d/capy-make-ship-queue-ready.md b/changelog.d/capy-make-ship-queue-ready.md deleted file mode 100644 index c82f422aa6a..00000000000 --- a/changelog.d/capy-make-ship-queue-ready.md +++ /dev/null @@ -1,4 +0,0 @@ ---- -important: blocker ---- -- **Under a merge-train policy, `gstack-ship-queue ready` no longer reports READY when its note never reached origin.** `land --pin` reads the READY note from origin's `refs/notes/gstack-trains`, but `ready` exited 0 even when it couldn't push that note, so a lane sent READY and the land was refused with `QUEUE_NOT_READY` (#4245 lost a land round this way). After pushing, `ready` now fetches origin's notes ref back and prints `notes pushed` only when origin holds the note. If three tries fail, or the push exits 0 and origin still lacks the note, it refuses with `QUEUE_READY_NOTE_UNPUSHED` and keeps the local receipt, so rerunning the same `ready` command once the push works records it (GST-2242). diff --git a/changelog.d/ci-carry-accepts-unrelated-job-rerun.md b/changelog.d/ci-carry-accepts-unrelated-job-rerun.md deleted file mode 100644 index 9fc3e8606f7..00000000000 --- a/changelog.d/ci-carry-accepts-unrelated-job-rerun.md +++ /dev/null @@ -1,4 +0,0 @@ ---- -important: blocker ---- -- **The CI carry now accepts a run where only an unrelated job was rerun.** Rerunning one job of a green run (a flaky `public-export`, say) made GitHub number the run's newest attempt 2 while the checks job, which wasn't rerun, still carried its attempt-1 `tree.json`, so `accept` refused with `artifact_mismatch`; rerunning the checks job too left two same-named artifacts and refused with `artifact_missing`. Run verification now works out which attempt each profile job actually ran in (GitHub relists a job it didn't rerun with its old start and finish times) and checks `tree.json` against that attempt, and with one artifact per attempt it reads the one from the uploading job's newest attempt. Every other field (head, merge commit, tree, event, job conclusion) is still compared exactly, and an older attempt's artifact is never read in place of the newest. The 24-hour freshness check now dates a run by its own test jobs, so rerunning an unrelated job never makes days-old results look fresh. When the pregate's skipped-tests command fails because the checkout has no installed dependencies, the refusal now says so (GST-2284, harness-evals HARN-56). diff --git a/changelog.d/drop-review-from-qm-edition.md b/changelog.d/drop-review-from-qm-edition.md deleted file mode 100644 index 599b83a77fb..00000000000 --- a/changelog.d/drop-review-from-qm-edition.md +++ /dev/null @@ -1 +0,0 @@ -- **The QM edition no longer includes `gstack-review`.** QM's default gstack skills are now just `gstack-plan`. A benchmark of the edition inside QM found that `gstack-review` flagged too many problems without making the reviewed work any better, so it was cut. To update a QM deployment, delete its `sandbox/skills/gstack-review/` folder and run `qm up`. gstack's own `/review` skill is unchanged. diff --git a/changelog.d/fix-brain-sync-scan-escaped-secrets-and-added-lines.md b/changelog.d/fix-brain-sync-scan-escaped-secrets-and-added-lines.md deleted file mode 100644 index 8e7a556a072..00000000000 --- a/changelog.d/fix-brain-sync-scan-escaped-secrets-and-added-lines.md +++ /dev/null @@ -1,4 +0,0 @@ ---- -important: security ---- -- **Brain sync now catches secrets hidden behind JSON escapes, and its pre-commit hook checks every family the sync does.** A hand-written learnings or timeline row could slip a Stripe key past the push-time scan by writing it with `\u` escapes, or slip an auth header past it inside an escaped JSON string. The scan now decodes each added line's JSON strings and scans them as well as the raw diff, so both are held. The pre-commit hook that `gstack-artifacts-init` and `gstack-brain-restore` install, which catches a manual `git commit` in `~/.gstack`, checked only the original six families; it now runs the same scanner as brain sync (`bin/gstack-brain-secret-scan.py`), so it also refuses Stripe live keys, Slack and npm tokens and database URLs with a password. Rerun `gstack-artifacts-init` to refresh a hook written by an older gstack. diff --git a/changelog.d/fix-flaky-checks-2026-11-10.md b/changelog.d/fix-flaky-checks-2026-11-10.md deleted file mode 100644 index 6ba4b653418..00000000000 --- a/changelog.d/fix-flaky-checks-2026-11-10.md +++ /dev/null @@ -1 +0,0 @@ -- **Six test and eval checks that misread correct work, or raced their own fixtures, now read it right (2026-11-10 daily flaky pass, GST-2338).** ship-docsync-store's fixture interface now declares the `gstack-docs-candidate attempt --state ` call that /ship's documentation step has asked for since #4192, so a model that follows the step is no longer stopped by the fixture (census 42748129558). tpa-absent-darwin no longer counts a gstack-browser option as an Aside drive just because it says Aside isn't available. tpa-present's defer check counts a "the step stays blocked on you" status line only when the option puts the step off ("later", "not yet", "not now"), so a status line after another instruction no longer passes as a defer offer. scrape-prototype-path also credits `$B goto >/dev/null && $B html` when the call proves the goto exited 0. Two free tests stop racing themselves: the CSO lease contender publishes its result file by rename, so the test never reads it empty, and the registry-socket deadline test sets a deadline that expires after the watchdog's startup handshake instead of inside it. No threshold, trial count, case kind or retry changed. diff --git a/changelog.d/fix-policy-floor-test-on-release-stamps.md b/changelog.d/fix-policy-floor-test-on-release-stamps.md deleted file mode 100644 index 2ac5773d505..00000000000 --- a/changelog.d/fix-policy-floor-test-on-release-stamps.md +++ /dev/null @@ -1 +0,0 @@ -- **The doctor floor-row test no longer fails every release that adds no policy key (GST-2441).** test/policy-floor-stable.test.ts now expects a lagging checkout to read policies as the newest policy key gstack knows, computed from the same key table validatePolicy reads, instead of the repo's own VERSION. Before this, any release stamp past the newest key (v1.99.1.0 in #4291) turned free-tests red. Test-only change; no product code moved. diff --git a/changelog.d/keep-review-working-in-copied-windows-installs.md b/changelog.d/keep-review-working-in-copied-windows-installs.md deleted file mode 100644 index adfb5ae4a8c..00000000000 --- a/changelog.d/keep-review-working-in-copied-windows-installs.md +++ /dev/null @@ -1,4 +0,0 @@ ---- -important: blocker ---- -- **/review and /ship start again on Windows under Codex, Cursor and the other non-Claude hosts.** On Windows, setup copies gstack's `bin/` and `lib/` into each host's runtime folder instead of linking them, and it left out three `scripts/` files those commands import. The review planner that /review and /ship run first stopped with `Cannot find module '../scripts/resolvers/fix-check'`, and the commands behind /retro and /write-skill had the same gap. Setup now copies `scripts/resolvers/fix-check.ts`, `scripts/discover-skills.ts` and `scripts/lib/ci-history.ts` too, and a test follows the static imports of the commands each host's skills run, so a new static import outside the runtime folder fails CI. Thanks to @SatriaSuriaAriffin, who found and reported the fix-check gap (#4275). diff --git a/changelog.d/let-owner-rulings-close-a-fix-checks-own-blockers.md b/changelog.d/let-owner-rulings-close-a-fix-checks-own-blockers.md deleted file mode 100644 index 77d4cf1d0ac..00000000000 --- a/changelog.d/let-owner-rulings-close-a-fix-checks-own-blockers.md +++ /dev/null @@ -1,4 +0,0 @@ ---- -important: blocker ---- -- **An owner's ruling now clears the new blockers a granted fix-check found, so /ship can finish with them listed as open notes.** When a granted fix-check finds a new CRITICAL, it logs the finding `open` and stops for the owner. The owner can rule it a disclosed note with `gstack-approvals rule`, but `gstack-ship-release finish` rejected the fix-check as unfinished before it looked at any ruling. It also ignored rulings on `open` findings, so the stop could only end with another fix-check (harness-evals#361, GST-2251). Now, once an approved ruling covers every finding that still holds it open, the fix-check counts at the tree it read, and each ruling is printed and listed in the PR body and receipt. A fix-check with a finding still unruled prints `FIX_CHECK_OPEN:`, which names every finding that still holds it open, including below-floor ones, and the full `gstack-approvals rule` command to run. A finding the lane only marks as accepted in its own review-log row still stays open, and so does a ruling at a head outside the fix-check's range. Edits made after the fix-check still route as post-review changes. diff --git a/changelog.d/pregate-verify-refuses-partial-run.md b/changelog.d/pregate-verify-refuses-partial-run.md deleted file mode 100644 index 9b74f93c6e2..00000000000 --- a/changelog.d/pregate-verify-refuses-partial-run.md +++ /dev/null @@ -1,4 +0,0 @@ ---- -important: security ---- -- **`gstack-pregate verify` no longer passes a record from a partial run.** A `--only ` or `--stage preflight|tests` run used to replace `.gstack/tmp/pregate.json` with only the checks it ran, and `verify` (so also `gstack-ship-queue ready` and `gstack-ship-receipt write`) accepted it as a full pass. So following pregate's own "rerun `--stage tests`" hint after a red full run could clear a secrets failure while the token was still in HEAD, and `--only strays` alone verified as green. Now `verify` refuses with `PREGATE_INCOMPLETE` unless the record holds every registered check, and it names what is missing. The PREGATE line prints `checks=N of M`. A staged or `--only` rerun at the same head, tree, base and policy keeps the checks it skipped from the record it replaces (it prints `PREGATE_MERGED: kept …`), so rerunning one stage keeps an earlier failure and an earlier pass. Any other partial run needs a full `gstack-pregate --allow-repo-commands` at that tree (GST-2194). diff --git a/changelog.d/ship-queue-ready-fetches-base-gst-2232.md b/changelog.d/ship-queue-ready-fetches-base-gst-2232.md deleted file mode 100644 index 6e48314c8b3..00000000000 --- a/changelog.d/ship-queue-ready-fetches-base-gst-2232.md +++ /dev/null @@ -1,4 +0,0 @@ ---- -important: blocker ---- -- **`gstack-ship-queue ready` no longer refuses a good receipt because the lane's copy of the base was old.** `ready` read `origin/` as the clone last fetched it, so a lane a few landings behind measured the PR from an older merge base, counted files from PRs that had already landed, and refused with a false `RECEIPT_INVALID field=review_exclude` (gbrain #8991). `ready` now fetches the base before it reads the policy or checks any receipt field, and refuses with the new `QUEUE_BASE_UNFETCHED` when the fetch fails; the stamp path of `land` refuses the same way instead of carrying on with the old ref. The selection itself was already measured from the merge base (the PR's own files), and a new test pins that (GST-2232). diff --git a/changelog.d/stop-uninstall-deleting-nested-and-locked-worktrees.md b/changelog.d/stop-uninstall-deleting-nested-and-locked-worktrees.md deleted file mode 100644 index c57105869e1..00000000000 --- a/changelog.d/stop-uninstall-deleting-nested-and-locked-worktrees.md +++ /dev/null @@ -1,4 +0,0 @@ ---- -important: data-loss ---- -- **`gstack-uninstall` no longer deletes a worktree nested inside another checkout, a locked worktree, a `.gstack/` that is its own git repo, or a worktree you edit while it asks to continue.** Since #4241 a plain uninstall stops when a `.gstack-worktrees/` checkout holds unsaved work, but it only looked at the top-level checkouts, so a worktree created inside a lane (as gstack does when it runs from inside one) was deleted with its uncommitted edits and exit 0. Now every checkout on disk is checked, nested ones included; a submodule inside a clean lane goes with it only when every commit it holds is on a remote-tracking branch, and otherwise stops the uninstall. A locked worktree (`git worktree lock`) stops the uninstall even with `--force-worktrees`, and the fix line says to `git worktree unlock` it. A `.gstack/` that is its own git repository, and that the project tracks nothing in, is kept with a message saying why, where before it was deleted with any commits it held. The worktree check now runs a second time after you confirm, before anything is removed, so work saved while the confirmation prompt waited is kept. Uninstall exits 2 and removes nothing, even when run from inside the gstack install. A `git worktree list` that fails stops the uninstall instead of letting `--force-worktrees` delete blind. The manual steps in docs/uninstall.md no longer tell you to `rm -rf .gstack .gstack-worktrees`; they remove only what git ignores and only worktrees that pass the same checks (GST-2268). diff --git a/changelog.d/uninstall-checks-every-folder-it-deletes-gst-2303.md b/changelog.d/uninstall-checks-every-folder-it-deletes-gst-2303.md deleted file mode 100644 index 0a0fef0ee01..00000000000 --- a/changelog.d/uninstall-checks-every-folder-it-deletes-gst-2303.md +++ /dev/null @@ -1,6 +0,0 @@ ---- -important: data-loss ---- -- **`gstack-uninstall` now checks every folder it deletes for unsaved git work, not only the repo you run it from.** Each host's install (global and project-local), the gstack-made Claude per-skill folders and `~/.gstack` are searched for git checkouts before anything is removed. One with uncommitted changes, commits no remote-tracking branch holds, or a locked worktree stops the uninstall with exit 2, naming the checkout. Before, an unpushed `.gstack` repo inside `~/.claude/skills/gstack`, an edited project-local install or a notes repo under `.agents/skills/gstack-*` was deleted without a check (GST-2303). -- **`--keep-state` no longer deletes the state it keeps.** Run from inside the gstack checkout, `--keep-state` skipped the worktree check and then deleted the whole install, taking the kept `.gstack-worktrees` lanes and tracked `.gstack` files with it. An install that holds kept state is now refused instead (GST-2303). -- **A locked worktree whose path contains a newline is kept under `--force --force-worktrees`.** The worktree list is now read NUL-separated, so the lock check sees the real path. A clean submodule nested inside another submodule of a clean lane no longer stops the uninstall as unregistered (GST-2303). diff --git a/changelog.d/warn-superseded-ci-refuse-unpushed-ready-note.md b/changelog.d/warn-superseded-ci-refuse-unpushed-ready-note.md deleted file mode 100644 index 9cee845e298..00000000000 --- a/changelog.d/warn-superseded-ci-refuse-unpushed-ready-note.md +++ /dev/null @@ -1,6 +0,0 @@ ---- -important: blocker ---- -- **`gstack-ship-queue ready` and `land` now say when a red check counted as green only because a run from another check suite replaced it.** A lane that dispatches `free-tests.yml` on its branch after a red `pull_request` run gets a green verdict from the branch-only run, which never tested the merge with main. Both commands now print `CI_SUPERSEDED: red run replaced by (suite → )` for each such run. It is a warning only and changes no verdict; a rerun in the same suite prints nothing (GST-2205). -- **Without a train policy, `gstack-ship-queue ready` no longer reports READY when its note never reached origin.** Under `changelog_fragments` it exited 0 even when the READY note push failed, so `land --pin` then refused `QUEUE_NOT_READY` because origin had no note. It now refuses with `QUEUE_READY_NOTE_UNPUSHED`, as the train path does, and rerunning the same `ready` command once the push works records it (GST-2205). -- **`gstack-ship-queue ready` now fetches the base before it picks the train or plain path.** It read the base policy first and fetched only inside plain `ready`, so a clone with no `origin/main` ref, or a stale one, ran plain `ready` under a train policy and skipped the train-only screen, conflict and READY-receipt steps. It now fetches first, and refuses `QUEUE_BASE_UNFETCHED` when it can't (GST-2205). diff --git a/package.json b/package.json index 4a13870c3de..0a427d1f338 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "gstack", - "version": "1.99.0", + "version": "1.99.1", "description": "Garry's Stack — Claude Code skills + fast headless browser. One repo, one install, entire AI engineering workflow.", "license": "MIT", "type": "module", From 19ed2ac5bbe82f681627fbb097b4992a66929c4c Mon Sep 17 00:00:00 2001 From: Garry Tan Date: Wed, 11 Nov 2026 09:59:26 -0800 Subject: [PATCH 06/31] Let browser checks and question preferences work from non-Claude hosts' gstack folders (GST-2442) (#4292) * Let browser checks and question preferences work from non-Claude hosts' gstack folders (GST-2442) gstack-browser-ensure looked for Playwright only in the host's gstack folder, which has no package.json or node_modules, so every browser skill on Codex, Cursor and the other non-Claude hosts reported Playwright missing. It now uses the checkout recorded in .source-path, but only when the folder has no package.json of its own and the pointer is a regular file naming an absolute path whose real directory holds gstack's package.json and this helper, neither a link. Anything else keeps the folder, as before, and --check never writes. Setup also copies scripts/one-way-doors.ts and scripts/psychographic-signals.ts into those folders: the question-preference helper loads them at run time, so its --check and --signal-keys failed with "Cannot find module". Co-authored-by: SatriaSuriaAriffin <57977752+SatriaSuriaAriffin@users.noreply.github.com> Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * Split a run-on sentence in the copied-installs changelog entry Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --------- Co-authored-by: SatriaSuriaAriffin <57977752+SatriaSuriaAriffin@users.noreply.github.com> Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- bin/gstack-browser-ensure | 17 ++++ ...stalls-find-browser-and-question-helper.md | 4 + setup | 5 +- test/gstack-browser-ensure.test.ts | 91 +++++++++++++++++++ test/runtime-root-assets.test.ts | 23 +++++ 5 files changed, 139 insertions(+), 1 deletion(-) create mode 100644 changelog.d/copied-installs-find-browser-and-question-helper.md diff --git a/bin/gstack-browser-ensure b/bin/gstack-browser-ensure index 5f8605f4ec2..0f87e327469 100755 --- a/bin/gstack-browser-ensure +++ b/bin/gstack-browser-ensure @@ -27,6 +27,23 @@ set -u GSTACK_BUN_CONFIG=/dev/null; case "${OSTYPE:-}" in msys*|cygwin*) if command -v cygpath >/dev/null 2>&1; then GSTACK_BUN_CONFIG=NUL; fi ;; esac ROOT="$(cd "$(dirname "$0")/.." && pwd -P)" || { echo "gstack-browser-ensure: cannot resolve the install root" >&2; exit 1; } +# A host runtime root (~/.codex/skills/gstack, ...) has no package.json or +# node_modules; setup records the gstack checkout it came from in .source-path. +# Use that checkout's dependencies only when the pointer is a regular file +# holding an absolute path whose real directory has gstack's own package.json +# and this helper, neither a link. Anything else keeps the root, as before. +if [ ! -e "$ROOT/package.json" ] && [ -f "$ROOT/.source-path" ] && [ ! -L "$ROOT/.source-path" ]; then + _src=$(head -1 "$ROOT/.source-path" | tr -d '\r') + case "$_src" in + /*|[A-Za-z]:/*) _src=$(cd "$_src" 2>/dev/null && pwd -P) || _src="" ;; + *) _src="" ;; + esac + if [ -n "$_src" ] && [ -f "$_src/package.json" ] && [ ! -L "$_src/package.json" ] \ + && [ -f "$_src/bin/gstack-browser-ensure" ] && [ ! -L "$_src/bin/gstack-browser-ensure" ] \ + && grep -Eq '^[[:space:]]*"name":[[:space:]]*"gstack",?[[:space:]]*$' "$_src/package.json"; then + ROOT="$_src" + fi +fi DOCS="https://github.com/garrytan/gstack/blob/main/docs/troubleshooting.md#browser-ensure-failed" CHECK=0 QUIET=0 WITH_DEPS="" for _arg in "$@"; do diff --git a/changelog.d/copied-installs-find-browser-and-question-helper.md b/changelog.d/copied-installs-find-browser-and-question-helper.md new file mode 100644 index 00000000000..4bb064216d7 --- /dev/null +++ b/changelog.d/copied-installs-find-browser-and-question-helper.md @@ -0,0 +1,4 @@ +--- +important: blocker +--- +- **Browser skills and question preferences work again from Codex, Cursor and the other non-Claude hosts' gstack folders.** Setup gives each of those hosts its own gstack folder (`~/.codex/skills/gstack` and the like) with no `package.json` or `node_modules`, and records the gstack checkout it came from in `.source-path`. `gstack-browser-ensure`, which every browser skill runs first, looked for Playwright only in that folder, so it reported `BROWSER_UNAVAILABLE playwright is not installed` even when the checkout had it. It now uses the checkout's dependencies, but only when the folder has no `package.json` of its own and `.source-path` is a regular file naming an absolute path whose real directory holds gstack's own `package.json` and `bin/gstack-browser-ensure`, neither one a link. An empty, stale, relative or linked pointer, or a directory that isn't gstack, is ignored as before, and `--check` still never writes. Setup also now puts `scripts/one-way-doors.ts` and `scripts/psychographic-signals.ts` in those folders. The question-preference helper loads them at run time, so its `--check` and `--signal-keys` stopped with `Cannot find module './scripts/one-way-doors.ts'`. Thanks to @SatriaSuriaAriffin, who found and reported both (#4290). diff --git a/setup b/setup index c969f3d7d94..f47cfec6915 100755 --- a/setup +++ b/setup @@ -793,7 +793,9 @@ _link_or_copy() { # And crew/lib, which bin and lib import (the crew/ move, GST-1833), plus the # scripts/ modules they import: a root whose bin and lib are copies (Windows) # needs them beside it to start (/review and /ship's review planner imports -# fix-check.ts). +# fix-check.ts), and the two classifiers bin/gstack-question-preference +# imports inside its bun -e (one-way-doors.ts, psychographic-signals.ts), +# which the import walk cannot see. # Pinned by test/runtime-root-assets.test.ts, which also follows those imports. A destination that already exists # as a real entry is left alone: in the repo-local sidecar review/ is a link to # the source, so its files already resolve and must never be linked over. @@ -816,6 +818,7 @@ _link_runtime_dists() { done for f in VERSION scripts/jargon-list.json scripts/question-registry.ts \ scripts/resolvers/fix-check.ts scripts/discover-skills.ts scripts/lib/ci-history.ts \ + scripts/one-way-doors.ts scripts/psychographic-signals.ts \ docs/askuserquestion-split.md docs/askuserquestion-cjk.md docs/test-value-bar.md \ review/checklist.md review/design-checklist.md review/greptile-triage.md review/TODOS-format.md \ plan-devex-review/dx-hall-of-fame.md; do diff --git a/test/gstack-browser-ensure.test.ts b/test/gstack-browser-ensure.test.ts index 31f2a684e64..4e4d9a71c7b 100644 --- a/test/gstack-browser-ensure.test.ts +++ b/test/gstack-browser-ensure.test.ts @@ -57,6 +57,97 @@ function fixture(opts: { playwright?: boolean } = {}) { const lastLine = (s: string) => s.trim().split('\n').at(-1); +// Value: protects=a runtime root with no package.json (~/.codex/skills/gstack and +// the other host roots) probes the dependencies of the gstack checkout its +// .source-path names, and only of a real gstack checkout; fails_when=the +// helper ignores the pointer, or follows an empty, stale, relative, linked or +// non-gstack one, or lets a pointer override a root's own package.json, or +// --check writes anything; why_new=no fixture had a .source-path; +// seam=none; no_claim=a real Chromium launch (Playwright is a stub). +describe('gstack-browser-ensure in a runtime root without package.json', () => { + const playwrightStub = (version: string) => + `module.exports.chromium = { launch: async () => ({ version: () => ${JSON.stringify(version)}, close: async () => {}, newPage: async () => ({ setContent: async () => {}, title: async () => "gstack smoke test" }) }) };\n`; + function runtime(checkoutName = 'checkout') { + const f = fixture({ playwright: false }); + const checkout = path.join(f.base, checkoutName); + write(path.join(checkout, 'package.json'), '{\n "name": "gstack",\n "version": "0.0.0"\n}\n'); + write(path.join(checkout, 'bin/gstack-browser-ensure'), '#!/usr/bin/env bash\n', 0o755); + write(path.join(checkout, 'node_modules/playwright/index.js'), playwrightStub('141.1.0')); + const point = (text: string) => write(path.join(f.root, '.source-path'), text); + const tree = () => walkFiles(f.base).filter(p => !p.startsWith(path.join(f.base, 'stub'))).sort(); + return { ...f, checkout, point, tree }; + } + const walkFiles = (dir: string): string[] => fs.readdirSync(dir, { withFileTypes: true }) + .flatMap(e => e.isDirectory() ? walkFiles(path.join(dir, e.name)) : [path.join(dir, e.name)]); + const unavailable = (root: string) => `BROWSER_UNAVAILABLE playwright is not installed under ${root}/node_modules`; + + for (const [label, name, eol] of [ + ['the recorded checkout', 'checkout', '\n'], + ['a checkout path with spaces', 'gstack checkout', '\n'], + ['a CRLF pointer', 'checkout', '\r\n'], + ] as const) { + test(`--check probes ${label} and writes nothing`, () => { + const f = runtime(name); + f.point(f.checkout + eol); + const files = f.tree(); + const r = f.run(['--check']); + expect(r.status, r.stdout + r.stderr).toBe(0); + expect(lastLine(r.stdout)).toBe('BROWSER_OK node 141.1.0'); + expect(f.tree()).toEqual(files); + expect(f.calls()).toBe(''); + }); + } + + test('without --check a valid pointer is a probe only, and a link to the checkout resolves to it', () => { + const f = runtime(); + const link = path.join(f.base, 'checkout-link'); + fs.symlinkSync(f.checkout, link); + f.point(link + '\n'); + const r = f.run(); + expect(r.status, r.stdout + r.stderr).toBe(0); + expect(lastLine(r.stdout)).toBe('BROWSER_OK node 141.1.0'); + expect(fs.existsSync(path.join(f.root, 'node_modules'))).toBe(false); + expect(f.calls()).toBe(''); + }); + + const refused: Array<[string, (f: ReturnType) => void]> = [ + ['an empty pointer', f => f.point('\n')], + ['a stale pointer', f => f.point(path.join(f.base, 'gone') + '\n')], + ['a relative pointer', f => f.point(path.relative(process.cwd(), f.checkout) + '\n')], + ['a pointer file that is a link', f => { write(path.join(f.base, 'elsewhere'), f.checkout + '\n'); fs.symlinkSync(path.join(f.base, 'elsewhere'), path.join(f.root, '.source-path')); }], + ['a directory whose package.json is not gstack\'s', f => { write(path.join(f.checkout, 'package.json'), '{\n "name": "left-pad"\n}\n'); f.point(f.checkout + '\n'); }], + ['a directory whose package.json is a link', f => { + write(path.join(f.base, 'real-package.json'), fs.readFileSync(path.join(f.checkout, 'package.json'), 'utf8')); + fs.rmSync(path.join(f.checkout, 'package.json')); + fs.symlinkSync(path.join(f.base, 'real-package.json'), path.join(f.checkout, 'package.json')); + f.point(f.checkout + '\n'); + }], + ['a directory without gstack-browser-ensure', f => { fs.rmSync(path.join(f.checkout, 'bin'), { recursive: true }); f.point(f.checkout + '\n'); }], + ]; + for (const [label, setUp] of refused) { + test(`--check ignores ${label} and reports the runtime root, as before`, () => { + const f = runtime(); + setUp(f); + const files = f.tree(); + const r = f.run(['--check']); + expect(r.status, r.stdout + r.stderr).toBe(1); + expect(lastLine(r.stdout)).toBe(unavailable(f.root)); + expect(f.tree()).toEqual(files); + expect(f.calls()).toBe(''); + }); + } + + test('a root with its own package.json keeps its own dependencies over a valid pointer', () => { + const f = runtime(); + write(path.join(f.root, 'package.json'), '{\n "name": "gstack"\n}\n'); + write(path.join(f.root, 'node_modules/playwright/index.js'), playwrightStub('142.2.0')); + f.point(f.checkout + '\n'); + const r = f.run(['--check']); + expect(r.status, r.stdout + r.stderr).toBe(0); + expect(lastLine(r.stdout)).toBe('BROWSER_OK node 142.2.0'); + }); +}); + describe('gstack-browser-ensure', () => { test('--check never installs: unavailable Chromium is BROWSER_UNAVAILABLE, exit 1, with the fix line and code', () => { const f = fixture(); diff --git a/test/runtime-root-assets.test.ts b/test/runtime-root-assets.test.ts index 5e5cb3635e7..be5647d4725 100644 --- a/test/runtime-root-assets.test.ts +++ b/test/runtime-root-assets.test.ts @@ -197,6 +197,29 @@ describe.skipIf(process.platform === 'win32')('runtime roots carry every $GSTACK expect(r.stdout).toContain('--fix-check-prompt'); }); + // Value: protects=the question helper's --check and --signal-keys start from a + // runtime root, linked or copied; fails_when=setup's asset list drops + // scripts/one-way-doors.ts or scripts/psychographic-signals.ts; + // why_new=the helper imports them inside a bash-quoted bun -e, which the + // static import walk above cannot see; seam=none; no_claim=native Windows. + for (const windows of [false, true]) { + test(`the question helper's checks start from a ${windows ? 'copied (Windows)' : 'linked'} runtime root`, () => { + const { root, stderr, status } = buildRoot('codex', windows); + expect(stderr).toBe(''); + expect(status).toBe(0); + const home = path.join(tmp, windows ? 'home-windows' : 'home'); + for (const [args, expected] of [[['--check', 'land-and-deploy-merge'], 'ASK_NORMALLY'], [['--signal-keys'], 'scope-appetite']] as const) { + const r = spawnSync('bash', [path.join(root, 'bin', 'gstack-question-preference'), ...args], { + cwd: tmp, encoding: 'utf8', timeout: 30_000, + env: { PATH: process.env.PATH ?? '/usr/bin:/bin', HOME: home, GSTACK_STATE_ROOT: path.join(home, 'question-state') }, + }); + expect(r.stderr).not.toContain('Cannot find module'); + expect(r.status, r.stdout + r.stderr).toBe(0); + expect(r.stdout).toContain(expected); + } + }); + } + test('a runtime root never gains a whole skill directory beside the rendered copies', () => { const { root } = buildRoot('codex'); for (const dir of ['plan-design-review', 'office-hours']) { From 0ead11c8e20a82e249f36c3abf89599dfe602324 Mon Sep 17 00:00:00 2001 From: Garry Tan Date: Wed, 11 Nov 2026 11:18:15 -0800 Subject: [PATCH 07/31] Stop the stable cut counting its own check runs against the commit it cuts (GST-2463) (#4297) * Stop the stable cut counting its own check runs against the commit it cuts (GST-2463) Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * Match the stable cut's own check runs by job, not by check suite (GST-2463) GitHub files a check run another workflow creates through the API (main-backstop from release-gate.yml and evals-main-backstop.yml) under any github-actions check suite on the commit, so suite membership could hide a red main-backstop. The cut now lists the jobs of its own workflow runs and sets aside only check runs whose id is one of those job ids. Review-Finding: p1/red-team#1 reader=red-team Review-Finding: p1/adversarial-native#1 reader=adversarial-native Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * Say that the stable cut's own-run lookup needs actions: read and fails safe (GST-2463) Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --------- Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- .github/workflows/weekly-release.yml | 3 + .../stable-cut-ignores-its-own-check-runs.md | 4 + crew/scripts/release-cut.ts | 23 +++++- crew/test/release-cut.test.ts | 79 ++++++++++++++++++- docs/releases.md | 8 +- test/weekly-release-workflow.test.ts | 4 +- 6 files changed, 113 insertions(+), 8 deletions(-) create mode 100644 changelog.d/stable-cut-ignores-its-own-check-runs.md diff --git a/.github/workflows/weekly-release.yml b/.github/workflows/weekly-release.yml index 768dfcf4f4e..3c9ea8756a1 100644 --- a/.github/workflows/weekly-release.yml +++ b/.github/workflows/weekly-release.yml @@ -77,6 +77,8 @@ jobs: contents: write # Reads the candidate's check runs. checks: read + # Finds this workflow's own runs on the candidate, whose check runs the gate sets aside. + actions: read # A security or regression cut reads the label on the # its reason names. issues: read pull-requests: read @@ -143,6 +145,7 @@ jobs: permissions: contents: read checks: read + actions: read steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: diff --git a/changelog.d/stable-cut-ignores-its-own-check-runs.md b/changelog.d/stable-cut-ignores-its-own-check-runs.md new file mode 100644 index 00000000000..c0a6dbf2013 --- /dev/null +++ b/changelog.d/stable-cut-ignores-its-own-check-runs.md @@ -0,0 +1,4 @@ +--- +important: blocker +--- +- **The stable release no longer blocks itself on its own check run.** The daily cut runs on main's newest commit, so its own "Cut the release" job showed up as a check run on the very commit it might release. While the cut ran, that commit looked unfinished and was skipped; when a cut failed, its red check run kept that commit out of every later cut. On 2026-11-11 this held v1.99.1.0 back after the release gate had passed it. The cut now sets aside check runs that belong to its own workflow (`.github/workflows/weekly-release.yml`, matched through the GitHub Actions run that produced them, not by job name) and judges every other check run exactly as before: a red or running check from any other workflow, a missing or running `free-tests`, a missing gate, a RED release record and a freeze still refuse. The workflow now also needs `actions: read` to look up its own runs; if that lookup fails, nothing is set aside and the cut behaves as it did before. diff --git a/crew/scripts/release-cut.ts b/crew/scripts/release-cut.ts index 8a10caf622f..167b7b3fa1f 100755 --- a/crew/scripts/release-cut.ts +++ b/crew/scripts/release-cut.ts @@ -19,7 +19,13 @@ * failed, and the trains notes ref (--notes-ref, default * refs/notes/gstack-trains) holds no active freeze. The newest such commit in * the window (7 days, 200 first-parent commits) is the candidate; a commit - * with a check run still going is skipped, not waited for. + * with a check run still going is skipped, not waited for. Check runs this + * workflow produced itself (CUT_WORKFLOW: the jobs of a workflow run whose path + * is that file; a job's id is its check run's id) are set aside, running or + * finished: a cut lands its own job on main's head, the commit it may cut. + * Matching by job, not check suite, keeps check runs other workflows create + * through the API, which GitHub files under any github-actions suite on the + * commit. When the workflow runs cannot be read, nothing is set aside. * * Gated means one of three kinds of evidence. Either the backstop check run * (--backstop-check, default main-backstop) succeeded: evals-main-backstop.yml @@ -70,6 +76,7 @@ export type Git = (args: string[]) => { ok: boolean; out: string }; export const REQUIRED_CHECK = 'free-tests'; export const BACKSTOP_CHECK = 'main-backstop'; export const NOTES_REF = 'refs/notes/gstack-trains'; +export const CUT_WORKFLOW = '.github/workflows/weekly-release.yml'; const NOTES_LOCAL = 'refs/notes/gstack-trains-release'; const RED = new Set(['failure', 'timed_out', 'cancelled', 'action_required', 'startup_failure', 'stale']); export const WINDOW_DAYS = 7; @@ -103,7 +110,7 @@ export function compareVersions(a: string, b: string): number { /** Green names what gated the commit: the backstop check's name, or `train `. Pending means a check run on it is still going. */ export type Verdict = { green: true; via: string } | { green: false; why: string; pending: boolean }; -interface CheckRun { name: string; status: string; conclusion: string | null } +interface CheckRun { id?: number; name: string; status: string; conclusion: string | null } /** Main commits a green, merging or merged train record lists in merged[], by sha and by tree, each naming the train; `release` maps a commit a green release gate passed to its run (crew/lib/release-gate.ts). */ export interface TrainEvidence { bySha: Map; byTree: Map; release?: Map } @@ -116,7 +123,17 @@ export function gateVerdict(gh: Gh, repo: string, sha: string, o: GateOptions = const paged = parseJson(gh(['api', '--paginate', '--slurp', `repos/${repo}/commits/${sha}/check-runs?per_page=100`])); if (!paged) return { green: false, why: 'cannot read its check runs', pending: false }; const pages = (Array.isArray(paged) ? paged : [paged]) as Array<{ check_runs?: CheckRun[] }>; - const runs = pages.flatMap(p => p.check_runs ?? []); + let runs = pages.flatMap(p => p.check_runs ?? []); + if (runs.some(c => c.status !== 'completed' || RED.has(c.conclusion ?? ''))) { + const wf = parseJson(gh(['api', '--paginate', '--slurp', `repos/${repo}/actions/runs?head_sha=${sha}&per_page=100`])); + const wfRuns = (Array.isArray(wf) ? wf : wf ? [wf] : []) as Array<{ workflow_runs?: Array<{ id?: number; path?: string }> }>; + const own = new Set(); + for (const w of wfRuns.flatMap(p => p.workflow_runs ?? []).filter(w => w.path === CUT_WORKFLOW && typeof w.id === 'number')) { + const jobs = parseJson(gh(['api', '--paginate', '--slurp', `repos/${repo}/actions/runs/${w.id}/jobs?filter=all&per_page=100`])); + for (const p of (Array.isArray(jobs) ? jobs : jobs ? [jobs] : []) as Array<{ jobs?: Array<{ id?: number }> }>) for (const j of p.jobs ?? []) if (typeof j.id === 'number') own.add(j.id); + } + runs = runs.filter(c => !(typeof c.id === 'number' && own.has(c.id))); + } let via = backstop; for (const name of [required, backstop]) { const named = runs.filter(c => c.name === name); diff --git a/crew/test/release-cut.test.ts b/crew/test/release-cut.test.ts index 5ca1c5fb88c..7abf1470957 100644 --- a/crew/test/release-cut.test.ts +++ b/crew/test/release-cut.test.ts @@ -13,8 +13,8 @@ import * as path from 'node:path'; import { bunIsolationArgs } from '../../lib/bun-isolation'; import { gitFixtureTemplate, rebindGitDir } from '../../test/helpers/git-fixture-template'; import { - BACKSTOP_CHECK, FLOOR_HOURS, NOTES_CAP, NOTES_REF, REQUIRED_CHECK, SCHEDULED_GRACE_HOURS, changelogEntries, compareVersions, cutRelease, describePlan, floorStatus, - gateVerdict, gitIn, planRelease, readTrainNotes, releaseNotes, sanitizeReason, stableMovedAt, verifyRegression, verifySecurity, type Gh, type Git, + BACKSTOP_CHECK, CUT_WORKFLOW, FLOOR_HOURS, NOTES_CAP, NOTES_REF, REQUIRED_CHECK, SCHEDULED_GRACE_HOURS, changelogEntries, compareVersions, cutRelease, describePlan, floorStatus, + gateVerdict, gitIn, planRelease, readTrainNotes, releaseNotes, sanitizeReason, stableMovedAt, verifyRegression, verifySecurity, type Gh, type Git, type TrainEvidence, } from '../scripts/release-cut'; const bases: string[] = []; @@ -306,6 +306,81 @@ describe('release-cut: the release gate holds and gates (crew/lib/release-gate.t }); }); +describe('release-cut: the cut sets aside its own check runs (GST-2463)', () => { + const OWN_JOB = 70001; + const ownRun = (status: string, conclusion: string | null, id = OWN_JOB) => ({ id, name: 'Cut the release', status, conclusion }) as CheckRun; + const workflowRuns = (sha: string, runs: Array<{ id: number; path: string; jobs: number[] }>) => Object.assign( + { ['repos/o/r/actions/runs?head_sha=' + sha + '&per_page=100']: [{ total_count: runs.length, workflow_runs: runs.map(({ id, path }) => ({ id, path, check_suite_id: id })) }] }, + ...runs.map(r => ({ ['repos/o/r/actions/runs/' + r.id + '/jobs?filter=all&per_page=100']: [{ total_count: r.jobs.length, jobs: r.jobs.map(id => ({ id })) }] }))); + const ownWorkflow = { id: 9001, path: CUT_WORKFLOW, jobs: [OWN_JOB] }; + const unbacked = GREEN.filter(c => c.name !== BACKSTOP_CHECK); + const gatedBy = (sha: string, run: string): TrainEvidence => ({ bySha: new Map(), byTree: new Map(), release: new Map([[sha, run]]) }); + const sha = 'c'.repeat(40); + const ghFor = (checks: CheckRun[], api: Record = workflowRuns(sha, [ownWorkflow, { id: 555, path: '.github/workflows/evals.yml', jobs: [70555] }])) => + fakeGh({ checks: { [sha]: checks }, released: new Set(), calls: [], api }); + + // Value: protects=the stable cut's own check run (in progress while it runs, red once it fails) never keeps a commit gated by a GREEN release record out + // of the cut, while a red or running check run from any other workflow, a running required check, a missing gate, a same-named job of another + // workflow and a check run another workflow created through the API (which GitHub may file under the cut's check suite) still do, and an unreadable + // workflow-runs API sets nothing aside; fails_when=the cut skips main's head because its own job is still running, a failed cut poisons the commit, + // or the exclusion is keyed on the display name or the check suite; why_new=gateVerdict judged every check run on the commit, including the cut's + // own (run 43076123863 on 19ed2ac5); seam=gh is faked with the check-runs, actions/runs and jobs payload shapes; no_claim=a live workflow run + test('gateVerdict: the cut\'s own running or failed check run is set aside; every other not-green signal still refuses', () => { + const evidence = gatedBy(sha, '43072520821'); + for (const own of [ownRun('in_progress', null), ownRun('queued', null), ownRun('completed', 'failure')]) { + expect(gateVerdict(ghFor([...unbacked, own]), 'o/r', sha, { evidence })).toEqual({ green: true, via: 'release gate run 43072520821' }); + } + expect(gateVerdict(ghFor([...unbacked, ownRun('completed', 'failure'), { name: 'quality', status: 'completed', conclusion: 'failure' }]), 'o/r', sha, { evidence })) + .toEqual({ green: false, why: 'red check runs: quality', pending: false }); + expect(gateVerdict(ghFor([...unbacked, ownRun('completed', 'failure', 70555)]), 'o/r', sha, { evidence })) + .toEqual({ green: false, why: 'red check runs: Cut the release', pending: false }); + expect(gateVerdict(ghFor([...unbacked, ownRun('in_progress', null, 80002)]), 'o/r', sha, { evidence })) + .toEqual({ green: false, why: 'check runs still going: Cut the release', pending: true }); + expect(gateVerdict(ghFor([...unbacked, ownRun('completed', 'failure'), { id: 80001, name: BACKSTOP_CHECK, status: 'completed', conclusion: 'failure', app: { slug: 'github-actions' }, check_suite: { id: 9001 } } as CheckRun]), 'o/r', sha, { evidence })) + .toEqual({ green: false, why: 'red check runs: ' + BACKSTOP_CHECK, pending: false }); + expect(gateVerdict(ghFor([{ name: REQUIRED_CHECK, status: 'in_progress', conclusion: null }, ownRun('in_progress', null)]), 'o/r', sha, { evidence })) + .toEqual({ green: false, why: REQUIRED_CHECK + ' is still running', pending: true }); + expect(gateVerdict(ghFor([...unbacked, ownRun('completed', 'failure')]), 'o/r', sha)) + .toEqual({ green: false, why: 'no ' + BACKSTOP_CHECK + ' check run', pending: false }); + expect(gateVerdict(ghFor([...unbacked, ownRun('completed', 'failure')], {}), 'o/r', sha, { evidence })) + .toEqual({ green: false, why: 'red check runs: Cut the release', pending: false }); + }); + + const note = (f: ReturnType, record: unknown, on: string) => { + git(f.seed, 'notes', '--ref=' + NOTES_REF, 'add', '-f', '-m', JSON.stringify(record), on); + git(f.seed, 'push', '-q', '-f', 'origin', NOTES_REF); + }; + const releaseRecord = (on: string, verdict: string, run: number) => ({ schema: 1, kind: 'release', repo_key: 'k', sha: on, verdict, run: { id: run, url: 'u' }, red_cases: verdict === 'RED' ? ['case-a'] : [], created_at: 'x', updated_at: 'x' }); + + // Value: protects=the 11-11 deadlock: with main's head still running its backstop and the cut's own job, a release-gated commit carrying a failed cut's + // red check run, and stable on the older released commit, the cut picks the gated commit instead of falling back to the released one; a RED release + // record still refuses; fails_when=the cut skips the gated commit for its own red check run and reports NO_RELEASE_PR or NOTHING_NEW, or the + // exclusion lifts the release-gate hold; why_new=no test put the cut's own check runs on a candidate; seam=gh faked, git real; no_claim=a live cut + test('the 11-11 state: head running its backstop and the cut, a gated commit with the failed cut\'s red run, stable on the released commit before it', () => { + const f = fixture(); + const released = f.shas['1.0.2']!, gated = f.shas['1.0.3']!; + execFileSync('git', ['tag', '-a', 'v1.0.2', released, '-m', 'gstack v1.0.2'], { cwd: f.seed, timeout: 30_000, env: { ...process.env, GIT_COMMITTER_NAME: 't', GIT_COMMITTER_EMAIL: 't@x' } }); + git(f.seed, 'push', '-q', 'origin', 'refs/tags/v1.0.2', released + ':refs/heads/stable'); + f.state.released.add('v1.0.2'); + const head = f.release('1.0.4', 'Fifth is still being gated.'); + f.refresh(); + note(f, releaseRecord(gated, 'GREEN', 43072520821), gated); + f.state.checks[head] = [...backstop('in_progress', null), ownRun('in_progress', null, 70002)]; + f.state.checks[gated] = [...unbacked, ownRun('completed', 'failure')]; + f.state.api = { ...workflowRuns(head, [{ id: 9002, path: CUT_WORKFLOW, jobs: [70002] }]), ...workflowRuns(gated, [ownWorkflow]) }; + const r = planRelease({ repo: f.repo, git: f.git, gh: f.gh, now: pastFloor }); + expect(r.ok, JSON.stringify(r)).toBe(true); + if (!r.ok) return; + expect(r.plan.sha).toBe(gated); + expect(r.plan.via).toBe('release gate run 43072520821'); + expect(r.plan.skipped).toEqual([head.slice(0, 12) + ': ' + BACKSTOP_CHECK + ' is still running']); + note(f, releaseRecord(gated, 'RED', 43072520822), gated); + const held = planRelease({ repo: f.repo, git: f.git, gh: f.gh, now: pastFloor }); + expect(held.ok).toBe(false); + if (!held.ok) { expect(held.code).toBe('REFUSED'); expect(held.message).toContain('release gate red on ' + gated.slice(0, 12)); } + }); +}); + describe('release-cut: train evidence gates a commit whose backstop never settled', () => { const train = (nonce: string, state: string, merged: Array<{ sha: string; tree: string }>) => ({ schema: 1, kind: 'train', nonce, state, merged: merged.map(m => ({ pr: '1', at: 'x', ...m })), updated_at: 'x' }); diff --git a/docs/releases.md b/docs/releases.md index 6e1bf74f1af..43506b18bca 100644 --- a/docs/releases.md +++ b/docs/releases.md @@ -46,7 +46,13 @@ regression fix (below). it has completed and none failed, and `refs/notes/gstack-trains` holds no active freeze. A cancelled check run counts as red. A commit with a check run still going is skipped and the next older one is considered, back through 7 -days or 200 first-parent commits. The workflow runs no tests and no paid evals +days or 200 first-parent commits. The cut's own job lands a check run on +main's head, the very commit it may cut, so check runs from this workflow's +own runs (its file path, `.github/workflows/weekly-release.yml`, matched +by the job ids of those workflow runs) are set aside whether running or +failed; every other check run counts as above. The lookup needs the +workflow's `actions: read` permission; when it cannot read those runs, nothing +is set aside. The workflow runs no tests and no paid evals of its own; it only reads what the trains, the backstop and the release gate already recorded. With nothing green in the window it fails and lists why each commit was diff --git a/test/weekly-release-workflow.test.ts b/test/weekly-release-workflow.test.ts index c5d6b17b2b2..0ad32aaef2c 100644 --- a/test/weekly-release-workflow.test.ts +++ b/test/weekly-release-workflow.test.ts @@ -49,7 +49,7 @@ describe('weekly-release.yml', () => { test('the cut job runs only off main for a schedule or dispatch, writes contents, reads checks, and rejects a ref that is not a 40-hex SHA', () => { const cut = wf.jobs.cut!; expect(cut.if).toBe("github.event_name != 'pull_request' && github.ref == 'refs/heads/main'"); - expect(cut.permissions).toEqual({ contents: 'write', checks: 'read', issues: 'read', 'pull-requests': 'read' }); + expect(cut.permissions).toEqual({ contents: 'write', checks: 'read', actions: 'read', issues: 'read', 'pull-requests': 'read' }); expect(cut.steps.find(s => s.uses?.startsWith('actions/checkout@'))!.with).toEqual({ 'fetch-depth': 0 }); const plan = cut.steps.find(s => s.name === 'Plan and cut')!; expect(plan.env!.GH_TOKEN).toBe('${{ github.token }}'); @@ -78,7 +78,7 @@ describe('weekly-release.yml', () => { test('the pull-request dry run is read-only, keeps no credentials, and always passes --dry-run', () => { const dry = wf.jobs['dry-run']!; expect(dry.if).toBe("github.event_name == 'pull_request'"); - expect(dry.permissions).toEqual({ contents: 'read', checks: 'read' }); + expect(dry.permissions).toEqual({ contents: 'read', checks: 'read', actions: 'read' }); expect(dry.steps.find(s => s.uses?.startsWith('actions/checkout@'))!.with).toEqual({ 'fetch-depth': 0, 'persist-credentials': false }); const plan = dry.steps.find(s => s.name === 'Plan only')!; expect(plan.run).toContain(BUN_RUN + ' --repo "$GITHUB_REPOSITORY" --summary "$GITHUB_STEP_SUMMARY" --dry-run\n'); From 842fef1f958f72e0388c0a6b2bba0ffbb7e68aaa Mon Sep 17 00:00:00 2001 From: Garry Tan Date: Wed, 11 Nov 2026 14:48:18 -0800 Subject: [PATCH 08/31] Let the sealed-output guard check pull requests larger than 256 MiB (GST-2494) (#4300) * Let the sealed-output guard read pull requests larger than 256 MiB (GST-2494) The guard's text check and landed-patch check buffered git diff-tree's whole output under spawnSync's 256 MiB maxBuffer, so a PR with millions of generated lines always refused with an empty-stderr error. Both now spool git's stdout to a private temp file and read it a line at a time after git exits 0; failures name the exit code, signal or timeout. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * Accept the platform spawn error text in the missing-git test (Windows says Executable not found) Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * Reword the sealed guard changelog entry to pass the prose check Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --------- Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- .../sealed-guard-stream-large-diffs.md | 4 + docs/troubleshooting.md | 11 + lib/sealed-guard.ts | 110 ++++++-- test/sealed-stream.test.ts | 254 ++++++++++++++++++ 4 files changed, 353 insertions(+), 26 deletions(-) create mode 100644 changelog.d/sealed-guard-stream-large-diffs.md create mode 100644 test/sealed-stream.test.ts diff --git a/changelog.d/sealed-guard-stream-large-diffs.md b/changelog.d/sealed-guard-stream-large-diffs.md new file mode 100644 index 00000000000..6082a7f572c --- /dev/null +++ b/changelog.d/sealed-guard-stream-large-diffs.md @@ -0,0 +1,4 @@ +--- +important: blocker +--- +- The sealed-output guard now reads pull requests of any size. The pre-push hook and `gstack-pregate sealed` read every published commit's patch through `git diff-tree`, and held all of git's output in memory under a 256 MiB limit. A pull request with about 4 million lines of generated fixtures produced 352 MB for the text check and 515 MB for the already-landed check, so the guard always refused it with `SEALED_OUTPUT_REFUSED` and an empty `git diff-tree -p failed:`. Both reads now write git's output to a private temporary file and check it one line at a time, so memory stays flat whatever the patch size. Findings, skipped commits and refusal codes are unchanged, and a test runs the old and new code on the same commits and gets the same answer. A git failure still refuses, and the message now names the exit code, the signal or the timeout, for example `git diff-tree -p failed (exit 128): fatal: ...` or `(killed by SIGKILL)`. The temporary file needs free disk space about the size of the patch. docs/troubleshooting.md#sealed-output-refused. diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index b2a7b2d07ff..f16e6962142 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -5007,6 +5007,17 @@ destination sets `"visibility": "private"` under `sealed` in the base branch's `.gstack/pregate.json`. Capy's pull-request tool may not run local hooks, so run `gstack-pregate sealed` yourself before any push or PR creation. +**`could not read the published commits: git diff-tree -p failed ()`.** +The guard could not read the published patches, so it refuses instead of +passing them unread. `` names what failed: an exit code followed by git's +own error (`exit 128): fatal: ...`), a signal (`killed by SIGKILL`), the +120-second timeout, or a git that could not start. The guard writes git's +output to a temporary file in the system temp directory and reads it a line at +a time, so patch size has no limit, but that directory needs free space about +the size of the patch (hundreds of MB for millions of generated lines); a full +disk shows up as a git exit. Fix the cause and rerun `gstack-pregate sealed`. +Older gstack refused any patch over 256 MiB here with nothing after the colon. + ### `EVAL_GATE_UNPRICED` diff --git a/lib/sealed-guard.ts b/lib/sealed-guard.ts index 773671b6a3d..38ebcee6f66 100644 --- a/lib/sealed-guard.ts +++ b/lib/sealed-guard.ts @@ -41,7 +41,9 @@ * combined-diff matching; any lookup failure scans everything. */ import { spawnSync } from 'node:child_process'; +import { createHash } from 'node:crypto'; import * as fs from 'node:fs'; +import * as os from 'node:os'; import * as path from 'node:path'; import { sha256Hex, writeReceipt } from './egress-receipt'; import { containedRelative, globToRegExp } from './ship-policy'; @@ -88,11 +90,63 @@ export function sealedErrors(raw: unknown): Array<{ path: string; message: strin return errors; } +const GIT_TIMEOUT_MS = 120_000; + function git(repoRoot: string, args: string[], input?: string, encoding: BufferEncoding = 'utf8'): { ok: boolean; out: string; err: string } { - const r = spawnSync('git', args, { cwd: repoRoot, encoding, input, timeout: 120_000, maxBuffer: 256 * 1024 * 1024 }); + const r = spawnSync('git', args, { cwd: repoRoot, encoding, input, timeout: GIT_TIMEOUT_MS, maxBuffer: 256 * 1024 * 1024 }); return { ok: r.status === 0, out: r.stdout ?? '', err: (r.stderr ?? '').trim() }; } +/** Test seams for the streamed reads: read size, git binary and timeout. */ +export interface GitStreamOptions { chunkBytes?: number; bin?: string; timeoutMs?: number } +type GitStdin = { text: string } | { file: string } | null; + +/** Runs git with stdout written to a private temp file, so no output size meets spawnSync's maxBuffer, and passes that file to `use` only after git exits 0. A spawn error, timeout, signal or non-zero exit throws `git