From 54723680fcaf10f6664fda5647de04075e845ba9 Mon Sep 17 00:00:00 2001 From: Garry Tan Date: Sun, 22 Nov 2026 02:18:51 -0800 Subject: [PATCH] /ship keeps a PR's review after a main merge that only updates a shared harness pin, and warns when reviewers ran unlogged (GST-3463) (#4669) A pull request no longer needs a fresh /ship when merging main only updates a harness pin file it shares with another PR, and /ship's review summary now warns when reviewers produced output that the run never logged. Why: #4652 paid for a full new review after such a merge, and a harness-evals run lost its granted follow-up review because nothing was logged. Nothing to do. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> Review-Finding: p1/red-team#1 reader=red-team --- bin/gstack-review-scope | 17 ++- capy/skill/gstack/SKILL.md | 2 +- ...eep-ship-review-after-harness-pin-merge.md | 1 + docs/review-policy.md | 1 + docs/ship-policy.md | 1 + lib/ship-receipt-patch.ts | 29 ++++- test/review-scope-unlogged-readers.test.ts | 96 +++++++++++++++ test/ship-receipt-carry-harness-repin.test.ts | 116 ++++++++++++++++++ 8 files changed, 257 insertions(+), 6 deletions(-) create mode 100644 changelog.d/keep-ship-review-after-harness-pin-merge.md create mode 100644 test/review-scope-unlogged-readers.test.ts create mode 100644 test/ship-receipt-carry-harness-repin.test.ts diff --git a/bin/gstack-review-scope b/bin/gstack-review-scope index 98d98d499..dcff39bad 100755 --- a/bin/gstack-review-scope +++ b/bin/gstack-review-scope @@ -26,8 +26,8 @@ import { resultLineWithDocs } from '../lib/result-codes'; import { runScriptSync } from '../lib/script-invocation'; import { isUnavailable, loadPolicyFromBase, policyUnavailableLine, resolveBaseBranch } from '../lib/ship-policy'; import { - deferredRecord, ledgerPass, parseFixTrailers, parseHunks, renderDeferredSection, reviewLoopLine, scopeFindings, scopeLine, summarizeReviewLoop, - REVIEW_SCOPE_POLICIES, type DeferredRecord, type ReviewScopePolicy, type ScopeFinding, type ScopedFinding, + deferredRecord, ledgerPass, parseFixTrailers, parseHunks, renderDeferredSection, reviewLoopLine, rowTime, scopeFindings, scopeLine, summarizeReviewLoop, + FIX_CHECK_SKILL, REVIEW_SCOPE_POLICIES, type DeferredRecord, type ReviewScopePolicy, type ScopeFinding, type ScopedFinding, } from '../lib/review-scope'; import { ledgerBlockers, type LedgerBlocker } from '../lib/review-ledger'; @@ -213,8 +213,19 @@ function cmdSummary(rest: string[], json: boolean): number { const log = spawnSync('git', ['log', '--first-parent', '--no-merges', `--since=${since}`, '--format=%H%x00%(trailers:key=Review-Finding,valueonly,separator=%x1f)%x1e', 'HEAD'], { encoding: 'utf8', timeout: 60_000, maxBuffer: 64 * 1024 * 1024 }); if (log.status !== 0) return refuse('summary', 'REVIEW_SCOPE_INPUT', `git log for Review-Finding trailers failed: ${(log.stderr ?? '').trim().split('\n')[0] ?? ''}`); const trailers = log.stdout.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)) : []; }); - const summary = summarizeReviewLoop(rows, since, ledgers, files.map(f => ledgerPass(f, keyOf(f))), trailers); + const ledgerPasses = files.map(f => ledgerPass(f, keyOf(f))); + const summary = summarizeReviewLoop(rows, since, ledgers, ledgerPasses, trailers); for (const u of summary.unbound ?? []) process.stderr.write(`REVIEW_SCOPE_UNBOUND: ${u}\n`); + // HARN-109: readers that ran with no row of this run behind them leave gstack-review-read at NO_REVIEWS, so a stop, a grant or finish cannot bind them. + const sinceMs = Date.parse(since); + const logged = rows.filter(r => r?.via === 'ship' && rowTime(r) >= sinceMs); + const passRows = logged.filter(r => r.skill === 'review'); + const fixCheckRows = new Set(logged.filter(r => r.skill === FIX_CHECK_SKILL).map(r => JSON.stringify([r.pass ?? null, r.commit_full ?? r.commit ?? '', r.review_binding?.started_at ?? r.timestamp ?? '', (Array.isArray(r.findings) ? r.findings : []).map((f: any) => f?.ledger_id ?? f?.fingerprint ?? '').sort()]))); + const ran = ledgerPasses.filter(p => !(p.started < sinceMs)); + const fixCheckLedgers = ran.filter(p => p.fixCheck); + const unloggedPasses = !logged.length ? ran.filter(p => !p.fixCheck) : ran.filter(p => !p.fixCheck && /^p\d+$/.test(p.name ?? '') && !passRows.some(r => `p${r.pass}` === p.name)); + const unlogged = [...unloggedPasses, ...(fixCheckLedgers.length > fixCheckRows.size ? fixCheckLedgers : [])]; + if (unlogged.length) process.stderr.write(`REVIEW_ROWS_MISSING: ${unloggedPasses.length ? 'readers ran' : 'a fix-check reader ran'} (ledger ${unlogged.map(p => p.name).join(', ')}) with no ${!logged.length ? 'review-log' : unloggedPasses.length ? 'review' : 'review-fix-check'} row from this run since ${since}: Step 9.4's persistence never ran for ${unlogged.length === 1 ? 'it' : 'them'}, so a stop, a fix-check grant or finish cannot bind ${unlogged.length === 1 ? 'it' : 'them'}; log each pass and fix-check with gstack-review-log --start/--finish, and never hand-run a reader\n`); for (const v of summary.voided ?? []) process.stderr.write(`REVIEW_SCOPE_VOIDED: ${v}\n`); const line = reviewLoopLine(summary); // A /ship invocation always runs Step 9 once, or, answering a stop with a fix-check grant, only that fix-check (GST-2968); no row at all means the wrong --since or a review log written elsewhere, never a loop to record. diff --git a/capy/skill/gstack/SKILL.md b/capy/skill/gstack/SKILL.md index 86ccc1a8c..b94d495e3 100644 --- a/capy/skill/gstack/SKILL.md +++ b/capy/skill/gstack/SKILL.md @@ -46,7 +46,7 @@ Capy checklist for `/autoplan`: drive `gstack-autoplan`, never a hand adaptation Token caps on /ship: pass a brief's cap as `--token-cap `. /ship reads `cost.tokens` and `cost.credits` from `tools.thread.get({ thread_id: "" })` (the thread running /ship, its reviewers included) inside the same execute program as the `gstack-ship-budget` command that takes them as `--reading --credits `, never alone. `ship/DRIVER.md` starts `--mode observe`: each program ends with `note`, and only a note past the cap stops (`docs/ship-budget.md`). -/ship on Capy is about a dozen calls, each an execute program (`ship/DRIVER.md`). Each review pass and Step 11 is one call to the checked-in pass program (fill only `input`): `const t0 = await now(); const p = (await tools.capy.bash({ command: ". '' && gstack-review-dispatch program", description: "Pass" })).output.split("\n"); return p[0] + "\n" + (await new (Object.getPrototypeOf(async () => {}).constructor)("tools", "sleep", "now", "input", JSON.parse(p[1]))(tools, sleep, now, { startedAt: t0, launch: "", cwd: "", base: "", out: "/p", pass: "-p", laneModel: "", planFlags: [], logStart: ["review"], jam: "", record: "", step: "9.2" }));` It plans, logs `logStart` (`reservation` mode from `RESERVATION_ID:`), sends each brief on `machine: "shared"`, then polls: one `tools.subagent.list` per ~20 s tick, returning 200 s after the program's first line, where a reader is settled only at status `done` or `failed` or with a `summary` (a just-created `idle` reader has not run); it starts readers under `rejected` with `tools.subagent.start` as slots free and stops on one stuck 20 minutes. It ends on `NEXT:` (`poll`: rerun) or `STOP:`. `models` maps roles to models (`outside-voice`: another family, pinned in `voice-models.json`); Step 11 swaps `logStart` for `stage: "voices"`; a full repeat pass, `diffBase: ""`. Steps 7, 8 and 14.5 (`step: "14.5"`) use `extras`, JSON `{name, prompt_file, first, model}` (prompts verbatim from their sections, Step 7 `first`); they cannot block, so omit `model`: the pass prints `AUDIT_MODEL:`. Every other phase is one call to `gstack-ship-phase program`, loaded the same way, with `input` `{ startedAt, launch, cwd, dir: "", phase: , commands: [" …"], record, jam, step: "" }` (Phase 2's `gstack-ship-budget start` takes `--reading "$GSTACK_SHIP_READING" --credits "$GSTACK_SHIP_CREDITS"`; `pass: { … }` runs that pass after the commands); on `NEXT: rerun`, call it again unchanged. Waits under about 80 minutes: never let 5 minutes pass between calls. While readers run, never end the turn on `wait`; rerun the loader. Else re-issue `wait` with `duration_seconds: 200` and operation ids. A wait expected past 80 minutes (full CI) ends the turn on one `wait` on its operations; never poll every 10-15 minutes. `STOP: past 100 minutes`: report its `stop.json` and end. At Step 22 report the `CALLS:` line of `gstack-ship-budget calls --record `. A small waiting child saves nothing. +/ship on Capy is about a dozen calls, each an execute program (`ship/DRIVER.md`). Each review pass and Step 11 is one call to the checked-in pass program (fill only `input`): `const t0 = await now(); const p = (await tools.capy.bash({ command: ". '' && gstack-review-dispatch program", description: "Pass" })).output.split("\n"); return p[0] + "\n" + (await new (Object.getPrototypeOf(async () => {}).constructor)("tools", "sleep", "now", "input", JSON.parse(p[1]))(tools, sleep, now, { startedAt: t0, launch: "", cwd: "", base: "", out: "/p", pass: "-p", laneModel: "", planFlags: [], logStart: ["review"], jam: "", record: "", step: "9.2" }));` It plans, logs `logStart` (`reservation` mode from `RESERVATION_ID:`), sends each brief on `machine: "shared"`, then polls: one `tools.subagent.list` per ~20 s tick, returning 200 s after the program's first line, where a reader is settled only at status `done` or `failed` or with a `summary` (a just-created `idle` reader has not run); it starts readers under `rejected` with `tools.subagent.start` as slots free and stops on one stuck 20 minutes. It ends on `NEXT:` (`poll`: rerun) or `STOP:`. `models` maps roles to models (`outside-voice`: another family, pinned in `voice-models.json`); Step 11 swaps `logStart` for `stage: "voices"`; a full repeat pass, `diffBase: ""`. Steps 7, 8 and 14.5 (`step: "14.5"`) use `extras`, JSON `{name, prompt_file, first, model}` (prompts verbatim from their sections, Step 7 `first`); they cannot block, so omit `model`: the pass prints `AUDIT_MODEL:`. Every other phase is one call to `gstack-ship-phase program`, loaded the same way, with `input` `{ startedAt, launch, cwd, dir: "", phase: , commands: [" …"], record, jam, step: "" }` (Phase 2's `gstack-ship-budget start` takes `--reading "$GSTACK_SHIP_READING" --credits "$GSTACK_SHIP_CREDITS"`; `pass: { … }` runs that pass after the commands); on `NEXT: rerun`, call it again unchanged. Waits under about 80 minutes: never let 5 minutes pass between calls. While readers run, never end the turn on `wait`; rerun the loader. Else re-issue `wait` with `duration_seconds: 200` and operation ids. A wait expected past 80 minutes (full CI) ends the turn on one `wait` on its operations; never poll every 10-15 minutes. `STOP: past 100 minutes`: report its `stop.json` and end. At Step 22 report the `CALLS:` line of `gstack-ship-budget calls --record `. A small waiting child saves nothing. Never hand-run a reader. Every pass, fix-check and Step 11 voice runs through that pass program, and each logs its row through Step 9.4's persistence (`gstack-review-log --start`/`--finish`); without the row `gstack-review-read` prints `NO_REVIEWS`, so no stop, fix-check grant or finish can bind the reading. A scoped or granted reader after the review bound is planned with `gstack-review-plan --post-review`, and run as it prints. ## Plan, approve, ship diff --git a/changelog.d/keep-ship-review-after-harness-pin-merge.md b/changelog.d/keep-ship-review-after-harness-pin-merge.md new file mode 100644 index 000000000..0faa1a089 --- /dev/null +++ b/changelog.d/keep-ship-review-after-harness-pin-merge.md @@ -0,0 +1 @@ +**A receipt now survives a base merge that only re-records a shared harness pin, and /ship warns when its readers ran without a logged review.** Before, a sibling PR that touched the same pinned harness file lost its receipt and paid for a fresh /ship (#4652); a pin whose recorded blob is its file's, with its reason and the harness version unchanged, now carries as a regenerated output. `gstack-review-scope summary` prints `REVIEW_ROWS_MISSING:` when a run's dispatch ledgers hold reader output that no review-log row of the run records, the case where the fix-check grant later could not bind. diff --git a/docs/review-policy.md b/docs/review-policy.md index ab5e7169a..20369d15f 100644 --- a/docs/review-policy.md +++ b/docs/review-policy.md @@ -895,6 +895,7 @@ puts in the receipt: | `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 | +| `REVIEW_ROWS_MISSING:` (stderr, not a receipt field) | dispatch ledgers of this run hold reader output that no review-log row of the run records (HARN-109): with no `via: ship` row since `--since`, every pass ledger; otherwise a `pN` ledger with no `review` row of pass N, or more fix-check ledgers than `review-fix-check` rows. Step 9.4's persistence never ran for those readers, so a stop, a fix-check grant or finish cannot bind them; log each pass and fix-check with `gstack-review-log --start`/`--finish`, and never hand-run a reader | Findings bind by id first (GST-1168). A row finding that came from a dispatched reader carries `ledger_id` (`/`, such as `p2/adversarial-native#3`) and pairs with that ledger entry whatever its path:line says, so a native finding with no path:line, or a row logged after its fix moved the line, still pairs. Each fix commit names what it fixed in a `Review-Finding: reader=` trailer, and a trailer counts the finding as fixed. A late defer re-logs its finding under the same id, so it counts once. Rows that record their head dedupe by kind, pass, head and finding ids, so a logger command run twice counts once. Rows and findings without an id keep the path:line pairing above. The native reader's own verdict line ("all FIXABLE, and none blocks", with no file:line, list mark, lead label or Severity/Blocks field) collects at FIXABLE, not CRITICAL; the findings it summarizes collect on their own lines. | `review_loop.deferred` | blocking findings in unchanged code, kept on the PR under `## Deferred findings` (a Step 11 late defer, logged as a `review-late-defer` row so it never displaces the newest `review` pass, counts here and is not a pass) | diff --git a/docs/ship-policy.md b/docs/ship-policy.md index 513cc526a..c0328c9c6 100644 --- a/docs/ship-policy.md +++ b/docs/ship-policy.md @@ -2342,6 +2342,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 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/lib/ship-receipt-patch.ts b/lib/ship-receipt-patch.ts index a8219e08e..ed1fe1065 100644 --- a/lib/ship-receipt-patch.ts +++ b/lib/ship-receipt-patch.ts @@ -79,6 +79,30 @@ export function verifiedOutputs(repoRoot: string, base: string, pregateFile: str return regen.proven.filter(p => !/[*?[\]\\]/.test(p) && matchesAny(owned, p)); } +const HARNESS_MANIFEST = 'scripts/harness-version.json'; +const HARNESS_PIN = /^scripts\/harness-pins\/(.+)\.json$/; + +/** + * A harness pin a base merge only re-recorded (GSTA-749, #4652): at both heads the pin's `blob` is its pinned file's blob, + * 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. + */ +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; + 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; + const [a, b] = [json(from, p), json(to, p)]; + 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); +} + export interface ProductRules { extra: { metadata: string[]; outputs: readonly string[]; fragments?: string }; metadata: string[]; templates: readonly string[]; placeholders: readonly string[] } export function productRules(repoRoot: string, base: string, outputs: readonly string[]): ProductRules { const load = loadPolicyFromBase(repoRoot, base); @@ -120,7 +144,8 @@ export function productSpec(repoRoot: string, rules: ProductRules, from: string, const entryAt = (ref: string, p: string) => git(['ls-tree', ref, '--', p], repoRoot); const sameEntry = (a: string, b: string, p: string) => { const x = entryAt(a, p); return x !== undefined && x === entryAt(b, p); }; const ownStampOnly = (p: string) => !!branch?.touched.has(p) && stamped(p) && branch.sides.every(([a, b]) => sameEntry(a, b, p) || classify(p, a, b) === 'metadata'); - const changed = changedRaw.split('\n').filter(Boolean).map(p => ({ path: p, class: ownStampOnly(p) ? 'metadata' as const : classify(p, from, to) })); + const changed = changedRaw.split('\n').filter(Boolean).map(p => ({ path: p, class: ownStampOnly(p) ? 'metadata' as const : branch && rederivedHarnessPin(repoRoot, from, to, p, rules.extra) ? 'generated' as const : classify(p, from, to) })); + const repinned = changed.filter(c => c.class === 'generated' && HARNESS_PIN.test(c.path)).map(c => `:(exclude,literal)${c.path}`); const excludeGlobs = (globs: readonly string[]) => globs.map(g => `:(exclude,glob)${g}`); const demoted = !branch ? changed.filter(c => c.class === 'product' && matchesAny(rules.metadata, c.path)).map(c => c.path) : [...branch.touched].filter(p => stamped(p) && (changed.some(c => c.path === p && c.class === 'product') || branch.sides.some(([a, b]) => blobAt(a, p) !== blobAt(b, p) && classify(p, a, b) === 'product'))); @@ -137,7 +162,7 @@ export function productSpec(repoRoot: string, rules: ProductRules, from: string, const lines = was.map((_, i) => i).filter(i => was[i] !== now[i]); return was.length === now.length && lines.length > 0 && lines.every(i => side.at.has(i + 1) && stampOnlyLine(was[i]!, now[i]!, oldVersion, newVersion, rules.templates, side, i + 1, rules.placeholders)); }); - return { changed, product: ['.', ...excludeGlobs(CARRY_TEST_GLOBS), ...excludeGlobs(metadataGlobs)], tests: [...CARRY_TEST_GLOBS.map(g => `:(glob)${g}`), ...excludeGlobs(metadataGlobs)], demoted, ownRows }; + return { changed, product: ['.', ...excludeGlobs(CARRY_TEST_GLOBS), ...excludeGlobs(metadataGlobs), ...repinned], tests: [...CARRY_TEST_GLOBS.map(g => `:(glob)${g}`), ...excludeGlobs(metadataGlobs), ...repinned], demoted, ownRows }; } /** A commit's product patch-id against its merge base with the base ('' for no product diff), as write records it and a rewritten-history carry recomputes it. */ diff --git a/test/review-scope-unlogged-readers.test.ts b/test/review-scope-unlogged-readers.test.ts new file mode 100644 index 000000000..6f851c5c7 --- /dev/null +++ b/test/review-scope-unlogged-readers.test.ts @@ -0,0 +1,96 @@ +/** + * HARN-109 (harness-evals#507): a /ship run dispatched its granted readers, then ran a reader by hand and never ran Step + * 9.4's persistence, so the review log held no row from the run, gstack-review-read printed NO_REVIEWS and the fix-check + * grant could not bind. gstack-review-scope summary reads both the run's dispatch ledgers and its rows, so it warns when + * readers produced output that no row of this run records. A run that logged its rows gets no warning. + */ +import { afterEach, describe, expect, setDefaultTimeout, test } from 'bun:test'; +import * as fs from 'node:fs'; +import * as path from 'node:path'; +import { EXIT } from '../lib/headless-artifacts'; +import { collect, readJsonl, recordJudgment, type MergedLine } from '../lib/review-ledger'; +import { cleanup, makeFixtureRepo, runBin, type FixtureRepo } from './helpers/restamp-fixture'; + +setDefaultTimeout(60_000); +const repos: FixtureRepo[] = []; +afterEach(() => { while (repos.length) cleanup(repos.pop()!); }); + +const SINCE = '2026-11-02T01:00:00Z'; +const at = (min: number) => new Date(Date.parse(SINCE) + min * 60_000).toISOString(); +const review = (min: number) => ({ skill: 'review', via: 'ship', timestamp: at(min), status: 'clean', review_scope: 'frozen', pass: 1, findings: [] }); +const fixCheck = (min: number) => ({ skill: 'review-fix-check', via: 'ship', timestamp: at(min), review_scope: 'frozen', completed: true, converged: true, findings: [] }); + +/** One pass directory of the run: each reader's output collected into its ledger and judged as labelled. */ +function ledger(dir: string, reader: string): void { + fs.mkdirSync(dir, { recursive: true }); + const file = path.join(dir, 'review-ledger.jsonl'); + const mergedFile = path.join(dir, 'merged.jsonl'); + fs.writeFileSync(mergedFile, ''); + expect(collect(file, reader, 'NO FINDINGS', mergedFile).review).toBe(true); + const merged = readJsonl(mergedFile); + const judgedFile = path.join(dir, 'judged.jsonl'); + fs.writeFileSync(judgedFile, merged.map(m => JSON.stringify({ id: m.id, severity: m.label }) + '\n').join('')); + expect(recordJudgment(file, merged, merged.map(m => ({ id: m.id, severity: m.label })), judgedFile, mergedFile).ok).toBe(true); +} + +function branchWith(rows: object[] | null): FixtureRepo { + const repo = makeFixtureRepo({ prefix: 'harn109-' }); + repos.push(repo); + repo.git('checkout', '-qb', 'feat'); + if (rows) { + const logDir = path.join(repo.home, 'projects', runBin(repo, 'gstack-slug', ['--get', 'SLUG']).out.trim()); + fs.mkdirSync(logDir, { recursive: true }); + fs.writeFileSync(path.join(logDir, 'feat-reviews.jsonl'), rows.map(r => JSON.stringify(r) + '\n').join('')); + } + return repo; +} +const summary = (repo: FixtureRepo, run: string) => runBin(repo, 'gstack-review-scope', ['summary', '--since', SINCE, '--run', run, '--json']); + +describe('summary warns when a run\'s readers ran but it logged no rows (HARN-109)', () => { + // Value: protects=a run that dispatched readers and skipped Step 9.4 hears so before finish refuses on NO_REVIEWS; + // fails_when=summary counts the fix-check ledger and stays silent; seam=bin/gstack-review-scope summary; no_claim=- + test('a granted fix-check reader with no review-log row at all warns', () => { + const repo = branchWith(null); + const run = path.join(repo.root, 'run'); + ledger(path.join(run, 'fc'), 'fix-check'); + const r = summary(repo, run); + expect(r.err).toContain('REVIEW_ROWS_MISSING:'); + expect(r.err).toContain('fc'); + expect(r.err).toContain('gstack-review-log'); + }); + + // Value: protects=a fix-check whose row was never logged is named even when the pass rows exist; fails_when=only the + // zero-row case warns; seam=summary; no_claim=- + test('a fix-check ledger with no review-fix-check row warns beside a logged pass', () => { + const repo = branchWith([review(5)]); + const run = path.join(repo.root, 'run'); + ledger(path.join(run, 'p1'), 'security'); + ledger(path.join(run, 'fc'), 'fix-check'); + const r = summary(repo, run); + expect(r.status).toBe(EXIT.ok); + expect(r.err).toContain('REVIEW_ROWS_MISSING:'); + expect(r.err).toContain('fc'); + }); + + // Value: protects=a pass whose review row was never logged is named even when a Step 11 voice row was; fails_when=any + // via:ship row counts as the pass's row; seam=summary; no_claim=- + test('a pass ledger with no review row warns beside a logged voice row', () => { + const repo = branchWith([{ skill: 'adversarial-review', via: 'ship', timestamp: at(20), status: 'clean', findings: [] }]); + const run = path.join(repo.root, 'run'); + ledger(path.join(run, 'p1'), 'security'); + const r = summary(repo, run); + expect(r.err).toContain('REVIEW_ROWS_MISSING: readers ran (ledger p1)'); + }); + + // Value: protects=no warning when every reader's row is logged (negative control); fails_when=the warning fires on a + // normal run; seam=summary; no_claim=- + test('a run that logged its pass and fix-check rows gets no warning', () => { + const repo = branchWith([review(5), fixCheck(30)]); + const run = path.join(repo.root, 'run'); + ledger(path.join(run, 'p1'), 'security'); + ledger(path.join(run, 'fc'), 'fix-check'); + const r = summary(repo, run); + expect(r.status).toBe(EXIT.ok); + expect(r.err).not.toContain('REVIEW_ROWS_MISSING'); + }); +}); diff --git a/test/ship-receipt-carry-harness-repin.test.ts b/test/ship-receipt-carry-harness-repin.test.ts new file mode 100644 index 000000000..418f4f9b4 --- /dev/null +++ b/test/ship-receipt-carry-harness-repin.test.ts @@ -0,0 +1,116 @@ +/** + * gstack-ship-receipt carry across a harness pin that a base merge re-recorded (GSTA-749, #4652 at cc9b831d): the branch + * edits a pinned harness file and records the edit as non-behavioral; the base lands its own edit and re-pin of the same + * 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. + */ +import { afterEach, describe, expect, test } from 'bun:test'; +import * as path from 'node:path'; +import { EXIT } from '../lib/headless-artifacts'; +import { cleanup, commit, makeFixtureRepo, runBin, write, type FixtureRepo } from './helpers/pregate-fixture'; + +const repos: FixtureRepo[] = []; +afterEach(() => { while (repos.length) cleanup(repos.pop()!); }); +const FILE = 'scripts/profile.ts'; +const PIN = `scripts/harness-pins/${FILE}.json`; +const MANIFEST = 'scripts/harness-version.json'; +const manifest = (version = 7) => `${JSON.stringify({ version, patterns: ['scripts/profile.ts'] }, null, 2)}\n`; +const BRANCH_REASON = 'the branch adds one free-only workflow name to the list, so no paid case selection can change'; +const pin = (blob: string, reason: string, since = 7) => `${JSON.stringify({ blob, since, nonBehavioral: reason })}\n`; +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 } { + const repo = makeFixtureRepo(); repos.push(repo); + const blob = () => repo.git('rev-parse', `HEAD:${FILE}`); + repo.git('checkout', '-q', 'main'); + commit(repo, { [MANIFEST]: manifest(), [FILE]: LINES.join('\n') }, 'main: harness file'); + commit(repo, { [PIN]: pin(blob(), 'main pins the harness file') }, 'main: pin'); + repo.git('push', '-q', 'origin', 'main'); + repo.git('checkout', '-q', 'feature'); + repo.git('reset', '-q', '--hard', 'origin/main'); + commit(repo, { [FILE]: [...LINES.slice(0, 2), " 'mutation.yml',", ...LINES.slice(2)].join('\n') }, 'feat: add a free-only workflow'); + commit(repo, { [PIN]: pin(blob(), BRANCH_REASON) }, 'feat: re-pin as non-behavioral'); + const body = path.join(repo.root, 'body.md'); + expect(runBin(repo, 'gstack-ship-receipt', ['write', '--pr', '4652', '--base', 'main', '--version', '1.0.0', '--session-kind', 'unattended', '--body', body]).status).toBe(EXIT.ok); + repo.git('checkout', '-q', 'main'); + commit(repo, { [FILE]: [...LINES.slice(0, -1), '// shared harness list', ''].join('\n') }, 'main: comment'); + commit(repo, { [PIN]: pin(blob(), 'main adds a comment') }, 'main: re-pin'); + 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); + repo.git('add', '-A'); + repo.git('commit', '-q', '--no-edit'); + return { body, repo }; +} +/** main pins a test helper; feature edits it and re-pins it as non-behavioral, /ship receipt there; then changes the helper's behavior and re-pins only its blob. */ +function repinnedHelper(): { body: string; repo: FixtureRepo; pinPath: string } { + const helper = 'test/helpers/gate.ts'; + const pinPath = `scripts/harness-pins/${helper}.json`; + const repo = makeFixtureRepo(); repos.push(repo); + const blob = () => repo.git('rev-parse', `HEAD:${helper}`); + repo.git('checkout', '-q', 'main'); + commit(repo, { [MANIFEST]: manifest(), [helper]: 'export const RETRIES = 1;\n' }, 'main: harness helper'); + commit(repo, { [pinPath]: pin(blob(), 'main pins the helper') }, 'main: pin'); + repo.git('push', '-q', 'origin', 'main'); + repo.git('checkout', '-q', 'feature'); + repo.git('reset', '-q', '--hard', 'origin/main'); + commit(repo, { [helper]: '// retry budget\nexport const RETRIES = 1;\n' }, 'feat: comment the helper'); + commit(repo, { [pinPath]: pin(blob(), 'a comment only, so no case verdict can change') }, 'feat: re-pin as non-behavioral'); + const body = path.join(repo.root, 'body.md'); + expect(runBin(repo, 'gstack-ship-receipt', ['write', '--pr', '4652', '--base', 'main', '--version', '1.0.0', '--session-kind', 'unattended', '--body', body]).status).toBe(EXIT.ok); + commit(repo, { [helper]: '// retry budget\nexport const RETRIES = 5;\n' }, 'feat: retry more'); + commit(repo, { [pinPath]: pin(blob(), 'a comment only, so no case verdict can change') }, 'feat: re-pin'); + return { body, repo, pinPath }; +} +const carry = (repo: FixtureRepo, body: string) => runBin(repo, 'gstack-ship-receipt', ['carry', '--body', body, '--base', 'main', '--dry-run']); + +describe('carry across a harness pin a base merge re-recorded (GSTA-749)', () => { + // Value: protects=a sibling PR keeps its receipt when a base merge only re-records a pin it shares (#4652 paid a fresh + // /ship); fails_when=the pin's new blob reads as a product change; seam=lib/ship-receipt-patch.ts productSpec; no_claim=gh pr edit + test('a pin whose only change is the merged file\'s blob carries as a regenerated output', () => { + const { repo, body } = repinned(merged => ({ [PIN]: pin(merged, BRANCH_REASON) })); + const out = carry(repo, body); + expect(out.status, out.err).toBe(EXIT.ok); + expect(out.out + out.err).toContain('regenerated outputs'); + }, 90_000); + + // Value: protects=fail closed on a pin that is not the pinned file's blob; fails_when=any pin edit carries; seam=productSpec; no_claim=gh pr edit + test('a pin whose blob is not the pinned file\'s still refuses', () => { + const { repo, body } = repinned(() => ({ [PIN]: pin('0'.repeat(40), BRANCH_REASON) })); + 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=the reviewed non-behavioral claim is the one that ships; fails_when=a rewritten reason carries; seam=productSpec; no_claim=gh pr edit + test('a pin whose reason changed since review still refuses', () => { + const { repo, body } = repinned(merged => ({ [PIN]: pin(merged, `${BRANCH_REASON}; also the base comment`) })); + const out = carry(repo, body); + expect(out.status).toBe(EXIT.refused); + expect(out.err).toContain(PIN); + }, 90_000); + + // Value: protects=a pinned test helper's behavior change after review still needs a fresh /ship: the helper carries as a test + // change, so its pin is the only product path that stops it (cross-family trail read on #4669); fails_when=any pin whose blob + // is its file's carries; seam=productSpec; no_claim=gh pr edit + test('a blob-only re-pin of a pinned test helper still refuses', () => { + const { repo, body, pinPath } = repinnedHelper(); + const out = carry(repo, body); + expect(out.status).toBe(EXIT.refused); + expect(out.err).toContain('RECEIPT_CARRY_PRODUCT_CHANGED'); + expect(out.err).toContain(pinPath); + }, 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) })); + const out = carry(repo, body); + expect(out.status).toBe(EXIT.refused); + expect(out.err).toContain('RECEIPT_CARRY_PRODUCT_CHANGED'); + }, 90_000); +});