From 465d911d9c7617d13543106706a8fe659755499e Mon Sep 17 00:00:00 2001 From: Garry Tan Date: Sun, 22 Nov 2026 01:38:36 -0800 Subject: [PATCH] A granted fix round that a follow-up check reads clean now closes the findings it fixed (GST-3260) (#4664) /ship now closes a review finding when its fix round was granted and a follow-up check read the fix clean, or when the fix commit names the finding and a later full review reads it clean. Before, someone had to write a ruling by hand. Why: since this was missing, PRs whose findings were already fixed and checked stalled at the round limit (#4537, harness-evals#508, #4597, harness-evals#504, #4612). Nothing to do. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> Review-Finding: p1/specialist-batched#1 reader=security Review-Finding: p1/red-team#1 reader=red-team Review-Finding: p1/red-team#2 reader=red-team --- bin/gstack-review-plan | 8 +- bin/gstack-ship-receipt | 44 ++- ...confirmed-fix-round-closes-its-findings.md | 1 + docs/review-policy.md | 28 +- lib/fix-check-clearing.ts | 136 +++++++++ lib/headless-artifacts.ts | 6 + lib/pr-review-history.ts | 7 +- lib/review-evidence.ts | 41 +++ lib/review-pass.ts | 2 + lib/review-scope.ts | 9 +- lib/ship-receipt.ts | 4 +- lib/ship-release.ts | 15 +- lib/ship-run-record.ts | 2 +- scripts/lib/windows-curation.ts | 4 + test/exercised-map.test.ts | 1 + test/fix-check-clearing.test.ts | 284 ++++++++++++++++++ test/fixtures/module-size-ratchet.json | 1 + 17 files changed, 565 insertions(+), 28 deletions(-) create mode 100644 changelog.d/confirmed-fix-round-closes-its-findings.md create mode 100644 lib/fix-check-clearing.ts create mode 100644 test/fix-check-clearing.test.ts diff --git a/bin/gstack-review-plan b/bin/gstack-review-plan index 3e12f65f2..3afd98f32 100755 --- a/bin/gstack-review-plan +++ b/bin/gstack-review-plan @@ -46,6 +46,8 @@ import { targetedDelta } from '../lib/review-targeted-delta'; import { docsChangeSince, ownChangeSince } from '../lib/ship-receipt-depth'; import { RISK_CLASSES, type RiskClass } from '../lib/review-risk'; import { renderFixCheckPrompt } from '../scripts/resolvers/fix-check'; +import { grantSpent } from '../lib/fix-check-clearing'; +import { recordFixCheckHunks } from '../lib/review-evidence'; const HELP = `gstack-review-plan — the review depth of the next /ship step (docs/review-policy.md#review-depth) @@ -145,6 +147,7 @@ function main(): number { const [fixList, touchedHunks, testResults, callers] = [read('--fix-list', true), read('--hunks', true), read('--tests', true), read('--callers', false)]; if (fixList === null || touchedHunks === null || testResults === null || callers === null) { process.stderr.write('gstack-review-plan: --fix-check-prompt needs readable --fix-list, --hunks and --tests files (--callers optional)\n'); return EXIT.usage; } process.stdout.write(renderFixCheckPrompt({ fixList, touchedHunks, testResults, callers })); + recordFixCheckHunks(process.cwd(), touchedHunks, undefined, fixList); return EXIT.ok; } const base = flag('--base'); @@ -190,6 +193,7 @@ function main(): number { if (![priorRounds, priorFull].every(n => Number.isInteger(n) && n >= 0)) { process.stderr.write('gstack-review-plan: --prior-rounds and --prior-full need integers >= 0 (PR_REVIEW_FLAGS: from gstack-ship-preflight)\n'); return EXIT.usage; } const roundGrant = flag('--round-grant'); let grantedStop: string | undefined; + let grantUnspent = false; if (has('--round-grant')) { const at = git(['rev-parse', 'HEAD'])?.trim(); const loc = locate({ cwd: root, env: process.env }); @@ -199,6 +203,8 @@ function main(): number { if (g && (g.kind === 'fix-check') !== has('--stop')) { process.stderr.write(`gstack-review-plan: --round-grant ${roundGrant}: ${g.kind === 'fix-check' ? 'a fix-check grant answers a stop record: pass the --stop PR_REVIEW_FLAGS: prints with it' : 'an extra-round grant names no stop: --stop takes a fix-check grant'} (docs/troubleshooting.md#pr-round-cap)\n`); return EXIT.refused; } if (g && g.kind === 'fix-check' && (stop !== g.head || (pr !== undefined && String(g.pr) !== pr))) { process.stderr.write(`gstack-review-plan: --round-grant ${roundGrant}: the fix-check grant names the stop at ${g.head.slice(0, 12)} for PR #${g.pr}, not --stop ${(flag('--stop') ?? '').slice(0, 12)}${pr ? ` and PR #${pr}` : ''}; a grant buys the fix round of the one stop it names (docs/troubleshooting.md#pr-round-cap)\n`); return EXIT.refused; } if (g?.kind === 'fix-check') grantedStop = g.approval; + const logged = g?.kind === 'fix-check' && last === 'fix-check' ? runScriptSync(path.join(path.dirname(Bun.fileURLToPath(import.meta.url)), 'gstack-review-read'), [], { encoding: 'utf8', timeout: 60_000, maxBuffer: 64 * 1024 * 1024 }) : null; + grantUnspent = !!logged && logged.status === 0 && !grantSpent((logged.stdout ?? '').split('\n---CONFIG---')[0]!.split('\n').flatMap(l => { try { const v = JSON.parse(l); return v && typeof v === 'object' ? [v] : []; } catch { return []; } }), g!); const atOrBefore = !!g && !!at && (g.head === at || git(['merge-base', '--is-ancestor', g.head, at]) !== null); if (!roundGrant || !g || !atOrBefore || (pr !== undefined && String(g.pr) !== pr)) { process.stderr.write(`gstack-review-plan: --round-grant ${roundGrant ?? ''}: no approved review_round_grant row ${roundGrant ?? ''} naming HEAD ${(at ?? 'unknown').slice(0, 12)} or a commit before it${pr ? ` and PR #${pr}` : ''} in this branch's approval record; record one with gstack-approvals round-grant (docs/troubleshooting.md#pr-round-cap)\n`); return EXIT.refused; } } @@ -286,7 +292,7 @@ function main(): number { const plan = planReview({ ...collected, ...exclusionInput, ...riskPaths, declared: declared as RiskClass[], shape: { panel: review.panel, readerModel: review.reader_model, platform: review.platform, head, platformReview: platform?.ok ? platform.review : null }, scope, gateTagged, targeted: { classes: targeted.classes, ran }, numbers: scanNumbers(kept(added)), force, gated: list('--gated'), floor, tiers: auditEffort !== 'host', criticalFound: has('--critical-found'), adversarialRan: has('--adversarial-ran'), reviewedNumbers: flag('--reviewed-numbers'), - history: { priorRounds, priorFull, ...(grantedStop ? { grantedStop } : roundGrant ? { roundGrant } : {}), fullPasses: pass, last, fixedBlocking: has('--fixed-blocking'), fixedBelow: (has('--fixed-below') || (postReview && pass > 0)) && last !== 'fix-check', blockingOpen: has('--blocking-open'), touchedGate: has('--touched-gate') || (!carried && (!!fixRange?.touched_gate || (postReview && pass > 0))), pass1Depth, rangeRuntimeLines: fixRange?.runtime_lines, granted: grant, fixChecks: has('--fix-checks') ? fixChecks : undefined, postReview, chained: inLoopLink }, + history: { priorRounds, priorFull, ...(grantedStop ? { grantedStop } : roundGrant ? { roundGrant } : {}), fullPasses: pass, last: grantUnspent ? 'none' : last, fixedBlocking: has('--fixed-blocking'), fixedBelow: (has('--fixed-below') || (postReview && pass > 0)) && last !== 'fix-check', blockingOpen: has('--blocking-open'), touchedGate: has('--touched-gate') || (!carried && (!!fixRange?.touched_gate || (postReview && pass > 0))), pass1Depth, rangeRuntimeLines: fixRange?.runtime_lines, granted: grant, fixChecks: has('--fix-checks') ? fixChecks : undefined, postReview, chained: inLoopLink }, }); if (plan.next.reason.startsWith('PR_ROUND_CAP')) plan.next.reason += `: record this stop with gstack-ship-receipt stop --pr ${flag('--pr') ?? ''} --run --since , which prints the fix-check round grant (gstack-approvals round-grant --kind fix-check) that buys its fix round, in this run or the next; once it is recorded, pass the --round-grant and --stop the PR_REVIEW_FLAGS: line prints: in this run from gstack-ship-receipt history --pr ${flag('--pr') ?? ''} --base --run (its preflight already ran, and a second one is refused), in a new run from its preflight (docs/troubleshooting.md#pr-round-cap)`; if (carried) plan.next.reason = `the edits after the last fix-check ${fixCheckAt!.slice(0, 12)} are ${carried.paths.length ? `${carried.verdict === 'plain' ? 'plain docs' : `docs (${carried.paths.join(', ')})`}${carried.stamps.length ? ' and release stamps' : ''}` : 'release stamps'} (docsChangeSince), no gate-class edit (GST-1702): ${plan.next.reason}`; diff --git a/bin/gstack-ship-receipt b/bin/gstack-ship-receipt index 12c1afd78..c7773bf61 100755 --- a/bin/gstack-ship-receipt +++ b/bin/gstack-ship-receipt @@ -69,6 +69,7 @@ import { securityFingerprints } from '../lib/security-findings'; import { laneExceptionBodyLines } from '../lib/test-lane-exception'; import { abandonMarker, grantedStop, grantMarker, historyLine, placeRunEntry, prReviewHistory, receiptedRun, reviewRoute, runStub, stopFrom, stopMarker } from '../lib/pr-review-history'; import { changeRunRecord } from '../lib/ship-run-record'; +import { splitAgentNotes, withAgentNotes } from '../lib/agent-notes'; import { grantFor, publicRoundGrant, readReviewRoundGrants, type ReviewRoundGrant } from '../lib/review-round-grant'; import { readMechanicalLines } from '../lib/ship-mechanical'; import { patchId, productPatchAgainstBase, productRules, productSpec, verifiedOutputs } from '../lib/ship-receipt-patch'; @@ -266,7 +267,7 @@ function callsArg(rest: string[]): number | undefined { try { return runCalls(record, process.env) ?? undefined; } catch (e: any) { throw new Error(`--budget-record ${record}: ${e.message}`); } } -function cmdWrite(rest: string[], json: boolean): number { +async function cmdWrite(rest: string[], json: boolean): Promise { const repoRoot = git(['rev-parse', '--show-toplevel']) ?? process.cwd(); const checkedOut = git(['rev-parse', 'HEAD'], repoRoot); const head = flag(rest, '--head') ?? checkedOut; @@ -379,7 +380,18 @@ function cmdWrite(rest: string[], json: boolean): number { const loopRaw = jsonArg(flag(rest, '--review-loop')); const reviewLoop = loopRaw ? parseReviewLoop(loopRaw) : undefined; if (loopRaw && !reviewLoop) throw new Error('--review-loop needs integer passes, blocking_found and deferred (gstack-review-scope summary --out , then @)'); - const open = unruledOpenBlockers(loopRaw, ruledNotes, ruledHead => spawnSync('git', ['merge-base', '--is-ancestor', ruledHead, headSha ?? head], { cwd: repoRoot, timeout: 30_000 }).status === 0); + const ruledOpen = unruledOpenBlockers(loopRaw, ruledNotes, ruledHead => spawnSync('git', ['merge-base', '--is-ancestor', ruledHead, headSha ?? head], { cwd: repoRoot, timeout: 30_000 }).status === 0); + const at = headSha ?? head, baseRef = `origin/${base.replace(/^origin\//, '')}`, run = flag(rest, '--run'), pr = Number(flag(rest, '--pr')); + const blockers = (Array.isArray(loopRaw?.open) ? loopRaw.open : []).filter((b: any) => ruledOpen.includes(typeof b === 'string' ? b : b?.id)); + const rows = ruledOpen.length ? reviewRows(repoRoot) ?? [] : []; + const grants = ruledOpen.length ? readReviewRoundGrants(repoRoot).filter(g => g.kind === 'fix-check' && g.pr === pr) : []; + const live = grants.length && !receiptRuns(bodyText).length && flag(rest, '--pr') ? readBody(['--pr', flag(rest, '--pr')!, ...(flag(rest, '--repo') ? ['--repo', flag(rest, '--repo')!] : [])]) : undefined; + const clearing = ruledOpen.length ? await import('../lib/fix-check-clearing') : undefined; + const byGrant = !grants.length || !clearing ? undefined : !run ? { ids: [], why: 'write names no --run, so no run spent the grant' } : clearing.clearByGrant(repoRoot, { pr, run, head: at, baseRef, body: live?.ok ? live.body : bodyText, grants, rows, open: blockers }); + const byTrailer = clearing ? clearing.clearByTrailer(repoRoot, { head: at, baseRef, rows, open: blockers }) : []; + if (byGrant) process.stderr.write(`FIX_CHECK_CLEAR: ${byGrant.ids.length ? `grant=${byGrant.approval} run=${byGrant.run} closed=${byGrant.ids.join(',')}` : 'none'}${byGrant.why ? ` (${byGrant.why})` : ''}\n`); + for (const t of byTrailer) process.stderr.write(`TRAILER_CLEAR: ${t.id} (fixed by ${t.commit.slice(0, 12)}, read clean by the full review at ${t.review.slice(0, 12)})\n`); + const open = ruledOpen.filter(id => !byGrant?.ids.includes(id) && !byTrailer.some(t => t.id === id)); if (open.length) { process.stderr.write(resultLineWithDocs('gstack-ship-receipt write', 'RECEIPT_BLOCKER_OPEN', `${open.join(', ')}; nothing written`) + '\n'); return EXIT.refused; } input = { schema_version: 1, pr: flag(rest, '--pr') !== undefined ? Number(flag(rest, '--pr')) : undefined, head, @@ -393,7 +405,7 @@ function cmdWrite(rest: string[], json: boolean): number { policy: flag(rest, '--policy') ?? tree?.policy, queue_mode: flag(rest, '--queue-mode'), preregistration: flag(rest, '--preregistration'), history: flag(rest, '--history'), ...pregate, issues: issuesFile ? receiptIssuesFrom(issuesFile) : undefined, approval: approval.kind === 'ok' ? approval.approval : undefined, review_loop: reviewLoop, ...(docs?.ok ? { docs: docs.docs } : {}), ...product, - gstack_version: installedGstackVersion(), review_depth: reviewDepth, review_loop_exception: loopException?.ok ? loopException.exception : undefined, review_round_grants: roundGrantsFor(repoRoot, flag(rest, '--pr'))?.map(g => publicRoundGrant(g, ruledNotes)), ruled_notes: ruledNotes.length ? ruledNotes.map(publicRuledNote) : undefined, gate_dispositions: gateDispositions.map(publicGateDisposition), mechanical: mechanical.length ? mechanical : undefined, review_targeted: targeted?.ok ? targeted.targeted : undefined, + gstack_version: installedGstackVersion(), review_depth: reviewDepth, review_loop_exception: loopException?.ok ? loopException.exception : undefined, review_round_grants: roundGrantsFor(repoRoot, flag(rest, '--pr'))?.map(g => publicRoundGrant(g, ruledNotes)), cleared_by_grant: byGrant?.ids.length ? { approval: byGrant.approval!, run: byGrant.run!, ids: byGrant.ids } : undefined, cleared_by_trailer: byTrailer.length ? byTrailer : undefined, ruled_notes: ruledNotes.length ? ruledNotes.map(publicRuledNote) : undefined, gate_dispositions: gateDispositions.map(publicGateDisposition), mechanical: mechanical.length ? mechanical : undefined, review_targeted: targeted?.ok ? targeted.targeted : undefined, design: review.frontend ? { mode: 'static', reason: 'no preview declared' } : undefined, base_red: pause ? receiptBaseRed(pause) : undefined, review_exclude: receiptExclude(review.exclude), @@ -424,12 +436,25 @@ function cmdWrite(rest: string[], json: boolean): number { const block = renderReceiptBlock(receipt); const out = flag(rest, '--out'); if (out) fs.writeFileSync(out, block); - if (body) fs.writeFileSync(body, placeReceipt(fs.existsSync(body) ? fs.readFileSync(body, 'utf8') : '', receipt)); + const closed = [...(receipt.cleared_by_grant ? [`Closed by grant ${receipt.cleared_by_grant.approval}: ${receipt.cleared_by_grant.ids.join(', ')} (the granted fix-check of run ${receipt.cleared_by_grant.run} read the fix clean)`] : []), + ...(receipt.cleared_by_trailer ?? []).map(t => `Closed by fix ${t.commit.slice(0, 12)}: ${t.id} (a later full review at ${t.review.slice(0, 12)} read it clean)`)]; + if (body) { + const text = fs.existsSync(body) ? fs.readFileSync(body, 'utf8') : ''; + const notes = splitAgentNotes(text).notes ?? ''; + const lines = closed.filter(l => !notes.includes(l)); + fs.writeFileSync(body, placeReceipt(lines.length ? withAgentNotes(text, [notes.trim(), ...lines].filter(Boolean).join('\n\n')) : text, receipt)); + } process.stderr.write(receiptSummaryLine(receipt) + '\n'); process.stdout.write(json ? JSON.stringify(receipt) + '\n' : block); return EXIT.ok; } +/** The branch's review-log rows as gstack-review-read prints them, or null when it fails. */ +function reviewRows(repoRoot: string): Record[] | null { + const log = runScriptSync(path.join(path.dirname(Bun.fileURLToPath(import.meta.url)), 'gstack-review-read'), [], { cwd: repoRoot, encoding: 'utf8', timeout: 60_000, maxBuffer: 64 * 1024 * 1024 }); + return log.status !== 0 ? null : (log.stdout ?? '').split('\n---CONFIG---')[0]!.split('\n').flatMap(l => { try { const v = JSON.parse(l); return v && typeof v === 'object' ? [v] : []; } catch { return []; } }); +} + function cmdRead(rest: string[], json: boolean): number { const bodyFile = flag(rest, '--body'); const pr = flag(rest, '--pr'); @@ -1003,9 +1028,8 @@ function cmdStop(rest: string[]): number { if (!repoRoot) { process.stderr.write('gstack-ship-receipt stop: run it inside the git checkout\n'); return EXIT.usage; } const read = readBody(rest); if (!read.ok) { process.stderr.write(`gstack-ship-receipt stop: ${read.why}; fix: ${read.fix}\n`); return EXIT.fail; } - const log = runScriptSync(path.join(path.dirname(Bun.fileURLToPath(import.meta.url)), 'gstack-review-read'), [], { cwd: repoRoot, encoding: 'utf8', timeout: 60_000, maxBuffer: 64 * 1024 * 1024 }); - if (log.status !== 0) { process.stderr.write(`gstack-ship-receipt stop: gstack-review-read exited ${log.status}; nothing recorded\n`); return EXIT.fail; } - const rows = (log.stdout ?? '').split('\n---CONFIG---')[0]!.split('\n').flatMap(l => { try { const v = JSON.parse(l); return v && typeof v === 'object' ? [v] : []; } catch { return []; } }); + const rows = reviewRows(repoRoot); + if (!rows) { process.stderr.write('gstack-ship-receipt stop: gstack-review-read failed; nothing recorded\n'); return EXIT.fail; } const headNow = git(['rev-parse', 'HEAD'], repoRoot) ?? ''; const found = stopFrom(rows, since, { treeOf: c => git(['rev-parse', '--verify', '--quiet', `${c}^{tree}`], repoRoot), onHead: c => ancestorIn(repoRoot)(c, headNow) }); if (!found.ok) { process.stderr.write(`${resultLine('gstack-ship-receipt stop', 'STOP_UNBOUND', `${found.why}; no stop record, so no fix-check grant can answer this stop`)}\n`); return EXIT.refused; } @@ -1036,7 +1060,7 @@ function cmdClaim(rest: string[]): number { if (!again.ok) { process.stderr.write(`gstack-ship-receipt claim: ${again.why}; the claim is unconfirmed, so do not dispatch\n`); return EXIT.fail; } const first = receiptRuns(again.body).find(r => r.mark === 'grant' && r.grant === id); if (first?.run !== run) { process.stderr.write(`${resultLine('gstack-ship-receipt claim', 'GRANT_SPENT', `grant ${id} was claimed by run ${first?.run ?? 'another run'} while this run claimed it: a grant buys one round; the lane or its Captain records a new one`)}\n`); return EXIT.refused; } - const recorded = changeRunRecord(repoRoot, 'claim', run, { claim: { grant: id, ...(g.stop_run ? { stop_run: g.stop_run } : {}), stop_head: g.head, findings: g.findings ?? [] } }); + const recorded = changeRunRecord(repoRoot, 'claim', run, { claim: { grant: id, ...(g.stop_run ? { stop_run: g.stop_run } : {}), stop_head: g.head, findings: g.findings ?? [], pr: g.pr } }); process.stdout.write(`GRANT_CLAIMED: grant=${id} kind=${g.kind} run=${run} head=${g.head.slice(0, 12)}\n${recorded.ok ? '' : `RUN_RECORD: claim not recorded (${recorded.why})\n`}`); return EXIT.ok; } @@ -1075,7 +1099,7 @@ function cmdAbandoned(rest: string[]): number { return EXIT.ok; } -function main(argv: string[]): number { +async function main(argv: string[]): Promise { const [cmd, ...rest] = argv; const json = rest.includes('--json'); if (!cmd || cmd === '--help' || cmd === '-h' || cmd === 'help') { process.stdout.write(HELP + '\n'); return cmd ? EXIT.ok : EXIT.usage; } @@ -1094,4 +1118,4 @@ function main(argv: string[]): number { return EXIT.usage; } -process.exitCode = main(process.argv.slice(2)); +process.exitCode = await main(process.argv.slice(2)); diff --git a/changelog.d/confirmed-fix-round-closes-its-findings.md b/changelog.d/confirmed-fix-round-closes-its-findings.md new file mode 100644 index 000000000..b944699f2 --- /dev/null +++ b/changelog.d/confirmed-fix-round-closes-its-findings.md @@ -0,0 +1 @@ +**A fix round that a grant bought and a fix-check read clean now closes the findings the grant names, with no hand-written ruling.** `gstack-ship-receipt write` checks the grant, the PR body's stop and claim entries and the fix-check's review-log row, which `gstack-review-log` now stamps from the run record's claim with the range it read and the digest of the hunks its reader was given; it records `cleared_by_grant` in the receipt and one line in the PR body's Agent notes, and says on a `FIX_CHECK_CLEAR:` line why anything less closes nothing (another PR's or run's grant, a spent grant, no stop record, another range, anything left open, or a grant id that names no single open finding), and it closes only the findings the fix-check's fix list named, only when the hunks its reader was given cover every file the fix changed. A finding whose fix commit carries its `Review-Finding:` trailer also closes once a later full review round leaves nothing open (#4597). `finish` counts a granted fix-check from the stop its grant names, not the newest reviewed tree (#4612), and the review plan routes a fix-check grant that answers a stop raised after a fix-check to its one fix-check (harness-evals#504). (GST-3260) diff --git a/docs/review-policy.md b/docs/review-policy.md index b9b7771a3..ab5e7169a 100644 --- a/docs/review-policy.md +++ b/docs/review-policy.md @@ -247,6 +247,32 @@ caught on another crew's PRs. Captain's check of the receipt's `review_round_grants` and the PR body's lines is the control. The receipt lists grants under `review_round_grants`. + +### What closes a finding (GST-3260) + +A fix-check that a grant bought and that read the fix clean closes exactly the +findings the grant names, with no owner ruling. `gstack-ship-receipt write` +checks it from records gstack's tools wrote, never from the `--review-loop` +file (`lib/fix-check-clearing.ts`): the grant answers the newest stop record +for this PR; the PR body's first claim of it is this run's; exactly one +`review-fix-check` row carries it, and `gstack-review-log` stamped that row from +the claim (`fix_check_base`, `run`, `grant`, `pr`) with the digest of the hunks +its reader was given, which cover every path the stop-to-fix diff changes, and +the ledger ids and fingerprints its fix list named; the row read the stop's head to the receipt head (or a +head that only merges the base in) on one committed tree, with nothing open at +any severity; and the stop, the claim and the row's start were recorded in that +order. Each grant id the fix list named closes the one open blocker carrying +that id; a grant id the fix list left out closes nothing, and a fingerprint +shared by two blockers closes neither. Anything less closes nothing, and write +says why on a `FIX_CHECK_CLEAR:` line. The receipt records `cleared_by_grant`, +and the Agent notes section gets one `Closed by grant …` line. A finding whose +fix commit carries its `Review-Finding:` trailer also closes once a later full +round, bound to its committed tree and holding that commit, left nothing open +at all, by its status, its findings file or an inline finding +(`cleared_by_trailer`, #4597). finish counts the same +stamped row, anchored on the grant's stop rather than the newest reviewed tree +(#4612). + ### Transitions @@ -865,7 +891,7 @@ puts in the receipt: | `review_loop.passes` | full review passes this ship ran (1 or 2; up to 3 under `review_scope: diff-plus-blocking` or `all`) | | `review_loop.blocking_found` | every blocker found (GST-951): the rows' blocking findings (classified, or an unclassified CRITICAL), plus each ledger CRITICAL (as collected or judged) that no row finding from the same reviewer at the same path:line accounts for (each row finding pairs with one per ledger), so an adversarial, outside-voice or not-yet-classified blocker counts and one whose newest classification is below the floor does not. An unreadable ledger, merged file or judged set, or a judged set changed since `judge`, is `REVIEW_SCOPE_LEDGER`, never a count | | `review_loop.unrecorded` | blockers found that no row gives a disposition (fixed, deferred, noted, skipped, a gate answer); absent when 0 | -| `review_loop.open` | blockers a row still holds as `open` at its newest action, gate findings aside (GST-3075), each its ledger id or fingerprint (or `{ id, fingerprint }`); Step 11's `adversarial-review` row counts here like a pass's row but is never a pass or a round. Only a later row's action clears one, and while any is left with no owner ruling, `gstack-ship-receipt write` refuses with [`RECEIPT_BLOCKER_OPEN`](troubleshooting.md#receipt-blocker-open); absent when 0 | +| `review_loop.open` | blockers a row still holds as `open` at its newest action, gate findings aside (GST-3075), each its ledger id or fingerprint (or `{ id, fingerprint }`); Step 11's `adversarial-review` row counts here like a pass's row but is never a pass or a round. Only a later row's action clears one, or a [granted fix-check or a trailer-carrying fix](#what-closes-a-finding) (`cleared_by_grant`, `cleared_by_trailer`), and while any is left with no owner ruling, `gstack-ship-receipt write` refuses with [`RECEIPT_BLOCKER_OPEN`](troubleshooting.md#receipt-blocker-open); absent when 0 | | `review_loop.unbound` | what could not bind (GST-1168), each printed as `REVIEW_SCOPE_UNBOUND: : `: a row with no start token and no readable time, a `pN` ledger with no review row of pass N (a fix-check ledger in a `pN` directory is not a pass ledger, GST-1775), a row finding's `ledger_id` no ledger collected, a `Review-Finding` trailer naming nothing; absent when 0 | | `review_loop.ledgers_read` | dispatch ledgers the count read; absent under `--no-ledger` | | `REVIEW_SCOPE_VOIDED:` (stderr, not a receipt field) | an abandoned pass (GBEV-3): a `pN` ledger never judged that no row names, replaced by a later `pM` ledger (M > N) that was judged or is named. Its findings are left out of every count above instead of counting as unbound and unrecorded. A fix-check ledger and the last pass are never voided | diff --git a/lib/fix-check-clearing.ts b/lib/fix-check-clearing.ts new file mode 100644 index 000000000..e388eef48 --- /dev/null +++ b/lib/fix-check-clearing.ts @@ -0,0 +1,136 @@ +/** + * fix-check-clearing — the one owner of when a granted fix-check counts and what it closes (GST-3260, + * docs/review-policy.md#what-closes-a-finding). A stop leaves a stop record in the PR body, the lane or its Captain records a + * fix-check grant naming it, a run claims the grant, and gstack-review-log stamps that run's review-fix-check row from the claim + * (fix_check_base, run, grant, pr) with the digest of the hunks its reader was given. finish's fixChecked counts such a row through + * bindFixCheckRow, anchored on the grant's stop rather than the newest reviewed tree (#4612); gstack-ship-receipt write closes + * exactly the open blockers the grant names through clearByGrant, and a fix whose Review-Finding trailer a later full round read + * clean through clearByTrailer (#4597). Anything less closes nothing and says why on one line. Every input is a record gstack's + * tools wrote (the PR body's stop and claim entries, the approval record, the review log); the agent's --review-loop file only + * lists which blockers are open. + */ +import { createHash } from 'node:crypto'; +import * as path from 'node:path'; +import { grantedStop } from './pr-review-history'; +import { ownLinesSame, type ReviewRoundGrant } from './review-round-grant'; +import { ledgerPass, parseFixTrailers, reviewRowKey, rowTime } from './review-scope'; +import { receiptRuns } from './ship-receipt'; +import { spawnSync } from './spawn-sync'; + +type Row = Record; +/** One entry of the loop summary's `open` list: a ledger id or fingerprint, or both. */ +export type OpenBlocker = string | { id: string; fingerprint: string }; +export type RowBinding = { ok: true; grant: ReviewRoundGrant; base: string; commit: string } | { ok: false; why: string }; +export interface GrantClearing { ids: string[]; approval?: string; run?: string; why?: string } +export interface TrailerClearing { id: string; commit: string; review: string } + +const SHA = /^[0-9a-f]{40}$/; +const s12 = (s: string) => s.slice(0, 12); +const git = (cwd: string, args: string[]) => { + const r = spawnSync('git', args, { cwd, encoding: 'utf8', timeout: 60_000, maxBuffer: 64 * 1024 * 1024 }); + return r.status === 0 ? r.stdout ?? '' : null; +}; +const ancestor = (cwd: string, a: string, d: string) => a === d || git(cwd, ['merge-base', '--is-ancestor', a, d]) !== null; +const treeOf = (cwd: string, c: string) => git(cwd, ['rev-parse', '--verify', '--quiet', `${c}^{tree}`])?.trim(); +const findingsOf = (r: Row): Row[] => (Array.isArray(r?.findings) ? r.findings.filter((f: unknown) => !!f && typeof f === 'object') : []); +const nameOf = (b: OpenBlocker) => (typeof b === 'string' ? b : b.id); + +/** A fix-check grant buys one fix-check: it is spent once a row carries it, or once any fix-check started after it was recorded. */ +export const grantSpent = (rows: readonly Row[], g: Pick) => + rows.some(r => r?.skill === 'review-fix-check' && (r.grant === g.approval || rowTime(r) > Date.parse(g.at))); + +/** + * The grant-and-row binding finish and write share (amendments A, B and H): a review-fix-check row gstack-review-log stamped from a + * claim, whose grant is an approved fix-check grant naming its fix_check_base as the stop head on its PR; no agent-written + * range_base that disagrees; a completed, converged read bound to its commit's own tree, which contains the base; nothing open in it + * (rule e: its status, an inline finding with action open at any severity, findings_open from a findings file, an id its dispatch + * ledger collected that the row does not dispose); and the hunks its reader was given are git diff over their paths, + * which cover every path that diff changes. + */ +export function bindFixCheckRow(cwd: string, row: Row, grants: readonly ReviewRoundGrant[]): RowBinding { + const no = (why: string): RowBinding => ({ ok: false, why }); + const base = typeof row.fix_check_base === 'string' ? row.fix_check_base.toLowerCase() : ''; + const commit = typeof row.commit_full === 'string' ? row.commit_full.toLowerCase() : ''; + const g = grants.find(x => x.kind === 'fix-check' && x.approval === row.grant); + const b = row.review_binding, h = row.hunks, findings = findingsOf(row); + if (!SHA.test(base)) return no('the row carries no fix_check_base that gstack-review-log stamped from a claim'); + if (!g) return no(`its grant ${row.grant ?? 'none'} is no approved fix-check grant in this branch's approval record`); + if (g.head !== base || g.pr !== row.pr) return no(`its fix_check_base ${s12(base)} on PR #${row.pr ?? '?'} is not the stop ${s12(g.head)} that grant ${g.approval} names on PR #${g.pr}`); + if (row.range_base !== undefined && git(cwd, ['rev-parse', '--verify', '--quiet', `${row.range_base}^{commit}`])?.trim() !== base) return no(`its range_base ${String(row.range_base).slice(0, 12)} disagrees with the logger's fix_check_base ${s12(base)}`); + if (row.completed !== true || row.converged !== true || b?.state !== 'verified' || typeof row.tree !== 'string' || b.start_wtree !== row.tree || b.end_wtree !== row.tree) return no('it is not a completed, converged read bound to one committed tree'); + if (!SHA.test(commit) || treeOf(cwd, commit) !== row.tree || !ancestor(cwd, base, commit)) return no(`its commit ${s12(commit) || 'missing'} does not hold the tree it read or does not contain the stop ${s12(base)}`); + if (row.status === 'issues_found' || row.status === 'issues_open' || Number(row.findings_open ?? 0) > 0 || findings.some(f => f.action === 'open')) return no('it left a finding open'); + if (!h || typeof h.sha256 !== 'string' || !Array.isArray(h.paths) || !h.paths.length) return no('it carries no record of the hunks its reader was given'); + const diff = git(cwd, ['diff', base, commit, '--', ...h.paths]); + if (diff === null || createHash('sha256').update(diff).digest('hex') !== h.sha256) return no(`the hunks its reader was given are not git diff ${s12(base)} ${s12(commit)}`); + const changed = git(cwd, ['diff', '--name-only', base, commit]); + const unread = changed === null ? null : changed.split('\n').filter(p => p && !h.paths.includes(p)); + if (unread === null || unread.length) return no(`the hunks its reader was given leave out ${unread?.join(', ') ?? 'paths git could not list'}, which git diff ${s12(base)} ${s12(commit)} changes`); + if (typeof h.ledger === 'string') { + let ids: string[]; + try { ids = ledgerPass(h.ledger, id => `${path.basename(path.dirname(h.ledger))}/${id}`).ids ?? []; } catch { return no(`its dispatch ledger ${h.ledger} is unreadable`); } + const disposed = new Set(findings.filter(f => f.action !== 'open').map(f => f.ledger_id)); + const left = ids.filter(id => !disposed.has(id)); + if (left.length) return no(`its dispatch ledger holds ${left.join(', ')}, which the row does not dispose`); + } + return { ok: true, grant: g, base, commit }; +} + +/** + * Rules a to f with amendments D and E: (a) grantedStop accepts the newest stop record's fix-check grant for this PR and run; + * (b) the PR body's first claim of the grant is this run's; (c) exactly one review-fix-check row carries the grant, stamped with + * this run, and it binds (bindFixCheckRow) at the stop's head and tree from the body, never the newest review row, on the receipt + * head or a head that only merges the base into it; (d) the stop, the claim and the row's start are recorded in that order; + * (e) inside the binding; (f) each grant id closes the one open blocker whose id it is, a fingerprint only for a blocker without a + * ledger id that no other blocker shares, never a gate finding, and only an id the fix list its reader was given named; an id + * that names nothing closes nothing. + */ +export function clearByGrant(cwd: string, o: { pr: number; run: string; head: string; baseRef: string; body: string; grants: readonly ReviewRoundGrant[]; rows: readonly Row[]; open: readonly OpenBlocker[] }): GrantClearing { + const none = (why: string): GrantClearing => ({ ids: [], why }); + const answer = grantedStop(o.body, o.grants, { pr: o.pr, head: o.head, run: o.run, isAncestor: (a, d) => ancestor(cwd, a, d) }); + if (!answer) return none(`no fix-check grant for PR #${o.pr}`); + if (!answer.ok) return none(answer.why); + const { grant: g, stop } = answer; + const claim = receiptRuns(o.body).find(r => r.mark === 'grant' && r.grant === g.approval); + if (claim?.run !== o.run) return none(`the PR body's first claim of grant ${g.approval} is ${claim ? `run ${claim.run}'s` : 'missing'}, not run ${o.run}'s`); + const stamped = [...new Map(o.rows.filter(r => r?.skill === 'review-fix-check' && r.grant === g.approval).map(r => [reviewRowKey(r), r] as const)).values()]; + const row = stamped[0]; + if (stamped.length !== 1 || row!.run !== o.run) return none(`grant ${g.approval} buys one fix-check row stamped with run ${o.run}, and the review log holds ${stamped.length}${row ? ` (run ${row.run}'s)` : ''}`); + const bound = bindFixCheckRow(cwd, row!, o.grants); + if (!bound.ok) return none(`the granted fix-check: ${bound.why}`); + if (bound.base !== stop.head || treeOf(cwd, stop.head) !== stop.tree) return none(`the granted fix-check read from ${s12(bound.base)}, not the stop record's head ${s12(stop.head)} and its tree`); + if (bound.commit !== o.head && !(ancestor(cwd, bound.commit, o.head) && ownLinesSame(cwd, o.baseRef, bound.commit, o.head))) return none(`the granted fix-check read ${s12(bound.commit)}, and ${s12(o.head)} is neither it nor a head that only merges the base into it`); + const started = row!.review_binding?.started_at; + if (!(Date.parse(String(stop.at)) < Date.parse(String(claim.at)) && Date.parse(String(claim.at)) < Date.parse(String(started)))) return none(`the stop (${stop.at ?? 'no time'}), the claim (${claim.at ?? 'no time'}) and the fix-check's start (${started ?? 'no time'}) are not recorded in that order`); + const gated = new Set(o.rows.flatMap(r => findingsOf(r).filter(f => f.gate !== undefined).flatMap(f => [f.ledger_id, f.fingerprint]))); + const asked = new Set(Array.isArray(row!.hunks?.fix_list) ? row!.hunks.fix_list : []); + const ids = g.findings!.filter(name => asked.has(name) && o.open.filter(b => nameOf(b) === name).length === 1 && !o.open.some(b => typeof b !== 'string' && b.fingerprint === name) && !gated.has(name)); + const unasked = g.findings!.filter(name => !asked.has(name)); + const unnamed = g.findings!.filter(name => asked.has(name) && !ids.includes(name)); + const why = [...(unasked.length ? [`the fix list its reader was given does not name ${unasked.join(', ')}`] : []), ...(unnamed.length ? [`grant ${g.approval} names ${unnamed.join(', ')}, which no open blocker carries alone`] : [])].join('; '); + return { ids, approval: g.approval, run: o.run, ...(why ? { why } : {}) }; +} + +/** + * The #4597 route: an open blocker closes when a branch commit carries its Review-Finding trailer (its exact ledger id, or its + * fingerprint when no other open blocker shares it) and a later complete full review, bound to its own committed tree on this + * branch and holding that commit in its range, left nothing open (the same open test as bindFixCheckRow: its status, findings_open + * from a findings file, an inline open finding). Gate findings never close this way. + */ +export function clearByTrailer(cwd: string, o: { head: string; baseRef: string; rows: readonly Row[]; open: readonly OpenBlocker[] }): TrailerClearing[] { + const log = git(cwd, ['log', '--no-merges', '--format=%H%x00%(trailers:key=Review-Finding,valueonly,separator=%x1f)%x1e', `${o.baseRef}..${o.head}`]); + const trailers = (log ?? '').split('\x1e').flatMap(rec => { const [sha, values] = rec.trim().split('\0'); return sha && values ? parseFixTrailers(sha, values.split('\x1f').map(v => v.trim()).filter(Boolean)) : []; }); + return o.open.flatMap(b => { + const id = nameOf(b), fp = typeof b === 'string' ? b : b.fingerprint; + const raised = o.rows.flatMap(r => findingsOf(r).filter(f => f.action === 'open' && (f.ledger_id === id || (f.ledger_id === undefined && f.fingerprint === fp))).map(f => ({ r, f }))); + const alone = o.open.filter(c => (typeof c === 'string' ? c : c.fingerprint) === fp).length === 1; + const t = trailers.find(x => x.finding === id || (alone && x.finding === fp)); + if (!t || !raised.length || raised.some(x => x.f.gate !== undefined)) return []; + const after = Math.max(...raised.map(x => rowTime(x.r))); + const review = o.rows.find(r => r?.skill === 'review' && r.via === 'ship' && r.completed === true && r.scope !== 'fix-range' && r.scope !== 'scoped' && rowTime(r) > after + && (r.review_binding?.state === 'verified' || r.review_binding?.state === 'incomplete') && typeof r.tree === 'string' && r.review_binding.start_wtree === r.tree && r.review_binding.end_wtree === r.tree + && SHA.test(String(r.commit_full)) && treeOf(cwd, r.commit_full) === r.tree && ancestor(cwd, t.commit, r.commit_full) && ancestor(cwd, r.commit_full, o.head) + && r.status !== 'issues_found' && r.status !== 'issues_open' && Number(r.findings_open ?? 0) === 0 && !findingsOf(r).some(f => f.action === 'open')); + return review ? [{ id, commit: t.commit, review: review.commit_full as string }] : []; + }); +} diff --git a/lib/headless-artifacts.ts b/lib/headless-artifacts.ts index f3e0f4ead..d046d7f7f 100644 --- a/lib/headless-artifacts.ts +++ b/lib/headless-artifacts.ts @@ -130,6 +130,10 @@ export interface ShipReceipt { review_loop_exception?: { accepted_by: string; date: string; via: string; reason: string; fix_check?: { head: string; findings: number; files?: string[] }; second_pass?: { head: string; deferred: string[] } }; /** Review round grants the lane or its Captain recorded for this PR (gstack-approvals round-grant, lib/review-round-grant.ts; GST-2673): never the owner's, so never in review_loop_exception. */ review_round_grants?: Array<{ kind: 'extra-round' | 'fix-check'; head: string; pr: number; by: string; reason: string; at: string; approval: string; stop_run?: string; findings?: string[] }>; + /** The open blockers a granted fix-check closed at write (lib/fix-check-clearing.ts clearByGrant; GST-3260): the grant, the run that spent it and the ids it named. */ + cleared_by_grant?: { approval: string; run: string; ids: string[] }; + /** The open blockers a Review-Finding trailer's fix closed because a later full round read it clean (clearByTrailer, #4597). */ + cleared_by_trailer?: Array<{ id: string; commit: string; review: string }>; /** The owner's rulings that a finding ships as a disclosed note (gstack-approvals rule, lib/ruled-notes.ts); the PR body lists each one word for word (GST-1537). */ ruled_notes?: Array<{ finding: string; head: string; by: string; reason: string; at: string; approval: string; relayed?: string; not_security?: true }>; /** The owner's dispositions of gate findings (gstack-approvals gate, lib/gate-dispositions.ts); the PR body lists each one word for word (GST-2491). */ @@ -287,6 +291,8 @@ export const ARTIFACT_SCHEMAS = { review_exclude_fallback: { type: 'object', required: ['source', 'errors'], properties: { source: str, errors: strList } }, review_loop_exception: { type: 'object', required: ['accepted_by', 'date', 'via', 'reason'], properties: { accepted_by: str, date: str, via: str, reason: str, fix_check: { type: 'object', required: ['head', 'findings'], properties: { head: str, findings: { type: 'integer', minimum: 0 }, files: strList } }, second_pass: { type: 'object', required: ['head', 'deferred'], properties: { head: str, deferred: strList } } } }, review_round_grants: { type: 'array', items: { type: 'object', required: ['kind', 'head', 'pr', 'by', 'reason', 'at', 'approval'], properties: { kind: { enum: ['extra-round', 'fix-check'] }, head: str, pr: { type: 'integer', minimum: 1 }, by: str, reason: str, at: str, approval: str, stop_run: str, findings: { type: 'array', items: str } } } }, + cleared_by_grant: { type: 'object', required: ['approval', 'run', 'ids'], properties: { approval: str, run: str, ids: strList } }, + cleared_by_trailer: { type: 'array', items: { type: 'object', required: ['id', 'commit', 'review'], properties: { id: str, commit: str, review: str } } }, ruled_notes: { type: 'array', items: { type: 'object', required: ['finding', 'head', 'by', 'reason', 'at', 'approval'], properties: { finding: str, head: str, by: str, reason: str, at: str, approval: str, relayed: str, not_security: { const: true } } } }, gate_dispositions: { type: 'array', items: { type: 'object', required: ['finding', 'gate_id', 'head', 'by', 'reason', 'words', 'at', 'approval'], properties: { finding: str, gate_id: str, head: str, by: str, reason: str, words: str, at: str, approval: str } } }, mechanical: strList, diff --git a/lib/pr-review-history.ts b/lib/pr-review-history.ts index eb5487dac..349b353b2 100644 --- a/lib/pr-review-history.ts +++ b/lib/pr-review-history.ts @@ -94,10 +94,11 @@ export const runStub = (o: { head: string; run: string; status: 'started' | 'voi /** * A stop record (GST-2968): the review a /ship run stopped on, written by gstack-ship-receipt stop when the plan prints NEXT: stop. * head is the commit that review read, tree its tree; the review row bound to it (lib/ship-stop.ts). A grant marker records - * that a run claimed a round grant before dispatching the round it buys. Markers count no round and are never trimmed. + * that a run claimed a round grant before dispatching the round it buys. Markers count no round and are never trimmed. Both carry + * when they were recorded, so a granted fix-check orders stop, claim and row from the PR body alone (lib/fix-check-clearing.ts). */ -export const stopMarker = (o: { head: string; tree: string; run: string }): ReceiptRun => ({ head: o.head, run: o.run, mark: 'stop', tree: o.tree }); -export const grantMarker = (o: { head: string; run: string; grant: string }): ReceiptRun => ({ head: o.head, run: o.run, mark: 'grant', grant: o.grant }); +export const stopMarker = (o: { head: string; tree: string; run: string; at?: string }): ReceiptRun => ({ head: o.head, run: o.run, mark: 'stop', tree: o.tree, at: o.at ?? new Date().toISOString() }); +export const grantMarker = (o: { head: string; run: string; grant: string; at?: string }): ReceiptRun => ({ head: o.head, run: o.run, mark: 'grant', grant: o.grant, at: o.at ?? new Date().toISOString() }); /** gstack-ship-run abandon's entry (GST-3260): who ended a run that stopped working, and why, at the head it was abandoned on. */ export const abandonMarker = (o: { head: string; run: string; by: string; reason: string }): ReceiptRun => ({ head: o.head, run: o.run, mark: 'abandoned', by: o.by, reason: o.reason }); /** The newest receipt a run id already wrote, in the runs block or current: a run id names one /ship run (gstack-evals#406). */ diff --git a/lib/review-evidence.ts b/lib/review-evidence.ts index e18542087..103f3cc34 100644 --- a/lib/review-evidence.ts +++ b/lib/review-evidence.ts @@ -4,6 +4,7 @@ import { closeSync, constants, fstatSync, lstatSync, mkdirSync, openSync, readFi import { join, resolve } from 'node:path'; import { deriveReviewStatus, isCriticalFinding, isOpenByAction, readJsonl } from './headless-artifacts'; import { resultLine, type ResultCodeName } from './result-codes'; +import { readRunRecord } from './ship-run-record'; const DIFF_REVIEWS = new Set(['review', 'review-fix-check', 'adversarial-review', 'codex-review', 'design-review-lite', 'ship']); const SHARED_LIBS_COVERAGE_VERSION = 1; @@ -203,6 +204,7 @@ export function captureReviewStart(skill: string, env = process.env, fixRange = throw new Error('cannot capture a diff review without a working-tree fingerprint'); } const fixBase = fixRange ? fixRangeBase(skill, env) : undefined; + const claimed = skill === 'review-fix-check' ? (r => (r.kind === 'record' && r.record.state === 'open' ? r.record : undefined))(readRunRecord(env.GSTACK_REVIEW_REPO)) : undefined; const dir = join(env.GSTACK_REVIEW_DIR!, '.review-starts'); mkdirSync(dir, { recursive: true, mode: 0o700 }); const token = crypto.randomUUID(); @@ -210,6 +212,7 @@ export function captureReviewStart(skill: string, env = process.env, fixRange = skill, repo: env.GSTACK_REVIEW_REPO, branch: env.GSTACK_REVIEW_BRANCH, wtree: env.GSTACK_STAMP_WTREE, started_at: new Date().toISOString(), ...(fixBase ? { scope: 'fix-range', fix_base: fixBase } : {}), + ...(claimed?.claim ? { fix_check: { base: claimed.claim.stop_head, run: claimed.run, grant: claimed.claim.grant, pr: claimed.claim.pr ?? claimed.pr } } : {}), }), { mode: 0o600, flag: 'wx' }); return fixBase ? `${token}\nFIX_BASE=${fixBase}` : token; } @@ -302,6 +305,11 @@ export function bindReview(rec: Record, token: string, env = proces if (error.code !== 'ENOENT') console.error(`gstack-review-log: cannot consume review start: ${error.message}`); } } + if (rec.skill === 'review-fix-check') { + for (const key of ['fix_check_base', 'run', 'grant', 'pr', 'hunks']) delete rec[key]; + const fc = start?.fix_check; + if (fc) Object.assign(rec, { fix_check_base: fc.base, run: fc.run, grant: fc.grant, ...(fc.pr ? { pr: fc.pr } : {}), ...(h => (h ? { hunks: h } : {}))(readFixCheckHunks(env.GSTACK_REVIEW_REPO!, start.started_at)) }); + } const end = env.GSTACK_STAMP_WTREE; const state = !start || !end ? 'uncaptured' : start.wtree !== end ? 'changed' @@ -475,3 +483,36 @@ export function reviewFreshness(rec: Record, currentWtree: string, } return { status: 'CURRENT', reason: merged ? `completed clean pass; ${merged}` : 'completed clean pass on unchanged content' }; } + +/** The hunks a fix-check reader was given: the sha256 of the file's bytes and every path its diff headers name. */ +export function hunksDigest(text: string): { sha256: string; paths: string[] } { + const paths = new Set(); + for (const m of text.matchAll(/^diff --git a\/(.+?) b\/(.+)$/gm)) { paths.add(m[1]!); paths.add(m[2]!); } + return { sha256: createHash('sha256').update(text).digest('hex'), paths: [...paths].sort() }; +} + +const hunksFile = (cwd: string) => { + const r = spawnSync('git', ['rev-parse', '--git-path', 'gstack-fix-check-hunks'], { cwd, encoding: 'utf8', timeout: 60_000 }); + return r.status === 0 && r.stdout.trim() ? resolve(cwd, r.stdout.trim()) : ''; +}; + +/** The ledger ids and path:line:category fingerprints a fix list names: the only grant ids its clean fix-check can close. */ +export function fixListNames(text: string): string[] { + return [...new Set(text.split(/[\s`'"(),;]+/).map(t => t.replace(/[.:]+$/, '')).filter(t => t.includes('#') || /:\d+:/.test(t)))].sort(); +} + +/** gstack-review-plan --fix-check-prompt and the pass program's fix-check render record the hunks and fix list they rendered from; a failed write only leaves the row without hunks, so it closes nothing. */ +export function recordFixCheckHunks(cwd: string, text: string, ledger: string | undefined, fixList: string): void { + try { + const file = hunksFile(cwd); + if (file) writeFileSync(file, JSON.stringify({ at: new Date().toISOString(), ...hunksDigest(text), fix_list: fixListNames(fixList), ...(ledger ? { ledger: resolve(ledger) } : {}) }) + '\n'); + } catch { /* the row carries no hunks and closes nothing */ } +} + +/** The hunks record gstack-review-log stamps on a granted fix-check row: the newest render at or after the row's start. */ +export function readFixCheckHunks(cwd: string, since: string): { sha256: string; paths: string[]; fix_list: string[]; ledger?: string } | undefined { + try { + const o = JSON.parse(readFileSync(hunksFile(cwd), 'utf8')); + return Date.parse(o.at) >= Date.parse(since) && typeof o.sha256 === 'string' && Array.isArray(o.paths) ? { sha256: o.sha256, paths: o.paths, fix_list: Array.isArray(o.fix_list) ? o.fix_list : [], ...(typeof o.ledger === 'string' ? { ledger: o.ledger } : {}) } : undefined; + } catch { return undefined; } +} diff --git a/lib/review-pass.ts b/lib/review-pass.ts index f20b1f72b..11afc42cf 100644 --- a/lib/review-pass.ts +++ b/lib/review-pass.ts @@ -18,6 +18,7 @@ import { AgentModelError, resolveAgentModel } from './agent-model'; import { BriefError, briefFile, checkoutRoot, checkoutTree, promptHash, renderBrief, sliceDiff, sliceNote, withWorkspace, type BriefRole, type SectionTexts, type Slots } from './review-brief'; import { REVIEW_DIFF_MAX_BYTES, disclosureDigest } from './review-exclude'; import { appendEvent, readerKey } from './review-ledger'; +import { recordFixCheckHunks } from './review-evidence'; import { policySelection, selectFor } from './review-selection'; import { diffCommand, type Dispatch } from './review-depth'; import { TARGETED_RULES, parseClassList, targetedBriefSha, targetedRead } from './review-targeted'; @@ -244,6 +245,7 @@ export function renderStage(m: Manifest, stage: Stage, t: SectionTexts, diffFor: const read = (f: string | undefined, what: string) => { if (!f) return undefined; try { return fs.readFileSync(f, 'utf8'); } catch { throw new BriefError(`cannot read the fix-check ${what} ${f}`); } }; const fc = m.fix_check!; Object.assign(slots, { fix_list: read(fc.fix_list, 'fix list'), hunks: read(fc.hunks, 'hunks'), tests: read(fc.tests, 'tests'), callers: read(fc.callers, 'callers') }); + recordFixCheckHunks(process.cwd(), slots.hunks ?? '', m.ledger, slots.fix_list ?? ''); } let targeted = {}; if (role === 'targeted' || (role === 'adversarial-native' && r.classes?.length)) { diff --git a/lib/review-scope.ts b/lib/review-scope.ts index 4f4a4c9ab..00a5a61a8 100644 --- a/lib/review-scope.ts +++ b/lib/review-scope.ts @@ -314,7 +314,7 @@ export interface ReviewLoopSummary { * writer fills `timestamp` by hand, so a date-only or guessed value could otherwise * sort a real pass before `--since` and leave the receipt without a loop to record. */ -function rowTime(row: Record): number { +export function rowTime(row: Record): number { for (const value of [row.review_binding?.started_at, row.timestamp]) { const ms = typeof value === 'string' ? Date.parse(value) : NaN; if (Number.isFinite(ms)) return ms; @@ -322,6 +322,9 @@ function rowTime(row: Record): number { return NaN; } +/** A repeated logger command writes the same row twice (#3911: one fix-check counted as two): rows that record their head dedupe by kind, pass, head and finding ids. */ +export const reviewRowKey = (r: Record) => JSON.stringify([r.skill, r.pass ?? null, r.commit_full ?? r.commit ?? '', (Array.isArray(r.findings) ? r.findings : []).map((f: any) => (f && typeof f === 'object' ? (typeof f.ledger_id === 'string' ? f.ledger_id : findingIdentity(f)) : '')).sort()]); + /** * A Step 11 late defer (a queued adversarial finding scoped `defer` after the * last Step 9 pass) is logged under this skill, not as a `review` row: its @@ -414,9 +417,7 @@ export function summarizeReviewLoop(rows: readonly Record[], since: const inRun = (r: Record) => r && r.via === 'ship' && Number.isFinite(rowTime(r)) && (!Number.isFinite(sinceMs) || rowTime(r) >= sinceMs); const unbound: string[] = rows.filter(r => r && r.via === 'ship' && loopSkill(r) && !Number.isFinite(rowTime(r))) .map(r => `row ${String(r.skill)} pass=${String(r.pass ?? '?')}: no start token and no readable timestamp, so it cannot be placed in this run`); - // A repeated logger command writes the same row twice (#3911: one fix-check counted as two): rows that record their head dedupe by kind, pass, head and finding ids. - const rowKey = (r: Record) => JSON.stringify([r.skill, r.pass ?? null, r.commit_full ?? r.commit ?? '', (Array.isArray(r.findings) ? r.findings : []).map((f: any) => (f && typeof f === 'object' ? (typeof f.ledger_id === 'string' ? f.ledger_id : findingIdentity(f)) : '')).sort()]); - const loopRows = [...new Map(rows.filter(r => inRun(r) && loopSkill(r)).map((r, i) => [r.commit_full || r.commit ? rowKey(r) : `#${i}`, r] as const)).values()]; + const loopRows = [...new Map(rows.filter(r => inRun(r) && loopSkill(r)).map((r, i) => [r.commit_full || r.commit ? reviewRowKey(r) : `#${i}`, r] as const)).values()]; const passes = loopRows.filter(r => r.skill === 'review'); const named = (dir: string) => { const n = /^p(\d+)$/.exec(dir)?.[1]; return loopRows.some(r => (n !== undefined && r.skill === 'review' && String(r.pass) === n) || (Array.isArray(r.findings) && r.findings.some((f: any) => typeof f?.ledger_id === 'string' && f.ledger_id.startsWith(`${dir}/`)))); }; const passNo = (p: LedgerPass) => (p.fixCheck ? undefined : Number(/^p(\d+)$/.exec(p.name ?? '')?.[1] ?? NaN)); diff --git a/lib/ship-receipt.ts b/lib/ship-receipt.ts index 96e193f16..647dc1ff9 100644 --- a/lib/ship-receipt.ts +++ b/lib/ship-receipt.ts @@ -25,7 +25,7 @@ const KEY_ORDER: Array = [ 'schema_version', 'pr', 'head', 'version', 'base', 'gated_tree', 'predecessor', 'tree', 'gate_reuse', 'gate', 'ci', 'ci_carried', 'spend_usd', 'calls', 'session_kind', 'artifacts_consumed', 'run', 'thread', 'policy', 'queue_mode', 'preregistration', 'history', 'head_tree', 'product_patch_id', 'gstack_version', 'review_depth', 'pregate', 'requires_remote', 'issues', 'approval', 'docs', 'review_loop', - 'review_loop_exception', 'review_round_grants', 'ruled_notes', 'gate_dispositions', 'mechanical', 'review_targeted', 'design', 'review_exclude', 'review_exclude_fallback', 'carry', 'base_red', 'flaky_exception', 'no_stop', + 'review_loop_exception', 'review_round_grants', 'cleared_by_grant', 'cleared_by_trailer', 'ruled_notes', 'gate_dispositions', 'mechanical', 'review_targeted', 'design', 'review_exclude', 'review_exclude_fallback', 'carry', 'base_red', 'flaky_exception', 'no_stop', ]; /** Keys in the fixed order so identifiers lead; undefined values are dropped. */ @@ -133,7 +133,7 @@ export const RUNS_RE = /```gstack-receipt-runs[ \t]*\r?\n([\s\S]*?)\r?\n```[ \t] * carries), `carry` for any other hop. status: a /ship run that * started and wrote no receipt yet (`started`, its counters so far) or ended on an infrastructure failure (`voided`). */ -export type ReceiptRun = Pick & { depth?: string; carried_from?: string; carry_kind?: 'carry' | 'recheck'; status?: 'started' | 'voided'; mark?: 'stop' | 'grant' | 'abandoned'; tree?: string; grant?: string; by?: string; reason?: string }; +export type ReceiptRun = Pick & { depth?: string; carried_from?: string; carry_kind?: 'carry' | 'recheck'; status?: 'started' | 'voided'; mark?: 'stop' | 'grant' | 'abandoned'; tree?: string; grant?: string; by?: string; reason?: string; at?: string }; /** The runs block keeps the newest RECEIPT_RUNS_KEPT run entries and every stop, grant or abandoned marker (lib/pr-review-history.ts), in order. */ export function keptRuns(runs: readonly ReceiptRun[]): ReceiptRun[] { const keep = new Set(runs.filter(r => !r.mark).slice(-RECEIPT_RUNS_KEPT)); diff --git a/lib/ship-release.ts b/lib/ship-release.ts index 71281f111..c7ca0c7fa 100644 --- a/lib/ship-release.ts +++ b/lib/ship-release.ts @@ -18,6 +18,7 @@ import { matchesAny } from './ship-policy'; import { baseHolds, boundedPaths, comparePath, contextPacket, gateEditedPaths, isTestCode, PACKET_SECTION_CAP, readScopedReview, touchedPaths, type BoundedKind, type PatchSides } from './ship-patch'; import { extractReceipt, heldBy, receiptRuns } from './ship-receipt'; import { finishRun, readRunRecord } from './ship-run-record'; +import { bindFixCheckRow, type RowBinding } from './fix-check-clearing'; import { locate, readRecord } from './approval-record'; import { mechanicalPaths, writeMechanicalRecord } from './ship-mechanical'; import { uidSidecars } from './ship-sidecar'; @@ -253,7 +254,7 @@ function patchBase(cwd: string, baseRef: string, commit: string, parent: string return parent && fork && holds(parent, commit) && holds(fork, parent) ? parent : fork; } -type FixLink = { row: Record; commit: string; from: string }; +type FixLink = { row: Record; commit: string; from: string; bound?: RowBinding }; type BridgeOpts = { reviewed: string; baseRef: string; metadata: (p: string) => boolean; bookkeeping: readonly string[]; testCode: readonly string[] }; /** @@ -300,12 +301,14 @@ function fixChecked(cwd: string, o: BridgeOpts & { now: string; parent?: string; const ancestor = (a: string, d: string) => git(cwd, ['merge-base', '--is-ancestor', a, d]).status === 0; const onBranch = (c: string) => !!c && ancestor(c, 'HEAD'); const commits = rows.map(row => commitOf(row.commit_full)); + const approvals = (loc => 'file' in loc ? readRecord(loc).rows : [])(locate({ cwd, env: process.env })); const chain: FixLink[] = []; 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) }; + const row = rows[i]!, bound = row.fix_check_base !== undefined ? bindFixCheckRow(cwd, row, reviewRoundGrants(approvals)) : undefined; + const link = { row, commit: commits[i]!, from: commitOf(bound ? row.fix_check_base : row.range_base), bound }; chain.unshift(link); - if (!onBranch(link.from) || git(cwd, ['rev-parse', `${link.from}^{tree}`]).stdout.trim() === o.reviewed) break; + if (bound?.ok || !onBranch(link.from) || git(cwd, ['rev-parse', `${link.from}^{tree}`]).stdout.trim() === o.reviewed) break; i = commits.slice(0, i).lastIndexOf(link.from); 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(',')})`; @@ -317,12 +320,12 @@ function fixChecked(cwd: string, o: BridgeOpts & { now: string; parent?: string; const gates = readGateDispositions(cwd); for (const d of gates) r.add(`GATE_DISPOSITION: ${gateDispositionText(d)}${reviewRows.some(v => dispositionedOn(cwd, v, [d]).length) ? '' : ' (no open gate finding at this fingerprint on a review row whose range holds this head; not applied)'}`); const gatedOn = (l: FixLink) => new Set(dispositionedOn(cwd, l.row, gates).map(d => gateKey(d.finding, d.gate_id))); - const grants = chain.length ? (loc => 'file' in loc ? readRecord(loc).rows : [])(locate({ cwd, env: process.env })).filter(g => g.outcome === 'approved' && (`${g.ask} ${g.scope}`.includes('review_loop_grant') || reviewRoundGrants([g]).some(x => x.kind === 'fix-check'))) : []; + const grants = approvals.filter(g => g.outcome === 'approved' && (`${g.ask} ${g.scope}`.includes('review_loop_grant') || reviewRoundGrants([g]).some(x => x.kind === 'fix-check'))); const granted: (typeof grants[number] | undefined)[] = []; const used = new Set(); for (let k = chain.length - 1; k >= 0; k--) { const l = chain[k]!; - const g = grants.filter(g => !used.has(g.id)) + const g = l.bound?.ok ? (id => grants.find(x => x.id === id && !used.has(x.id)))(l.bound.grant.approval) : grants.filter(g => !used.has(g.id)) .flatMap(g => { const fc = reviewRoundGrants([g]).find(x => x.kind === 'fix-check'); return (fc ? (commitOf(fc.head) === l.from ? [fc.head] : []) : `${g.ask} ${g.scope}`.match(/\b[0-9a-f]{7,40}\b/g) ?? []).map(commitOf).filter(c => !!c && inRange(l, c)).map(stop => ({ g, stop })); }) .reduce<{ g: typeof grants[number]; stop: string } | undefined>((best, c) => (!best || ancestor(best.stop, c.stop) ? c : best), undefined)?.g; if (g) used.add(g.id); @@ -332,7 +335,7 @@ function fixChecked(cwd: string, o: BridgeOpts & { now: string; parent?: string; const why = (l: FixLink) => { const read = l.row.wtree ?? l.row.review_binding?.end_wtree; const fresh = reviewFreshness(l.row, read, ruledOn(l), gatedOn(l)); - return fresh?.status !== 'CURRENT' ? fresh?.reason ?? 'not a review row' + return l.bound && !l.bound.ok ? `the granted fix-check row: ${l.bound.why}` : fresh?.status !== 'CURRENT' ? fresh?.reason ?? 'not a review row' : l.row.tree !== read || !onBranch(l.commit) ? 'the row was logged on content no branch commit holds' : !onBranch(l.from) ? 'the row names no range_base commit on this branch' : ''; }; diff --git a/lib/ship-run-record.ts b/lib/ship-run-record.ts index c57386cba..b967a7565 100644 --- a/lib/ship-run-record.ts +++ b/lib/ship-run-record.ts @@ -17,7 +17,7 @@ export type RunState = 'open' | 'stopped' | 'finished' | 'abandoned'; export interface RunRecord { v: 1; run: string; state: RunState; pr?: number; head: string; started_at: string; beat_at: string; stop?: { head: string; tree: string }; - claim?: { grant: string; stop_run?: string; stop_head: string; findings: string[] }; + claim?: { grant: string; stop_run?: string; stop_head: string; findings: string[]; pr?: number }; ended_by?: string; reason?: string; } export type RunRead = diff --git a/scripts/lib/windows-curation.ts b/scripts/lib/windows-curation.ts index 800b6065b..c015e403e 100644 --- a/scripts/lib/windows-curation.ts +++ b/scripts/lib/windows-curation.ts @@ -472,6 +472,10 @@ export const KNOWN_WINDOWS_INCOMPATIBLE: Array<{ file: string; reason: string }> file: 'test/ship-run-record.test.ts', reason: 'drives bin/gstack-ship-preflight, gstack-ship-run, gstack-ship-receipt, gstack-approvals, gstack-review-log, gstack-lease and gstack-skill-end (shebangs) through test/helpers/ship-bin-fixture.ts like test/round-cap-granted-stop.test.ts; a bin spawn fails on windows-latest the same way (first-bin-spawn failure class of test/ship-uid-sidecar.test.ts)', }, + { + file: 'test/fix-check-clearing.test.ts', + reason: 'drives bin/gstack-ship-receipt, gstack-approvals, gstack-review-log, gstack-review-plan, gstack-review-scope, gstack-review-read and gstack-ship-release (shebangs) through test/helpers/ship-bin-fixture.ts like test/round-cap-granted-stop.test.ts; a bin spawn fails on windows-latest the same way (first-bin-spawn failure class of test/ship-uid-sidecar.test.ts)', + }, { file: 'test/round-cap-granted-stop.test.ts', reason: 'drives bin/gstack-ship-receipt, gstack-approvals, gstack-review-plan, gstack-review-log, gstack-review-scope and gstack-ship-release (shebangs) through test/helpers/ship-bin-fixture.ts like test/ship-finish-fixed-links.test.ts; a bin spawn fails on windows-latest the same way (first-bin-spawn failure class of test/ship-uid-sidecar.test.ts)', diff --git a/test/exercised-map.test.ts b/test/exercised-map.test.ts index 345ab0657..a12363f3f 100644 --- a/test/exercised-map.test.ts +++ b/test/exercised-map.test.ts @@ -332,6 +332,7 @@ describe('parity with the measured prototype', () => { 'lib/ship-receipt-prose.ts': 'bin/gstack-ship-receipt imports it (read --check-prose), so it reaches every consumer of the receipt binary', 'lib/ship-clock.ts': 'G2: bin/gstack-ship-receipt (write --budget-record), lib/ship-budget-cli.ts (note, resume) and lib/ship-phase.ts import it, so it reaches every consumer of the receipt and budget binaries', 'scripts/resolvers/load-injection.ts': 'GST-3157: the preamble resolvers (generate-preamble-bash, preamble-hoist) and scripts/gen-skill-docs.ts import it, so it reaches every consumer of the generated skills', + 'lib/fix-check-clearing.ts': 'GST-3260: lib/ship-release.ts (finish), lib/review-evidence.ts (gstack-review-log), lib/review-pass.ts and the receipt and review-plan bins import it, so it reaches every consumer of finish, the review logger, the pass program and receipt write', 'lib/ship-run-record.ts': 'GST-3260: lib/ruled-notes.ts, lib/gate-dispositions.ts, the preflight, release and receipt libraries and bins, gstack-review-log and gstack-skill-end read or beat the run record, so it reaches every consumer of those guards', 'lib/default-base.ts': 'GST-511/GST-774: lib/ship-policy.ts (resolveBaseBranch), lib/gate-diff/git.ts, lib/pregate/context.ts, lib/ship-receipt-depth.ts and the review-plan, gate-diff, pregate, docs-candidate and diff-scope bins import or run it, so it reaches every consumer of those readers', }; diff --git a/test/fix-check-clearing.test.ts b/test/fix-check-clearing.test.ts new file mode 100644 index 000000000..a3e2857c1 --- /dev/null +++ b/test/fix-check-clearing.test.ts @@ -0,0 +1,284 @@ +/** + * GST-3260 PR 2: a granted fix-check that read the fix clean closes exactly the findings its grant names, with no owner ruling. + * Before, a clean fix-check under a fix-check grant left RECEIPT_BLOCKER_OPEN (gstack #4537, harness-evals #508, #4585, #4567), + * a Review-Finding trailer whose fix a later full round read clean stayed open (#4597), and finish anchored a granted fix-check on + * the newest reviewed tree instead of the stop the grant names (#4612). The closed #4546 tried this and its second-model trail + * reads found the gaps each negative case below pins (captain drive reports/GSTA-665.md). Fixtures are synthetic; the replays + * follow each case's shape, not its bytes. + */ +import { afterAll, afterEach, beforeAll, describe, expect, setDefaultTimeout, test } from 'bun:test'; +import * as fs from 'node:fs'; +import * as path from 'node:path'; +import { bindFixCheckRow, clearByGrant, clearByTrailer, grantSpent } from '../lib/fix-check-clearing'; +import { hunksDigest } from '../lib/review-evidence'; +import { grantMarker, placeRunEntry, stopMarker } from '../lib/pr-review-history'; +import { readReviewRoundGrants, type ReviewRoundGrant } from '../lib/review-round-grant'; +import { extractReceipt, receiptRuns } from '../lib/ship-receipt'; +import { renderFixCheckPrompt } from '../scripts/resolvers/fix-check'; +import { RELEASE, shipFixture, type ShipFx } from './helpers/ship-bin-fixture'; + +setDefaultTimeout(120_000); +const BIN = path.dirname(RELEASE); +const fxs: ShipFx[] = []; +afterEach(() => { while (fxs.length) fxs.pop()!.cleanup(); }); + +const ID = 'p1/outside-voice#1', FP = 'src/x.ts:1:outside-voice'; +const TEST = "import { expect, test } from 'bun:test';\ntest('a', () => { expect(2).toBe(2); });\n"; +const blocker = { fingerprint: FP, severity: 'CRITICAL', action: 'open', blocking: true, ledger_id: ID, raised_by: 'outside-voice' }; +const CLEAN = { completed: true, converged: true, status: 'clean', issues_found: 0, critical: 0, informational: 0, findings: [] }; + +type Granted = { f: ShipFx; run: (bin: string, args: string[]) => ReturnType; S: string; F: string; grant: string; body: string; since: string; fixRun: string }; +const headOf = (f: ShipFx) => f.git('rev-parse', 'HEAD').stdout.trim(); +const marker = (f: ShipFx, run: string) => fs.writeFileSync(path.resolve(f.work, f.git('rev-parse', '--git-path', 'gstack-ship-run').stdout.trim()), run + '\n'); +const ok = (r: { status: number | null; stderr: string; stdout: string }) => { expect(r.status, r.stderr + r.stdout).toBe(0); return r.stdout; }; + +/** A full review row through the logger: --start, then the row with --finish, bound to the committed HEAD. */ +function logRow(g: Pick, skill: string, row: Record) { + const start = ok(g.run('gstack-review-log', ['--start', skill])).trim(); + ok(g.run('gstack-review-log', [JSON.stringify({ skill, timestamp: new Date().toISOString(), via: 'ship', review_scope: 'frozen', ...row }), '--finish', start])); +} + +/** + * The stopped run stops on a review that left ID open at S and records the stop; the lane grants one fix-check naming it; the fix + * run (the stop's own run for harness-evals #508, a new run for gstack #4537) claims the grant, commits the fix at F and runs the + * fix-check from the stop head through the logger and gstack-review-plan --fix-check-prompt, which records its hunks. + */ +function grantedRun(o: { sameRun: boolean; fixRow?: Record; extra?: Record; hunkPaths?: string[] }): Granted { + const f = shipFixture({ 'src/x.ts': 'export const x = 1;\n' }, { 'src/x.ts': 'export const x = 2;\n', 'test/x.test.ts': TEST }); + fxs.push(f); + const run = (bin: string, args: string[]) => f.run(path.join(BIN, bin), args, { GSTACK_APPROVALS_MIRROR: '0' }); + const body = path.join(f.root, 'body.md'); + fs.writeFileSync(body, 'Fixes a thing.\n'); + const since = new Date(Date.now() - 1000).toISOString(); + const S = headOf(f); + marker(f, 'ro'); + logRow({ run }, 'review', { pass: 1, completed: true, converged: false, status: 'issues_found', issues_found: 1, critical: 1, informational: 0, findings: [blocker] }); + ok(run('gstack-ship-receipt', ['stop', '--body', body, '--pr', '7', '--run', 'ro', '--since', since])); + const grant = /APPROVAL_RECORDED: (a-[0-9a-f]{12})/.exec(ok(run('gstack-approvals', ['round-grant', '--pr', '7', '--head', S, '--kind', 'fix-check', '--stop-run', 'ro', '--findings', ID, '--reason', 'fixable blocker', '--by', 'Captain GStack Minder (GSTA-36)'])))![1]!; + const fixRun = o.sameRun ? 'ro' : 'fc1'; + if (!o.sameRun) marker(f, fixRun); + f.write({ 'src/x.ts': 'export const x = 3;\n', ...o.extra }); f.commit('fix the blocker'); + const F = headOf(f); + expect(ok(run('gstack-ship-receipt', ['claim', '--body', body, '--run', fixRun, '--grant', grant]))).not.toContain('RUN_RECORD'); + const start = ok(run('gstack-review-log', ['--start', 'review-fix-check'])).trim(); + const files = Object.entries({ fixes: 'fix ' + ID + '\n', hunks: f.git('diff', S, F, ...(o.hunkPaths ? ['--', ...o.hunkPaths] : [])).stdout, tests: '3 pass\n' }).map(([k, v]) => { const p = path.join(f.root, k + '.txt'); fs.writeFileSync(p, v); return p; }); + ok(run('gstack-review-plan', ['--fix-check-prompt', '--fix-list', files[0]!, '--hunks', files[1]!, '--tests', files[2]!])); + ok(run('gstack-review-log', [JSON.stringify({ skill: 'review-fix-check', timestamp: new Date().toISOString(), via: 'ship', review_scope: 'frozen', range_base: S, ...CLEAN, ...o.fixRow }), '--finish', start])); + return { f, run, S, F, grant, body, since, fixRun }; +} + +const rowsOf = (g: Granted) => g.run('gstack-review-read', []).stdout.split('\n---CONFIG---')[0]!.split('\n').flatMap(l => { try { const v = JSON.parse(l); return v && typeof v === 'object' ? [v] : []; } catch { return []; } }); +const grantsOf = (g: Granted) => readReviewRoundGrants(g.f.work, { ...process.env, GSTACK_STATE_ROOT: g.f.state, GSTACK_HOME: g.f.state }); + +/** /ship Step 19: the summary since the stopped run began, then write for the fix run. */ +function summaryThenWrite(g: Granted, extra: string[] = []) { + const loop = path.join(g.f.root, 'loop.json'); + ok(g.run('gstack-review-scope', ['summary', '--since', g.since, '--no-ledger', '--out', loop])); + return { loop: JSON.parse(fs.readFileSync(loop, 'utf8')), w: g.run('gstack-ship-receipt', ['write', '--pr', '7', '--run', g.fixRun, '--base', 'main', '--session-kind', 'unattended', '--review-loop', '@' + loop, '--body', g.body, ...extra]) }; +} + +describe('the logger stamps a granted fix-check row from the run record\'s claim (amendment A)', () => { + // Value: protects=the range a granted fix-check read comes from the claim, never from an agent-typed range; fails_when=the row + // carries no fix_check_base, or the agent's own fix_check_base or grant survives, or the row turns into a fix-range pass; + // seam=gstack-review-log --start/--finish, gstack-review-plan --fix-check-prompt + test('fix_check_base, run, grant, pr and the hunks digest are stamped, and scope stays a normal verified row', () => { + const g = grantedRun({ sameRun: false, fixRow: { fix_check_base: 'f'.repeat(40), grant: 'a-000000000000', run: 'forged' } }); + const row = rowsOf(g).filter(r => r.skill === 'review-fix-check').at(-1)!; + expect(row).toMatchObject({ fix_check_base: g.S, run: 'fc1', grant: g.grant, pr: 7, hunks: hunksDigest(g.f.git('diff', g.S, g.F).stdout), review_binding: { state: 'verified' } }); + expect(row.scope).toBeUndefined(); + expect(bindFixCheckRow(g.f.work, row, grantsOf(g))).toMatchObject({ ok: true, base: g.S, commit: g.F }); + }); +}); + +describe('a granted, clean fix-check closes exactly its grant\'s findings at write (positive replays)', () => { + // Value: protects=gstack #4537, a new run answers another run's stop and its clean fix-check closes the blocker with no ruling; + // fails_when=write refuses RECEIPT_BLOCKER_OPEN; seam=gstack-ship-receipt write + test('gstack #4537: a new run spends the grant on the read-only run\'s stop', () => { + const g = grantedRun({ sameRun: false }); + const { loop, w } = summaryThenWrite(g); + expect(loop.open).toEqual([{ id: ID, fingerprint: FP }]); + expect(w.status, w.stderr).toBe(0); + expect(w.stderr).toContain('FIX_CHECK_CLEAR: grant=' + g.grant + ' run=fc1 closed=' + ID); + expect(extractReceipt(fs.readFileSync(g.body, 'utf8')).receipt).toMatchObject({ cleared_by_grant: { approval: g.grant, run: 'fc1', ids: [ID] } }); + expect(fs.readFileSync(g.body, 'utf8')).toContain('Closed by grant ' + g.grant + ': ' + ID + ' (the granted fix-check of run fc1 read the fix clean)'); + }); + + // Value: protects=harness-evals #508, the run that stopped claims its own stop's grant and closes it; fails_when=write refuses + // RECEIPT_BLOCKER_OPEN; seam=gstack-ship-receipt write + test('harness-evals #508: the stopped run spends the grant on its own stop', () => { + const g = grantedRun({ sameRun: true }); + const { w } = summaryThenWrite(g); + expect(w.status, w.stderr).toBe(0); + expect(JSON.parse(g.run('gstack-ship-receipt', ['read', '--body', g.body, '--json']).stdout)).toMatchObject({ cleared_by_grant: { run: 'ro', ids: [ID] } }); + }); + + // Value: protects=#4612, finish anchors a granted fix-check on the stop the grant names, not the newest reviewed tree; + // fails_when=FIX_CHECK: not counted (range_base ... does not hold the reviewed tree); seam=gstack-ship-release finish + test('#4612: finish counts the stamped fix-check when the reviewed tree it was given is the fix commit\'s', () => { + const g = grantedRun({ sameRun: false }); + const post = path.join(g.f.root, 'post.json'); + ok(g.run('gstack-docs-candidate', ['snapshot', '--out', post, '--audit-id', 'a1', '--mode', 'edit', '--base', 'main', '--docs', 'README.md'])); + const tree = g.f.git('rev-parse', g.F + '^{tree}').stdout.trim(); + const fin = g.f.run(RELEASE, ['finish', '--base', 'main', '--reviewed-tree', tree, '--docs-post', post, '--reviewed-base', g.f.git('merge-base', 'origin/main', 'HEAD').stdout.trim(), '--lane', 'tests=printf " 3 pass\\n 0 fail\\nRan 3 tests across 1 file. [5.00ms]\\n"'], { GSTACK_APPROVALS_MIRROR: '0' }); + expect(fin.stdout).toContain('FIX_CHECK: reviewed none (fix-check at ' + g.F.slice(0, 12) + ', range from ' + g.S.slice(0, 12) + ', grant ' + g.grant + ')'); + const { w } = summaryThenWrite(g); + expect(w.status, w.stderr).toBe(0); + }); + + // Value: protects=#4597, a fix whose Review-Finding trailer a later full round read clean closes; fails_when=write refuses + // RECEIPT_BLOCKER_OPEN because the round-2 row left the finding out; seam=gstack-ship-receipt write + test('#4597: a trailer plus a later clean full round closes the voice finding', () => { + const f = shipFixture({ 'src/x.ts': 'export const x = 1;\n' }, { 'src/x.ts': 'export const x = 2;\n' }); + fxs.push(f); + const run = (bin: string, args: string[]) => f.run(path.join(BIN, bin), args, { GSTACK_APPROVALS_MIRROR: '0' }); + const g = { f, run, body: path.join(f.root, 'body.md'), since: new Date(Date.now() - 1000).toISOString(), fixRun: 'r1' } as Granted; + fs.writeFileSync(g.body, 'Fixes a thing.\n'); + logRow(g, 'review', { pass: 1, ...CLEAN }); + logRow(g, 'adversarial-review', { status: 'issues_found', source: 'outside-voice', phase: 'adversarial', gate: 'informational', completed: true, findings: [blocker] }); + f.write({ 'src/x.ts': 'export const x = 3;\n' }); + f.git('add', '-A'); f.git('commit', '-qm', 'fix the outside voice blocker', '--trailer', 'Review-Finding: ' + ID + ' reader=outside-voice'); + const before = summaryThenWrite(g); + expect(before.w.status).toBe(3); + logRow(g, 'review', { pass: 2, ...CLEAN }); + const { loop, w } = summaryThenWrite(g); + expect(loop.open).toEqual([{ id: ID, fingerprint: FP }]); + expect(w.status, w.stderr).toBe(0); + expect(w.stderr).toContain('TRAILER_CLEAR: ' + ID + ' (fixed by ' + headOf(f).slice(0, 12)); + expect(extractReceipt(fs.readFileSync(g.body, 'utf8')).receipt?.cleared_by_trailer).toEqual([{ id: ID, commit: headOf(f), review: headOf(f) }]); + // Value: protects=a later round that left anything open never clears by trailer, even with its findings in a findings file; + // fails_when=a round-2 row whose status says issues remain closes the trailer's finding; seam=clearByTrailer + const rows = rowsOf(g), pass2 = rows.filter(r => r.skill === 'review').at(-1)!; + const byTrailer = (r2: Record) => clearByTrailer(f.work, { head: headOf(f), baseRef: 'origin/main', rows: [...rows.filter(r => r !== pass2), r2], open: loop.open }); + expect(byTrailer(pass2)).toHaveLength(1); + expect(byTrailer({ ...pass2, status: 'issues_found', findings_open: 1, findings_file: '/tmp/f.jsonl', status_source: 'derived' })).toEqual([]); + expect(byTrailer({ ...pass2, findings: [{ fingerprint: 'src/x.ts:9:style', severity: 'INFORMATIONAL', action: 'open' }] })).toEqual([]); + }); +}); + +describe('a fix-check reader given only part of the fix closes nothing', () => { + // Value: protects=the hunks a granted fix-check read cover the whole stop-to-fix diff; fails_when=hunks over one of two changed + // files bind and close the grant; seam=bindFixCheckRow + test('hunks covering only part of the stop..fix diff close nothing', () => { + const g = grantedRun({ sameRun: false, extra: { 'src/y.ts': 'export const y = 1;\n' }, hunkPaths: ['src/x.ts'] }); + const row = rowsOf(g).filter(r => r.skill === 'review-fix-check').at(-1)!; + expect(row.hunks.paths).toEqual(['src/x.ts']); + expect(bindFixCheckRow(g.f.work, row, grantsOf(g))).toMatchObject({ ok: false, why: expect.stringContaining('leave out src/y.ts') }); + }); +}); + +describe('harness-evals#504: a fix-check grant answering a stop after a gate-class edit plans its fix-check on the plain route', () => { + // Value: protects=a grant stays unspent until a fix-check carries it or starts after it, so it buys exactly one fix-check; + // fails_when=a fix-check that ran before the grant spends it, or one that carries it leaves it unspent; seam=grantSpent + test('a grant is spent by the fix-check that carries it or starts after it, never by an earlier one', () => { + const g = { approval: 'a-2', at: '2026-11-21T01:00:00.000Z' }; + expect(grantSpent([{ skill: 'review-fix-check', review_binding: { started_at: '2026-11-21T00:59:00.000Z' } }], g)).toBe(false); + expect(grantSpent([{ skill: 'review-fix-check', review_binding: { started_at: '2026-11-21T01:01:00.000Z' } }], g)).toBe(true); + expect(grantSpent([{ skill: 'review-fix-check', grant: 'a-2', review_binding: { started_at: '2026-11-21T00:00:00.000Z' } }], g)).toBe(true); + }); + + // Value: protects=the same through the CLI: --round-grant and --stop after --last fix-check with a gate-class fix plan next=fix-check + // with the fix-check reader only; fails_when=the plan prints next=stop; seam=gstack-review-plan + test('gstack-review-plan plans the granted fix-check after a fix-check that edited a gate-class path', () => { + const g = grantedRun({ sameRun: true }); + const s2 = g.F; + expect(ok(g.run('gstack-ship-receipt', ['stop', '--body', g.body, '--pr', '7', '--run', 'ro', '--since', g.since]))).toContain('STOP_RECORD: run=ro head=' + s2); + const g2 = /APPROVAL_RECORDED: (a-[0-9a-f]{12})/.exec(ok(g.run('gstack-approvals', ['round-grant', '--pr', '7', '--head', s2, '--kind', 'fix-check', '--stop-run', 'ro', '--findings', 'p2/fix-check#1', '--reason', 'gate edit', '--by', 'Captain GStack Minder (GSTA-36)', '--owner-ref', 'GSTA-36:2026-11-21T02:00:00Z', '--words', 'grant one fix-check'])))![1]!; + g.f.write({ 'src/x.ts': 'export const x = 4;\n' }); g.f.commit('fix the fix-check finding'); + const plan = g.run('gstack-review-plan', ['--base', 'main', '--gate-tagged', '0', '--prior-rounds', '3', '--prior-full', '2', '--pr', '7', '--round-grant', g2, '--stop', s2, '--range-base', s2, '--last', 'fix-check', '--fix-checks', '1', '--touched-gate']); + expect(plan.status, plan.stderr).toBe(0); + expect(plan.stdout).toContain('next=fix-check'); + }); +}); + +describe('the fix-check reader\'s packet is byte-identical with and without a claim (rule 15)', () => { + // Value: protects=no reviewer packet changes: the stamp and the hunks record ride beside the prompt; fails_when=a claimed run's + // prompt bytes differ from renderFixCheckPrompt's; seam=gstack-review-plan --fix-check-prompt + test('--fix-check-prompt prints renderFixCheckPrompt\'s bytes, claimed or not, and records the hunks digest', () => { + const f = shipFixture(); + fxs.push(f); + const files = { fixList: 'fix p1/outside-voice#1\n', touchedHunks: 'diff --git a/src/b.ts b/src/b.ts\n+x\n', testResults: '3 pass\n', callers: '' }; + const args = Object.entries({ '--fix-list': files.fixList, '--hunks': files.touchedHunks, '--tests': files.testResults }).flatMap(([k, v]) => { const p = path.join(f.root, k.slice(2)); fs.writeFileSync(p, v); return [k, p]; }); + const prompt = () => f.run(path.join(BIN, 'gstack-review-plan'), ['--fix-check-prompt', ...args]).stdout; + const plain = prompt(); + fs.writeFileSync(path.resolve(f.work, f.git('rev-parse', '--git-path', 'gstack-ship-run').stdout.trim()), JSON.stringify({ v: 1, run: 'fc1', state: 'open', head: 'a'.repeat(40), started_at: new Date().toISOString(), beat_at: new Date().toISOString(), claim: { grant: 'a-000000000001', stop_head: 'a'.repeat(40), findings: [], pr: 7 } })); + expect(Buffer.from(prompt())).toEqual(Buffer.from(plain)); + expect(Buffer.from(plain)).toEqual(Buffer.from(renderFixCheckPrompt(files))); + const rec = JSON.parse(fs.readFileSync(path.resolve(f.work, f.git('rev-parse', '--git-path', 'gstack-fix-check-hunks').stdout.trim()), 'utf8')); + expect(rec).toMatchObject(hunksDigest(files.touchedHunks)); + }); +}); + +describe('clearing refuses every gap GSTA-665\'s trail reads found in #4546 (lib/fix-check-clearing.ts)', () => { + let g: Granted; + let base: { pr: number; run: string; head: string; baseRef: string; body: string; grants: ReviewRoundGrant[]; rows: Record[]; open: Array }; + const fixRow = () => base.rows.filter(r => r.skill === 'review-fix-check').at(-1)!; + const withRow = (row: Record) => [...base.rows.filter(r => r.skill !== 'review-fix-check'), row]; + const clear = (o: Partial = {}) => clearByGrant(g.f.work, { ...base, ...o }); + beforeAll(() => { + g = grantedRun({ sameRun: false }); + fxs.length = 0; + base = { pr: 7, run: 'fc1', head: g.F, baseRef: 'origin/main', body: fs.readFileSync(g.body, 'utf8'), grants: grantsOf(g), rows: rowsOf(g), open: [{ id: ID, fingerprint: FP }] }; + }); + afterAll(() => g.f.cleanup()); + + test('the baseline closes the granted id', () => { + expect(clear()).toEqual({ ids: [ID], approval: g.grant, run: 'fc1' }); + }); + test('another PR\'s grant closes nothing', () => { + expect(clear({ grants: base.grants.map(x => ({ ...x, pr: 8 })) })).toMatchObject({ ids: [], why: 'no fix-check grant for PR #7' }); + }); + test('with no stop record the grant closes nothing', () => { + expect(clear({ body: base.body.split('\n').filter(l => !l.includes('"mark":"stop"')).join('\n') })).toMatchObject({ ids: [], why: expect.stringContaining('no stop record') }); + }); + test('another run\'s first claim closes nothing for this run', () => { + const body = base.body.replace('"run":"fc1","mark":"grant"', '"run":"fc9","mark":"grant"'); + expect(receiptRuns(body).find(r => r.mark === 'grant')?.run).toBe('fc9'); + expect(clear({ body }).ids).toEqual([]); + expect(clear({ run: 'fc9' }).ids).toEqual([]); + }); + test('a spent grant (a second stamped row) closes nothing', () => { + expect(clear({ rows: [...base.rows, { ...fixRow(), run: 'fc2', commit_full: g.S, findings: [{ fingerprint: 'x' }] }] })).toMatchObject({ ids: [], why: expect.stringContaining('holds 2') }); + }); + test('a row with another fix_check_base, or an agent range_base that disagrees, closes nothing', () => { + const fork = g.f.git('merge-base', 'origin/main', 'HEAD').stdout.trim(); + expect(clear({ rows: withRow({ ...fixRow(), fix_check_base: fork }) }).why).toContain('is not the stop'); + expect(clear({ rows: withRow({ ...fixRow(), range_base: fork }) }).why).toContain('disagrees with the logger'); + }); + test('two ledger ids sharing a fingerprint: the fingerprint closes neither, the ledger id closes only its own', () => { + const open = [{ id: ID, fingerprint: FP }, { id: 'p1/red-team#2', fingerprint: FP }]; + expect(clear({ open, grants: base.grants.map(x => ({ ...x, findings: [FP] })) }).ids).toEqual([]); + expect(clear({ open }).ids).toEqual([ID]); + }); + test('an open critical in a findings file closes nothing', () => { + expect(clear({ rows: withRow({ ...fixRow(), status: 'issues_found', findings_open: 1, findings_file: '/tmp/f.jsonl', status_source: 'derived' }) }).why).toContain('left a finding open'); + }); + test('an inline open finding at low severity closes nothing', () => { + expect(clear({ rows: withRow({ ...fixRow(), findings: [{ fingerprint: 'src/x.ts:2:style', severity: 'INFORMATIONAL', action: 'open', blocking: false }] }) }).why).toContain('left a finding open'); + }); + test('a newer review on a dirty tree after the stop does not displace the stop head', () => { + const dirty = { skill: 'review', via: 'ship', completed: true, converged: true, commit_full: g.F, tree: 'e'.repeat(40), wtree: 'd'.repeat(40), review_binding: { state: 'changed', start_wtree: 'd'.repeat(40), end_wtree: 'e'.repeat(40), started_at: new Date().toISOString() }, timestamp: new Date().toISOString(), findings: [] }; + expect(clear({ rows: [...base.rows, dirty] })).toEqual({ ids: [ID], approval: g.grant, run: 'fc1' }); + }); + test('a grant id that names nothing open closes nothing, and the rest still close', () => { + const grants = base.grants.map(x => ({ ...x, findings: [ID, 'p9/nope#1'] })); + expect(clear({ grants })).toMatchObject({ ids: [ID], why: expect.stringContaining('p9/nope#1') }); + expect(clear({ grants: base.grants.map(x => ({ ...x, findings: ['p9/nope#1'] })) }).ids).toEqual([]); + }); + test('hunks that are not git diff , out-of-order records, or a gate finding close nothing', () => { + expect(clear({ rows: withRow({ ...fixRow(), hunks: { ...fixRow().hunks, sha256: '0'.repeat(64) } }) }).why).toContain('hunks'); + const stop = receiptRuns(base.body).find(r => r.mark === 'stop')!; + const late = placeRunEntry(base.body.replace(/\{"head":"[0-9a-f]{40}","run":"ro","mark":"stop"[^\n]*\n/, ''), stopMarker({ head: stop.head, tree: stop.tree!, run: 'ro', at: '2099-01-01T00:00:00.000Z' })); + expect(clear({ body: late }).why).toContain('not recorded in that order'); + expect(clear({ rows: [...base.rows, { skill: 'review', via: 'ship', findings: [{ ledger_id: ID, gate: 'RH1', action: 'open' }] }] }).ids).toEqual([]); + }); + // Value: protects=a clean fix-check closes only the grant ids its fix list named; fails_when=a grant id the reader was never + // asked about closes; seam=gstack-review-plan --fix-check-prompt, clearByGrant + test('the fix list\'s names are recorded, and a grant id the fix list left out closes nothing', () => { + expect(fixRow().hunks.fix_list).toEqual([ID]); + expect(clear({ rows: withRow({ ...fixRow(), hunks: { ...fixRow().hunks, fix_list: [] } }) })).toMatchObject({ ids: [], why: expect.stringContaining('does not name ' + ID) }); + }); + test('no trailer, or a trailer with no later full round, closes nothing by trailer', () => { + expect(clearByTrailer(g.f.work, { head: g.F, baseRef: 'origin/main', rows: base.rows, open: base.open })).toEqual([]); + expect(grantMarker({ head: g.S, run: 'x', grant: 'a' }).at).toMatch(/^\d{4}-/); + }); +}); diff --git a/test/fixtures/module-size-ratchet.json b/test/fixtures/module-size-ratchet.json index 20ccba40a..d2c48157a 100644 --- a/test/fixtures/module-size-ratchet.json +++ b/test/fixtures/module-size-ratchet.json @@ -134,6 +134,7 @@ { "file": "lib/tree-receipt.ts", "movedFrom": "(new: tree equality modulo stamps and per-gate reuse, C3)" }, { "file": "lib/ship-receipt.ts", "movedFrom": "(new: the ship receipt block, PR-body placement and adoption census, C5)" }, { "file": "lib/ship-run-record.ts", "movedFrom": "(new: the /ship run record that replaces the bare run marker, its transition table and the gate lock, GST-3260)" }, + { "file": "lib/fix-check-clearing.ts", "movedFrom": "(new: when a granted fix-check counts and what it closes, shared by finish and receipt write, GST-3260)" }, { "file": "lib/ship-receipt-docs.ts", "movedFrom": "(new: the receipt's docs record, the owner exception and the policy doc caps, kept out of lib/ship-receipt.ts; convergence lane PR 2)" }, { "file": "lib/spend-ledger.ts", "movedFrom": "(new: the spend cap admission ledger reserve/settle/release and the file lock, B2)" }, { "file": "lib/outside-voice-runner.ts", "movedFrom": "(new: the outside-voice adapter interface, model families and runner selection, B3)" },