diff --git a/bin/gstack-ship-receipt b/bin/gstack-ship-receipt index c7773bf61..18f0433a6 100755 --- a/bin/gstack-ship-receipt +++ b/bin/gstack-ship-receipt @@ -53,7 +53,7 @@ import { approvalForReceipt } from '../lib/approval-citations'; import { CARRY_NAMED_PATHS, bindReceipt, carryReceipt, recheckCarried, classifyCarryPath, computeCensus, extractReceipt, landedStackParent, missingIssueLines, orderReceipt, parseReviewLoop, placeReceipt, planCarry, planTreeCarry, - receiptIssuesFrom, receiptRuns, receiptSummaryLine, renderCensus, renderReceiptBlock, unruledOpenBlockers, validateReceipt, type CensusPr, + RUNS_FENCE, receiptIssuesFrom, receiptRuns, receiptSummaryLine, renderCensus, renderReceiptBlock, unruledOpenBlockers, validateReceipt, type CensusPr, } from '../lib/ship-receipt'; import { checkDocsCaps, docsCapLine, docsExceptionLine, parseReceiptDocs } from '../lib/ship-receipt-docs'; import { comparePath, contextPacket, PACKET_SECTION_CAP, readScopedReview, touchedPaths } from '../lib/ship-patch'; @@ -68,7 +68,7 @@ import { appliedGateDispositions, gateDispositionText, publicGateDisposition } f 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 { changeRunRecord, readRunRecord } 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'; @@ -439,7 +439,15 @@ async function cmdWrite(rest: string[], json: boolean): Promise { 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') : ''; + let text = fs.existsSync(body) ? fs.readFileSync(body, 'utf8') : ''; + const pr = flag(rest, '--pr'); + if (pr && fs.existsSync(body) && !extractReceipt(text).found && !receiptRuns(text).length) { + const live = readBody(['--pr', pr, ...(flag(rest, '--repo') ? ['--repo', flag(rest, '--repo')!] : [])]); + const prior = live.ok ? extractReceipt(live.body).receipt : undefined; + const runs = live.ok ? receiptRuns(live.body) : []; + if (!live.ok) process.stderr.write(`RECEIPT_RUNS: PR #${pr}'s earlier runs were not read (${live.why}), so ${body} keeps only this run; fix: ${live.fix}\n`); + else if (prior || runs.length) text = withAgentNotes(text, [(splitAgentNotes(text).notes ?? '').trim(), prior ? renderReceiptBlock(prior) : '', runs.length ? '```' + RUNS_FENCE + '\n' + runs.map(r => JSON.stringify(r)).join('\n') + '\n```\n' : ''].filter(Boolean).join('\n\n')); + } 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)); @@ -1061,6 +1069,7 @@ function cmdClaim(rest: string[]): number { 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 ?? [], pr: g.pr } }); + if (!recorded.ok && readRunRecord(repoRoot).kind !== 'none') { process.stderr.write(`gstack-ship-receipt claim: the run record did not take the claim (${recorded.why}); not claimed, so do not dispatch: the PR body already holds run ${run}'s claim, so rerun claim with this same --run once the record is writable (a new run id reads GRANT_SPENT)\n`); return EXIT.fail; } 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; } diff --git a/changelog.d/ship-claim-and-rerun-history.md b/changelog.d/ship-claim-and-rerun-history.md new file mode 100644 index 000000000..ff2ac1930 --- /dev/null +++ b/changelog.d/ship-claim-and-rerun-history.md @@ -0,0 +1 @@ +**/ship's bookkeeping holds up in three more cases.** A shared harness pin counts as already reviewed after a main merge only when it is a regular file and both pinned files resolve, so a pin turned into a symlink needs a fresh review. `gstack-ship-receipt claim` now fails, and says not to start reviewers, when the run record could not save the claim, instead of reporting it claimed. `gstack-ship-receipt write --pr` keeps the PR's earlier /ship runs when Step 19 hands it a freshly written description, so later runs count the PR's review rounds correctly. The docs audit steps now say a re-audit carries an earlier audit that stopped before its post snapshot with `--carry-stopped` (GST-3463). diff --git a/docs/review-policy.md b/docs/review-policy.md index cff0afd78..aa9cdba7e 100644 --- a/docs/review-policy.md +++ b/docs/review-policy.md @@ -231,7 +231,10 @@ caught on another crew's PRs. A run whose flags name a grant runs `gstack-ship-receipt claim` before its first dispatch, which writes a grant record into the runs block; a grant another run claimed is refused (`GRANT_SPENT`), a voided run's claim still - spends it, and stop and grant records are never trimmed from the block. + spends it, and stop and grant records are never trimmed from the block. When + the run record cannot save the claim, claim fails and the run starts no + reviewers; rerun claim with the same `--run` once the record is writable, since + a new run id reads `GRANT_SPENT`. gstack never grants itself a round: `--by` naming gstack (one of the names gstack writes for itself, `gstack` or `gstack no-stop default (K1)`, matched whole and case-insensitively, so "gstack-evals Captain" or "GStack Minder" can diff --git a/docs/ship-policy.md b/docs/ship-policy.md index f128f6b28..1d9da4c2f 100644 --- a/docs/ship-policy.md +++ b/docs/ship-policy.md @@ -1713,7 +1713,7 @@ recorded by accident, but it does not read the review ledger: a write given the `expected=` digest passes without a review, and only the review run shows that the reviewers read that selection. Write, carry and the queue make one exception (GST-1408, GST-1415, GST-1434, GST-1446): when the digests differ but the recorded selection and HEAD's give the PR's files the same selection, meaning the same applied patterns, the same excluded files and the same kept files with their reasons, write records HEAD's digest, carry carries the receipt and records HEAD's digest, and the queue (`ready`, train build, land) binds it. So a pattern the base gains, adds, removes or reverts that changes nothing about the PR's files does not void the review. No recorded selection (`none`) counts as the empty one. A receipt's record counts only when its digest is built from its list hash. Write gets only a digest, so it rebuilds the recorded selection: the digest binds when the `review_exclude_paths` the base held at some commit that changed the policy file, combined with HEAD's list hash, gives that digest. It prints `REVIEW_EXCLUDE_POLICY_MOVED:`. A digest no such policy gives, an omitted `--review-exclude`, a selection that differs over the PR's files and an unreadable base policy still refuse. -Write makes one exception for Step 14.5's docs audit, which runs after the review (GST-1429): with `--docs-post -post.json` it accepts the reviewed digest when that digest is HEAD's selection with every file under a pattern that changed since the snapshot's HEAD reset to it, each such file is uncommitted in the snapshot with the content HEAD holds, each is excluded or kept only because code names it, and every other file is excluded or kept alike on both sides. With `--docs-pre ` only the files whose content changed between the audit's two snapshots reset, to their Prepare content, so uncommitted docs the reviewers read stay as they are; content compares as git stores it or as it checks out (autocrlf, filters). It prints `REVIEW_EXCLUDE_DOCS_AUDIT:` and records HEAD's digest. Any other change to the selection, an audit file the exclusion keeps for another reason, an edit after the snapshot and a missing or unreadable snapshot still refuse. When one `/ship` run audits twice (a re-audit after a base merge and restamp), every snapshot names the run (`--run `), each post snapshot names its Prepare snapshot (`--pre`, recording the files the audit edited), and the re-audit's post snapshot carries the earlier one (`--carry `; GST-1616). Write then also resets each file an earlier audit of the run edited, to its content before that audit, when HEAD (or the re-audit's Prepare snapshot) holds what the audit left; a file no audit edited still refuses, and a carried audit of another run is refused by the snapshot and by write. After a base merge, write does not count a file under a pattern that only the merged base changed (the PR's own three-dot diff leaves it alone), a re-audit that edited nothing still binds through the audits it carries, and the rebuilt selection binds the reviewed digest even when the merge moved the base policy (for example, added a pattern); a docs file the PR itself changes after the last audit still refuses (GST-3260). +Write makes one exception for Step 14.5's docs audit, which runs after the review (GST-1429): with `--docs-post -post.json` it accepts the reviewed digest when that digest is HEAD's selection with every file under a pattern that changed since the snapshot's HEAD reset to it, each such file is uncommitted in the snapshot with the content HEAD holds, each is excluded or kept only because code names it, and every other file is excluded or kept alike on both sides. With `--docs-pre ` only the files whose content changed between the audit's two snapshots reset, to their Prepare content, so uncommitted docs the reviewers read stay as they are; content compares as git stores it or as it checks out (autocrlf, filters). It prints `REVIEW_EXCLUDE_DOCS_AUDIT:` and records HEAD's digest. Any other change to the selection, an audit file the exclusion keeps for another reason, an edit after the snapshot and a missing or unreadable snapshot still refuse. When one `/ship` run audits twice (a re-audit after a base merge and restamp), every snapshot names the run (`--run `), each post snapshot names its Prepare snapshot (`--pre`, recording the files the audit edited), and the re-audit's post snapshot carries the earlier one (`--carry `; GST-1616). Write then also resets each file an earlier audit of the run edited, to its content before that audit, when HEAD (or the re-audit's Prepare snapshot) holds what the audit left; a file no audit edited still refuses, and a carried audit of another run is refused by the snapshot and by write. When an earlier audit stopped as blocked before its post snapshot, the re-audit's post snapshot carries it with `--carry-stopped `, taken at the same HEAD, and its edits are what changed between the two Prepare snapshots (GST-3502). After a base merge, write does not count a file under a pattern that only the merged base changed (the PR's own three-dot diff leaves it alone), a re-audit that edited nothing still binds through the audits it carries, and the rebuilt selection binds the reviewed digest even when the merge moved the base policy (for example, added a pattern); a docs file the PR itself changes after the last audit still refuses (GST-3260). **Adopting it.** (1) Open a PR on the base that adds the patterns and `min_gstack_version` at least `REVIEW_EXCLUDE_KEY_VERSION`, and ship it like any @@ -2347,7 +2347,7 @@ receipt when the base moves: |---|---| | a merge of the base, product diff unchanged (tests, release metadata, registered outputs the pregate's regen check proved) | carries; no review reruns | | a merge of the base that edited lines next to the branch's unchanged hunks (the branch's +/- lines identical and in the same places) | carries after one fix-check reviewer reads the hunks and comes back clean (`RECEIPT_CARRY_SCOPED_REVIEW`, then `carry --scoped-review `) | -| a merge of the base that only re-records the harness pin of a product file (`scripts/harness-pins/.json`; a pinned test or metadata file's pin stays product): at both heads the pin's `blob` is its file's blob, its other fields are the reviewed ones, and `scripts/harness-version.json`'s version and patterns did not move; the pinned file itself still counts as product | carries (reason `regenerated outputs`, GSTA-749) | +| a merge of the base that only re-records the harness pin of a product file (`scripts/harness-pins/.json`; a pinned test or metadata file's pin stays product): at both heads the pin is a regular file (not a symlink), both pinned files resolve, the pin's `blob` is its file's blob, its other fields are the reviewed ones, and `scripts/harness-version.json`'s version and patterns did not move; the pinned file itself still counts as product | carries (reason `regenerated outputs`, GSTA-749) | | a merge of the base whose resolution changed product code, or moved the branch's lines elsewhere | a fresh /ship (`RECEIPT_CARRY_PRODUCT_CHANGED`) | | a rebase or force-push onto a tree the receipt covers, product diff against the new base unchanged | carries (`carry.ancestry: rewritten`) | | any other rebase or force-push | a fresh /ship (`RECEIPT_CARRY_TREE_MISMATCH`) | diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index 5531a9f33..b4cdea417 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -4142,7 +4142,8 @@ removing files under a pattern, pass that run's `--docs-post -post.jso `--docs-pre` as well instead of rerunning the review; the refusal's `the docs-audit exception does not apply:` clause says why when it cannot ([ship-policy.md](ship-policy.md#review-exclude-paths), GST-1429). When the run audited twice (a re-audit after a base merge), pass the last audit's pair; its post snapshot must carry the earlier audit (`--carry `, GST-1616), or the -earlier audit's files stay in the selection and write refuses as before. The last audit may have edited nothing: write still binds +earlier audit's files stay in the selection and write refuses as before. An earlier audit that stopped before its post snapshot +is carried with `--carry-stopped ` at the same HEAD instead (GST-3502). The last audit may have edited nothing: write still binds through the audits it carries, ignores docs files only the merged base changed, and accepts a base policy that gained a pattern in that merge (GST-3260). diff --git a/lib/ship-receipt-patch.ts b/lib/ship-receipt-patch.ts index ed1fe1065..9bb74132f 100644 --- a/lib/ship-receipt-patch.ts +++ b/lib/ship-receipt-patch.ts @@ -87,11 +87,13 @@ const HARNESS_PIN = /^scripts\/harness-pins\/(.+)\.json$/; * its other fields are the reviewed ones, and the harness manifest's version and patterns did not move. The pin is then a * function of the pinned file's bytes, so it is a regenerated output, but only when the pinned file is itself product: a * pinned test or metadata file carries on its own, so its re-pin is the only change that stops an unreviewed harness edit. - * Anything else is product. + * The pin must be a regular file at both heads, since the harness reads a symlinked pin through its target while git shows the + * link text, and both pinned blobs must resolve. Anything else is product. */ function rederivedHarnessPin(repoRoot: string, from: string, to: string, p: string, extra: ProductRules['extra']): boolean { const pinned = HARNESS_PIN.exec(p)?.[1]; if (!pinned || classifyCarryPath(pinned, extra) !== 'product') return false; + if (![from, to].every(ref => git(['ls-tree', ref, '--', p], repoRoot)?.startsWith('100644 blob '))) return false; const json = (ref: string, rel: string): any => { const r = spawnSync('git', ['show', `${ref}:${rel}`], { cwd: repoRoot, encoding: 'utf8', timeout: 30_000, maxBuffer: 16 * 1024 * 1024 }); try { return r.status === 0 ? JSON.parse(r.stdout) : null; } catch { return null; } }; const [ma, mb] = [json(from, HARNESS_MANIFEST), json(to, HARNESS_MANIFEST)]; if (!ma || !mb || ma.version !== mb.version || JSON.stringify(ma.patterns) !== JSON.stringify(mb.patterns)) return false; @@ -99,8 +101,8 @@ function rederivedHarnessPin(repoRoot: string, from: string, to: string, p: stri if (!a || !b || typeof a !== 'object' || typeof b !== 'object' || Array.isArray(a) || Array.isArray(b)) return false; const { blob: blobA, ...restA } = a; const { blob: blobB, ...restB } = b; - return blobA === git(['rev-parse', '--verify', '--quiet', `${from}:${pinned}`], repoRoot) && blobB === git(['rev-parse', '--verify', '--quiet', `${to}:${pinned}`], repoRoot) - && JSON.stringify(restA) === JSON.stringify(restB); + const [pinnedA, pinnedB] = [from, to].map(ref => git(['rev-parse', '--verify', '--quiet', `${ref}:${pinned}`], repoRoot)); + return !!pinnedA && !!pinnedB && blobA === pinnedA && blobB === pinnedB && JSON.stringify(restA) === JSON.stringify(restB); } export interface ProductRules { extra: { metadata: string[]; outputs: readonly string[]; fragments?: string }; metadata: string[]; templates: readonly string[]; placeholders: readonly string[] } diff --git a/scripts/lib/windows-curation.ts b/scripts/lib/windows-curation.ts index 43e1642b3..08f1b75d8 100644 --- a/scripts/lib/windows-curation.ts +++ b/scripts/lib/windows-curation.ts @@ -484,6 +484,14 @@ export const KNOWN_WINDOWS_INCOMPATIBLE: Array<{ file: string; reason: string }> 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/ship-receipt-claim-fail-closed.test.ts', + reason: 'drives bin/gstack-ship-preflight, gstack-ship-receipt, gstack-approvals and gstack-review-log (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/ship-receipt-write-keeps-earlier-runs.test.ts', + reason: 'puts a #!/bin/sh gh shim on a PATH it joins for bin/gstack-ship-receipt write; windows-latest cannot launch an extensionless shell script, like the gh shim in test/ship-queue-land.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/ship/sections/documentation.md b/ship/sections/documentation.md index 87edbed2a..0354c1abd 100644 --- a/ship/sections/documentation.md +++ b/ship/sections/documentation.md @@ -105,8 +105,8 @@ branch's copy (a PR cannot raise its own cap), prints one `DOCS_CAP: -post.json` changed and `--pre ` added, -plus `--carry ` on a re-audit so receipt write -resets both audits' files; Step 16 `compare`s it; never type hashes), status, and keep the `-result.json` and private `-documentation.md` +plus, on a re-audit, `--carry ` for each earlier audit of this run that saved one and `--carry-stopped ` +for each that stopped before its post snapshot, so receipt write resets every audit's files; Step 16 `compare`s it; never type hashes), status, and keep the `-result.json` and private `-documentation.md` that `result` wrote. That section file is the section's single source; reports and Step 19 insert it by command (`cat`) where they can, never retyped or edited. Save records once; cite files by path, never copying their content. @@ -136,8 +136,8 @@ auto-commit or push unexpected child commits. `RETRY_NOTE:` text verbatim. Repeat Prepare using current inputs and a fresh id/snapshot, run the remaining attempt, then validate it through Parent processing. When the stopped audit saved no post - snapshot, the re-audit's post snapshot adds `--carry-stopped ` - so receipt write resets the stopped audit's edits too. + snapshot, the re-audit's post snapshot adds `--carry-stopped `, keeping + `--carry` for any earlier audit that saved one, so receipt write resets the stopped audit's edits too. 3. Otherwise STOP before commit/publication and do not launch another child. AskUserQuestion: stop for repair (recommended), or ship with the specific named documentation risk. Only an actual user exception counts, never a default, diff --git a/ship/sections/documentation.md.tmpl b/ship/sections/documentation.md.tmpl index 9804b6447..e7f988b5d 100644 --- a/ship/sections/documentation.md.tmpl +++ b/ship/sections/documentation.md.tmpl @@ -103,8 +103,8 @@ branch's copy (a PR cannot raise its own cap), prints one `DOCS_CAP: -post.json` changed and `--pre ` added, -plus `--carry ` on a re-audit so receipt write -resets both audits' files; Step 16 `compare`s it; never type hashes), status, and keep the `-result.json` and private `-documentation.md` +plus, on a re-audit, `--carry ` for each earlier audit of this run that saved one and `--carry-stopped ` +for each that stopped before its post snapshot, so receipt write resets every audit's files; Step 16 `compare`s it; never type hashes), status, and keep the `-result.json` and private `-documentation.md` that `result` wrote. That section file is the section's single source; reports and Step 19 insert it by command (`cat`) where they can, never retyped or edited. Save records once; cite files by path, never copying their content. @@ -134,8 +134,8 @@ auto-commit or push unexpected child commits. `RETRY_NOTE:` text verbatim. Repeat Prepare using current inputs and a fresh id/snapshot, run the remaining attempt, then validate it through Parent processing. When the stopped audit saved no post - snapshot, the re-audit's post snapshot adds `--carry-stopped ` - so receipt write resets the stopped audit's edits too. + snapshot, the re-audit's post snapshot adds `--carry-stopped `, keeping + `--carry` for any earlier audit that saved one, so receipt write resets the stopped audit's edits too. 3. Otherwise STOP before commit/publication and do not launch another child. AskUserQuestion: stop for repair (recommended), or ship with the specific named documentation risk. Only an actual user exception counts, never a default, diff --git a/test/gstack-docs-candidate.test.ts b/test/gstack-docs-candidate.test.ts index cd5629e81..0f77ac144 100644 --- a/test/gstack-docs-candidate.test.ts +++ b/test/gstack-docs-candidate.test.ts @@ -234,7 +234,7 @@ describe('gstack-docs-candidate', () => { // ci-37198445662 gate-census-2: ship-docsync-completion/-store parents spent 45-78 s of model time // retyping hash maps, child output and records into several artifacts after the child returned. const gate = fs.readFileSync(path.resolve(import.meta.dir, '..', 'ship/sections/documentation.md.tmpl'), 'utf8').replace(/\s+/g, ' '); - expect(gate).toContain('post-child hashes (rerun the Prepare `snapshot` with only `--out -post.json` changed and `--pre ` added, plus `--carry ` on a re-audit so receipt write resets both audits\' files; Step 16 `compare`s it; never type hashes)'); + expect(gate).toContain('post-child hashes (rerun the Prepare `snapshot` with only `--out -post.json` changed and `--pre ` added, plus, on a re-audit, `--carry ` for each earlier audit of this run that saved one and `--carry-stopped ` for each that stopped before its post snapshot, so receipt write resets every audit\'s files; Step 16 `compare`s it; never type hashes)'); expect(gate).toContain('Save records once; cite files by path, never copying their content.'); const { dir, root, record } = repo(); const args = ['--audit-id', 'a1', '--mode', 'edit', '--base', 'main', '--docs', 'handbook']; diff --git a/test/gstack-ship-receipt.test.ts b/test/gstack-ship-receipt.test.ts index 98e2b1511..afd6777be 100644 --- a/test/gstack-ship-receipt.test.ts +++ b/test/gstack-ship-receipt.test.ts @@ -43,7 +43,7 @@ describe('gstack-ship-receipt write', () => { const ok = runBin(repo, 'gstack-ship-receipt', ['write', '--pr', '42', '--base', 'main', '--receipt', treeReceipt, '--gate', '{"tests":{"pass":1,"fail":0,"skip":0}}', '--ci', '@' + path.join(repo.root, 'ci.json'), '--spend-usd', '0.42', '--session-kind', 'unattended', '--artifacts-consumed', '2/3', '--run', 'run-1', '--thread', 'jam_1', '--queue-mode', 'stamp-at-merge', - '--preregistration', 'none (no preregistration_shas)', '--history', 'squash-ok', '--body', body, '--out', path.join(repo.root, 'receipt.md')]); + '--preregistration', 'none (no preregistration_shas)', '--history', 'squash-ok', '--body', body, '--out', path.join(repo.root, 'receipt.md')], ghShim(repo, { 42: { body: '' } })); expect(ok.status).toBe(EXIT.ok); expect(ok.err.trim()).toBe(`SHIP_RECEIPT: pr=42 head=${head.slice(0, 12)} version=1.2.4.0 base=main gated_tree=${repo.git('rev-parse', 'HEAD^{tree}').slice(0, 12)} tree=same-modulo-stamps gate-reuse=eligible (reusable: tests; rerun: -) predecessor=${'b'.repeat(12)} session_kind=unattended artifacts_consumed=2/3 depth=light`); const parsed = extractReceipt(ok.out); diff --git a/test/ship-receipt-carry-harness-repin.test.ts b/test/ship-receipt-carry-harness-repin.test.ts index 418f4f9b4..2bdcdc9f6 100644 --- a/test/ship-receipt-carry-harness-repin.test.ts +++ b/test/ship-receipt-carry-harness-repin.test.ts @@ -4,9 +4,10 @@ * file; merging the base re-records the pin's blob for the merged file and nothing else. The pin is then a function of * the pinned file's bytes, which the carry still compares as product, so it carries as a regenerated output. Controls: * a pin whose blob is not the file's, a changed reason, a moved harness version and a blob-only re-pin of a pinned test - * helper (which carries as a test change on its own) still refuse. + * helper (which carries as a test change on its own) and a pin turned into a symlink still refuse. */ import { afterEach, describe, expect, test } from 'bun:test'; +import * as fs from 'node:fs'; import * as path from 'node:path'; import { EXIT } from '../lib/headless-artifacts'; import { cleanup, commit, makeFixtureRepo, runBin, write, type FixtureRepo } from './helpers/pregate-fixture'; @@ -22,7 +23,7 @@ const pin = (blob: string, reason: string, since = 7) => `${JSON.stringify({ blo const LINES = ['export const FREE = [', " 'a.yml',", '];', ...Array.from({ length: 8 }, (_, i) => `export const K${i} = ${i};`), '']; /** main pins FILE; feature edits its start and re-pins, /ship receipt there; main edits its end and re-pins; feature merges main and resolves the pin with `resolve`. */ -function repinned(resolve: (merged: string) => Record): { body: string; repo: FixtureRepo } { +function repinned(resolve: (merged: string) => Record, linkPin = false): { body: string; repo: FixtureRepo } { const repo = makeFixtureRepo(); repos.push(repo); const blob = () => repo.git('rev-parse', `HEAD:${FILE}`); repo.git('checkout', '-q', 'main'); @@ -41,7 +42,11 @@ function repinned(resolve: (merged: string) => Record): { body: repo.git('push', '-q', 'origin', 'main'); repo.git('checkout', '-q', 'feature'); try { repo.git('merge', '-q', '--no-edit', 'origin/main'); } catch { /* the pin conflicts; resolved below */ } - for (const [rel, text] of Object.entries(resolve(repo.git('hash-object', FILE)))) write(repo.work, rel, text); + for (const [rel, text] of Object.entries(resolve(repo.git('hash-object', FILE)))) { + if (!linkPin || rel !== PIN) { write(repo.work, rel, text); continue; } + fs.rmSync(path.join(repo.work, rel), { force: true }); + fs.symlinkSync(text.trim(), path.join(repo.work, rel)); + } repo.git('add', '-A'); repo.git('commit', '-q', '--no-edit'); return { body, repo }; @@ -106,6 +111,18 @@ describe('carry across a harness pin a base merge re-recorded (GSTA-749)', () => expect(out.err).toContain(pinPath); }, 90_000); + // Value: protects=the harness reads the pin git shows: a symlink's link text can spell the reviewed pin while the harness + // follows it elsewhere (second-model review of #4669); fails_when=a pin is read without its tree mode; seam=productSpec; + // no_claim=gh pr edit + test.skipIf(process.platform === 'win32')('a pin turned into a symlink whose link text is the pin still refuses', () => { + const { repo, body } = repinned(merged => ({ [PIN]: pin(merged, BRANCH_REASON) }), true); + expect(repo.git('ls-tree', 'HEAD', '--', PIN)).toStartWith('120000 '); + const out = carry(repo, body); + expect(out.status).toBe(EXIT.refused); + expect(out.err).toContain('RECEIPT_CARRY_PRODUCT_CHANGED'); + expect(out.err).toContain(PIN); + }, 90_000); + // Value: protects=a version bump starts a new pass-rate series, a behavior change; fails_when=a bump rides a re-record; seam=productSpec; no_claim=gh pr edit test('a re-record beside a harness version bump still refuses', () => { const { repo, body } = repinned(merged => ({ [PIN]: pin(merged, BRANCH_REASON, 8), [MANIFEST]: manifest(8) })); diff --git a/test/ship-receipt-claim-fail-closed.test.ts b/test/ship-receipt-claim-fail-closed.test.ts new file mode 100644 index 000000000..696bc352d --- /dev/null +++ b/test/ship-receipt-claim-fail-closed.test.ts @@ -0,0 +1,68 @@ +/** + * gstack-ship-receipt claim fails closed when it cannot record the claim in the run record (#4654 review note): the run + * record's claim is what limits a stopped run to one self-granted fix round, so a claim the record never took must not + * read as GRANT_CLAIMED with exit 0, or the run could stop and grant itself again. + */ +import { afterEach, describe, expect, setDefaultTimeout, test } from 'bun:test'; +import * as fs from 'node:fs'; +import * as path from 'node:path'; +import { PREFLIGHT, shipFixture, type ShipFx } from './helpers/ship-bin-fixture'; + +setDefaultTimeout(120_000); +const BIN = path.join(import.meta.dir, '..', 'bin'); +const CHECKOUT = { GSTACK_LEASE_DIR: '', GSTACK_APPROVALS_MIRROR: '0' }; +const fixtures: ShipFx[] = []; +afterEach(() => { while (fixtures.length) fixtures.pop()!.cleanup(); }); + +const run = (f: ShipFx, bin: string, args: string[]) => f.run(path.join(BIN, bin), args, CHECKOUT); +const gitPath = (f: ShipFx, name: string) => path.resolve(f.work, f.git('rev-parse', '--git-path', name).stdout.trim()); +const record = (f: ShipFx) => JSON.parse(fs.readFileSync(gitPath(f, 'gstack-ship-run'), 'utf8')); + +/** A run ro that stopped on one blocker and granted itself the fix-check for its own stop: returns the grant id and the body file. */ +function stoppedWithOwnGrant(f: ShipFx): { grant: string; body: string } { + expect(f.run(PREFLIGHT, ['--base', 'main', '--run', 'ro'], CHECKOUT).status).toBe(0); + const start = run(f, 'gstack-review-log', ['--start', 'review']); + expect(start.status, start.stderr).toBe(0); + const row = { skill: 'review', timestamp: new Date().toISOString(), via: 'ship', pass: 1, review_scope: 'frozen', completed: true, converged: false, status: 'issues_found', issues_found: 1, critical: 1, informational: 0, findings: [{ fingerprint: 'src/x.ts:1:outside-voice', severity: 'CRITICAL', action: 'open', blocking: true, ledger_id: 'p1/outside-voice#1', raised_by: 'outside-voice' }] }; + expect(run(f, 'gstack-review-log', [JSON.stringify(row), '--finish', start.stdout.trim()]).status).toBe(0); + const body = path.join(f.root, 'body.md'); + fs.writeFileSync(body, 'Fixes a thing.\n'); + expect(run(f, 'gstack-ship-receipt', ['stop', '--body', body, '--pr', '7', '--run', 'ro', '--since', '2000-01-01T00:00:00Z']).status).toBe(0); + const head = f.git('rev-parse', 'HEAD').stdout.trim(); + const granted = run(f, 'gstack-approvals', ['round-grant', '--pr', '7', '--head', head, '--kind', 'fix-check', '--stop-run', 'ro', '--findings', 'p1/outside-voice#1', '--reason', 'fixable blocker', '--by', 'Captain GStack Minder (GSTA-36)']); + const grant = /APPROVAL_RECORDED: (a-[0-9a-f]{12})/.exec(granted.stdout)?.[1]; + expect(grant, granted.stderr).toBeDefined(); + return { grant: grant!, body }; +} + +describe('claim fails closed when the run record cannot take it (#4654)', () => { + // Value: protects=the once-per-run self-grant limit, which reads the run record's claim; fails_when=claim prints + // GRANT_CLAIMED and exits 0 after the record write failed; seam=gstack-ship-receipt claim; no_claim=gh pr edit + test('a claim whose run-record write fails exits non-zero and says not to dispatch', () => { + const f = shipFixture({ 'src/x.ts': 'export const x = 1;\n' }, { 'src/x.ts': 'export const x = 2;\n' }); + fixtures.push(f); + const { grant, body } = stoppedWithOwnGrant(f); + fs.mkdirSync(gitPath(f, 'gstack-gate-disposition.lock')); + const claim = run(f, 'gstack-ship-receipt', ['claim', '--body', body, '--run', 'ro', '--grant', grant]); + expect(claim.status).not.toBe(0); + expect(claim.stdout).not.toContain('GRANT_CLAIMED'); + expect(claim.stderr).toContain('do not dispatch'); + expect(record(f).claim).toBeUndefined(); + }); + + // Value: protects=a claim retried after the failure clears records the claim once (positive control); fails_when=the + // failed attempt's body marker blocks its own retry; seam=gstack-ship-receipt claim; no_claim=gh pr edit + test('the same claim retried once the record is writable records it', () => { + const f = shipFixture({ 'src/x.ts': 'export const x = 1;\n' }, { 'src/x.ts': 'export const x = 2;\n' }); + fixtures.push(f); + const { grant, body } = stoppedWithOwnGrant(f); + const lock = gitPath(f, 'gstack-gate-disposition.lock'); + fs.mkdirSync(lock); + expect(run(f, 'gstack-ship-receipt', ['claim', '--body', body, '--run', 'ro', '--grant', grant]).status).not.toBe(0); + fs.rmSync(lock, { recursive: true, force: true }); + const again = run(f, 'gstack-ship-receipt', ['claim', '--body', body, '--run', 'ro', '--grant', grant]); + expect(again.status, again.stderr).toBe(0); + expect(again.stdout).toContain('GRANT_CLAIMED: grant=' + grant); + expect(record(f)).toMatchObject({ run: 'ro', state: 'open', claim: { grant } }); + }); +}); diff --git a/test/ship-receipt-write-keeps-earlier-runs.test.ts b/test/ship-receipt-write-keeps-earlier-runs.test.ts new file mode 100644 index 000000000..0b8a33ae0 --- /dev/null +++ b/test/ship-receipt-write-keeps-earlier-runs.test.ts @@ -0,0 +1,59 @@ +/** + * gstack-ship-receipt write keeps the PR's earlier /ship runs when Step 19 hands it a freshly composed body (GST-3463 item 4): + * Step 19 builds the body file from parts, so it holds no receipt and no runs block, and write placed only the new receipt + * there; publishing it dropped every earlier run from the PR, so the next run's history counted fewer review rounds than the + * PR had. With --pr, write now reads the live body's receipt and runs into a fresh body before placing the new receipt. + * Control: an unreadable live body keeps today's output and says the earlier runs were not read. + */ +import { afterEach, describe, expect, test } from 'bun:test'; +import * as fs from 'node:fs'; +import * as path from 'node:path'; +import { EXIT } from '../lib/headless-artifacts'; +import { extractReceipt, receiptRuns } from '../lib/ship-receipt'; +import { cleanup, commit, makeFixtureRepo, runBin, type FixtureRepo } from './helpers/pregate-fixture'; + +const repos: FixtureRepo[] = []; +afterEach(() => { while (repos.length) cleanup(repos.pop()!); }); + +/** A feature branch with one /ship receipt already on the PR; the second head's write gets a fresh body file. */ +function secondRun(live: (firstBody: string) => string | null): { repo: FixtureRepo; first: string; out: ReturnType; body: string } { + const repo = makeFixtureRepo(); repos.push(repo); + repo.git('checkout', '-q', 'feature'); + const write = (body: string, env: Record = {}) => runBin(repo, 'gstack-ship-receipt', ['write', '--pr', '4700', '--base', 'main', '--version', '1.0.0', '--session-kind', 'unattended', '--body', body], env); + const firstBody = path.join(repo.root, 'first.md'); + expect(write(firstBody).status).toBe(EXIT.ok); + const first = repo.git('rev-parse', 'HEAD'); + commit(repo, { 'src/second.js': 'module.exports = 2;\n' }, 'feat: second head'); + const stub = path.join(repo.root, 'stub'); + fs.mkdirSync(stub); + const text = live(fs.readFileSync(firstBody, 'utf8')); + const json = path.join(repo.root, 'live.json'); + if (text !== null) fs.writeFileSync(json, JSON.stringify({ body: text })); + fs.writeFileSync(path.join(stub, 'gh'), text === null ? '#!/bin/sh\necho "gh: not authenticated" >&2\nexit 1\n' : `#!/bin/sh\ncat '${json}'\n`, { mode: 0o755 }); + const body = path.join(repo.root, 'second.md'); + fs.writeFileSync(body, 'The second head fixes the rest.\n'); + const out = write(body, { PATH: `${stub}${path.delimiter}${process.env.PATH}` }); + return { repo, first, out, body }; +} + +describe('receipt write keeps the PR\'s earlier runs in a freshly composed body (GST-3463 item 4)', () => { + // Value: protects=R51's per-PR round count, which reads the runs the PR body records; fails_when=a Step 19 body rewrite + // publishes only the newest receipt; seam=gstack-ship-receipt write --pr --body; no_claim=gh pr edit + test('a fresh body gets the live body\'s receipt as an earlier run', () => { + const { repo, first, out, body } = secondRun(t => t); + expect(out.status, out.err).toBe(EXIT.ok); + const text = fs.readFileSync(body, 'utf8'); + expect(text).toContain('The second head fixes the rest.'); + expect(extractReceipt(text).receipt?.head).toBe(repo.git('rev-parse', 'HEAD')); + expect(receiptRuns(text).map(r => r.head)).toEqual([first]); + }, 120_000); + + // Value: protects=a failed read is visible instead of a silent undercount (negative control); fails_when=write hides that it + // could not read the earlier runs; seam=gstack-ship-receipt write --pr; no_claim=gh pr edit + test('an unreadable live body leaves only this run and says why', () => { + const { out, body } = secondRun(() => null); + expect(out.status, out.err).toBe(EXIT.ok); + expect(out.err).toContain("RECEIPT_RUNS: PR #4700's earlier runs were not read"); + expect(receiptRuns(fs.readFileSync(body, 'utf8'))).toEqual([]); + }, 120_000); +}); diff --git a/test/size-ledger/ship/ship-claim-and-rerun-history.json b/test/size-ledger/ship/ship-claim-and-rerun-history.json new file mode 100644 index 000000000..cb7890a79 --- /dev/null +++ b/test/size-ledger/ship/ship-claim-and-rerun-history.json @@ -0,0 +1,4 @@ +{ + "bytes": 180, + "why": "The docs audit steps say a re-audit carries each earlier audit by its post snapshot, or by its Prepare snapshot with --carry-stopped when it stopped before one" +}