From d5f7ab5f20901bf52a1fbe2229e23d99aef9f139 Mon Sep 17 00:00:00 2001 From: Garry Tan Date: Mon, 9 Nov 2026 22:00:01 -0800 Subject: [PATCH 1/7] Count a granted follow-up review whose range starts after a docs-only commit (GST-2294) (#4278) * Count a fix-check whose range starts after a docs-only commit (GST-2294) Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * Name the follow-up review rule in plain words in the changelog (GST-2294) Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * Bridge a docs-only gap only through paths the router itself treats as release metadata (GST-2294) 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> --- ...follow-up-review-after-docs-only-commit.md | 4 + docs/review-policy.md | 3 +- docs/ship-policy.md | 14 ++ lib/ship-release.ts | 40 ++++- test/ship-finish-fixed-links.test.ts | 158 +++++++++++++++++- 5 files changed, 210 insertions(+), 9 deletions(-) create mode 100644 changelog.d/accept-follow-up-review-after-docs-only-commit.md 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 new file mode 100644 index 00000000000..abcbd8af0cd --- /dev/null +++ b/changelog.d/accept-follow-up-review-after-docs-only-commit.md @@ -0,0 +1,4 @@ +--- +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/docs/review-policy.md b/docs/review-policy.md index 750af39221a..1092f60c9fe 100644 --- a/docs/review-policy.md +++ b/docs/review-policy.md @@ -732,7 +732,8 @@ through earlier rows whose commit is the next row's `range_base` is a completed clean read on committed content (freshness `CURRENT` against its own tree; a fix-check that stopped on findings the owner has since ruled notes reads clean, [ruled notes](ship-policy.md#ruled-notes)) whose commit is on the branch, the oldest link's `range_base` is a branch commit -holding the reviewed tree, and for each link an approved `review_loop_grant` in +holding the reviewed tree (or following its commit by docs and release metadata +only, [docs bridge](ship-policy.md#fix-check-docs-bridge)), and for each link an approved `review_loop_grant` in `gstack-approvals` names a stop head inside its `range_base..commit`, each code or test path inside a link's `range_base..commit` that is unchanged since, or whose change against the base is still the one the fix-check read after a base merge also edited it (GST-1195), routes as diff --git a/docs/ship-policy.md b/docs/ship-policy.md index 3f7c46755c2..e87346d9962 100644 --- a/docs/ship-policy.md +++ b/docs/ship-policy.md @@ -1913,6 +1913,20 @@ reason (`range_base does not hold the reviewed tree`); a link that is stale or ungranted refuses with its reason and `; fix-check at , link of `. Either way nothing in the chain counts. +One gap is not a gap: the oldest link's `range_base` may follow the reviewed +tree's commit by commits that change only authored docs or release metadata, +such as the Step 14.5 docs commit (harness-evals#361, GST-2294). finish walks +`range_base`'s first parents back to the nearest commit holding the reviewed tree +and accepts the range when every commit after it is a single-parent commit whose +every path it routes as docs or release metadata, printing +`FIX_CHECK_DOCS_BRIDGE: range_base follows the reviewed commit by +docs or release metadata only ()`. Those docs still take the docs route +and its recheck. A code or test commit in between, a merge, a `range_base` the +reviewed commit descends from, and a `range_base` on another branch still refuse. +Pass `--reviewed-tree` as the tree the bound review read, never the fix-check's +own tree: with the fix-check's tree, `range_base` sits before the "reviewed" +commit and finish refuses (#4267, #4270). + ## `test_code` and Godot UID sidecars after review diff --git a/lib/ship-release.ts b/lib/ship-release.ts index 1c39b46437b..835f171662a 100644 --- a/lib/ship-release.ts +++ b/lib/ship-release.ts @@ -249,6 +249,29 @@ function patchBase(cwd: string, baseRef: string, commit: string, parent: string } type FixLink = { row: Record; commit: string; from: string }; +type BridgeOpts = { reviewed: string; baseRef: string; metadata: (p: string) => boolean; bookkeeping: readonly string[]; testCode: readonly string[] }; + +/** + * A range_base that follows the reviewed tree's commit by docs and release metadata alone (GST-2294, harness-evals#361: the + * fix-check range started at the Step 14.5 docs commit). Walks range_base's first parents off the base back to the nearest commit + * holding the reviewed tree; every commit after it, range_base included, must be a single-parent commit whose every path finish + * routes as release metadata (route's own per-path rule, so baseRelease on a landed stack parent) or authored docs, so the paths + * outside the fix-check's read keep the docs route and its recheck. + * A merge, a code or test path, or no reviewed commit behind range_base returns null. + */ +function docsBridge(cwd: string, from: string, o: BridgeOpts): { reviewedAt: string; commits: string[] } | null { + const log = git(cwd, ['log', '--first-parent', '--format=%H %T %P', from, '--not', o.baseRef]); + if (log.status !== 0) return null; + const docsOnly = (p: string) => o.metadata(p) || (!isTestCode(p, o.testCode) && classifyPath(p, cwd) === 'docs' && !matchesAny(o.bookkeeping, p)); + const commits: string[] = []; + for (const [commit, tree, ...parents] of log.stdout.trim().split('\n').filter(Boolean).map(l => l.split(' '))) { + if (tree === o.reviewed) return commits.length ? { reviewedAt: commit!, commits: commits.reverse() } : null; + const paths = parents.length === 1 ? touchedPaths(cwd, parents[0]!, commit!) : null; + if (!paths || ![...paths].every(docsOnly)) return null; + commits.push(commit!); + } + return null; +} /** * The granted fix-checks finish counts (GST-1130, GST-1627): the newest review-fix-check row and, while its range_base does @@ -257,13 +280,14 @@ type FixLink = { row: Record; commit: string; from: string }; * head inside its range_base..commit, its own commit included (the post-review flow grants each fix-check at the commit it * reads, GST-1676); a grant counts for one link only, assigned newest link first, so one grant naming the boundary or two * links' commits covers one, and the older link needs a grant of its own. - * A range_base no earlier row ends at is a gap, and the chain does not count. A link before the newest may, instead of a clean + * A range_base no earlier row ends at is a gap, and the chain does not count, unless docs and release metadata alone sit between + * the reviewed tree's commit and it (docsBridge, GST-2294). A link before the newest may, instead of a clean * read, be a finished read bound to its own committed content that found issues (logged converged:false, GST-1973) when its * findings account for its counts and each open or blocking one names a file it read: it counts no path itself, and a path its * findings name counts only through a clean link after it, and a finding no later clean link's range touched refuses the chain. A path counts as fix_checked when a clean link's range touched it and it is unchanged since that link, * or its patch against the base is still the one the link read. */ -function fixChecked(cwd: string, o: { reviewed: string; now: string; baseRef: string; parent?: string; currentBase?: string; candidates: string[] }, r: Report): { counted: boolean; paths: string[] } | null { +function fixChecked(cwd: string, o: BridgeOpts & { now: string; parent?: string; currentBase?: string; candidates: string[] }, r: Report): { counted: boolean; paths: string[] } | null { const rows: Record[] = bin(cwd, 'gstack-review-read', [], 60_000).stdout.split('\n---CONFIG---')[0].split('\n') .flatMap(l => { try { const v = JSON.parse(l); return v?.skill === 'review-fix-check' ? [v] : []; } catch { return []; } }); const commitOf = (c: unknown) => typeof c === 'string' && /^[0-9a-f]{7,64}$/.test(c) ? git(cwd, ['rev-parse', '--verify', '--quiet', `${c}^{commit}`]).stdout.trim() : ''; @@ -271,13 +295,15 @@ function fixChecked(cwd: string, o: { reviewed: string; now: string; baseRef: st const onBranch = (c: string) => !!c && ancestor(c, 'HEAD'); const commits = rows.map(row => commitOf(row.commit_full)); const chain: FixLink[] = []; - let gap = ''; + let gap = '', bridged = ''; for (let i = rows.length - 1; i >= 0;) { const link = { row: rows[i]!, commit: commits[i]!, from: commitOf(rows[i]!.range_base) }; chain.unshift(link); if (!onBranch(link.from) || git(cwd, ['rev-parse', `${link.from}^{tree}`]).stdout.trim() === o.reviewed) break; i = commits.slice(0, i).lastIndexOf(link.from); - if (i < 0) gap = `range_base ${link.from.slice(0, 12)} does not hold the reviewed tree`; + const bridge = i < 0 ? docsBridge(cwd, link.from, o) : null; + if (bridge) bridged = `FIX_CHECK_DOCS_BRIDGE: range_base ${link.from.slice(0, 12)} follows the reviewed commit ${bridge.reviewedAt.slice(0, 12)} by docs or release metadata only (${bridge.commits.map(c => c.slice(0, 12)).join(',')})`; + else if (i < 0) gap = `range_base ${link.from.slice(0, 12)} does not hold the reviewed tree`; } const inRange = (l: FixLink, c: string) => !!l.from && !!l.commit && ancestor(l.from, c) && ancestor(c, l.commit); const rulings = readRuledNotes(cwd).map(n => ({ ...n, links: chain.filter(l => inRange(l, n.head)) })); @@ -325,6 +351,7 @@ function fixChecked(cwd: string, o: { reviewed: string; now: string; baseRef: st const rulable = (l: FixLink) => (Array.isArray(l.row.findings) ? l.row.findings : []).filter((f: any) => !!f && !f.gate && RULABLE.has(f.action) && holdsOpen(f) && typeof f.fingerprint === 'string' && !ruledOn(l).has(f.fingerprint)).map((f: any) => f.fingerprint as string); for (const l of notCounted ? chain : []) if (rulable(l).length) r.add(`FIX_CHECK_OPEN: ${rulable(l).join(',')} on the fix-check at ${l.commit.slice(0, 12)}: the owner rules each one a disclosed note with gstack-approvals rule --finding --head ${l.commit.slice(0, 12)} --reason '' --words '' --by ''; a review-loop exception accepts edits after a fix-check, never its findings (docs/troubleshooting.md#fix-check-open)`); if (!chain.length || notCounted) return { counted: false, paths: [] }; + if (bridged) r.add(bridged); const read: ((p: string) => boolean)[] = []; for (const [k, l] of chain.entries()) { if (!clean.has(l)) continue; @@ -361,10 +388,11 @@ function route(cwd: string, base: string, reviewed: string, reviewedBase: Review shipped = b; } const by: Routed = { behavior: [], docs: [], metadata: [], tests: [], base: [], context: [], bounded: [], mechanical: [], accepted: [], fix_checked: [], sidecar: [] }; + const isMetadata = (p: string) => parent && shipped.has(p) ? opts.baseRelease!.includes(p) || harnessRepin(cwd, sides!.currentBase, now, p) : release.includes(p) || harnessRepin(cwd, reviewed, now, p); const onlyShipped = new Set(parent ? [...shipped].filter(p => !changedSet.has(p)) : []); for (const p of [...changedSet, ...onlyShipped].sort()) { const verdict = sides ? (!touched.has(p) || (parent && !shipped.has(p) && baseHolds(cwd, sides, p)) ? 'same' : comparePath(cwd, sides, p)) : 'changed'; - const metadata = parent && shipped.has(p) ? opts.baseRelease!.includes(p) || harnessRepin(cwd, sides!.currentBase, now, p) : release.includes(p) || harnessRepin(cwd, reviewed, now, p); + const metadata = isMetadata(p); by[verdict === 'same' ? 'base' : metadata ? 'metadata' : sides && isTestCode(p, opts.testCode) ? 'tests' : classifyPath(p, cwd) === 'docs' && !matchesAny(opts.bookkeeping, p) ? 'docs' : verdict === 'context' ? 'context' : 'behavior'].push(p); } const shippedTests = by.tests.filter(p => onlyShipped.has(p)); @@ -384,7 +412,7 @@ function route(cwd: string, base: string, reviewed: string, reviewedBase: Review by.behavior.push(...packetBody.over); for (const k of ['context', 'tests', 'bounded'] as const) by[k] = by[k].filter(p => !packetBody.over.includes(p)); } - const fix = fixChecked(cwd, { reviewed, now, baseRef, parent, currentBase: sides?.currentBase, candidates: [...by.behavior, ...by.tests, ...by.context, ...by.bounded] }, r); + const fix = fixChecked(cwd, { reviewed, now, baseRef, parent, currentBase: sides?.currentBase, metadata: isMetadata, bookkeeping: opts.bookkeeping, testCode: opts.testCode, candidates: [...by.behavior, ...by.tests, ...by.context, ...by.bounded] }, r); if (!fix) return null; const counted = fix.counted; by.fix_checked = fix.paths; diff --git a/test/ship-finish-fixed-links.test.ts b/test/ship-finish-fixed-links.test.ts index c6634995f52..e3417804e40 100644 --- a/test/ship-finish-fixed-links.test.ts +++ b/test/ship-finish-fixed-links.test.ts @@ -60,10 +60,10 @@ function link(f: ShipFx, from: string, row: Record, o: { grant? expect(logged.status, logged.stderr).toBe(0); return { commit, grant }; } -function finish(f: ShipFx, reviewed: string, reviewedBase: string) { +function finish(f: ShipFx, reviewed: string, reviewedBase: string, extra: string[] = []) { const post = path.join(f.root, 'post.json'); expect(f.run(path.join(BIN, 'gstack-docs-candidate'), ['snapshot', '--out', post, '--audit-id', 'a1', '--mode', 'edit', '--base', 'main', '--docs', 'README.md']).status).toBe(0); - return f.run(RELEASE, ['finish', '--base', 'main', '--reviewed-tree', reviewed, '--docs-post', post, '--reviewed-base', reviewedBase, '--lane', LANE]); + return f.run(RELEASE, ['finish', '--base', 'main', '--reviewed-tree', reviewed, '--docs-post', post, '--reviewed-base', reviewedBase, '--lane', LANE, ...extra]); } describe('finish counts a fix-check chain whose earlier links found issues a later clean link read (GST-1973)', () => { @@ -240,3 +240,157 @@ describe('finish still refuses fix-check chains that do not read the fixes (GST- } }); }); + +describe('finish counts a fix-check whose range starts after docs-only commits (GST-2294)', () => { + const README = { 'README.md': '# Fx\n\nHow to run the canary.\n' }; + const notHeld = (c: string) => `FIX_CHECK: not counted (range_base ${at(c)} does not hold the reviewed tree)`; + + // Value: protects=harness-evals#361's shape counts: the reviewed commit, then the Step 14.5 docs commit, then the granted + // fix-check whose range starts at that docs commit; fails_when=finish refuses the range_base because its tree is not the + // reviewed tree and no earlier fix-check ends at it, so src/x.ts routes as behavior; seam=finish's chain walk + test.each([ + ['one docs commit', [README]], + ['a docs commit and a changelog stamp', [README, { 'CHANGELOG.md': '# Changelog\n\n## [Unreleased]\n\n- pending\n- canary docs\n' }]], + ])('a range_base after %s counts', (_name, commits) => { + const { f, t, reviewed, reviewedBase } = reviewedShape(); + const between = (commits as Record[]).map((files, k) => edit(f, files, `docs commit ${k + 1}`)); + const from = between[between.length - 1]!; + edit(f, { 'src/x.ts': 'export const x = 3;\n', 'test/x.test.ts': TEST_V2 }, 'fix the round-2 blocker'); + const c = link(f, from, CLEAN); + const r = finish(f, reviewed, reviewedBase, ['--docs-rechecked']); + expect(lineOf(r.stdout, 'FIX_CHECK_DOCS_BRIDGE'), r.stdout).toBe(`FIX_CHECK_DOCS_BRIDGE: range_base ${at(from)} follows the reviewed commit ${at(t)} by docs or release metadata only (${between.map(at).join(',')})`); + expect(lineOf(r.stdout, 'FIX_CHECK'), r.stdout).toBe(`FIX_CHECK: reviewed src/x.ts,test/x.test.ts (fix-check at ${at(c.commit)}, range from ${at(from)}, grant ${c.grant})`); + expect([r.status, lineOf(r.stdout, 'ROUTE')], r.stdout).toEqual([0, expect.stringMatching(/ behavior=0 .* fix_checked=2$/)]); + }); + + // Value: protects=only docs and release metadata bridge the gap: a code or test commit, alone or after a docs commit, between + // the reviewed commit and range_base is a read no fix-check made; fails_when=finish accepts any range_base that descends from + // the reviewed commit; seam=finish's chain walk + test.each([ + ['a code commit', [{ 'src/y.ts': 'export const y = 2;\n' }]], + ['a test commit', [{ 'test/x.test.ts': TEST_V2 }]], + ['a docs commit, then a code commit', [README, { 'src/y.ts': 'export const y = 2;\n' }]], + ])('a range_base after %s still refuses', (_name, commits) => { + const { f, reviewed, reviewedBase } = reviewedShape(); + const between = (commits as Record[]).map((files, k) => edit(f, files, `unread commit ${k + 1}`)); + const from = between[between.length - 1]!; + edit(f, { 'src/x.ts': 'export const x = 3;\n' }, 'fix the round-2 blocker'); + link(f, from, CLEAN); + const r = finish(f, reviewed, reviewedBase, ['--docs-rechecked']); + expect(lineOf(r.stdout, 'FIX_CHECK_DOCS_BRIDGE'), r.stdout).toBe(''); + expect([r.status, lineOf(r.stdout, 'FIX_CHECK')], r.stdout).toEqual([3, notHeld(from)]); + }); + + // Value: protects=the bridge runs only forward from the reviewed commit: a docs-only commit before it (so the reviewed commit + // descends from range_base, as when --reviewed-tree names the fix-check's own tree) is no bridge; fails_when=finish accepts a + // docs-only diff between range_base and the reviewed commit in either direction; seam=finish's chain walk + test('a docs commit before the reviewed commit refuses: range_base is not a descendant of it', () => { + const { f } = reviewedShape(); + const before = edit(f, README, 'docs before review'); + edit(f, { 'src/y.ts': 'export const y = 2;\n' }, 'more reviewed code'); + const reviewed = f.run(path.join(BIN, 'gstack-wtree'), []).stdout.trim(); + const reviewedBase = f.git('merge-base', 'origin/main', 'HEAD').stdout.trim(); + edit(f, { 'src/x.ts': 'export const x = 3;\n' }, 'fix the round-2 blocker'); + link(f, before, CLEAN); + const r = finish(f, reviewed, reviewedBase, ['--docs-rechecked']); + expect([r.status, lineOf(r.stdout, 'FIX_CHECK')], r.stdout).toEqual([3, notHeld(before)]); + }); + + // Value: protects=a base merge between the reviewed commit and range_base is no bridge, even when the base change is docs; + // fails_when=finish reads a merge commit's first-parent diff as the branch's own docs edit; seam=finish's chain walk + test('a merge commit between the reviewed commit and range_base refuses', () => { + const { f, reviewed, reviewedBase } = reviewedShape(); + f.advanceBase({ 'docs/base.md': '# Base docs\n' }); + expect(f.git('fetch', '-q', 'origin').status).toBe(0); + expect(f.git('merge', '-q', '--no-edit', 'origin/main').status).toBe(0); + const merge = headOf(f); + edit(f, { 'src/x.ts': 'export const x = 3;\n' }, 'fix the round-2 blocker'); + link(f, merge, CLEAN); + const r = finish(f, reviewed, reviewedBase, ['--docs-rechecked']); + expect(lineOf(r.stdout, 'FIX_CHECK'), r.stdout).toBe(notHeld(merge)); + expect(r.status, r.stdout).toBe(3); + }); + + // Value: protects=a range_base on another branch still refuses, docs-only or not; fails_when=the bridge looks up the reviewed + // commit from a range_base HEAD does not contain; seam=finish's chain walk + test('a docs-only range_base on another branch refuses', () => { + const { f, reviewed, reviewedBase } = reviewedShape(); + expect(f.git('checkout', '-qb', 'side').status).toBe(0); + const side = edit(f, README, 'docs on a side branch'); + expect(f.git('checkout', '-q', 'feat').status).toBe(0); + edit(f, { 'src/x.ts': 'export const x = 3;\n' }, 'fix the round-2 blocker'); + link(f, side, CLEAN); + const r = finish(f, reviewed, reviewedBase); + expect([r.status, lineOf(r.stdout, 'FIX_CHECK')], r.stdout).toEqual([3, 'FIX_CHECK: not counted (the row names no range_base commit on this branch)']); + }); + + // Value: protects=a range_base whose tree is the reviewed tree counts with no bridge line (an empty commit after review); + // fails_when=the bridge replaces the equal-tree check; seam=finish's chain walk + test('a range_base whose tree equals the reviewed tree counts', () => { + const { f, reviewed, reviewedBase } = reviewedShape(); + expect(f.git('commit', '-q', '--allow-empty', '-m', 'an empty commit after review').status).toBe(0); + const same = headOf(f); + edit(f, { 'src/x.ts': 'export const x = 3;\n', 'test/x.test.ts': TEST_V2 }, 'fix the round-2 blocker'); + const c = link(f, same, CLEAN); + const r = finish(f, reviewed, reviewedBase); + expect(lineOf(r.stdout, 'FIX_CHECK_DOCS_BRIDGE'), r.stdout).toBe(''); + expect(lineOf(r.stdout, 'FIX_CHECK'), r.stdout).toBe(`FIX_CHECK: reviewed src/x.ts,test/x.test.ts (fix-check at ${at(c.commit)}, range from ${at(same)}, grant ${c.grant})`); + expect(r.status, r.stdout).toBe(0); + }); +}); + +describe('the docs bridge uses the router\'s own metadata rule on a landed stack parent (GST-2294 audit)', () => { + const POLICY_SRC = ['export const allow = false;', ...Array.from({ length: 28 }, (_, k) => `export const l${k} = ${k};`), 'export const label = "old";', ''].join('\n'); + /** A child branch reviewed after its stack parent P, with src/policy.ts optionally declared under key; P then lands on main and main merges into the child. */ + function stackShape(key: string | null, after: (f: ShipFx) => void) { + const f = shipFixture({ ...(key ? { '.gstack/ship-policy.json': JSON.stringify({ min_gstack_version: '1.99.0.0', [key]: ['src/policy.ts'] }) } : {}), 'src/policy.ts': POLICY_SRC, 'src/x.ts': 'export const x = 1;\n' }, { 'src/parent.ts': 'export const parent = 1;\n' }); + ships.push(f); + const parent = headOf(f); + edit(f, { 'src/x.ts': 'export const x = 2;\n' }, 'child'); + const reviewed = f.run(path.join(BIN, 'gstack-wtree'), []).stdout.trim(); + const from = edit(f, { 'src/policy.ts': POLICY_SRC.replace('allow = false', 'allow = true') }, 'unreviewed logic change'); + after(f); + link(f, from, CLEAN); + f.advanceBase({ 'src/parent.ts': 'export const parent = 1;\n' }); + expect(f.git('fetch', '-q', 'origin').status).toBe(0); + expect(f.git('merge', '-q', '--no-edit', 'origin/main').status).toBe(0); + return { r: finish(f, reviewed, parent, ['--docs-rechecked']), from }; + } + const notHeld = (c: string) => `FIX_CHECK: not counted (range_base ${at(c)} does not hold the reviewed tree)`; + + // Value: protects=a declared stamp or release-output path the router classes as behavior on a landed stack parent never bridges + // the gap, whether the fix-check rewrites that file or only appends to it; fails_when=the bridge reads the broad release list and + // credits src/policy.ts as fix_checked (finish exits 0, fix_checked=2); seam=finish's chain walk and route's metadata rule + test.each([ + ['stamp_paths', 'a rewrite'], ['release_outputs', 'a rewrite'], ['stamp_paths', 'an append'], ['release_outputs', 'an append'], + ])('%s: a logic change in the gap, then %s in the fix-check range, refuses', (key, kind) => { + const { r, from } = stackShape(key, f => edit(f, { + 'src/policy.ts': kind === 'a rewrite' ? POLICY_SRC.replace('allow = false', 'allow = true').replace('"old"', '"new"') : `${POLICY_SRC.replace('allow = false', 'allow = true')}export const tail = 1;\n`, + 'src/x.ts': 'export const x = 3;\n', + }, 'fix-check reads this range')); + expect(lineOf(r.stdout, 'FIX_CHECK_DOCS_BRIDGE'), r.stdout).toBe(''); + expect([r.status, lineOf(r.stdout, 'FIX_CHECK')], r.stdout).toEqual([3, notHeld(from)]); + }); + + // Value: protects=the two controls of the append repro: with no append the fix-check never touched src/policy.ts, and with no + // declaration the path was never metadata; both refuse; fails_when=either control counts; seam=finish's route + test('controls: no append stops on src/policy.ts, and no declaration refuses the bridge', () => { + const noAppend = stackShape('stamp_paths', f => edit(f, { 'src/x.ts': 'export const x = 3;\n' }, 'fix-check reads this range')); + expect([noAppend.r.status, noAppend.r.stdout.includes('src/policy.ts')], noAppend.r.stdout).toEqual([3, true]); + const undeclared = stackShape(null, f => edit(f, { 'src/policy.ts': `${POLICY_SRC.replace('allow = false', 'allow = true')}export const tail = 1;\n`, 'src/x.ts': 'export const x = 3;\n' }, 'fix-check reads this range')); + expect([undeclared.r.status, lineOf(undeclared.r.stdout, 'FIX_CHECK')], undeclared.r.stdout).toEqual([3, notHeld(undeclared.from)]); + }); +}); + +describe('the docs bridge line prints only when the fix-check counts (GST-2294 audit)', () => { + // Value: protects=FIX_CHECK_DOCS_BRIDGE never sits beside a refused chain; fails_when=the line prints before the grant check + // refuses; seam=finish's FIX_CHECK output + test('an ungranted fix-check after a docs commit prints no bridge line', () => { + const { f, reviewed, reviewedBase } = reviewedShape(); + const d = edit(f, { 'README.md': '# Fx\n\nHow to run the canary.\n' }, 'docs commit'); + edit(f, { 'src/x.ts': 'export const x = 3;\n', 'test/x.test.ts': TEST_V2 }, 'fix the round-2 blocker'); + link(f, d, CLEAN, { grant: false }); + const r = finish(f, reviewed, reviewedBase, ['--docs-rechecked']); + expect([r.status, lineOf(r.stdout, 'FIX_CHECK_DOCS_BRIDGE'), lineOf(r.stdout, 'FIX_CHECK')], r.stdout).toEqual([3, '', 'FIX_CHECK: not counted (no approved review_loop_grant names a stop head inside its range_base..commit)']); + }); +}); From 90fded4dd0b08b73831330e38686b93dd8f8e42a Mon Sep 17 00:00:00 2001 From: Garry Tan Date: Mon, 9 Nov 2026 22:22:58 -0800 Subject: [PATCH 2/7] Brain sync scans binary files and split authorization values for secrets (GST-2292) (#4276) * Brain sync scans binary files and split authorization values for secrets (GST-2292) Git showed a file with a NUL byte or UTF-16 text as "Binary files differ", so the push-time secret scan never saw an AWS key inside it. The sync and the pre-commit hook now diff with --text --no-textconv, the scanner also reads NUL-bearing lines as UTF-16 and with NULs removed, and a section git still did not diff as text is held as binary-not-scanned. A Bearer value added under an unchanged "authorization": line was missed because the + marker broke the match; each hunk's new text is now scanned as one block too. The docs say plainly that an already-committed secret stays held after deletion and only --skip-file clears it. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * Secret scan catches split auth values in UTF-16 files and under diff.context=0 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 Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * Sync docs say a secret already committed in ~/.gstack stays held until you skip the file Approved docs-audit repair: approval a-029ea2b533be (GStack Minder GSTA-36, lane brief item 3). Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * Secret scan keeps the plain git diff as one reading beside the text reading The sync and the pre-commit hooks had replaced git's plain staged diff with a --text --no-textconv -U3 diff. That lost two things the old scan held: an unchanged line that the user's diff.context showed (5 lines away from an edit), and a secret that only a configured textconv driver decodes. The scanner now takes both diffs and holds a file when either reading matches; binary-not-scanned applies to the text reading only. Review-Finding: sol-audit-201c6a0#1 reader=cross-family-audit Review-Finding: sol-audit-201c6a0#2 reader=cross-family-audit Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * Secret scan decodes JSON escapes in UTF-16 text and keeps its diff files private A \u-escaped AWS key inside a UTF-16 JSON file passed both scans, because the UTF-16 and NUL-stripped readings skipped the JSON decoding every other reading gets. The sync's two scan diffs, which now carry binary bytes, were written with the user's umask (0644 under /tmp); they are created 0600. Review-Finding: p3/outside-voice#1 reader=outside-voice Review-Finding: p3/outside-voice#2 reader=outside-voice 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-artifacts-init | 8 +- bin/gstack-brain-restore | 8 +- bin/gstack-brain-secret-scan.py | 111 ++++++++-- bin/gstack-brain-sync | 22 +- ...ry-files-and-split-authorization-values.md | 4 + docs/gbrain-sync-errors.md | 10 +- docs/gbrain-sync.md | 32 ++- test/brain-sync.test.ts | 204 +++++++++++++++++- 8 files changed, 362 insertions(+), 37 deletions(-) create mode 100644 changelog.d/brain-sync-scans-binary-files-and-split-authorization-values.md diff --git a/bin/gstack-artifacts-init b/bin/gstack-artifacts-init index 6f94f781110..3f94121b7aa 100755 --- a/bin/gstack-artifacts-init +++ b/bin/gstack-artifacts-init @@ -431,7 +431,13 @@ if [ ! -f "$SCAN" ]; then echo "gstack-artifacts pre-commit: refusing commit — the secret scanner $SCAN is missing; rerun gstack-artifacts-init to reinstall this hook." >&2 exit 1 fi -hits=$(git diff --cached --no-renames --no-color --no-ext-diff | python3 "$SCAN" gate -) +TEXT=$(mktemp) || { echo "gstack-artifacts pre-commit: refusing commit — could not create a temporary file for the secret scan." >&2; exit 1; } +trap 'rm -f "$TEXT"' EXIT +if ! git diff --cached --no-renames --no-color --no-ext-diff --text --no-textconv -U3 > "$TEXT"; then + echo "gstack-artifacts pre-commit: refusing commit — git could not read the staged diff for the secret scan." >&2 + exit 1 +fi +hits=$(git diff --cached --no-renames --no-color --no-ext-diff | python3 "$SCAN" gate - "$TEXT") rc=$? [ "$rc" -eq 0 ] && exit 0 if [ "$rc" -eq 3 ]; then diff --git a/bin/gstack-brain-restore b/bin/gstack-brain-restore index fbba3ad3d48..18c081f4fcd 100755 --- a/bin/gstack-brain-restore +++ b/bin/gstack-brain-restore @@ -216,7 +216,13 @@ if [ ! -f "$SCAN" ]; then echo "gstack-brain pre-commit: refusing commit — the secret scanner $SCAN is missing; rerun gstack-brain-restore to reinstall this hook." >&2 exit 1 fi -hits=$(git diff --cached --no-renames --no-color --no-ext-diff | python3 "$SCAN" gate -) +TEXT=$(mktemp) || { echo "gstack-brain pre-commit: refusing commit — could not create a temporary file for the secret scan." >&2; exit 1; } +trap 'rm -f "$TEXT"' EXIT +if ! git diff --cached --no-renames --no-color --no-ext-diff --text --no-textconv -U3 > "$TEXT"; then + echo "gstack-brain pre-commit: refusing commit — git could not read the staged diff for the secret scan." >&2 + exit 1 +fi +hits=$(git diff --cached --no-renames --no-color --no-ext-diff | python3 "$SCAN" gate - "$TEXT") rc=$? [ "$rc" -eq 0 ] && exit 0 if [ "$rc" -eq 3 ]; then diff --git a/bin/gstack-brain-secret-scan.py b/bin/gstack-brain-secret-scan.py index 48dcc20565c..2b52788d579 100644 --- a/bin/gstack-brain-secret-scan.py +++ b/bin/gstack-brain-secret-scan.py @@ -6,6 +6,20 @@ a secret in a file name or one that lines up across an unchanged line is held. Each added line is also scanned with its JSON string literals decoded, so a secret hidden behind \u escapes or backslash-escaped quotes is caught. +Each hunk's new text (its unchanged and added lines without their diff +markers) is scanned as one block too, so a key on an unchanged line joins a +value added under it. + +Callers pass two readings of the same staged diff and every check runs on +both, so neither can lose what the other holds. The first is the plain +`git diff` the hook has always scanned, with the user's diff.context and +textconv drivers. The second is the same diff with --text, --no-textconv and +-U3, so a file git calls binary arrives as its bytes and a diff.context below +3 cannot drop the unchanged lines around an edit. A line or hunk holding a +NUL byte is also read as UTF-16 in both byte orders and alignments, and with +its NULs removed. A section of the second reading that still says "Binary +files ... differ" or carries a "GIT binary patch" was not diffed as text; it +is flagged as binary-not-scanned (fail closed). The first six pattern families are the original hook's; the four after them mirror lib/redact-patterns.ts HIGH rules (stripe.secret/restricted, @@ -15,10 +29,11 @@ The diff is read as bytes and decoded with replacement, so undecodable bytes cannot crash the scan into a false "clean". - gate exit 0 clean, 3 hit (prints the family + gate [] exit 0 clean, 3 hit (prints the family names); anything else is a scanner failure (fail closed). "-" reads stdin. - attribute one pass: splits the diff on its + attribute [] + one pass: splits each diff on its "diff --git" headers, pairs each section with the NUL-separated names from "git diff --name-only -z" (same order), @@ -113,6 +128,50 @@ def added_lines(lines): return out +def post_images(lines): + """Each hunk's new text as bytes: its unchanged and added lines, markers + removed, joined on the newline byte git split them at.""" + out, cur, in_hunk = [], [], False + for line in lines: + if line.startswith(b"diff --git ") or line.startswith(b"@@"): + if cur: + out.append(b"\n".join(cur)) + cur, in_hunk = [], line.startswith(b"@@") + elif in_hunk and line[:1] in (b" ", b"+"): + cur.append(line[1:]) + if cur: + out.append(b"\n".join(cur)) + return out + + +def nul_readings(bodies): + """Each byte string holding a NUL byte, read with its NULs removed and as + UTF-16LE and UTF-16BE from both byte alignments.""" + out = [] + for body in bodies: + if b"\0" not in body: + continue + out.append(body.replace(b"\0", b"").decode("utf-8", "replace")) + for chunk in (body, body[1:]): + chunk = chunk[:len(chunk) // 2 * 2] + out.append(chunk.decode("utf-16-le", "replace")) + out.append(chunk.decode("utf-16-be", "replace")) + return out + + +def unscanned_binary(lines): + """True when a section's header says git did not diff a file as text.""" + in_hunk = False + for line in lines: + if line.startswith(b"diff --git "): + in_hunk = False + elif line.startswith(b"@@"): + in_hunk = True + elif not in_hunk and (line.startswith(b"Binary files ") or line == b"GIT binary patch"): + return True + return False + + def decoded_in_place(text): """text with every escaped JSON string literal replaced by its decoded value in quotes, so a key and its value are matched together even when @@ -127,13 +186,19 @@ def decode(m): return json_string.sub(decode, text) -def families(lines): +def families(lines, text_reading=False): added = added_lines(lines) raw = b"\n".join(lines).decode("utf-8", "replace") - texts = [raw] + [decoded_in_place(line) for line in added] + [s for line in added for s in decoded_strings(line)] + posts = post_images(lines) + post_texts = [post.decode("utf-8", "replace") for post in posts] + texts = ([raw] + [decoded_in_place(line) for line in added] + [s for line in added for s in decoded_strings(line)] + + post_texts + [decoded_in_place(text) for text in post_texts] + + [t for nul in nul_readings([line[1:] for line in lines] + posts) + for t in [nul, decoded_in_place(nul)] + decoded_strings(nul)]) text = "\n".join(texts) - return [name for name, rx, real in patterns - if any(real is None or real(m) for m in rx.finditer(text))] + found = ['binary-not-scanned'] if text_reading and unscanned_binary(lines) else [] + return found + [name for name, rx, real in patterns + if any(real is None or real(m) for m in rx.finditer(text))] def read(path): @@ -143,9 +208,27 @@ def read(path): return f.read() +def union(plain, text): + hits = families(plain) + if text is not None: + hits += [h for h in families(text, text_reading=True) if h not in hits] + return hits + + +def sections(path): + out = [] + for line in read(path).split(b"\n"): + if line.startswith(b"diff --git "): + out.append([line]) + elif out: + out[-1].append(line) + return out + + mode = sys.argv[1] if mode == "gate": - hits = families(read(sys.argv[2]).split(b"\n")) + text = read(sys.argv[3]).split(b"\n") if len(sys.argv) > 3 else None + hits = union(read(sys.argv[2]).split(b"\n"), text) if hits: print(",".join(hits)) sys.exit(3) @@ -155,18 +238,14 @@ def read(path): diff_path, names_path, out_path = sys.argv[2:5] names = [n.decode("utf-8", "surrogateescape") for n in read(names_path).split(b"\0") if n] -sections = [] -for line in read(diff_path).split(b"\n"): - if line.startswith(b"diff --git "): - sections.append([line]) - elif sections: - sections[-1].append(line) -if len(sections) != len(names): +plain = sections(diff_path) +text = sections(sys.argv[5]) if len(sys.argv) > 5 else [None] * len(plain) +if len(plain) != len(names) or len(text) != len(names): sys.exit(4) with open(out_path, "w", encoding="utf-8", errors="surrogateescape", newline="\n") as out: - for name, body in zip(names, sections): + for name, body, text_body in zip(names, plain, text): if "\n" in name or "\t" in name: sys.exit(4) - hits = families(body) + hits = union(body, text_body) if hits: out.write(hits[0] + "\t" + name + "\n") diff --git a/bin/gstack-brain-sync b/bin/gstack-brain-sync index 7ea71acdab8..fd89a98d316 100755 --- a/bin/gstack-brain-sync +++ b/bin/gstack-brain-sync @@ -206,12 +206,17 @@ sync_active() { # Secret scan over a staged diff file: bin/gstack-brain-secret-scan.py, the # same scanner the artifacts repo's pre-commit hook runs. It scans the whole -# diff as written and each added line with its JSON string literals decoded, -# and prints only family names, never the matched text. -# secret_scan gate exit 0 clean, 3 hit (prints the +# diff as written, each added line with its JSON string literals decoded and +# each hunk's new text, and prints only family names, never the matched text. +# It reads two diffs of the same index: the plain diff (the user's +# diff.context and textconv drivers apply) and one with --text --no-textconv +# -U3, so binary files arrive as bytes and a small diff.context cannot hide +# the unchanged lines. Every finding from either reading counts. +# secret_scan gate [] exit 0 clean, 3 hit (prints the # family names); anything else is # a scanner failure (fail closed) -# secret_scan attribute writes "\t" per +# secret_scan attribute [] +# writes "\t" per # flagged path; exit 0, or 4 when # the diff's sections and the # `git diff --name-only -z` names @@ -1038,9 +1043,11 @@ hold_flagged_paths() { WAITING=0 : > "$scan.hits" : > "$scan.blobs" + (umask 077 && : > "$scan.diff" && : > "$scan.text") || rc=1 git -C "$GSTACK_HOME" diff --cached --no-renames --no-color --no-ext-diff > "$scan.diff" 2>/dev/null || rc=1 + git -C "$GSTACK_HOME" diff --cached --no-renames --no-color --no-ext-diff --text --no-textconv -U3 > "$scan.text" 2>/dev/null || rc=1 git -C "$GSTACK_HOME" diff --cached --no-renames -z --name-only > "$scan.names" 2>/dev/null || rc=1 - [ "$rc" -eq 0 ] && { secret_scan attribute "$scan.diff" "$scan.names" "$scan.hits" || rc=1; } + [ "$rc" -eq 0 ] && { secret_scan attribute "$scan.diff" "$scan.names" "$scan.hits" "$scan.text" || rc=1; } [ "$rc" -eq 0 ] && { append_invalid_json_hits "$scan.names" "$scan.hits" || rc=1; } # A successful add need not stage the requested spelling or current bytes # (case-insensitive indexes and assume-unchanged can both report success). @@ -1076,11 +1083,12 @@ hold_flagged_paths() { { grep -vxF -f "$scan.unstage" "$paths_file" || true; } > "$paths_file.kept" mv -f "$paths_file.kept" "$paths_file" fi - if ! git -C "$GSTACK_HOME" diff --cached --no-renames --no-color --no-ext-diff > "$scan.diff" 2>/dev/null; then + if ! git -C "$GSTACK_HOME" diff --cached --no-renames --no-color --no-ext-diff > "$scan.diff" 2>/dev/null \ + || ! git -C "$GSTACK_HOME" diff --cached --no-renames --no-color --no-ext-diff --text --no-textconv -U3 > "$scan.text" 2>/dev/null; then block_drain "git could not read the staged diff for the re-scan" return 1 fi - gate_out=$(secret_scan gate "$scan.diff") || gate_rc=$? + gate_out=$(secret_scan gate "$scan.diff" "$scan.text") || gate_rc=$? [ "$gate_rc" -eq 0 ] && return 0 if [ "$gate_rc" -eq 3 ]; then block_drain "a re-scan after holding back the flagged files still matched ($gate_out)" 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 new file mode 100644 index 00000000000..912149f8782 --- /dev/null +++ b/changelog.d/brain-sync-scans-binary-files-and-split-authorization-values.md @@ -0,0 +1,4 @@ +--- +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/docs/gbrain-sync-errors.md b/docs/gbrain-sync-errors.md index 2d14d7f073f..aba6258e76c 100644 --- a/docs/gbrain-sync-errors.md +++ b/docs/gbrain-sync-errors.md @@ -55,13 +55,17 @@ from it. **Held files.** When the secret scan flags a file, only that file is held back (with any file coupled to it, such as a decision log and its active snapshot); everything else syncs. The held file stays queued and is -re-scanned on every sync, so editing it clears the hold automatically. +re-scanned on every sync, so removing a secret that was never synced clears +the hold automatically. A secret already committed in `~/.gstack` stays on a +removed line of the next diff, so that file stays held until you skip it. `--status` lists each held file under `held`, with the scanner rule that matched (never the matched text), the files held with it (`dependents`) and both fixes: -1. **If it's a real secret**: edit the file to remove it. The next skill run - re-scans and syncs it. +1. **If it's a real secret**: edit the file to remove it. If that line was + never synced, the next skill run re-scans and syncs it. If it is already + committed in `~/.gstack`, skip the file (fix 2) and, if it was pushed, + treat the secret as exposed. 2. **If the match is a false positive** you never want synced: ```bash ~/.claude/skills/gstack/bin/gstack-brain-sync --skip-file diff --git a/docs/gbrain-sync.md b/docs/gbrain-sync.md index 19e7aeaf0d5..c31bab1c6a7 100644 --- a/docs/gbrain-sync.md +++ b/docs/gbrain-sync.md @@ -160,12 +160,27 @@ The last four follow gstack's redaction rules, so placeholders such as `sk_live_EXAMPLE…`, `${DB_PASSWORD}` or `postgres:postgres@localhost` are not held. -The scan reads the whole staged diff, including file names and the unchanged -lines shown around each edit. Each added line is also scanned with its JSON -strings decoded, so a secret written with `\u` escapes or inside an escaped -JSON string is still caught. Because unchanged lines are scanned too, a file -that already holds a flagged line is held on every edit until you remove the -line or skip the file. +The scan reads the whole staged diff twice: once as `git diff` shows it to +you (your `diff.context` and any textconv driver apply), and once as raw text +with three unchanged lines around each edit. A match in either reading holds +the file. Both readings include file names. Each added line is also +scanned with its JSON strings decoded, so a secret written with `\u` escapes or inside an escaped +JSON string is still caught. Each edited block is also read as the new file +text, so a key on an unchanged line and a value added under it are matched +together, whatever your git `diff.context` setting is. Files git treats as +binary (a NUL byte, UTF-16 text) are scanned by their bytes, read plainly, +without NULs and as UTF-16. If git still reports a file as binary instead of +showing its bytes, the file is held as `binary-not-scanned`. Bytes that none +of these readings turn into text, such as a compressed file, are not held +unless a pattern matches them. + +Because unchanged and removed lines are scanned too, a file that already holds +a flagged line is held on every edit while that line is in the diff. If the +flagged line was never synced, delete it and the next sync goes through. If it +is already committed in `~/.gstack`, deleting it leaves it on a removed line +of the next diff, so the file stays held and only `--skip-file` clears it. +Skipping stops syncing the file, so a copy that was already pushed stays on +the remote; if it was pushed, treat the secret as exposed. If a scan hits, only the flagged file is held back (with any file coupled to it); everything else syncs. The held file stays queued and is re-scanned @@ -182,7 +197,10 @@ To remediate: 2. If the match is a false positive on content you never want synced, run `gstack-brain-sync --skip-file ` to permanently exclude that path; `gstack-brain-sync --unskip-file ` undoes it. -3. Otherwise, edit the file to remove the secret; the next skill run syncs it. +3. Otherwise, edit the file to remove the secret. If that line was never + synced, the next skill run syncs the file. If it is already committed in + `~/.gstack`, the file stays held and only `--skip-file` clears it; if it + was pushed, treat the secret as exposed. There's a defense-in-depth hook at `~/.gstack/.git/hooks/pre-commit` that runs the same scanner (`bin/gstack-brain-secret-scan.py`) if you manually diff --git a/test/brain-sync.test.ts b/test/brain-sync.test.ts index 70b3f1ef753..6ff7036ef9d 100644 --- a/test/brain-sync.test.ts +++ b/test/brain-sync.test.ts @@ -312,6 +312,70 @@ describe('init + sync + restore round-trip', () => { } }); + test('the pre-commit hook init and restore write refuses an AWS key in a binary file (GST-2292)', () => { + const body = Buffer.from('\0' + 'AKIA' + 'ABCDEFGHIJKLMNOP' + '\n', 'latin1'); + const commitRefused = (home: string) => { + fs.mkdirSync(path.join(home, 'projects/p/ceo-plans'), { recursive: true }); + fs.writeFileSync(path.join(home, 'projects/p/ceo-plans/note.md'), body); + git(['add', '-f', 'projects/p/ceo-plans/note.md'], home); + const r = git(['-c', 'user.name=fixture', '-c', 'user.email=fixture@example.com', 'commit', '-q', '-m', 'manual commit'], home); + expect(r.status).not.toBe(0); + expect(r.stderr).toContain('aws-access-key'); + }; + expect(run(['gstack-artifacts-init', '--remote', bareRemote]).status).toBe(0); + commitRefused(tmpHome); + const machineB = fs.mkdtempSync(path.join(os.tmpdir(), 'brain-machineB-')); + try { + expect(run(['gstack-brain-restore', bareRemote], { env: { GSTACK_HOME: machineB } }).status).toBe(0); + commitRefused(machineB); + } finally { + fs.rmSync(machineB, { recursive: true, force: true }); + } + }); + + test('the scanner flags a binary section it was not given the bytes of', () => { + const textDiff = path.join(tmpHome, 'text.diff'); + const scan = (diff: string) => { + fs.writeFileSync(textDiff, diff); + return spawnSync('python3', [path.join(BIN, 'gstack-brain-secret-scan.py'), 'gate', '-', textDiff], { input: diff.replace(/^Binary files .*$|^GIT binary patch$/gm, ''), encoding: 'utf-8', timeout: 30_000 }); + }; + const header = 'diff --git a/n.md b/n.md\nnew file mode 100644\nindex 0000000..1111111\n'; + for (const tail of ['Binary files /dev/null and b/n.md differ\n', 'GIT binary patch\nliteral 3\nKcmZ?wFaQ7m\n\n']) { + const r = scan(header + tail); + expect(r.status).toBe(3); + expect(r.stdout.trim()).toBe('binary-not-scanned'); + } + const text = scan(header + '--- /dev/null\n+++ b/n.md\n@@ -0,0 +1 @@\n+Binary files are mentioned here\n'); + expect(text.status).toBe(0); + }); + + // GST-2292 audit: the hook keeps scanning the plain diff main scanned (the + // user's diff.context and textconv drivers apply) beside the --text reading. + for (const [name, setup, body] of [ + ['an AWS key on a context line that diff.context 5 shows', (home: string) => { + fs.writeFileSync(path.join(home, 'projects/p/ceo-plans/note.md'), ' AKIA' + 'ABCDEFGHIJKLMNOP\n1\n2\n3\nbefore\n'); + git(['add', '-f', 'projects/p/ceo-plans/note.md'], home); + expect(git(['-c', 'user.name=fixture', '-c', 'user.email=fixture@example.com', 'commit', '-q', '--no-verify', '-m', 'baseline'], home).status).toBe(0); + git(['config', 'diff.context', '5'], home); + }, ' AKIA' + 'ABCDEFGHIJKLMNOP\n1\n2\n3\nafter\n'], + ['an AWS key that only a textconv driver decodes', (home: string) => { + fs.writeFileSync(path.join(home, '.git/info/attributes'), 'projects/p/ceo-plans/note.md diff=audit\n'); + git(['config', 'diff.audit.textconv', 'base64 -d'], home); + }, Buffer.from('AKIA' + 'ABCDEFGHIJKLMNOP\n').toString('base64') + '\n'], + ] as [string, (home: string) => void, string][]) { + test(`the pre-commit hook refuses ${name}`, () => { + expect(run(['gstack-artifacts-init', '--remote', bareRemote]).status).toBe(0); + fs.mkdirSync(path.join(tmpHome, 'projects/p/ceo-plans'), { recursive: true }); + fs.mkdirSync(path.join(tmpHome, '.git/info'), { recursive: true }); + setup(tmpHome); + fs.writeFileSync(path.join(tmpHome, 'projects/p/ceo-plans/note.md'), body); + git(['add', '-f', 'projects/p/ceo-plans/note.md']); + const r = git(['-c', 'user.name=fixture', '-c', 'user.email=fixture@example.com', 'commit', '-q', '-m', 'manual commit']); + expect(r.status).not.toBe(0); + expect(r.stderr).toContain('aws-access-key'); + }); + } + test('the pre-commit hook fails closed when its scanner is missing or fails', () => { expect(run(['gstack-artifacts-init', '--remote', bareRemote]).status).toBe(0); const hook = path.join(tmpHome, '.git/hooks/pre-commit'); @@ -527,6 +591,141 @@ describe('gstack-brain-sync secret scan', () => { expect(statusJson().held.map((h: any) => h.path)).toEqual([rel]); }); + // GST-2292: git prints "Binary files ... differ" for a file with a NUL byte + // instead of its bytes, so the scan has to read the bytes some other way. + function syncFile(rel: string, body: string | Buffer, env?: Record) { + fs.mkdirSync(path.dirname(path.join(tmpHome, rel)), { recursive: true }); + fs.writeFileSync(path.join(tmpHome, rel), body); + run(['gstack-brain-enqueue', rel]); + expect(run(['gstack-brain-sync', '--once'], { env }).status).toBe(0); + return JSON.parse(fs.readFileSync(path.join(tmpHome, '.brain-sync-status.json'), 'utf-8')); + } + const remoteFiles = () => + spawnSync('git', ['--git-dir=' + bareRemote, 'ls-tree', '-r', '--name-only', 'main'], { encoding: 'utf-8', timeout: 30_000 }).stdout; + const AWS_KEY = 'AKIA' + 'ABCDEFGHIJKLMNOP'; + const BINARY_CASES: [string, Buffer][] = [ + ['a NUL byte', Buffer.from('\0' + AWS_KEY + '\n', 'latin1')], + ['UTF-16LE text', Buffer.from('note ' + AWS_KEY + '\n', 'utf16le')], + ['UTF-16BE text', Buffer.from('note ' + AWS_KEY + '\n', 'utf16le').swap16()], + ]; + for (const [name, body] of BINARY_CASES) { + test(`an AWS key in a file git calls binary (${name}) is held`, () => { + run(['gstack-artifacts-init', '--remote', bareRemote]); + run(['gstack-config', 'set', 'artifacts_sync_mode', 'full']); + const rel = 'projects/p/ceo-plans/note.md'; + const status = syncFile(rel, body); + expect(status.status).toBe('held'); + expect(status.held.map((h: any) => h.path)).toEqual([rel]); + expect(remoteFiles()).not.toContain(rel); + }); + } + + test('an AWS key added to a clean binary file that already synced is held', () => { + run(['gstack-artifacts-init', '--remote', bareRemote]); + run(['gstack-config', 'set', 'artifacts_sync_mode', 'full']); + const rel = 'projects/p/ceo-plans/note.md'; + const clean = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 0x0d, 0x49, 0x48, 0x44, 0x52, 0xff, 0x00, 0x10]); + const first = syncFile(rel, clean); + expect(first.held_count ?? 0).toBe(0); + expect(remoteFiles()).toContain(rel); + const second = syncFile(rel, Buffer.concat([clean, Buffer.from('\n' + AWS_KEY + '\0', 'latin1')])); + expect(second.status).toBe('held'); + expect(second.held.map((h: any) => h.path)).toEqual([rel]); + const shown = spawnSync('git', ['--git-dir=' + bareRemote, 'show', 'main:' + rel], { timeout: 30_000 }).stdout as Buffer; + expect(shown.toString('latin1')).not.toContain(AWS_KEY); + }); + + test('a Bearer value added under an unchanged authorization key is held', () => { + run(['gstack-artifacts-init', '--remote', bareRemote]); + run(['gstack-config', 'set', 'artifacts_sync_mode', 'full']); + const rel = 'projects/p/ceo-plans/headers.md'; + const first = syncFile(rel, '{\n "authorization":\n}\n'); + expect(first.held_count ?? 0).toBe(0); + const value = ' "Bearer ' + 'abcdef1234567890' + 'abcdef1234567890"\n'; + const second = syncFile(rel, '{\n "authorization":\n' + value + '}\n'); + expect(second.status).toBe('held'); + expect(second.held.map((h: any) => h.path)).toEqual([rel]); + }); + + test('a Bearer value added under an unchanged authorization key in UTF-16 text is held', () => { + run(['gstack-artifacts-init', '--remote', bareRemote]); + run(['gstack-config', 'set', 'artifacts_sync_mode', 'full']); + const rel = 'projects/p/ceo-plans/headers.md'; + const first = syncFile(rel, Buffer.from('{\n "authorization":\n}\n', 'utf16le')); + expect(first.held_count ?? 0).toBe(0); + const value = ' "Bearer ' + 'abcdef1234567890' + 'abcdef1234567890"\n'; + const second = syncFile(rel, Buffer.from('{\n "authorization":\n' + value + '}\n', 'utf16le')); + expect(second.status).toBe('held'); + expect(second.held.map((h: any) => h.path)).toEqual([rel]); + }); + + test('a Bearer value added under an unchanged authorization key is held when git diff.context is 0', () => { + run(['gstack-artifacts-init', '--remote', bareRemote]); + run(['gstack-config', 'set', 'artifacts_sync_mode', 'full']); + const env = { GIT_CONFIG_COUNT: '1', GIT_CONFIG_KEY_0: 'diff.context', GIT_CONFIG_VALUE_0: '0' }; + const rel = 'projects/p/ceo-plans/headers.md'; + const first = syncFile(rel, '{\n "authorization":\n}\n', env); + expect(first.held_count ?? 0).toBe(0); + const value = ' "Bearer ' + 'abcdef1234567890' + 'abcdef1234567890"\n'; + const second = syncFile(rel, '{\n "authorization":\n' + value + '}\n', env); + expect(second.status).toBe('held'); + expect(second.held.map((h: any) => h.path)).toEqual([rel]); + }); + + // GST-2292 audit: the scan keeps main's plain diff as one reading, so a + // larger diff.context or a textconv driver still shows it what main saw. + test('an AWS key on an unchanged line that the user\'s diff.context 5 shows is held', () => { + run(['gstack-artifacts-init', '--remote', bareRemote]); + run(['gstack-config', 'set', 'artifacts_sync_mode', 'full']); + const rel = 'projects/p/ceo-plans/note.md'; + fs.mkdirSync(path.join(tmpHome, 'projects/p/ceo-plans'), { recursive: true }); + fs.writeFileSync(path.join(tmpHome, rel), ' ' + AWS_KEY + '\n1\n2\n3\nbefore\n'); + git(['add', '-f', rel]); + expect(git(['-c', 'user.name=fixture', '-c', 'user.email=fixture@example.com', 'commit', '-q', '--no-verify', '-m', 'baseline']).status).toBe(0); + git(['config', 'diff.context', '5']); + const status = syncFile(rel, ' ' + AWS_KEY + '\n1\n2\n3\nafter\n'); + expect(status.status).toBe('held'); + expect(status.held.map((h: any) => h.path)).toEqual([rel]); + }); + + test('a \\u-escaped AWS key in a UTF-16 JSON file is held', () => { + run(['gstack-artifacts-init', '--remote', bareRemote]); + run(['gstack-config', 'set', 'artifacts_sync_mode', 'full']); + const rel = 'projects/p/ceo-plans/note.md'; + const status = syncFile(rel, Buffer.from('{"k":"\\u0041KIA' + 'ABCDEFGHIJKLMNOP"}\n', 'utf16le')); + expect(status.status).toBe('held'); + expect(status.held.map((h: any) => h.path)).toEqual([rel]); + expect(remoteFiles()).not.toContain(rel); + }); + + test('the scan files that hold staged bytes are private to the user', () => { + run(['gstack-artifacts-init', '--remote', bareRemote]); + run(['gstack-config', 'set', 'artifacts_sync_mode', 'full']); + const shimDir = path.join(tmpHome, 'shim'); + const modes = path.join(tmpHome, 'scan-modes.txt'); + fs.mkdirSync(shimDir, { recursive: true }); + const realGit = spawnSync('sh', ['-c', 'command -v git'], { encoding: 'utf-8', timeout: 30_000 }).stdout.trim(); + fs.writeFileSync(path.join(shimDir, 'git'), `#!/bin/sh\n"${realGit}" "$@"\nrc=$?\nfor f in "${tmpHome}"/brain-sync-paths.*.scan.diff "${tmpHome}"/brain-sync-paths.*.scan.text; do [ -f "$f" ] && ls -ln "$f" | cut -c1-10 >> '${modes}'; done\nexit $rc\n`, { mode: 0o755 }); + const status = syncFile('projects/p/ceo-plans/note.md', '# a plan\n', { PATH: shimDir + path.delimiter + process.env.PATH, TMPDIR: tmpHome }); + expect(status.held_count ?? 0).toBe(0); + const seen = fs.readFileSync(modes, 'utf-8').split('\n').filter(Boolean); + expect(seen.length).toBeGreaterThan(0); + expect([...new Set(seen)]).toEqual(['-rw-------']); + }); + + test('an AWS key that only a configured textconv driver decodes is held', () => { + run(['gstack-artifacts-init', '--remote', bareRemote]); + run(['gstack-config', 'set', 'artifacts_sync_mode', 'full']); + const rel = 'projects/p/ceo-plans/note.md'; + fs.mkdirSync(path.join(tmpHome, '.git/info'), { recursive: true }); + fs.writeFileSync(path.join(tmpHome, '.git/info/attributes'), rel + ' diff=audit\n'); + git(['config', 'diff.audit.textconv', 'base64 -d']); + const status = syncFile(rel, Buffer.from(AWS_KEY + '\n').toString('base64') + '\n'); + expect(status.status).toBe('held'); + expect(status.held.map((h: any) => h.path)).toEqual([rel]); + expect(remoteFiles()).not.toContain(rel); + }); + test('a clean file whose name is an AWS access key is held', () => { run(['gstack-artifacts-init', '--remote', bareRemote]); run(['gstack-config', 'set', 'artifacts_sync_mode', 'full']); @@ -760,8 +959,9 @@ describe('gstack-brain-sync per-file hold', () => { expect(remoteLog()).toMatch(/sync: 997 file/); const calls = shim.calls(); expect(calls.filter((c) => / add /.test(` ${c} `)).length).toBe(1); - // attribution diff + name list + post-hold re-scan diff + empty-diff check - expect(calls.filter((c) => c.includes('diff --cached')).length).toBeLessThanOrEqual(4); + // attribution diffs (plain and --text, GST-2292) + name list + post-hold + // re-scan diffs (plain and --text) + empty-diff check + expect(calls.filter((c) => c.includes('diff --cached')).length).toBeLessThanOrEqual(6); expect(spoolFiles()).toHaveLength(3); }, 120_000); From 4685fa9233dd6ae858140c5c8d87a7772ebd37fb Mon Sep 17 00:00:00 2001 From: Garry Tan Date: Mon, 9 Nov 2026 22:36:56 -0800 Subject: [PATCH 3/7] Warn when a branch-only run hides a red PR check, and make ready refuse when its note or base is missing (GST-2205) (#4270) * Warn when a red check is replaced by a run from another suite, and refuse a plain ready whose note never reached origin (GST-2205) Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * Fetch the base before ready picks the train or plain path (GST-2205) Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * Let the train path report its own fetch failure when ready cannot refresh the base (GST-2205) Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * Give the no-origin/main routing test a complete pregate record (GST-2205) Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * Give the unpushed ready-note test a complete pregate record (GST-2205) 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-ship-queue | 4 +- ...uperseded-ci-refuse-unpushed-ready-note.md | 6 ++ crew/lib/ship-queue-train-ready.ts | 5 +- crew/lib/ship-queue-train-record.ts | 8 +++ docs/ship-policy.md | 20 +++++- docs/troubleshooting.md | 30 ++++++-- lib/ship-queue-land-direct.ts | 2 +- lib/ship-queue-land.ts | 2 +- lib/ship-queue.ts | 72 ++++++++++++++----- test/gstack-ship-queue.test.ts | 29 ++++++++ test/ship-queue-land-direct.test.ts | 59 ++++++++++++++- test/ship-queue-ready-fresh-base.test.ts | 21 +++++- 12 files changed, 226 insertions(+), 32 deletions(-) create mode 100644 changelog.d/warn-superseded-ci-refuse-unpushed-ready-note.md diff --git a/bin/gstack-ship-queue b/bin/gstack-ship-queue index c7ebfad1a40..0b38d53ea4a 100755 --- a/bin/gstack-ship-queue +++ b/bin/gstack-ship-queue @@ -37,7 +37,7 @@ import { EXIT, exitTableHelp, formatResult } from '../lib/headless-artifacts'; import { versionAtRef } from '../lib/restamp'; import { RESULT_CODES } from '../lib/result-codes'; import { resolveBaseBranch } from '../lib/ship-policy'; -import { loadBasePolicy, ready, stamp, verify, type QueueContext, type StepOutput } from '../lib/ship-queue'; +import { loadBasePolicy, ready, refreshBase, stamp, verify, type QueueContext, type StepOutput } from '../lib/ship-queue'; import { attemptFile, listAttempts, prepareGateAhead, recordGateAhead, type QueueFailure } from '../crew/lib/ship-queue-gate'; import { logShipCall } from '../lib/ship-call-log'; @@ -197,8 +197,10 @@ async function main(argv: string[]): Promise { if (gateExit !== undefined && !/^-?\d+$/.test(gateExit)) return usage('--gate-exit needs an exit code'); const gate = { gateExit: gateExit === undefined ? undefined : Number(gateExit), gateLog: flag(args, '--gate-log') }; if (cmd === 'ready') { + const unfetched = refreshBase(ctx); const loaded = loadBasePolicy(ctx); if (!('message' in loaded) && loaded.policy.train) return (await import('../crew/lib/ship-queue-train-cli')).readyMain(ctx, args, { pr, pregate: flag(args, '--pregate'), ...gate }); + if (unfetched) return finish('ready', { ok: false, lines: [], run: 'none', failure: unfetched }); if (['--screen', '--no-screen', '--broad'].some(f => args.includes(f))) process.stderr.write('gstack-ship-queue ready: --screen/--no-screen/--broad ignored: the base policy declares no train block\n'); return finish('ready', ready(ctx, { pr, pregate: flag(args, '--pregate'), ...gate })); } diff --git a/changelog.d/warn-superseded-ci-refuse-unpushed-ready-note.md b/changelog.d/warn-superseded-ci-refuse-unpushed-ready-note.md new file mode 100644 index 00000000000..9cee845e298 --- /dev/null +++ b/changelog.d/warn-superseded-ci-refuse-unpushed-ready-note.md @@ -0,0 +1,6 @@ +--- +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/crew/lib/ship-queue-train-ready.ts b/crew/lib/ship-queue-train-ready.ts index 8a37d9d9f94..7c7debe1401 100644 --- a/crew/lib/ship-queue-train-ready.ts +++ b/crew/lib/ship-queue-train-ready.ts @@ -29,7 +29,7 @@ import { recordVerdict, screenVerdict, verdictLines, type ScreenOutcome } from ' import { execFor, prInfo, repoSlug } from './ship-queue-train-github'; import { bindTrainReceipt } from './ship-queue-train-gate'; import { extractReceipt } from '../../lib/ship-receipt'; -import { loadReady, nowIso, persist, readyPath, rebuildFromNotes, type ReadyReceipt, type ScreenChoice } from './ship-queue-train-record'; +import { loadReady, nowIso, persist, readyNoteUnpushed, readyPath, rebuildFromNotes, type ReadyReceipt, type ScreenChoice } from './ship-queue-train-record'; import { baseOverlap, fetchBase, mergeCommit, outOk, outPending, outRefused, trainEnv, type TrainEnv, type TrainOut } from './ship-queue-train'; import { checkWavePin } from './ship-queue-wave'; import { readyPlan } from '../../lib/plan-record'; @@ -183,8 +183,7 @@ function recordReceipt(env: TrainEnv, receipt: ReadyReceipt, lines: string[], ag const p = persist(env.ctx.repoRoot, [receipt], { remote: env.remote }); lines.push(`READY_RECEIPT: ${file} (${p.detail})`); if (p.pushed) return null; - return outRefused({ code: 'QUEUE_READY_NOTE_UNPUSHED', message: `the READY receipt for #${receipt.pr} at ${receipt.head.slice(0, 12)} is written locally, but ${env.remote} does not hold its note on refs/notes/gstack-trains (${p.detail}); land reads that note, so this head is not READY` }, - lines, `fix the notes push to ${env.remote}, then ${again}`, file); + return outRefused(readyNoteUnpushed(receipt.pr, receipt.head, env.remote, p.detail), lines, `fix the notes push to ${env.remote}, then ${again}`, file); } const screenLine = (c: ScreenChoice) => `screen: ${c.choice}${c.policy ? ` policy=${c.policy} nonce=${c.nonce} run=${c.run ?? '-'}${c.verdict ? ` verdict=${c.verdict.outcome}` : ''}` : ''}`; diff --git a/crew/lib/ship-queue-train-record.ts b/crew/lib/ship-queue-train-record.ts index c61dacb93f8..c147d9d00a1 100644 --- a/crew/lib/ship-queue-train-record.ts +++ b/crew/lib/ship-queue-train-record.ts @@ -324,6 +324,14 @@ export function persist(repoRoot: string, records: AnyRecord[], opts: { push?: b return { pushed: false, detail: `git push ${NOTES_REF} failed after 3 tries: ${last}` }; } +/** + * QUEUE_READY_NOTE_UNPUSHED: `land --pin` reads the READY note on the remote, so a READY receipt written only here is + * not READY (reports/GSTA-461.md item 19). The train and plain ready paths both refuse with it. + */ +export function readyNoteUnpushed(pr: string, head: string, remote: string, detail: string): { code: 'QUEUE_READY_NOTE_UNPUSHED'; message: string } { + return { code: 'QUEUE_READY_NOTE_UNPUSHED', message: `the READY receipt for #${pr} at ${head.slice(0, 12)} is written locally, but ${remote} does not hold its note on ${NOTES_REF} (${detail}); land reads that note, so this head is not READY` }; +} + function newerOrMissing(r: AnyRecord): boolean { try { const cur = JSON.parse(fs.readFileSync(recordPath(r), 'utf8')); diff --git a/docs/ship-policy.md b/docs/ship-policy.md index e87346d9962..e84f35c8deb 100644 --- a/docs/ship-policy.md +++ b/docs/ship-policy.md @@ -223,7 +223,10 @@ READY_RECEIPT: /ship-queue/ready//42-.json (notes pu ``` Under `changelog_fragments`, a `READY_RECEIPT:` line follows, written only when -every check above passed; `land` refuses a pin without one. +every check above passed; `land` refuses a pin without one. It says `notes +pushed` only once origin holds the note; otherwise `ready` refuses with +[`QUEUE_READY_NOTE_UNPUSHED`](troubleshooting.md#queue-ready-note-unpushed), +as it does under a train, because `land` reads the note on origin. CI's Version Gate (`scripts/compare-pr-version.ts`) accepts that head as unstamped when `VERSION` and `package.json`'s version match its merge base, the @@ -276,6 +279,14 @@ counts as a failed check ` (run , no jobs)` unless a later run of the same workflow replaced it; a run cancelled before any job is not counted. An unreadable list is unknown, never green. +When a check counts as passing only because a newer run from another check +suite replaced a red one (a branch-only `free-tests.yml` dispatch beside the red +`pull_request` run, which tested the merge with the base), `ready` prints +`CI_SUPERSEDED: red run replaced by (suite → )` under +the `ci:` line, one per replaced run, and `land` prints the same under its `CI:` +line. It is a warning and changes no verdict; a rerun in the same suite prints +nothing ([what to do](troubleshooting.md#ci-superseded)). + It refuses (`QUEUE_NOT_READY`) when the working tree has tracked edits, HEAD is not the PR's pushed head, CI at that exact head is not green, or the pregate result is not a current pass, and (`QUEUE_RECEIPT_MISSING`, @@ -732,9 +743,12 @@ slot. The queue enforces this at every step from the PR body alone: `REVIEW_TARGETED:` line) when a targeted class the head needs has no done targeted pass in the receipt, and `QUEUE_RECEIPT_EXCEPTION_INVALID` when an owner exception it records does not stand ([the ship receipt](#ship-receipt)). - There is no flag around it. Before any of these checks, `ready` fetches + There is no flag around it. Before any of these checks, and before it + chooses the train or plain path from the policy, `ready` fetches `origin/` and reads the policy and every receipt field against that - fresh ref, so a lane clone whose base is behind the remote never turns a good + fresh ref (a clone with a missing or stale base ref would otherwise run plain + `ready` under a train policy and skip the screen, conflict and READY-receipt + steps), so a lane clone whose base is behind the remote never turns a good receipt into `RECEIPT_INVALID` (GST-2232); a failed fetch refuses with `QUEUE_BASE_UNFETCHED` before anything is compared. The stamp path of `land` refuses the same way; `land --pin` (`merge: direct`) refuses a failed fetch diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index 50e62d95aaf..1a6366f2e77 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -5503,8 +5503,8 @@ resumes its own lock. ### `QUEUE_BASE_UNFETCHED` **Meaning.** `gstack-ship-queue ready` (or the stamp path of `land`) could not -fetch `origin/`, so it stopped before reading the policy or comparing -any receipt field. Both compare the receipt's recorded selection, depth and +fetch `origin/`, so it stopped before reading the policy (which also +picks `ready`'s train or plain path) or comparing any receipt field. Both compare the receipt's recorded selection, depth and targeted classes with what the current base gives the head; a local `origin/` a few landings old measures the PR from an older merge base, pulls in files of PRs that already landed, and reports a false @@ -6525,10 +6525,30 @@ CHANGELOG drops or renames a released heading (the message then names the CHANGELOG). `train prune --stale` deletes the scratch branches of merged or closed PRs. + +### `CI_SUPERSEDED: red run replaced by (suite → )` + +**Meaning.** `gstack-ship-queue ready` or `land` judges each check by its +newest run, and here the newest run passed in a different check suite from an +older red run of the same check. The usual cause is a lane dispatching +`free-tests.yml` on its branch after the `pull_request` run went red. The +`pull_request` run tested GitHub's merge of the branch with the base, and the +dispatched run tested the branch alone, so a failure that exists only on the +merge with main can be hidden. The line is a warning: CI still counts as +green, and nothing is refused. A rerun of the red run in its own suite prints +nothing (reports/GSTA-461.md item 7). + +**Fix.** Nothing is required. Before sending READY or landing, open the red +run (`gh run view ` names the job) and check whether it failed for a reason +the branch-only run could not see. If it was a flaky test, log it as flaky the +usual way. To clear the line, rerun the failed `pull_request` run itself +(`gh run rerun --failed`), which replaces it in the same suite. + ### `QUEUE_READY_NOTE_UNPUSHED` -**Meaning.** `gstack-ship-queue ready` wrote the READY receipt in the local +**Meaning.** `gstack-ship-queue ready` (under a train policy, or under +`changelog_fragments` without one) wrote the READY receipt in the local state root, but origin does not hold its note on `refs/notes/gstack-trains`. `ready` pushes the notes ref, then fetches it back and requires origin's tip to be the local tip or to contain it. It tries three times, fetching and @@ -6543,7 +6563,9 @@ the land failed instead (#4245). Don't send the READY block. refused it, then run the `NEXT:` line, which is the same `ready` command without `--pregate`, `--gate-exit` or `--gate-log`: add back any of those you passed the first time. It keeps the first `ready_at`, follows a screen run already dispatched at the -same merge SHA, and pushes the kept receipt. To see the raw error, run +same merge SHA, and pushes the kept receipt. Without a train policy there is +no `NEXT:` line: rerun the same `ready` command with the same flags, and it +writes the receipt again and pushes it. To see the raw error, run `git push origin refs/notes/gstack-trains:refs/notes/gstack-trains`. diff --git a/lib/ship-queue-land-direct.ts b/lib/ship-queue-land-direct.ts index 3e83ab8eb79..97fd0fcc9e9 100644 --- a/lib/ship-queue-land-direct.ts +++ b/lib/ship-queue-land-direct.ts @@ -189,7 +189,7 @@ export function landDirect(ctx: QueueContext, o: DirectOptions): StepOutput { } const ci = ciAtHead(ctx, o.pin); - lines.push(`CI: ${ci.line}`); + lines.push(`CI: ${ci.line}`, ...ci.superseded); if (!ci.green) return fail(lines, { code: 'QUEUE_LAND_CHECKS', message: `checks are ${ci.line}`, fix: `wait for pending checks (gstack-pr-wait ${o.pr} --until green), or fix the red one at a new head; then rerun land` }); const passed = new Set([...ci.checks.filter(c => c.conclusion === 'success').map(c => c.name), ...ci.contexts.filter(c => c.state === 'success').map(c => c.name)]); const missing = (policy.changelog_fragments?.required_checks ?? []).filter(n => !passed.has(n)); diff --git a/lib/ship-queue-land.ts b/lib/ship-queue-land.ts index 3f58372e602..d8232fc6c5a 100644 --- a/lib/ship-queue-land.ts +++ b/lib/ship-queue-land.ts @@ -357,7 +357,7 @@ export function land(ctx: QueueContext, o: LandOptions): StepOutput { } if (!j) { const ci = ciAtHead(ctx, pin); - lines.push(`CI: ${ci.line}`); + lines.push(`CI: ${ci.line}`, ...ci.superseded); if (!ci.green) return fail(lines, { code: 'QUEUE_NOT_READY', message: `required checks are not green at the pin ${pin.slice(0, 12)}` }, run); } if (o.dryRun) { diff --git a/lib/ship-queue.ts b/lib/ship-queue.ts index b396b04036e..82eb917877d 100644 --- a/lib/ship-queue.ts +++ b/lib/ship-queue.ts @@ -41,7 +41,7 @@ import { type AttemptRecord, type QueueFailure, } from '../crew/lib/ship-queue-gate'; import { wtreeFingerprint } from './script-invocation'; -import { nowIso, persist, readyPath, repoIdentity } from '../crew/lib/ship-queue-train-record'; +import { nowIso, persist, readyNoteUnpushed, readyPath, repoIdentity } from '../crew/lib/ship-queue-train-record'; import { buildReceipt, type TreeReceipt } from './tree-receipt'; export type Gh = (args: string[]) => { ok: boolean; out: string; err?: string }; @@ -134,22 +134,46 @@ function readAllPages(ctx: QueueContext, endpoint: string, key: 'check_runs' | ' * completed run with no readable completed_at, is never collapsed and counts on * its own (fail closed). */ -export function latestRunPerName(runs: T[]): T[] { +type CheckRun = { name?: unknown; id?: unknown; status?: unknown; completed_at?: unknown; app?: unknown }; +const runRank = (r: CheckRun) => (r.status !== 'completed' ? Infinity : typeof r.completed_at === 'string' ? Date.parse(r.completed_at) : NaN); +/** One app's check name, or null for a run that is never collapsed (no name, or completed with no readable completed_at). */ +function checkKey(r: CheckRun): string | null { + if (typeof r.name !== 'string' || !r.name || Number.isNaN(runRank(r))) return null; + const app = (r.app as { id?: unknown } | null | undefined)?.id; + return `${typeof app === 'number' || typeof app === 'string' ? app : ''}\0${r.name}`; +} + +export function latestRunPerName(runs: T[]): T[] { const latest = new Map(); const standalone: T[] = []; - const rank = (r: T) => (r.status !== 'completed' ? Infinity : typeof r.completed_at === 'string' ? Date.parse(r.completed_at) : NaN); const id = (r: T) => (typeof r.id === 'number' ? r.id : Number(r.id) || 0); for (const r of runs) { - const app = (r.app as { id?: unknown } | null | undefined)?.id; - if (typeof r.name !== 'string' || !r.name || Number.isNaN(rank(r))) { standalone.push(r); continue; } - const key = `${typeof app === 'number' || typeof app === 'string' ? app : ''}\0${r.name}`; + const key = checkKey(r); + if (key === null) { standalone.push(r); continue; } const have = latest.get(key); - if (!have || rank(r) > rank(have) || (rank(r) === rank(have) && id(r) > id(have))) latest.set(key, r); + if (!have || runRank(r) > runRank(have) || (runRank(r) === runRank(have) && id(r) > id(have))) latest.set(key, r); } return [...latest.values(), ...standalone]; } const suiteOf = (r: Record) => String((r.check_suite as { id?: unknown } | null | undefined)?.id ?? ''); +const PASSING = ['success', 'skipped', 'neutral']; + +/** + * A CI_SUPERSEDED line for each red run whose check counts by a passing newer run from another check suite, such as a + * branch-only dispatch that replaced a red pull_request run, which tested the merge with the base (reports/GSTA-461.md + * item 7). It only warns: the verdict is latestRunPerName's. A rerun in the same suite prints nothing. + */ +function supersededLines(runs: Array>, judged: Array>): string[] { + const winners = new Map(judged.map(r => [checkKey(r), r] as const).filter(([k]) => k !== null)); + return runs.flatMap(r => { + const key = checkKey(r); + const by = key === null ? undefined : winners.get(key); + if (!by || by === r || r.status !== 'completed' || PASSING.includes(String(r.conclusion))) return []; + if (by.status !== 'completed' || !PASSING.includes(String(by.conclusion)) || suiteOf(r) === suiteOf(by)) return []; + return [`CI_SUPERSEDED: ${String(r.name)} red run ${String(r.id ?? '?')} replaced by ${String(by.id ?? '?')} (suite ${suiteOf(r) || '?'} → ${suiteOf(by) || '?'})`]; + }); +} /** * Workflow runs at a head that ended without a passing conclusion and without one check run (a startup_failure, or a @@ -183,19 +207,20 @@ export function joblessRuns(latestSuites: Set, judged: Array; contexts: Array<{ name: string; state: string }> } { +export function ciAtHead(ctx: QueueContext, sha: string): { line: string; green: boolean; none: boolean; checks: Array<{ name: string; status: string; conclusion: string | null }>; contexts: Array<{ name: string; state: string }>; superseded: string[] } { const at = sha.slice(0, 12); const latest = readAllPages(ctx, `repos/{owner}/{repo}/commits/${sha}/check-runs`, 'check_runs'); - if ('error' in latest) return { line: `unknown at ${at} (${latest.error})`, green: false, none: false, checks: [], contexts: [] }; + if ('error' in latest) return { line: `unknown at ${at} (${latest.error})`, green: false, none: false, checks: [], contexts: [], superseded: [] }; const all = readAllPages(ctx, `repos/{owner}/{repo}/commits/${sha}/check-runs?filter=all`, 'check_runs'); - if ('error' in all) return { line: `unknown at ${at} (${all.error})`, green: false, none: false, checks: [], contexts: [] }; + if ('error' in all) return { line: `unknown at ${at} (${all.error})`, green: false, none: false, checks: [], contexts: [], superseded: [] }; const statuses = readAllPages(ctx, `repos/{owner}/{repo}/commits/${sha}/status`, 'statuses'); - if ('error' in statuses) return { line: `unknown at ${at} (${statuses.error})`, green: false, none: false, checks: [], contexts: [] }; + if ('error' in statuses) return { line: `unknown at ${at} (${statuses.error})`, green: false, none: false, checks: [], contexts: [], superseded: [] }; const workflowRuns = readAllPages(ctx, `repos/{owner}/{repo}/actions/runs?head_sha=${sha}`, 'workflow_runs'); - if ('error' in workflowRuns) return { line: `unknown at ${at} (${workflowRuns.error})`, green: false, none: false, checks: [], contexts: [] }; + if ('error' in workflowRuns) return { line: `unknown at ${at} (${workflowRuns.error})`, green: false, none: false, checks: [], contexts: [], superseded: [] }; const latestSuites = new Set(latest.items.map(suiteOf).filter(Boolean)); const latestIds = new Set(latest.items.map(r => String(r.id ?? '')).filter(Boolean)); - const judged = latestRunPerName([...latest.items, ...all.items.filter(r => suiteOf(r) ? !latestSuites.has(suiteOf(r)) : !!r.id && !latestIds.has(String(r.id)))]); + const candidates = [...latest.items, ...all.items.filter(r => suiteOf(r) ? !latestSuites.has(suiteOf(r)) : !!r.id && !latestIds.has(String(r.id)))]; + const judged = latestRunPerName(candidates); const checks = [ ...judged.map(c => ({ name: String(c.name ?? ''), status: String(c.status ?? ''), conclusion: c.conclusion === undefined || c.conclusion === null ? null : String(c.conclusion) })), ...joblessRuns(latestSuites, judged, workflowRuns.items), @@ -207,7 +232,7 @@ export function ciAtHead(ctx: QueueContext, sha: string): { line: string; green: const count = (v: string) => verdicts.filter(x => x === v).length; const [passed, failed, pending, skipped] = [count('passed'), count('failed'), count('pending'), count('skipped')]; const green = verdicts.length > 0 && pending === 0 && failed === 0; - return { line: `${green ? 'green' : pending ? 'pending' : verdicts.length ? 'red' : 'none'} at ${at} (passed=${passed} failed=${failed} pending=${pending} skipped=${skipped})`, green, none: verdicts.length === 0, checks, contexts: statuses.items.map(s => ({ name: String(s.context ?? ''), state: String(s.state ?? '') })) }; + return { line: `${green ? 'green' : pending ? 'pending' : verdicts.length ? 'red' : 'none'} at ${at} (passed=${passed} failed=${failed} pending=${pending} skipped=${skipped})`, green, none: verdicts.length === 0, checks, contexts: statuses.items.map(s => ({ name: String(s.context ?? ''), state: String(s.state ?? '') })), superseded: supersededLines(candidates, judged) }; } /** @@ -256,11 +281,21 @@ function gateLine(policy: LoadedPolicy, attempt: AttemptRecord | null): string { return `gate: command=${p.gate_command ? JSON.stringify(p.gate_command) : 'none'} full_e2e=${p.full_e2e ? 'yes' : 'no'} gate-ahead=${rec}`; } +/** + * Refresh origin/: ready reads the base policy (which also picks the train or plain path) and binds the receipt + * against the current base, never a ref it did not refresh. + */ +export function refreshBase(ctx: QueueContext): QueueFailure | null { + const fetched = git(ctx.repoRoot, ['fetch', '--no-tags', '-q', 'origin', `+refs/heads/${ctx.base}:refs/remotes/origin/${ctx.base}`]); + if (fetched.ok) return null; + return { code: 'QUEUE_BASE_UNFETCHED', message: `cannot fetch origin/${ctx.base} (${fetched.err.trim().split('\n')[0]?.slice(0, 200) ?? ''}); ready reads the policy and checks the receipt against the current base, never a ref it did not refresh`, fix: `fix the fetch (git fetch origin ${ctx.base}), then rerun ready` }; +} + /** READY: one block, identifiers first, about the exact pushed PR head. */ export function ready(ctx: QueueContext, o: { pr: string; pregate?: string; gateExit?: number; gateLog?: string }): StepOutput { const run = PREGATE_OUT_REL; - const fetched = git(ctx.repoRoot, ['fetch', '--no-tags', '-q', 'origin', `+refs/heads/${ctx.base}:refs/remotes/origin/${ctx.base}`]); - if (!fetched.ok) return fail({ code: 'QUEUE_BASE_UNFETCHED', message: `cannot fetch origin/${ctx.base} (${fetched.err.trim().split('\n')[0]?.slice(0, 200) ?? ''}); ready reads the policy and checks the receipt against the current base, never a ref it did not refresh`, fix: `fix the fetch (git fetch origin ${ctx.base}), then rerun ready` }, [], run); + const unfetched = refreshBase(ctx); + if (unfetched) return fail(unfetched, [], run); const policy = loadBasePolicy(ctx); if ('message' in policy) return fail(policy, [], run); const head = git(ctx.repoRoot, ['rev-parse', 'HEAD']).out; @@ -318,6 +353,7 @@ export function ready(ctx: QueueContext, o: { pr: string; pregate?: string; gate `version: ${version}`, `base: origin/${ctx.base}@${baseSha}`, `ci: ${ci.line}`, + ...ci.superseded, ...(hint ? [hint] : []), pregateLine, ...(accepted ? flakyExceptionLines(accepted) : []), @@ -340,8 +376,10 @@ export function ready(ctx: QueueContext, o: { pr: string; pregate?: string; gate if (!policy.policy.train && policy.policy.changelog_fragments) { const repo = repoIdentity(ctx.repoRoot); const now = nowIso(); - const p = persist(ctx.repoRoot, [{ schema: 1, kind: 'ready', repo_key: repo.key, pr: o.pr, head, base_sha: baseSha, ready_at: now, screen: { choice: 'no-screen', policy: null, nonce: null, run: null, merge_sha: null }, updated_at: now, ...(plan.record ? { plan: plan.record } : {}) }], { remote: ctx.remote ?? 'origin' }); + const remote = ctx.remote ?? 'origin'; + const p = persist(ctx.repoRoot, [{ schema: 1, kind: 'ready', repo_key: repo.key, pr: o.pr, head, base_sha: baseSha, ready_at: now, screen: { choice: 'no-screen', policy: null, nonce: null, run: null, merge_sha: null }, updated_at: now, ...(plan.record ? { plan: plan.record } : {}) }], { remote }); lines.push(`READY_RECEIPT: ${readyPath(repo.key, o.pr, head)} (${p.detail})`); + if (!p.pushed) return fail({ ...readyNoteUnpushed(o.pr, head, remote, p.detail), fix: `fix the notes push to ${remote} (the READY_RECEIPT line ends with its error), then rerun gstack-ship-queue ready --pr ${o.pr} with the same flags` }, lines, run); } return { ok: true, lines, run }; } diff --git a/test/gstack-ship-queue.test.ts b/test/gstack-ship-queue.test.ts index 32b5b69f884..310bb6a47d1 100644 --- a/test/gstack-ship-queue.test.ts +++ b/test/gstack-ship-queue.test.ts @@ -689,6 +689,35 @@ describe('ready reads all of CI at the head (review #3235 P1-5)', () => { expect(plain.r.status).toBe(EXIT.ok); }, 240_000); + // Value: protects=ready names each red run that a newer run from another check suite replaced (a branch-only dispatch beside the red pull_request + // run) and keeps the verdict; fails_when=free-tests red in suite 1 and green in suite 3 prints green with no CI_SUPERSEDED line, or a rerun in the + // same suite, a pass replacing a pass, or a red newest run prints one; why_new=reports/GSTA-461.md item 7; seam=ciAtHead's latestRunPerName through + // the gh shim; no_claim=which suite tested the merge with main + test('a red run that a newer run from another check suite replaced prints CI_SUPERSEDED and changes no verdict (GSTA-461 item 7)', () => { + const app = { id: 15368 }; + const run = (id: number, name: string, conclusion: string, completed_at: string, suite: number, earlier = false) => ({ id, name, status: 'completed', conclusion, completed_at, app, check_suite: { id: suite }, ...(earlier ? { earlier_attempt: true } : {}) }); + const title = run(50, 'Plain title', 'success', '2026-11-09T10:05:00Z', 2); + const superseded = (out: string) => out.split('\n').filter(l => l.startsWith('CI_SUPERSEDED:')); + const replaced = readyWith({ check_runs: [run(10, 'free-tests', 'failure', '2026-11-09T10:00:00Z', 1), run(30, 'free-tests', 'success', '2026-11-09T10:20:00Z', 3), title] }); + expect(replaced.r.status).toBe(EXIT.ok); + const lines = replaced.r.out.split('\n'); + const ci = lines.indexOf(`ci: green at ${replaced.at} (passed=2 failed=0 pending=0 skipped=0)`); + expect(ci).toBeGreaterThan(0); + expect(lines[ci + 1]).toBe('CI_SUPERSEDED: free-tests red run 10 replaced by 30 (suite 1 → 3)'); + expect(superseded(replaced.r.out)).toHaveLength(1); + const two = readyWith({ check_runs: [run(30, 'free-tests', 'success', '2026-11-09T10:20:00Z', 3), run(10, 'free-tests', 'failure', '2026-11-09T10:00:00Z', 1), run(11, 'Plain title', 'timed_out', '2026-11-09T10:01:00Z', 1), run(51, 'Plain title', 'success', '2026-11-09T10:30:00Z', 4)] }); + expect(two.r.status).toBe(EXIT.ok); + expect(superseded(two.r.out)).toEqual(['CI_SUPERSEDED: free-tests red run 10 replaced by 30 (suite 1 → 3)', 'CI_SUPERSEDED: Plain title red run 11 replaced by 51 (suite 1 → 4)']); + const sameSuite = readyWith({ check_runs: [run(10, 'free-tests', 'failure', '2026-11-09T10:00:00Z', 1, true), run(30, 'free-tests', 'success', '2026-11-09T10:20:00Z', 1), title] }); + expect(sameSuite.r.status).toBe(EXIT.ok); + expect(superseded(sameSuite.r.out)).toEqual([]); + const passOverPass = readyWith({ check_runs: [run(10, 'free-tests', 'success', '2026-11-09T10:00:00Z', 1), run(30, 'free-tests', 'success', '2026-11-09T10:20:00Z', 3), title] }); + expect(superseded(passOverPass.r.out)).toEqual([]); + const redNewest = readyWith({ check_runs: [run(10, 'free-tests', 'success', '2026-11-09T10:00:00Z', 1), run(30, 'free-tests', 'failure', '2026-11-09T10:20:00Z', 3), title] }); + expect(redNewest.r.status).toBe(EXIT.refused); + expect(superseded(redNewest.r.out)).toEqual([]); + }, 240_000); + // Value: protects=the workflow-runs read fails closed like the check-runs read; fails_when=ready treats an unreadable or short actions/runs list // as zero jobless runs and calls the head green; seam=ciAtHead's readAllPages over actions/runs?head_sha; no_claim=GitHub's own pagination test('an unreadable or short workflow-runs list is unknown, never green', () => { diff --git a/test/ship-queue-land-direct.test.ts b/test/ship-queue-land-direct.test.ts index 967626be8d2..d25bf3ae71e 100644 --- a/test/ship-queue-land-direct.test.ts +++ b/test/ship-queue-land-direct.test.ts @@ -27,9 +27,11 @@ import { readTrainNotes } from '../crew/scripts/release-cut'; import { gitIn } from '../crew/scripts/train-gate'; import type { GhRunner } from '../crew/scripts/recover-receipts'; import { TRAIN_BLOCK } from './helpers/ship-queue-train-fixture'; +import { CHECK_IDS } from '../lib/pregate/index'; const REQUIRED = ['free-tests', 'Check VERSION is not stale vs queue']; const POLICY = { ...BASE_POLICY, release_tool: null, release_outputs: [], changelog_fragments: { dir: 'changelog.d', required_checks: REQUIRED }, merge: 'direct', min_gstack_version: MERGE_KEY_VERSION }; +const FULL_CHECKS = CHECK_IDS.map(id => ({ id, status: 'pass' })); /** The base policy with land.merged_checks: the first proves the checks see the merged tree, the second stands in for a budget cap a stale base can break (#3886). */ const CHECKED = { ...POLICY, land: { merged_checks: ['test -e other.txt && ls pr-*.txt >/dev/null', "test ! -e budget.md || test ! -e other.txt || { echo 'budget.md over its cap' >&2; exit 1; }"] }, min_gstack_version: LAND_KEY_VERSION }; const repos: FixtureRepo[] = []; @@ -59,7 +61,7 @@ function setup(policy: Record = POLICY): Fx { " if(m[2]==='status'){console.log(JSON.stringify({total_count:0,statuses:[]}));process.exit(0)}", " const set=d.checks[m[1]]??Object.fromEntries(d.defaultChecks.map(n=>[n,'success']));", " const all=/[?&]filter=all(&|$)/.test(a[1]);", - " const runs=Object.entries(set).filter(([,v])=>all||!v.earlierAttempt).map(([name,v],i)=>{const c=typeof v==='string'?v:v.conclusion;return {id:i+1,name,status:c==='pending'?'in_progress':'completed',conclusion:c==='pending'?null:c,completed_at:'2026-11-03T00:00:00Z',app:{id:1}}});", + " const runs=Array.isArray(set)?set.filter(r=>all||!r.earlier_attempt):Object.entries(set).filter(([,v])=>all||!v.earlierAttempt).map(([name,v],i)=>{const c=typeof v==='string'?v:v.conclusion;return {id:i+1,name,status:c==='pending'?'in_progress':'completed',conclusion:c==='pending'?null:c,completed_at:'2026-11-03T00:00:00Z',app:{id:1}}});", " console.log(JSON.stringify({total_count:runs.length,check_runs:runs}));process.exit(0)}", "if(a[0]==='pr'&&a[1]==='merge'){const p=d.prs[a[2]];const want=a[a.indexOf('--match-head-commit')+1];const head=g('rev-parse','refs/heads/'+p.headRefName);", " if(head!==want){console.error('Head branch was modified');process.exit(1)}", @@ -477,6 +479,61 @@ describe('land --pin: direct merge at the PR\'s own green head', () => { }, 90_000); }); +describe('land --pin and ready under merge: direct (GSTA-461 items 7 and 19)', () => { + const run = (id: number, name: string, conclusion: string, completed_at: string, suite: number) => ({ id, name, status: 'completed', conclusion, completed_at, app: { id: 1 }, check_suite: { id: suite } }); + + // Value: protects=land --pin names each red run that a newer run from another check suite replaced, right after its CI line, and still lands; + // fails_when=land prints plain green and merges with no word when free-tests failed in suite 1 and a branch-only run passed in suite 3; + // why_new=reports/GSTA-461.md item 7; seam=the gh shim's raw check-run list; no_claim=the same-suite rule that would refuse (after the freeze) + test('a red check replaced by a pass from another check suite lands with a CI_SUPERSEDED line', () => { + const fx = setup(); + const pin = openPr(fx, '9'); + fx.write(d => { d.checks[pin] = [run(1, 'free-tests', 'failure', '2026-11-09T10:00:00Z', 1), run(2, 'Check VERSION is not stale vs queue', 'success', '2026-11-09T10:02:00Z', 2), run(3, 'free-tests', 'success', '2026-11-09T10:20:00Z', 3)]; }); + const r = land(fx, '9', pin); + expect(r.err).toBe(''); + expect(r.status).toBe(EXIT.ok); + const lines = r.out.split('\n'); + const ci = lines.findIndex(l => l.startsWith('CI: green at ')); + expect(ci).toBeGreaterThanOrEqual(0); + expect(lines[ci + 1]).toBe('CI_SUPERSEDED: free-tests red run 1 replaced by 3 (suite 1 → 3)'); + expect(r.out).toContain('MERGED: #9 as '); + }, 90_000); + + // Value: protects=ready without a train block refuses when origin never receives its READY note, and a rerun after the fix pushes the kept note + // that land --pin then reads from origin; fails_when=ready prints a READY_RECEIPT line and exits 0 while origin lacks the note (our own land on + // 11-09 refused QUEUE_NOT_READY this way); why_new=#4254 covers only the train path; seam=a pre-receive hook in the fixture's bare origin, and a + // separate state root for ready so land can only find the note on origin; no_claim=GitHub's own rejection messages + test('origin rejects refs/notes/*: ready refuses QUEUE_READY_NOTE_UNPUSHED; once origin accepts, a rerun pushes the note and land merges', () => { + const fx = setup(); + const head = openPr(fx, '31', { ready: false }); + fx.repo.git('checkout', '-q', 'pr-31'); + const pregate = path.join(fx.repo.root, 'pregate.json'); + fs.writeFileSync(pregate, JSON.stringify({ schema_version: 1, tree: runBin(fx.repo, 'gstack-wtree', []).out.trim(), head, verdict: 'pass', checks: FULL_CHECKS })); + const env = { ...fx.env, GSTACK_STATE_ROOT: path.join(fx.repo.root, 'ready-state') }; + const ready = () => runBin(fx.repo, 'gstack-ship-queue', ['ready', '--pr', '31', '--pregate', pregate, '--base', 'main'], env); + const hook = path.join(fx.repo.origin, 'hooks', 'pre-receive'); + const remoteNotes = () => fx.repo.git('ls-remote', 'origin', 'refs/notes/gstack-trains').split(/\s+/)[0] ?? ''; + fs.writeFileSync(hook, '#!/bin/sh\nwhile read old new ref; do case "$ref" in refs/notes/*) echo "notes refused by fixture" >&2; exit 1;; esac; done; exit 0\n', { mode: 0o755 }); + const refused = ready(); + expect(refused.status).toBe(EXIT.refused); + expect(refused.err).toContain('(QUEUE_READY_NOTE_UNPUSHED)'); + expect(refused.err).toContain('gstack-ship-queue ready --pr 31'); + expect(refused.out).not.toContain('notes pushed'); + expect(refused.out).toMatch(/^GSTACK_RESULT: .*status=refused/m); + expect(remoteNotes()).toBe(''); + fs.rmSync(hook); + const again = ready(); + expect(again.err).toBe(''); + expect(again.status).toBe(EXIT.ok); + expect(again.out).toMatch(/^READY_RECEIPT: .* \(notes pushed to origin refs\/notes\/gstack-trains\)$/m); + expect(remoteNotes()).not.toBe(''); + fx.repo.git('checkout', '-q', '--detach', 'origin/main'); + const r = land(fx, '31', head); + expect(r.status).toBe(EXIT.ok); + expect(r.out).toContain('MERGED: #31 as '); + }, 120_000); +}); + describe('land --pin: refusals (nothing merged)', () => { const refused = (fx: Fx, r: { status: number | null; err: string }, code: string) => { expect(r.status).not.toBe(EXIT.ok); diff --git a/test/ship-queue-ready-fresh-base.test.ts b/test/ship-queue-ready-fresh-base.test.ts index ce4fde81d81..701459a8304 100644 --- a/test/ship-queue-ready-fresh-base.test.ts +++ b/test/ship-queue-ready-fresh-base.test.ts @@ -12,7 +12,7 @@ import { CHECK_IDS } from '../lib/pregate/index'; import { REVIEW_EXCLUDE_KEY_VERSION } from '../lib/ship-policy'; import { BASE_POLICY, cleanup, makeFixtureRepo, runBin, type FixtureRepo } from './helpers/restamp-fixture'; import { ghQueueShim } from './helpers/ship-queue-fixture'; -import { shippedBody } from './helpers/ship-queue-train-fixture'; +import { openPr, queue as trainQueue, shippedBody, trainFixture } from './helpers/ship-queue-train-fixture'; const repos: FixtureRepo[] = []; afterEach(() => { while (repos.length) cleanup(repos.pop()!); }); @@ -103,4 +103,23 @@ describe('ready refreshes origin/ before comparing receipt fields (GST-223 expect([after.status, after.err]).toEqual([EXIT.ok, '']); expect(after.out).toContain(`base: origin/main@${moved}`); }, 180_000); + + // Value: protects=ready chooses the train or plain path from the policy on a freshly fetched base, so a clone with no origin/main + // ref never runs plain ready under a train policy (which skips the screen, conflict and READY-receipt steps); + // fails_when=the bin reads the base policy before ready fetches it, finds none, prints that the policy declares no train block + // and exits 0 with no READY_RECEIPT; why_new=#4256's fetch sits inside ready(), after the routing; seam=bin/gstack-ship-queue's + // ready routing; no_claim=a base whose fetch fails (the case above refuses it) + test('a clone with no origin/main ref routes ready by the fetched base policy: the train path, never plain ready', () => { + const fx = trainFixture(); + repos.push(fx.repo); + const head = openPr(fx, '1'); + fx.write(d => { d.ci[head] = [{ status: 'completed', conclusion: 'success' }]; }); + const pregate = path.join(fx.repo.root, 'pregate.json'); + fs.writeFileSync(pregate, JSON.stringify({ schema_version: 1, tree: runBin(fx.repo, 'gstack-wtree', []).out.trim(), head, verdict: 'pass', checks: FULL_CHECKS })); + fx.repo.git('update-ref', '-d', 'refs/remotes/origin/main'); + const r = trainQueue(fx, ['ready', '--pr', '1', '--pregate', pregate, '--no-screen']); + expect(r.err).not.toContain('declares no train block'); + expect([r.status, r.err]).toEqual([EXIT.ok, '']); + expect(r.out).toMatch(/^READY_RECEIPT: .* \(notes pushed to origin refs\/notes\/gstack-trains\)$/m); + }, 180_000); }); From 6c23638d6dfd78d01191c37249de1d4785cdc9ed Mon Sep 17 00:00:00 2001 From: Garry Tan Date: Mon, 9 Nov 2026 23:15:05 -0800 Subject: [PATCH 4/7] Stop gstack-uninstall deleting nested worktrees, locked worktrees and a .gstack repo (GST-2268) (#4267) * Stop gstack-uninstall deleting nested worktrees, locked worktrees and a .gstack repo (GST-2268) The worktree check now walks every checkout under .gstack-worktrees/, nested ones included, and keeps a submodule of a clean lane covered by that lane's status. A locked worktree stops the uninstall even with --force-worktrees. A .gstack/ that holds its own git repository is kept with a message. The check runs again right before .gstack-worktrees/ is deleted, so work saved while the prompt waited is kept (exit 2). The manual steps in docs/uninstall.md no longer rm -rf the per-project folders. test/uninstall.test.ts is already excluded from the Windows subset by scripts/lib/windows-curation.ts (it spawns a bin/ shebang script). Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * Keep a lane's submodule when it holds commits no remote-tracking branch has (GST-2268) The submodule exemption trusted the lane's status, which only compares the submodule's HEAD to the recorded gitlink. Commits on the submodule's own branches or stash live in the lane's git dir and were deleted with exit 0. Uninstall now refuses such a submodule, and matches the gitlink by exact path instead of a prefix or glob pathspec. Review-Finding: s11/outside-voice#1 reader=outside-voice Review-Finding: s11/adversarial-native#1 reader=adversarial-native Review-Finding: p1/specialist-batched#1 reader=testing Review-Finding: p1/red-team#3 reader=red-team Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * Explain the submodule rule in the uninstall docs (GST-2268) docs/uninstall.md now says a submodule inside a clean lane goes only when its commits are on a remote-tracking branch, and the changelog entry drops a mid-sentence colon. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * Make every gstack-uninstall keep check run before anything is deleted (GST-2268) The post-prompt worktree check now runs right after confirmation, before the install root or anything else is removed, so running uninstall from inside the gstack install no longer deletes a worktree edited during the prompt. A .gstack/ holding its own git repository inside the install being removed now stops the uninstall. A failing git worktree list stops it too, even with --force-worktrees. The manual cleanup in docs/uninstall.md now matches worktree paths by prefix, so it never removes a worktree outside the project whose path merely contains it. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * Also stop gstack-uninstall when a .gstack repo sits inside a Cursor, OpenCode, Copilot, Antigravity or Gemini install (GST-2268) Review-Finding: p1/specialist-batched#1 reader=red-team Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * Split a run-on sentence in the uninstall release note (GST-2268) 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 | 149 ++++++++-- ...ll-deleting-nested-and-locked-worktrees.md | 4 + docs/uninstall.md | 28 +- test/uninstall.test.ts | 267 +++++++++++++++++- 4 files changed, 416 insertions(+), 32 deletions(-) create mode 100644 changelog.d/stop-uninstall-deleting-nested-and-locked-worktrees.md diff --git a/bin/gstack-uninstall b/bin/gstack-uninstall index 7b0bc209eed..7b35678d4bb 100755 --- a/bin/gstack-uninstall +++ b/bin/gstack-uninstall @@ -7,14 +7,19 @@ # gstack-uninstall --keep-state — remove skills but keep all gstack state, # including the repo's .gstack/ and .gstack-worktrees/ # gstack-uninstall --force-worktrees — also delete .gstack-worktrees/ checkouts -# that have uncommitted changes +# that have uncommitted changes (never a +# locked worktree) # # Per-project state: git-tracked files under .gstack/ (ship policy and the -# like) are never deleted; only the files git ignores go. A checkout under -# .gstack-worktrees/ with uncommitted changes, commits no branch or tag holds, -# a status git cannot read, or no registration as this repository's worktree -# stops the uninstall (exit 2, before anything is removed) unless -# --force-worktrees is given. +# like) are never deleted; only the files git ignores go, and a .gstack/ that +# holds its own git repository is kept. A checkout under .gstack-worktrees/ +# (nested ones included) with uncommitted changes, commits no branch or tag +# holds, a status git cannot read, or no registration as this repository's +# worktree stops the uninstall (exit 2, before anything is removed) unless +# --force-worktrees is given; a locked worktree, or a worktree list git cannot +# read, stops it either way. The check runs again after the prompt, still before +# anything is removed. Run from inside the install being removed, a .gstack/ +# holding its own git repository also stops it. # # State: only the default root ~/.gstack/ is ever deleted. A state root # selected elsewhere (GSTACK_HOME, GSTACK_STATE_ROOT, GSTACK_STATE_DIR or @@ -141,16 +146,23 @@ if [ "$KEEP_STATE" -eq 0 ] && [ -e "$RESOLVED_ROOT" ]; then fi fi # ─── Per-project worktree safety ───────────────────────────── -# Every checkout root on disk under .gstack-worktrees/ (a folder holding a .git), -# registered or not, NUL-separated so no name can split into a relative path. -# A symlinked .gstack-worktrees is never followed: uninstall removes only the link. +# Every checkout on disk under .gstack-worktrees/ (a folder holding a .git), +# registered or not, including checkouts nested inside another one, +# NUL-separated so no name can split into a relative path. Symlinks are never +# followed; a symlinked .gstack-worktrees is only unlinked. _project_worktrees() { [ -d "$_GIT_ROOT/.gstack-worktrees" ] || return 0 - find "$_GIT_ROOT/.gstack-worktrees" -mindepth 0 -type d -exec sh -c 'test -e "$1/.git"' sh {} \; -print0 -prune 2>/dev/null + find "$_GIT_ROOT/.gstack-worktrees" -name .git -prune -print0 2>/dev/null | while IFS= read -r -d '' _dotgit; do + printf '%s\0' "${_dotgit%/.git}" + done } -# Real paths of the worktrees this repository registered. +# 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 | sed -n 's/^worktree //p' | while IFS= read -r _wt; do + 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 } @@ -162,36 +174,105 @@ _wt_git() { } # Prints why deleting checkout $1 would lose work; prints nothing when it is safe. # A checkout this repository did not register is never opened with git, so its -# own config cannot run anything. +# own config cannot run anything; a submodule of a registered lane is the one +# exception, read with rev-list under _wt_git. _worktree_risk() { - local _dir _status _head + local _dir _status _head _local _dir="$(_real "$1")" case "$_dir" in ""|*" "*) echo "it is not a registered worktree of this repository"; return 0 ;; esac - printf '%s\n' "$_REGISTERED_WORKTREES" | grep -Fxq -- "$_dir" || { echo "it is not a registered worktree of this repository"; return 0; } + if ! printf '%s\n' "$_REGISTERED_WORKTREES" | grep -Fxq -- "$_dir"; 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" + return 0 + fi [ "$(_real "$(_wt_git "$1" rev-parse --show-toplevel 2>/dev/null)")" = "$_dir" ] || { echo "git cannot read it as a checkout"; return 0; } _status="$(_wt_git "$1" status --porcelain --untracked-files=all --ignore-submodules=none 2>/dev/null)" || { echo "git cannot read its status"; return 0; } [ -z "$_status" ] || { echo "it has uncommitted changes"; return 0; } _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" } -if [ "$KEEP_STATE" -eq 0 ] && [ "$FORCE_WORKTREES" -eq 0 ] && [ -n "$_GIT_ROOT" ] && [ -d "$_GIT_ROOT/.gstack-worktrees" ] && [ ! -L "$_GIT_ROOT/.gstack-worktrees" ]; then - _DIRTY_WORKTREES=0 +# 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. +_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 + case "$1" in "$_wt"/*) [ ${#_wt} -gt ${#_parent} ] && _parent="$_wt" ;; esac + done </dev/null | tr '\0' '\n')" + case "$_entry" in 160000\ *) ;; *) return 1 ;; esac + [ "${_entry#* }" = "$_rel" ] +} +# Prints one "refusing to delete" line per checkout under .gstack-worktrees/ +# that must be kept; prints nothing when every one can go. A locked worktree +# is kept even with --force-worktrees. +_worktree_refusals() { + local _wt _risk + if ! git -C "$_GIT_ROOT" worktree list --porcelain >/dev/null 2>&1; 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)" - while IFS= read -r -d '' _WT; do - [ -n "$_WT" ] || continue - _WT_RISK="$(_worktree_risk "$_WT")" - [ -n "$_WT_RISK" ] || continue - echo "gstack-uninstall: refusing to delete $_WT: $_WT_RISK" >&2 - _DIRTY_WORKTREES=1 + _LOCKED_WORKTREES="$(_registered_worktrees locked)" + while IFS= read -r -d '' _wt; do + [ -n "$_wt" ] || continue + if [ -n "$_LOCKED_WORKTREES" ] && printf '%s\n' "$_LOCKED_WORKTREES" | grep -Fxq -- "$(_real "$_wt")"; then + _risk="it is locked (git worktree lock)" + elif [ "$FORCE_WORKTREES" -eq 1 ]; then + continue + else + _risk="$(_worktree_risk "$_wt")" + fi + [ -z "$_risk" ] || echo "gstack-uninstall: refusing to delete $_wt: $_risk" done < <(_project_worktrees) - if [ "$_DIRTY_WORKTREES" -eq 1 ]; then - echo "fix: commit the work to a branch or stash it, re-run with --keep-state to keep every worktree, or re-run with --force-worktrees to delete them anyway" >&2 +} +_WORKTREES_FIX="fix: commit the work to a branch or stash it, unlock a locked worktree with git worktree unlock , re-run with --keep-state to keep every worktree, or re-run with --force-worktrees to delete the unlocked ones anyway" +# Succeeds when the current repository sits inside a gstack install this +# uninstall deletes, so nothing in it can be kept by keeping one folder. +_git_root_in_install() { + local _install _root + _root="$(_real "$_GIT_ROOT")" + for _install in "$HOME/.claude/skills/gstack" "$HOME"/.codex/skills/gstack* "$HOME"/.factory/skills/gstack* "$HOME"/.kiro/skills/gstack* \ + "$HOME"/.cursor/skills/gstack* "$HOME"/.config/opencode/skills/gstack* "$HOME"/.copilot/skills/gstack* \ + "$HOME"/.gemini/antigravity-cli/skills/gstack* "$HOME"/.gemini/skills/gstack*; do + [ -d "$_install" ] || continue + _is_at_or_above "$(_real "$_install")" "$_root" && return 0 + done + return 1 +} +# Every keep decision for per-project state, made before anything is removed: +# exits 2 when a checkout must be kept, or when the repository's .gstack/ holds +# its own git repository inside the install being deleted. $1, when set, is +# printed before the fix line. +_check_project_keep() { + [ -n "$_GIT_ROOT" ] || return 0 + if [ "$KEEP_STATE" -eq 0 ] && [ -d "$_GIT_ROOT/.gstack-worktrees" ] && [ ! -L "$_GIT_ROOT/.gstack-worktrees" ]; then + _REFUSALS="$(_worktree_refusals)" + if [ -n "$_REFUSALS" ]; then + printf '%s\n' "$_REFUSALS" >&2 + [ -z "${1:-}" ] || echo "$1" >&2 + echo "$_WORKTREES_FIX" >&2 + exit 2 + fi + fi + if [ -d "$_GIT_ROOT/.gstack" ] && [ ! -L "$_GIT_ROOT/.gstack" ] && [ -n "$(find "$_GIT_ROOT/.gstack" -name .git -print -quit 2>/dev/null)" ] && _git_root_in_install; then + echo "gstack-uninstall: refusing to uninstall: $_GIT_ROOT/.gstack/ holds its own git repository, and it sits inside the gstack install being removed" >&2 + echo "fix: move $_GIT_ROOT/.gstack/ out of the install (or push its commits), then re-run gstack-uninstall" >&2 exit 2 fi -fi +} +_check_project_keep _report_left_root() { [ -n "$_LEAVE_ROOT" ] || return 0 @@ -238,6 +319,7 @@ if [ "$FORCE" -eq 0 ]; then y|Y|yes|YES) ;; *) echo "Aborted."; exit 0 ;; esac + _check_project_keep "nothing was removed: a checkout changed while the prompt waited" fi REMOVED=() @@ -563,6 +645,10 @@ _remove_project_dir() { return 0 fi if [ -z "$_tracked" ]; then + if [ -n "$(find "$_dir" -name .git -print -quit 2>/dev/null)" ]; then + echo "kept $_dir/: it holds its own git repository, whose commits may exist nowhere else; check it, then remove it by hand" >&2 + return 0 + fi rm -rf "$_dir" REMOVED+=("$_dir/") return 0 @@ -577,12 +663,19 @@ if [ -n "$_GIT_ROOT" ] && [ "$KEEP_STATE" -eq 0 ]; then rm -f -- "$_GIT_ROOT/.gstack-worktrees" REMOVED+=("$_GIT_ROOT/.gstack-worktrees (link only)") elif [ -d "$_GIT_ROOT/.gstack-worktrees" ]; then + _WTS=() + _WT_REALS=() while IFS= read -r -d '' _WT; do [ -n "$_WT" ] || continue - _WT_REAL="$(_real "$_WT")" + _WTS+=("$_WT") + _WT_REALS+=("$(_real "$_WT")") + done < <(_project_worktrees) + for _WT in ${_WTS[@]+"${_WTS[@]}"}; do rm -rf "$_WT" + done + for _WT_REAL in ${_WT_REALS[@]+"${_WT_REALS[@]}"}; do [ -n "$_WT_REAL" ] && [ ! -e "$_WT_REAL" ] && git -C "$_GIT_ROOT" worktree remove --force "$_WT_REAL" >/dev/null 2>&1 || true - done < <(_project_worktrees) + done _remove_project_dir .gstack-worktrees fi fi diff --git a/changelog.d/stop-uninstall-deleting-nested-and-locked-worktrees.md b/changelog.d/stop-uninstall-deleting-nested-and-locked-worktrees.md new file mode 100644 index 00000000000..c57105869e1 --- /dev/null +++ b/changelog.d/stop-uninstall-deleting-nested-and-locked-worktrees.md @@ -0,0 +1,4 @@ +--- +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/docs/uninstall.md b/docs/uninstall.md index 9b6be3f8384..3d62af1d20e 100644 --- a/docs/uninstall.md +++ b/docs/uninstall.md @@ -10,7 +10,7 @@ If gstack is installed on your machine: This handles skills, symlinks, harness registrations (the files `gstack-harness` wrote into OpenClaw, Hermes, a Dot or another harness, from their ledgers, plus the opt-in [start hook](hosts.md#start-hook), which it turns off through the harness's own CLI), global state (`~/.gstack/`), project-local state, browse daemons, and temp files. Use `--keep-state` to preserve config and analytics; it also keeps the repo's `.gstack/` and `.gstack-worktrees/`. Use `--force` to skip confirmation. -A plain uninstall keeps the git-tracked files under `.gstack/` (such as ship policy) and removes only the ones git ignores. It stops with exit 2, before removing anything, when a checkout under `.gstack-worktrees/` has uncommitted changes, has commits no branch or tag holds, or is not a worktree this repo registered. Pass `--force-worktrees` to delete those checkouts anyway. When `.gstack-worktrees` is a symlink, uninstall removes only the link and never follows it, so the folder it points at and the worktrees there are kept. It checks only the top-level checkouts: a worktree created inside another checkout under `.gstack-worktrees/` is not checked and is deleted with its parent, so commit or stash its work before you uninstall. +A plain uninstall keeps the git-tracked files under `.gstack/` (such as ship policy) and removes only the ones git ignores. It stops with exit 2, before removing anything, when a checkout under `.gstack-worktrees/` has uncommitted changes, has commits no branch or tag holds, or is not a worktree this repo registered. Pass `--force-worktrees` to delete those checkouts anyway. Every checkout is checked, including a worktree created inside another checkout under `.gstack-worktrees/`. A git submodule inside a clean checkout is deleted with it only when every commit it holds is on a remote-tracking branch; otherwise it stops the uninstall. A locked worktree (`git worktree lock`) always stops the uninstall, even with `--force-worktrees`; unlock it with `git worktree unlock ` if you want it gone. If `git worktree list` fails, the uninstall stops too, even with `--force-worktrees`. The check runs again after you confirm, before anything is removed, so a checkout you edit while the confirmation prompt waits is kept: uninstall exits 2 and removes nothing. Run from inside the gstack install itself, a `.gstack/` that holds its own git repository also stops the uninstall, because deleting the install would take it along. A `.gstack/` that is its own git repository is kept, with a message saying so, because its commits may exist nowhere else. When `.gstack-worktrees` is a symlink, uninstall removes only the link and never follows it, so the folder it points at and the worktrees there are kept. ## Option 2: Manual removal (no local repo) @@ -62,10 +62,32 @@ rm -rf ~/.gemini/skills/gstack* 2>/dev/null rm -f /tmp/gstack-* 2>/dev/null # 7. Per-project cleanup (run from each project root) -rm -rf .gstack .gstack-worktrees .claude/skills/gstack 2>/dev/null -rm -rf .agents/skills/gstack* .factory/skills/gstack* 2>/dev/null +rm -rf .claude/skills/gstack .agents/skills/gstack* .factory/skills/gstack* 2>/dev/null +# Browse state: removes only the files git ignores, so tracked files such as +# ship policy, and a .gstack/ that is its own git repo, stay. +git clean -fdXq -- .gstack 2>/dev/null +# Worktrees, deepest first: each goes only when it has no uncommitted changes, +# no commits a branch or tag lacks, and no checkout inside it. git refuses a +# locked one. Anything printed as kept still holds work: save it, then re-run. +root=$(git rev-parse --show-toplevel) +git worktree list --porcelain | sed -n 's/^worktree //p' | sort -r | +while IFS= read -r wt; do + case "$wt" in "$root/.gstack-worktrees/"*) ;; *) continue ;; esac + if [ -z "$(git -C "$wt" status --porcelain --untracked-files=all)" ] && + [ -z "$(git -C "$wt" log --oneline -1 HEAD --not --branches --tags)" ] && + [ -z "$(find "$wt" -mindepth 2 -name .git -print -quit)" ]; then + git worktree remove "$wt" || echo "kept $wt" + else + echo "kept $wt: it holds work or another checkout" + fi +done +find .gstack-worktrees -depth -type d -empty -delete 2>/dev/null || true ``` +Never `rm -rf .gstack-worktrees` by hand: a checkout there can hold uncommitted +work, commits no branch has, or another worktree nested inside it, and `rm -rf` +deletes all of it. Anything the loop above keeps, check and remove yourself. + Manual removal leaves gstack's hook entries behind in `~/.claude/settings.json` (the uninstall script removes all of them for you, including entries whose `_gstack_source` tag was stripped). Edit that file and delete every hook whose diff --git a/test/uninstall.test.ts b/test/uninstall.test.ts index 6cd3b0788e1..c17f6f22eb8 100644 --- a/test/uninstall.test.ts +++ b/test/uninstall.test.ts @@ -1,5 +1,5 @@ import { describe, test, expect, beforeEach, afterEach } from 'bun:test'; -import { spawnSync } from 'child_process'; +import { spawn, spawnSync } from 'child_process'; import * as fs from 'fs'; import * as path from 'path'; import * as os from 'os'; @@ -827,6 +827,271 @@ describe('per-project state: tracked files and dirty worktrees survive (GSTA-461 expect(fs.existsSync(path.join(repo, worktree))).toBe(true); }); + test('a symlink inside .gstack-worktrees to a repo outside is only unlinked by --force --force-worktrees', () => { + const outside = path.join(tmp, 'outside'); + fs.mkdirSync(outside); + git(['init', '-q', '-b', 'main'], outside); + fs.writeFileSync(path.join(outside, 'keep.txt'), 'keep\n'); + fs.mkdirSync(path.join(repo, '.gstack-worktrees', 'run-1'), { recursive: true }); + fs.symlinkSync(outside, path.join(repo, '.gstack-worktrees', 'run-1', 'lane')); + const r = uninstall(['--force', '--force-worktrees']); + expect(r.status).toBe(0); + expect(fs.existsSync(path.join(repo, '.gstack-worktrees'))).toBe(false); + expect(fs.readFileSync(path.join(outside, 'keep.txt'), 'utf-8')).toBe('keep\n'); + expect(fs.existsSync(path.join(outside, '.git', 'HEAD'))).toBe(true); + }); + + test('a dirty worktree nested inside a clean lane stops the uninstall and keeps its edit', () => { + addWorktree(false); + const inner = path.join(repo, worktree, '.gstack-worktrees', 'run-2', 'inner'); + git(['worktree', 'add', '-q', '--detach', inner, 'HEAD'], path.join(repo, worktree)); + fs.writeFileSync(path.join(inner, 'README.md'), 'unsaved edit\n'); + const r = uninstall(['--force']); + expect(r.status).toBe(2); + expect(r.stderr).toContain(`refusing to delete ${inner}: it has uncommitted changes`); + expect(fs.readFileSync(path.join(inner, 'README.md'), 'utf-8')).toBe('unsaved edit\n'); + expect(fs.existsSync(path.join(home, '.claude', 'skills', 'gstack'))).toBe(true); + }); + + test('a clean worktree nested inside a clean lane is removed with its registration', () => { + addWorktree(false); + const inner = path.join(repo, worktree, '.gstack-worktrees', 'run-2', 'inner'); + git(['worktree', 'add', '-q', '--detach', inner, 'HEAD'], path.join(repo, worktree)); + const r = uninstall(['--force']); + expect(r.status).toBe(0); + expect(fs.existsSync(path.join(repo, '.gstack-worktrees'))).toBe(false); + expect(git(['worktree', 'list', '--porcelain'])).not.toContain('.gstack-worktrees'); + }); + + test('an initialized submodule inside a clean lane does not stop the uninstall', () => { + const lib = path.join(tmp, 'lib'); + fs.mkdirSync(lib); + git(['init', '-q', '-b', 'main'], lib); + fs.writeFileSync(path.join(lib, 'lib.txt'), 'lib\n'); + git(['add', 'lib.txt'], lib); + git(['commit', '-q', '-m', 'lib'], lib); + git(['-c', 'protocol.file.allow=always', 'submodule', 'add', '-q', lib, 'vendor/lib']); + git(['commit', '-q', '-m', 'submodule']); + addWorktree(false); + git(['-c', 'protocol.file.allow=always', 'submodule', 'update', '-q', '--init'], path.join(repo, worktree)); + expect(fs.existsSync(path.join(repo, worktree, 'vendor', 'lib', '.git'))).toBe(true); + const r = uninstall(['--force']); + expect(r.stderr).toBe(''); + expect(r.status).toBe(0); + expect(fs.existsSync(path.join(repo, '.gstack-worktrees'))).toBe(false); + }); + + test('a submodule inside a clean lane with a commit no remote-tracking branch holds stops the uninstall', () => { + const lib = path.join(tmp, 'lib'); + fs.mkdirSync(lib); + git(['init', '-q', '-b', 'main'], lib); + fs.writeFileSync(path.join(lib, 'lib.txt'), 'lib\n'); + git(['add', 'lib.txt'], lib); + git(['commit', '-q', '-m', 'lib'], lib); + git(['-c', 'protocol.file.allow=always', 'submodule', 'add', '-q', lib, 'vendor/lib']); + git(['commit', '-q', '-m', 'submodule']); + addWorktree(false); + git(['-c', 'protocol.file.allow=always', 'submodule', 'update', '-q', '--init'], path.join(repo, worktree)); + const sub = path.join(repo, worktree, 'vendor', 'lib'); + const recorded = git(['rev-parse', 'HEAD'], sub).trim(); + git(['switch', '-q', '-c', 'wip'], sub); + fs.writeFileSync(path.join(sub, 'wip.txt'), 'local only\n'); + git(['add', 'wip.txt'], sub); + git(['commit', '-q', '-m', 'wip'], sub); + const wip = git(['rev-parse', 'HEAD'], sub).trim(); + git(['switch', '-q', '--detach', recorded], sub); + expect(git(['status', '--porcelain', '--ignore-submodules=none'], path.join(repo, worktree))).toBe(''); + const r = uninstall(['--force']); + expect(r.status).toBe(2); + expect(r.stderr).toContain(`refusing to delete ${sub}: it is a submodule with commits no remote-tracking branch contains`); + expect(git(['cat-file', '-t', wip], sub).trim()).toBe('commit'); + }); + + for (const flags of [['--force'], ['--force', '--force-worktrees']]) { + test(`a locked worktree stops ${flags.join(' ')} and is kept with its registration`, () => { + addWorktree(false); + git(['worktree', 'lock', '--reason', 'on a USB disk', worktree]); + const r = uninstall(flags); + expect(r.status).toBe(2); + expect(r.stderr).toContain(`refusing to delete ${path.join(repo, worktree)}: it is locked`); + expect(r.stderr).toMatch(/^fix: .*git worktree unlock/m); + expect(fs.existsSync(path.join(repo, worktree, 'README.md'))).toBe(true); + expect(git(['worktree', 'list', '--porcelain'])).toContain(`worktree ${path.join(repo, worktree)}\n`); + }); + } + + test('a .gstack that is its own git repo is kept, with the reason, when the project tracks nothing there', () => { + git(['init', '-q', '-b', 'main'], path.join(repo, '.gstack')); + fs.writeFileSync(path.join(repo, '.gstack', 'notes.md'), 'mine\n'); + git(['add', 'notes.md'], path.join(repo, '.gstack')); + git(['commit', '-q', '-m', 'unpushed notes'], path.join(repo, '.gstack')); + const r = uninstall(['--force']); + expect(r.status).toBe(0); + expect(r.stderr).toContain(`kept ${repo}/.gstack/: it holds its own git repository`); + expect(git(['log', '--format=%s'], path.join(repo, '.gstack'))).toBe('unpushed notes\n'); + expect(fs.existsSync(path.join(home, '.gstack'))).toBe(false); + }); + + test('a worktree edited while the prompt waits is kept: the check runs again before deleting', async () => { + addWorktree(false); + const child = spawn('bash', [UNINSTALL], { + cwd: repo, timeout: 30_000, stdio: ['pipe', 'pipe', 'pipe'], + 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: '' }, + }); + let stdout = '', stderr = ''; + child.stderr.on('data', (d) => { stderr += d; }); + child.stdout.on('data', (d) => { + stdout += d; + if (stdout.includes('Continue? [y/N]') && !child.stdin.writableEnded) { + fs.writeFileSync(path.join(repo, worktree, 'wip.txt'), 'typed during the prompt\n'); + child.stdin.end('y\n'); + } + }); + const status = await new Promise((resolve) => child.on('close', resolve)); + expect(status).toBe(2); + expect(stderr).toContain(`refusing to delete ${path.join(repo, worktree)}: it has uncommitted changes`); + expect(stderr).toContain('nothing was removed: a checkout changed while the prompt waited'); + expect(fs.existsSync(path.join(home, '.claude', 'skills', 'gstack'))).toBe(true); + expect(fs.readFileSync(path.join(repo, worktree, 'wip.txt'), 'utf-8')).toBe('typed during the prompt\n'); + }); + + const promptRun = (cwd: string, onPrompt: () => void) => new Promise<{ status: number | null; stderr: string }>((resolve) => { + const child = spawn('bash', [UNINSTALL], { + cwd, timeout: 30_000, stdio: ['pipe', 'pipe', 'pipe'], + 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: '' }, + }); + let stdout = '', stderr = ''; + child.stderr.on('data', (d) => { stderr += d; }); + child.stdout.on('data', (d) => { + stdout += d; + if (stdout.includes('Continue? [y/N]') && !child.stdin.writableEnded) { onPrompt(); child.stdin.end('y\n'); } + }); + child.on('close', (status) => resolve({ status, stderr })); + }); + const makeInstallRepo = () => { + const install = path.join(home, '.claude', 'skills', 'gstack'); + git(['init', '-q', '-b', 'main'], install); + fs.writeFileSync(path.join(install, '.git', 'info', 'exclude'), '.gstack-worktrees/\n.gstack/\n'); + git(['add', 'SKILL.md'], install); + git(['commit', '-q', '-m', 'install'], install); + return install; + }; + + test('run from inside the install, a worktree edited during the prompt stops the uninstall before anything is removed', async () => { + const install = makeInstallRepo(); + const lane = path.join(install, '.gstack-worktrees', 'run-1', 'lane'); + git(['worktree', 'add', '-q', '--detach', lane, 'HEAD'], install); + const r = await promptRun(install, () => fs.writeFileSync(path.join(lane, 'wip.txt'), 'typed during the prompt\n')); + expect(r.status).toBe(2); + expect(r.stderr).toContain(`refusing to delete ${lane}: it has uncommitted changes`); + expect(fs.readFileSync(path.join(lane, 'wip.txt'), 'utf-8')).toBe('typed during the prompt\n'); + expect(fs.existsSync(path.join(install, 'SKILL.md'))).toBe(true); + expect(fs.existsSync(path.join(home, '.gstack'))).toBe(true); + }); + + test('run from inside the install, a .gstack that is its own repo stops the uninstall before anything is removed', () => { + const install = makeInstallRepo(); + const own = path.join(install, '.gstack'); + fs.mkdirSync(own); + git(['init', '-q', '-b', 'main'], own); + fs.writeFileSync(path.join(own, 'notes.md'), 'mine\n'); + git(['add', 'notes.md'], own); + git(['commit', '-q', '-m', 'unpushed notes'], own); + const r = spawnSync('bash', [UNINSTALL, '--force'], { + cwd: install, encoding: 'utf-8', timeout: 30_000, + env: { ...gitEnv, 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(`${install}/.gstack/ holds its own git repository`); + expect(git(['log', '--format=%s'], own)).toBe('unpushed notes\n'); + expect(fs.existsSync(path.join(home, '.gstack'))).toBe(true); + }); + + test('run from inside a Cursor install, a .gstack that is its own repo stops the uninstall before anything is removed', () => { + const install = path.join(home, '.cursor', 'skills', 'gstack'); + fs.mkdirSync(install, { recursive: true }); + fs.writeFileSync(path.join(install, 'SKILL.md'), '\n'); + git(['init', '-q', '-b', 'main'], install); + fs.writeFileSync(path.join(install, '.git', 'info', 'exclude'), '.gstack/\n'); + git(['add', 'SKILL.md'], install); + git(['commit', '-q', '-m', 'install'], install); + const own = path.join(install, '.gstack'); + fs.mkdirSync(own); + git(['init', '-q', '-b', 'main'], own); + fs.writeFileSync(path.join(own, 'notes.md'), 'mine\n'); + git(['add', 'notes.md'], own); + git(['commit', '-q', '-m', 'unpushed notes'], own); + const r = spawnSync('bash', [UNINSTALL, '--force'], { + cwd: install, 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: '' }, + }); + expect(r.status).toBe(2); + expect(r.stderr).toContain(`${install}/.gstack/ holds its own git repository`); + expect(git(['log', '--format=%s'], own)).toBe('unpushed notes\n'); + expect(fs.existsSync(path.join(install, 'SKILL.md'))).toBe(true); + }); + + test('a failing git worktree list stops --force --force-worktrees and keeps the checkouts', () => { + addWorktree(true); + const realGit = spawnSync('bash', ['-c', 'command -v git'], { encoding: 'utf-8', timeout: 30_000 }).stdout.trim(); + const shim = path.join(tmp, 'shim'); + fs.mkdirSync(shim); + fs.writeFileSync(path.join(shim, 'git'), `#!/bin/sh\ncase " $* " in *" worktree list "*) echo "fatal: broken" >&2; exit 128 ;; esac\nexec '${realGit}' "$@"\n`, { mode: 0o755 }); + const r = spawnSync('bash', [UNINSTALL, '--force', '--force-worktrees'], { + cwd: repo, encoding: 'utf-8', timeout: 30_000, + env: { ...gitEnv, PATH: `${shim}:${process.env.PATH}`, 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: '' }, + }); + expect(r.status).toBe(2); + expect(r.stderr).toContain("git cannot list this repository's worktrees"); + expect(fs.readFileSync(path.join(repo, worktree, 'wip.txt'), 'utf-8')).toBe('unsaved work\n'); + expect(fs.existsSync(path.join(home, '.claude', 'skills', 'gstack'))).toBe(true); + }); + + test('the manual cleanup in docs/uninstall.md never touches a worktree outside the project whose path contains it', () => { + const doc = fs.readFileSync(path.join(ROOT, 'docs', 'uninstall.md'), 'utf-8'); + const start = doc.indexOf('# 7. Per-project cleanup'); + const block = doc.slice(start, doc.indexOf('\n```', start)); + const external = path.join(tmp, 'mirror') + path.join(repo, '.gstack-worktrees', 'run-1', 'lane'); + git(['worktree', 'add', '-q', '--detach', external, 'HEAD']); + fs.appendFileSync(path.join(repo, '.git', 'info', 'exclude'), 'personal.txt\n'); + fs.writeFileSync(path.join(external, 'personal.txt'), 'mine\n'); + const r = spawnSync('bash', ['-c', block], { cwd: repo, encoding: 'utf-8', timeout: 30_000, env: gitEnv }); + expect(r.status).toBe(0); + expect(fs.readFileSync(path.join(external, 'personal.txt'), 'utf-8')).toBe('mine\n'); + expect(git(['worktree', 'list', '--porcelain'])).toContain(`worktree ${external}\n`); + }); + + test('the manual per-project cleanup in docs/uninstall.md keeps dirty and nested worktrees and tracked policy', () => { + const doc = fs.readFileSync(path.join(ROOT, 'docs', 'uninstall.md'), 'utf-8'); + const start = doc.indexOf('# 7. Per-project cleanup'); + expect(start).toBeGreaterThan(-1); + const block = doc.slice(start, doc.indexOf('\n```', start)); + trackPolicyAndAddBrowseState(); + addWorktree(true); + const lane = path.join(repo, '.gstack-worktrees', 'run-1', 'lane-2'); + git(['worktree', 'add', '-q', '--detach', lane, 'HEAD']); + const inner = path.join(lane, '.gstack-worktrees', 'run-2', 'inner'); + git(['worktree', 'add', '-q', '--detach', inner, 'HEAD'], lane); + fs.writeFileSync(path.join(inner, 'README.md'), 'unsaved edit\n'); + const clean = path.join(repo, '.gstack-worktrees', 'run-3', 'lane'); + git(['worktree', 'add', '-q', '--detach', clean, 'HEAD']); + const r = spawnSync('bash', ['-c', block], { cwd: repo, encoding: 'utf-8', timeout: 30_000, env: gitEnv }); + expect(r.status).toBe(0); + expect(fs.readFileSync(path.join(repo, worktree, 'wip.txt'), 'utf-8')).toBe('unsaved work\n'); + expect(fs.readFileSync(path.join(inner, 'README.md'), 'utf-8')).toBe('unsaved edit\n'); + expect(fs.existsSync(clean)).toBe(false); + expect(fs.existsSync(path.join(repo, '.gstack', 'ship-policy.json'))).toBe(true); + expect(fs.existsSync(path.join(repo, '.gstack', 'browse.json'))).toBe(false); + }); + test('hold: a plain uninstall still removes untracked .gstack state and clean worktrees entirely', () => { fs.writeFileSync(path.join(repo, '.gstack', 'browse.json'), '{}\n'); fs.mkdirSync(path.join(repo, '.gstack', 'reports'), { recursive: true }); From ee3bae40284a90c281ddf5b45f67e23a452c15a7 Mon Sep 17 00:00:00 2001 From: Garry Tan Date: Mon, 9 Nov 2026 23:58:50 -0800 Subject: [PATCH 5/7] QM edition no longer ships the review skill (GST-2306) (#4279) * Drop the review skill from the QM edition A benchmark of the QM edition found gstack-review flagged too many problems without making the reviewed work better, so the edition now ships only gstack-plan. Regenerated qm/ and removed the review-only first-step script. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * Regenerate the QM edition without the review skill and update its docs and tests Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * Give the deleted QM review script an empty test lane so the pre-merge check accepts its removal Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * Point the deleted QM review script at the QM edition test instead of no test lane 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> --- .gstack/pregate.json | 3 +- changelog.d/drop-review-from-qm-edition.md | 1 + docs/hosts.md | 2 +- hosts/qm.ts | 75 +-------- hosts/qm/scripts/diff-base.sh | 52 ------ qm/README.md | 10 +- qm/edition.json | 10 -- qm/sandbox/skills/gstack-review/SKILL.md | 157 ------------------ .../skills/gstack-review/scripts/diff-base.sh | 52 ------ test/context-budget-ratchet.test.ts | 2 +- test/qm-edition.test.ts | 88 +--------- 11 files changed, 17 insertions(+), 435 deletions(-) create mode 100644 changelog.d/drop-review-from-qm-edition.md delete mode 100644 hosts/qm/scripts/diff-base.sh delete mode 100644 qm/sandbox/skills/gstack-review/SKILL.md delete mode 100644 qm/sandbox/skills/gstack-review/scripts/diff-base.sh diff --git a/.gstack/pregate.json b/.gstack/pregate.json index d659c715ee8..04502a58f51 100644 --- a/.gstack/pregate.json +++ b/.gstack/pregate.json @@ -14,7 +14,8 @@ "LICENSE": [], "licenses/**": [], "contrib/**": [], - "supabase/**": [] + "supabase/**": [], + "qm/sandbox/skills/gstack-review/scripts/diff-base.sh": ["test/qm-edition.test.ts"] }, "selection": { "free-tests.yml/free-suite": "bun run scripts/test-free-shards.ts --list" diff --git a/changelog.d/drop-review-from-qm-edition.md b/changelog.d/drop-review-from-qm-edition.md new file mode 100644 index 00000000000..599b83a77fb --- /dev/null +++ b/changelog.d/drop-review-from-qm-edition.md @@ -0,0 +1 @@ +- **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/docs/hosts.md b/docs/hosts.md index 35c2bea02d8..2cfdba64664 100644 --- a/docs/hosts.md +++ b/docs/hosts.md @@ -64,7 +64,7 @@ characters, the part of a description Hermes's skills index shows. | OpenClaw | default `--skills hybrid`: `gstack-review`, `gstack-qa` and `gstack-ship` as top-level skills plus one `gstack` router skill whose body lists every other skill and its path, in `${OPENCLAW_STATE_DIR:-~/.openclaw}/skills`. With OpenClaw 2026.10.6's 19 eligible bundled skills, hybrid's skills section stays in full format under its 18,000-character budget; `--skills all` (17,971, compact format, descriptions cut) lists every skill as its own folder, `--skills router` (6,701) only the router. OpenClaw serves a registered skill's `SKILL.md` whole or refuses it ("Skill instructions cannot be partially served"), at most 32,768 bytes when its model catalog has no context window for the model and 32,000 characters with a 100K-200K-token window, so any registered skill over 32,000 bytes (three of the four in hybrid, 25 of 62 in `all` today) is a short entry `SKILL.md` with the same name and description that sends the agent to its full `SKILL.md` in a plain copy of every skill (the router's `gstack/skills/`, or `.gstack-skills/` under `--skills all`, a folder OpenClaw's skill scan skips), which OpenClaw reads in pages. A context window under 100K tokens lowers that budget to 16,000 characters, which this limit does not cover | `./setup --host openclaw`, or `./setup` inside OpenClaw | `openclaw skills list --json` shows `gstack` and the four task skills (source `openclaw-managed`, eligible) | `gstack-harness unregister openclaw` | | Hermes | every skill, as `gstack-` in one `gstack` category, in `${HERMES_HOME:-~/.hermes}/skills/gstack`. Hermes's skills index lists only skills registered as folders, so a router would leave the rest out of the listing (`skill_view` still loads an unlisted skill by name, but nothing tells the model it exists) | `./setup --host hermes`, or `./setup` inside Hermes | `hermes skills list` shows the `gstack-*` skills in category `gstack` | `gstack-harness unregister hermes` | | dots (feder-cr) | the `gstack` router in `/home/dot/skills/gstack`, which the Dot lists every turn | `./setup` on the Dot's computer, or `gstack-harness register dots` | the Dot's Skills page, or `GET /skills` | `gstack-harness unregister dots` | -| QM | two skills (`gstack-review`, `gstack-plan`) in QM's own skill format, from `qm/sandbox/skills/` ([qm/README.md](../qm/README.md)). `gstack-harness register qm --yes` still stops before sending anything: QM imports a skill pack by cloning the whole repository and caps it at 32 MiB and 5,000 files, and gstack's repository is about 73 MiB ([why](troubleshooting.md#harness-qm-pack-too-large)) | copy `qm/sandbox/skills/gstack-*` into `/sandbox/skills/` and run `qm up` | ask it for a gstack skill | remove the folders and run `qm up` again | +| QM | one skill (`gstack-plan`) in QM's own skill format, from `qm/sandbox/skills/` ([qm/README.md](../qm/README.md)). `gstack-harness register qm --yes` still stops before sending anything: QM imports a skill pack by cloning the whole repository and caps it at 32 MiB and 5,000 files, and gstack's repository is about 73 MiB ([why](troubleshooting.md#harness-qm-pack-too-large)) | copy `qm/sandbox/skills/gstack-*` into `/sandbox/skills/` and run `qm up` | ask it for a gstack skill | remove the folders and run `qm up` again | | Muse Code, Grok Build | nothing: both read `~/.claude/skills`, so the Claude install (`./setup`) is what they see, with Claude tool names | `./setup` | `gstack-harness status` runs `muse skills list` / `grok inspect` and reports *discovered (Claude-rendered, unverified)* | `gstack-uninstall` | | Grok Bot, any chat-only skill library | nothing on disk | `gstack-harness register generic --print`, then paste the router and block into the app | ask it for a gstack skill | delete the pasted text | | any other harness | the router in an Agent Skills folder you name, and/or a 600-byte routing block between `` markers in a context file you name | `gstack-harness register generic --skills-dir ` and/or `--context `; `gstack-harness manifest generic` prints every skill as JSON | the harness's own skill list | `gstack-harness unregister generic` | diff --git a/hosts/qm.ts b/hosts/qm.ts index 1e3a3780740..af12917c7a7 100644 --- a/hosts/qm.ts +++ b/hosts/qm.ts @@ -1,5 +1,5 @@ /** - * QM edition: two gstack skills in QM's own skill format. + * QM edition: one gstack skill (gstack-plan) in QM's own skill format. * * QM (a work assistant) lists skills in a name-and-description index with a * 12,000-char budget and loads a body only when the agent asks for it through @@ -10,7 +10,7 @@ * install hook, so every command a skill names is a POSIX utility, git, or a * POSIX sh script shipped inside the skill. * - * This is not a HostConfig in hosts/index.ts: it renders two skills by + * This is not a HostConfig in hosts/index.ts: it renders its skills by * section selection, without the shared preamble, instead of the whole * catalog through gen-skill-docs. scripts/gen-qm-edition.ts reads this spec * and writes qm/sandbox/skills// plus qm/edition.json; test/qm-edition.test.ts enforces the @@ -89,78 +89,7 @@ export const QM_EDITION = { skills: [] as QmSkill[], }; -/** - * QM rewrites the literal text `skills//` in SKILL.md to the absolute - * folder its `skill` tool synced the files into (materialize.ts:22-33), and - * the shell starts in the workspace root with scripts not executable, so a - * skill runs its script as `sh skills//scripts/`. - */ -export const qmScriptCommand = (id: string, script: string, args = ''): string => - ['sh', `skills/${id}/scripts/${script}`, args].filter(Boolean).join(' '); - - QM_EDITION.skills.push( - { - id: 'gstack-review', - source: 'review', - description: 'Use before merging a branch or PR: review the diff for bugs that pass CI but break production, fix the obvious ones and ask about the rest. (gstack)', - header: [ - '# Review: find what passes CI but breaks in production', - '', - '**Start here.** In the repository (`cd` into it first: the shell starts in the workspace root), run with `execute` (pass the base branch if you know it):', - '', - '```sh', - qmScriptCommand('gstack-review', 'diff-base.sh', ''), - '```', - '', - 'It prints the base, the merge base, the commits since the base and the diff stat, then `NEXT: git diff `; run that and read the whole diff and every untracked file before you comment (on `UNTRACKED_MORE:`, list the rest with the command it names). On `NOTHING_TO_REVIEW`, say so and stop. On `BASE: none`, ask the user for the base branch or review the uncommitted changes it shows.', - '', - 'QM fills in the absolute path of the folder its `skill` tool synced (it prints that path too). If the script is missing, run this instead:', - '', - '```sh', - 'git merge-base origin/main HEAD', - 'git diff --stat ', - '```', - '', - '## How to review', - '', - '1. Read the full diff, then the unchanged callers of anything it changes.', - '2. Apply the CRITICAL categories, then the INFORMATIONAL ones, below. Respect the suppressions.', - '3. Classify each finding with the Fix-First Heuristic: fix AUTO-FIX items directly; for ASK items, ask the user in one message (a numbered list, each with a recommended fix) and stop until they answer.', - '4. Verify each claim (below), then report: `CRITICAL` and `INFORMATIONAL` lists, one line problem and one line fix each, with file:line, then what you fixed. `NO FINDINGS` is a complete result.', - ].join('\n'), - parts: [ - { - file: 'review/checklist.md', heading: 'Review Categories', level: 2, - dropBlocks: ['gstack-timing-ok', 'CC+gstack'], - replaceText: [["route it to /investigate's flake recipe (timing flakes)", 'find the timing cause and fix that, with a test that fails on it first']], - skipHeadings: [ - 'Gate Integrity', 'Approval Classes and Data Repairs', 'Dead Code & Consistency (version/changelog only — other items handled by maintainability specialist)', - 'Keyboard-Count Test Loops', 'Distribution & CI/CD Pipeline', 'Repo Conventions & Platform Fit (runs on every PR type)', - ], - }, - { - file: 'review/checklist.md', heading: 'Fix-First Heuristic', level: 2, - dropBlocks: ['This heuristic is referenced by', 'Severity glossary', '**blocker**', '**should**', '**nit**'], - replaceText: [ - ['├─ Anything changing user-visible', '└─ Anything changing user-visible'], - ['│ behavior\n └─ Gate Integrity (always ASK; four\n gate options, never Fix/Skip)', ' behavior'], - ], - }, - { - file: 'review/checklist.md', heading: 'Suppressions — DO NOT flag these', level: 2, - dropBlocks: ['Eval threshold changes', 'gstack-shortcut'], - }, - { file: 'review/SKILL.md.tmpl', heading: 'Verification of claims', level: 2 }, - { - file: 'review/SKILL.md.tmpl', heading: 'Important Rules', level: 2, - dropBlocks: ['greptile-triage.md', 'Optional extractions stay advisory'], - replaceText: [["that's /ship's job", 'leave that to the user']], - }, - ], - firstStep: { command: qmScriptCommand('gstack-review', 'diff-base.sh', ''), marker: 'diff-base\\.sh|\\bgit\\s+(diff|merge-base)\\b' }, - scripts: { 'diff-base.sh': 'diff-base.sh' }, - }, { id: 'gstack-plan', source: 'plan-eng-review', diff --git a/hosts/qm/scripts/diff-base.sh b/hosts/qm/scripts/diff-base.sh deleted file mode 100644 index 3972c62aae0..00000000000 --- a/hosts/qm/scripts/diff-base.sh +++ /dev/null @@ -1,52 +0,0 @@ -#!/bin/sh -# gstack-review first step: find the base, the merge base and what changed. -# Usage: sh diff-base.sh [base] (POSIX sh and git only) -set -u -if ! git rev-parse --is-inside-work-tree >/dev/null 2>&1; then - echo "NOT_A_GIT_REPO: $(pwd)" - exit 0 -fi -no_base() { - echo "BASE: none ($1)" - echo "== uncommitted changes" - git status --short | head -n 40 - if git rev-parse --verify --quiet HEAD >/dev/null; then - echo "== diff stat against HEAD" - git diff --stat HEAD -- - fi - echo "NEXT: pass the base branch (sh diff-base.sh ) or review the uncommitted changes with git diff HEAD" - exit 0 -} -base=${1:-} -if [ -z "$base" ]; then - base=$(git symbolic-ref --quiet --short refs/remotes/origin/HEAD 2>/dev/null || true) -fi -if [ -z "$base" ]; then - for candidate in origin/main main origin/master master; do - if git rev-parse --verify --quiet "$candidate^{commit}" >/dev/null; then - base=$candidate - break - fi - done -fi -[ -n "$base" ] || no_base "no origin/HEAD, main or master" -merge_base=$(git merge-base "$base" HEAD 2>/dev/null) || no_base "$base has no merge base with HEAD" -echo "BRANCH: $(git symbolic-ref --quiet --short HEAD 2>/dev/null || echo detached)" -echo "BASE: $base" -echo "MERGE_BASE: $merge_base" -echo "== commits since base" -git log --oneline "$merge_base..HEAD" -- | head -n 30 -echo "== diff stat (working tree against merge base)" -git diff --stat "$merge_base" -- -untracked=$(git ls-files --others --exclude-standard) -echo "== untracked files" -printf '%s\n' "$untracked" | head -n 30 -untracked_count=$(printf '%s\n' "$untracked" | grep -c . || true) -if [ "$untracked_count" -gt 30 ]; then - echo "UNTRACKED_MORE: $((untracked_count - 30)) more untracked files; list them all with git ls-files --others --exclude-standard" -fi -if git diff --quiet "$merge_base" -- && [ -z "$untracked" ]; then - echo "NOTHING_TO_REVIEW" - exit 0 -fi -echo "NEXT: git diff $merge_base" diff --git a/qm/README.md b/qm/README.md index 221ead7f94c..c170d15745a 100644 --- a/qm/README.md +++ b/qm/README.md @@ -1,12 +1,14 @@ # gstack for QM -Two gstack skills in QM's own skill format: `gstack-review` (review a branch before merge) and `gstack-plan` (review a feature plan before building it). +One gstack skill in QM's own skill format: `gstack-plan` (review a feature plan before building it). + +The edition no longer ships `gstack-review`. A benchmark of the edition in QM found that it flagged too many problems without making the reviewed work any better, so it was cut. gstack's own `/review` skill is unchanged. QM lists each skill by name and description and loads the body only when it's needed, so nothing goes into the org SOUL and nothing is installed. Each file stays under 15,000 characters so QM's `read` and `skill` tools return it whole, and every command a skill names is a POSIX utility, `git`, or a POSIX `sh` script shipped inside the skill. QM's sandbox images have no bun and no gstack checkout. ## Install as a QM deployment layer -Copy the skill folders into your QM deployment directory and sync it: +Copy the skill folder into your QM deployment directory and sync it: ```sh mkdir -p /sandbox/skills @@ -14,7 +16,7 @@ cp -R qm/sandbox/skills/gstack-* /sandbox/skills/ qm up ``` -The skills install into the org scope. Removing the folders and running `qm up` again archives them. +The skill installs into the org scope. Removing the folder and running `qm up` again archives it. A git pack that points at this whole repository won't work: QM's pack fetcher stops at 32 MiB and 5,000 files, and it would pick up every other gstack `SKILL.md` too. To ship it as a git pack, put `qm/sandbox/skills/` in a small repository of its own. @@ -24,7 +26,7 @@ A git pack that points at this whole repository won't work: QM's pack fetcher st ## Change it -The skills are generated. Don't edit `qm/` by hand. The edition spec is `hosts/qm.ts` (the sections kept from each gstack skill, the QM header, the limits and the allowed commands), the review script is `hosts/qm/scripts/diff-base.sh`, and the rest comes from the gstack skill templates. Regenerate with: +The skill is generated. Don't edit `qm/` by hand. The edition spec is `hosts/qm.ts` (the sections kept from each gstack skill, the QM header, the limits and the allowed commands), and the rest comes from the gstack skill templates. Regenerate with: ```sh bun run scripts/gen-qm-edition.ts diff --git a/qm/edition.json b/qm/edition.json index 1977bd46b8e..2da39d4c41c 100644 --- a/qm/edition.json +++ b/qm/edition.json @@ -2,16 +2,6 @@ "edition": "gstack-qm", "layer_root": "qm/sandbox/skills", "skills": [ - { - "id": "gstack-review", - "source": "review", - "files": [ - "SKILL.md", - "scripts/diff-base.sh" - ], - "first_step": "sh skills/gstack-review/scripts/diff-base.sh ", - "first_step_marker": "diff-base\\.sh|\\bgit\\s+(diff|merge-base)\\b" - }, { "id": "gstack-plan", "source": "plan-eng-review", diff --git a/qm/sandbox/skills/gstack-review/SKILL.md b/qm/sandbox/skills/gstack-review/SKILL.md deleted file mode 100644 index 51961b6013b..00000000000 --- a/qm/sandbox/skills/gstack-review/SKILL.md +++ /dev/null @@ -1,157 +0,0 @@ ---- -name: gstack-review -description: "Use before merging a branch or PR: review the diff for bugs that pass CI but break production, fix the obvious ones and ask about the rest. (gstack)" ---- - - -# Review: find what passes CI but breaks in production - -**Start here.** In the repository (`cd` into it first: the shell starts in the workspace root), run with `execute` (pass the base branch if you know it): - -```sh -sh skills/gstack-review/scripts/diff-base.sh -``` - -It prints the base, the merge base, the commits since the base and the diff stat, then `NEXT: git diff `; run that and read the whole diff and every untracked file before you comment (on `UNTRACKED_MORE:`, list the rest with the command it names). On `NOTHING_TO_REVIEW`, say so and stop. On `BASE: none`, ask the user for the base branch or review the uncommitted changes it shows. - -QM fills in the absolute path of the folder its `skill` tool synced (it prints that path too). If the script is missing, run this instead: - -```sh -git merge-base origin/main HEAD -git diff --stat -``` - -## How to review - -1. Read the full diff, then the unchanged callers of anything it changes. -2. Apply the CRITICAL categories, then the INFORMATIONAL ones, below. Respect the suppressions. -3. Classify each finding with the Fix-First Heuristic: fix AUTO-FIX items directly; for ASK items, ask the user in one message (a numbered list, each with a recommended fix) and stop until they answer. -4. Verify each claim (below), then report: `CRITICAL` and `INFORMATIONAL` lists, one line problem and one line fix each, with file:line, then what you fixed. `NO FINDINGS` is a complete result. - -## Review Categories - -### Pass 1 — CRITICAL - -#### SQL & Data Safety -- String interpolation in SQL (even if values are `.to_i`/`.to_f` — use parameterized queries (Rails: sanitize_sql_array/Arel; Node: prepared statements; Python: parameterized queries)) -- TOCTOU races: check-then-set patterns that should be atomic `WHERE` + `update_all` -- Bypassing model validations for direct DB writes (Rails: update_column; Django: QuerySet.update(); Prisma: raw queries) -- N+1 queries: Missing eager loading (Rails: .includes(); SQLAlchemy: joinedload(); Prisma: include) for associations used in loops/views - -#### Race Conditions & Concurrency -- Read-check-write without uniqueness constraint or catch duplicate key error and retry (e.g., `where(hash:).first` then `save!` without handling concurrent insert) -- find-or-create without unique DB index — concurrent calls can create duplicates -- Status transitions that don't use atomic `WHERE old_status = ? UPDATE SET new_status` — concurrent updates can skip or double-apply transitions -- Unsafe HTML rendering (Rails: .html_safe/raw(); React: dangerouslySetInnerHTML; Vue: v-html; Django: |safe/mark_safe) on user-controlled data (XSS) - -#### LLM Output Trust Boundary -- LLM-generated values (emails, URLs, names) written to DB or passed to mailers without format validation. Add lightweight guards (`EMAIL_REGEXP`, `URI.parse`, `.strip`) before persisting. -- Structured tool output (arrays, hashes) accepted without type/shape checks before database writes. -- LLM-generated URLs fetched without allowlist — SSRF risk if URL points to internal network (Python: `urllib.parse.urlparse` → check hostname against blocklist before `requests.get`/`httpx.get`) -- LLM output stored in knowledge bases or vector DBs without sanitization — stored prompt injection risk - -#### Shell Injection (Python-specific) -- `subprocess.run()` / `subprocess.call()` / `subprocess.Popen()` with `shell=True` AND f-string/`.format()` interpolation in the command string — use argument arrays instead -- `os.system()` with variable interpolation — replace with `subprocess.run()` using argument arrays -- `eval()` / `exec()` on LLM-generated code without sandboxing - -#### Enum & Value Completeness -When the diff introduces a new enum value, status string, tier name, or type constant, or loosens what an input accepts (a new MIME type, extension or flag, or a widened validator/parser/guard): -- **Trace it through every consumer.** Read (don't just grep — READ) each file that switches on, filters by, or displays that value. If any consumer doesn't handle the new value, flag it. Common miss: adding a value to the frontend dropdown but the backend model/compute method doesn't persist it. -- **Check allowlists/filter arrays.** Search for arrays or `%w[]` lists containing sibling values (e.g., if adding "revise" to tiers, find every `%w[quick lfg mega]` and verify "revise" is included where needed). -- **Check `case`/`if-elsif` chains.** If existing code branches on the enum, does the new value fall through to a wrong default? -- **Loosened acceptance breaks unchanged consumers.** Grep every consumer of the same field and confirm each handles the newly accepted shape; the broken code is usually outside the diff. -To do this: use Grep to find all references to the sibling values (e.g., grep for "lfg" or "mega" to find all tier consumers). Read each match. This step requires reading code OUTSIDE the diff. - -### Pass 2 — INFORMATIONAL - -#### Async/Sync Mixing (Python-specific) -- Synchronous `subprocess.run()`, `open()`, `requests.get()` inside `async def` endpoints — blocks the event loop. Use `asyncio.to_thread()`, `aiofiles`, or `httpx.AsyncClient` instead. -- `time.sleep()` inside async functions — use `asyncio.sleep()` -- Sync DB calls in async context without `run_in_executor()` wrapping - -#### Column/Field Name Safety -- Verify column names in ORM queries (`.select()`, `.eq()`, `.gte()`, `.order()`) against actual DB schema — wrong column names silently return empty results or throw swallowed errors -- Check `.get()` calls on query results use the column name that was actually selected -- Cross-reference with schema documentation when available - -#### LLM Prompt Issues -- 0-indexed lists in prompts (LLMs reliably return 1-indexed) -- Prompt text listing available tools/capabilities that don't match what's actually wired up in the `tool_classes`/`tools` array -- Word/token limits stated in multiple places that could drift - -#### Completeness Gaps -- Shortcut implementations where the complete version would cost <30 minutes CC time (e.g., partial enum handling, incomplete error paths, missing edge cases that are straightforward to add) -- Test coverage gaps where adding the missing tests is a "lake" not an "ocean" (e.g., missing negative-path tests, missing edge case tests that mirror happy-path structure) -- Features implemented at 80-90% when 100% is achievable with modest additional code - -#### Time Window Safety -- Date-key lookups that assume "today" covers 24h — report at 8am PT only sees midnight→8am under today's key -- Mismatched time windows between related features — one uses hourly buckets, another uses daily keys for the same data - -#### Timing-Dependent Tests -- A diff that raises an existing timing bound or adds a retry to make a flake pass: the bound is not the cause; find the timing cause and fix that, with a test that fails on it first - -#### Type Coercion at Boundaries -- Values crossing Ruby→JSON→JS boundaries where type could change (numeric vs string) — hash/digest inputs must normalize types -- Hash/digest inputs that don't call `.to_s` or equivalent before serialization — `{ cores: 8 }` vs `{ cores: "8" }` produce different hashes - -#### View/Frontend -- Inline `