diff --git a/bin/gstack-approvals b/bin/gstack-approvals index e5b7fd7eb..362def8b0 100755 --- a/bin/gstack-approvals +++ b/bin/gstack-approvals @@ -8,7 +8,7 @@ * gstack-approvals import --autoplan [--by ] [--branch | --stack ] [--json] * gstack-approvals render [--no-heading] [--full | --redacted] [--branch ] [--plan ] * gstack-approvals plan-check --plan - * gstack-approvals rule --finding --head --reason --words --by [--json] + * gstack-approvals rule --finding --head --reason --words --by [--owner-ref :] [--not-security] [--json] * gstack-approvals rulings [--branch ] * gstack-approvals gate --finding --gate-id --head --reason --words --by [--json] * gstack-approvals dispositions [--branch ] @@ -29,7 +29,7 @@ import { spawnSync } from 'node:child_process'; import * as path from 'node:path'; import { EXIT, exitTableHelp } from '../lib/headless-artifacts'; import { appendRows, branchExists, buildRow, importAutoplan, locate, readRecord, renderMode, renderRecord, repoVisibility, syncRecord, type RecordError, type StoreLocation } from '../lib/approval-record'; -import { GSTACK_ACTOR, openShipRun, RULED_NOTE_SCOPE, ruledNoteRow, ruledNotes, ruledNoteText } from '../lib/ruled-notes'; +import { GSTACK_ACTOR, isGstackActorName, openShipRun, OWNER_REF, RULED_NOTE_SCOPE, ruledNoteRow, ruledNoteSource, ruledNotes, ruledNoteText } from '../lib/ruled-notes'; import { resultLine } from '../lib/result-codes'; import { parsePlanLine, publicPlanLine, resolvePlan } from '../lib/plan-record'; import { TEST_LANE_EXCEPTION_SCOPE, testLaneExceptionRow } from '../lib/test-lane-exception'; @@ -43,10 +43,13 @@ const HELP = `gstack-approvals — the per-thread approval record (capy/skill/gs import --autoplan [--by ] [--stack ] --stack writes the same rows to every branch of a stack; each branch is checked first, and one unknown branch writes none rule --finding --head --reason - --words --by + --words --by [--owner-ref :] [--not-security] the owner's ruling that a review finding ships as a disclosed note (docs/ship-policy.md#ruled-notes); finish counts that finding closed on a fix-check whose range_base..commit holds the head, and the receipt and PR body - list it; refused inside this checkout's open /ship run + list it; inside this checkout's open /ship run it needs --owner-ref, the message the lane relays the owner's + words from, and the row, receipt and Ruled note line then say relayed from it (APPROVAL_RULING_RUN_OPEN without); + --not-security: the owner's call that a red-team finding is not security class, so public text shows it; + refused while a /ship run is open on this checkout rulings the "Ruled note: …" lines the Pre-Landing Review and the PR body carry gate --finding --gate-id --head --reason --words --by @@ -90,7 +93,7 @@ Example: ${exitTableHelp()}`; -const VALUE_FLAGS = new Set(['--ask', '--words', '--by', '--scope', '--pending', '--outcome', '--date', '--source', '--branch', '--autoplan', '--stack', '--finding', '--reason', '--head', '--files', '--plan', '--gate-id', '--pr', '--kind', '--stop-run', '--findings']); +const VALUE_FLAGS = new Set(['--ask', '--words', '--by', '--scope', '--pending', '--outcome', '--date', '--source', '--branch', '--autoplan', '--stack', '--finding', '--reason', '--head', '--files', '--plan', '--gate-id', '--pr', '--kind', '--stop-run', '--findings', '--owner-ref']); function parse(args: string[]): { flags: Record; bools: Set; error?: string } { const flags: Record = {}; @@ -101,7 +104,7 @@ function parse(args: string[]): { flags: Record; bools: Set; bools: Set'); const head = spawnSync('git', ['rev-parse', '--verify', '--quiet', `${flags['--head'] ?? ''}^{commit}`], { encoding: 'utf8', timeout: 10_000 }); if (!flags['--head'] || head.status !== 0) return invalid('round-grant needs --head '); - if (!by || GSTACK_ACTOR.test(by)) return invalid('round-grant needs --by : gstack never grants itself a round'); + if (!by || isGstackActorName(by)) return invalid('round-grant needs --by : gstack never grants itself a round'); const open = openShipRun(process.cwd()); if (open) return invalid(`/ship run ${open} is open on this checkout: a round grant is the lane's or its Captain's, never the run's own; record it from the lane after the run stops`); const stopRun = (flags['--stop-run'] ?? '').trim(), findings = [...new Set((flags['--findings'] ?? '').split(',').map(f => f.trim()).filter(Boolean))]; @@ -206,9 +209,13 @@ function main(argv: string[]): number { const head = spawnSync('git', ['rev-parse', '--verify', '--quiet', `${flags['--head'] ?? ''}^{commit}`], { encoding: 'utf8', timeout: 10_000 }); if (!flags['--head'] || head.status !== 0) return invalid('rule needs --head '); if (GSTACK_ACTOR.test((flags['--by'] ?? '').trim())) return invalid('--by names gstack; a ruling is the owner\'s, so --by names who ruled'); + const ownerRef = flags['--owner-ref']?.trim(), notSecurity = bools.has('--not-security'); + if (ownerRef !== undefined && (!OWNER_REF.test(ownerRef) || !(flags['--words'] ?? '').trim() || !(flags['--by'] ?? '').trim())) return invalid('--owner-ref relays the owner\'s ruling: : (GSTA-36:2026-11-19T12:29:59Z), with --by and --words '); + if (notSecurity && !/:red-team$/i.test(finding)) return invalid('--not-security is the owner\'s call on a red-team finding (path:line:red-team); a security, auth or secret finding is security class by its category'); const open = openShipRun(process.cwd()); - if (open) return invalid(`/ship run ${open} is open on this checkout: a ruling is the owner's, never the lane's own runner's; record it from the owner's session`); - const built = buildRow({ ...ruledNoteRow(finding, head.stdout.trim(), reason), words: flags['--words'] ?? '', by: flags['--by'] ?? '', date: flags['--date'] }, loc.branch); + if (open && notSecurity) return invalid(`--not-security lifts a red-team finding's redaction, so it is recorded only outside a /ship run: /ship run ${open} is open on this checkout; record it after the run stops`); + if (open && ownerRef === undefined) return fail(cmd, { code: 'APPROVAL_RULING_RUN_OPEN', message: `/ship run ${open} is open on this checkout, and its own runner cannot rule on the run's findings: relay the owner's ruling with --owner-ref : --by --words , or record it after the run stops` }); + const built = buildRow({ ...ruledNoteRow(finding, head.stdout.trim(), reason), words: flags['--words'] ?? '', by: flags['--by'] ?? '', date: flags['--date'], source: ruledNoteSource({ ownerRef, notSecurity }) }, loc.branch); if ('code' in built) return fail(cmd, built); rows = [built]; } else if (cmd === 'gate') { diff --git a/bin/gstack-doctor-components.sh b/bin/gstack-doctor-components.sh index b6db3cee4..82650dce9 100644 --- a/bin/gstack-doctor-components.sh +++ b/bin/gstack-doctor-components.sh @@ -383,6 +383,7 @@ gstack_result_anchor() { PUSH_GIT_FAILED) printf '%s' 'push-git-failed' ;; SPAWN_OUTPUT_INCOMPLETE) printf '%s' 'spawn-output-incomplete' ;; APPROVAL_RECORD_INVALID) printf '%s' 'approval-record-invalid' ;; + APPROVAL_RULING_RUN_OPEN) printf '%s' 'approval-ruling-run-open' ;; APPROVAL_RECORD_SECRET) printf '%s' 'approval-record-secret' ;; APPROVAL_RECORD_NO_BRANCH) printf '%s' 'approval-record-no-branch' ;; APPROVAL_RECORD_UNAVAILABLE) printf '%s' 'approval-record-unavailable' ;; diff --git a/bin/gstack-post b/bin/gstack-post index 97067270b..64e07cdc0 100755 --- a/bin/gstack-post +++ b/bin/gstack-post @@ -34,6 +34,7 @@ const code = runPost(process.argv.slice(2), { readFile: (p) => fs.readFileSync(p, "utf8"), out: (t) => process.stdout.write(t), err: (t) => process.stderr.write(t), + ghRepo: process.env.GH_REPO, ...(hostPublishes() ? { hostPublish: (op: string, target: string | undefined, parts: Array<["title" | "body", string]>, dest: HostDest) => handOff({ op, target, parts, ...dest }) } : {}), }, path.join(import.meta.dir, "gstack-config")); process.exitCode = code; diff --git a/bin/gstack-ship-queue b/bin/gstack-ship-queue index b8bcd6180..fcc4359c9 100755 --- a/bin/gstack-ship-queue +++ b/bin/gstack-ship-queue @@ -3,7 +3,7 @@ * gstack-ship-queue — the shared merge queue, one subcommand per protocol * step (field list 2, W1; docs/ship-policy.md#run-a-shared-merge-queue). * - * gstack-ship-queue ready --pr [--pregate ] [--gate-exit --gate-log ] + * gstack-ship-queue ready --pr [--pregate ] [--trail ] [--gate-exit --gate-log ] * (refused with QUEUE_RECEIPT_MISSING|STALE unless the PR body carries /ship's receipt for HEAD) * gstack-ship-queue stamp --pr --version --expect-gated --expect-base * [--expect-order ] [--allow-repo-commands] [--gate-exit --gate-log ] @@ -47,9 +47,11 @@ logShipCall('gstack-ship-queue'); const HELP = `gstack-ship-queue — the shared merge queue's protocol steps (docs/ship-policy.md#run-a-shared-merge-queue) - ready --pr [--pregate ] [--gate-exit --gate-log ] + ready --pr [--pregate ] [--trail ] [--gate-exit --gate-log ] READY # STAMP_VERSION=, CI at that head, PREGATE, gate state, - SHIP_RECEIPT (refused unless the PR body carries /ship's receipt for that head) + SHIP_RECEIPT (refused unless the PR body carries /ship's receipt for that head), + TRIAL_MERGES for each open PR sharing a file, and the Attention line: a risk-class + receipt names the --trail's newest trail-read row, or prints MISSING: cross-family trail read stamp --pr --version --expect-gated --expect-base [--expect-order ] [--allow-repo-commands] [--gate-exit --gate-log ] restamp, commit and prove: QUEUE_STAMP: head= gated= tree= receipt= @@ -234,10 +236,10 @@ async function main(argv: string[]): Promise { if (cmd === 'ready') { const unfetched = refreshBase(ctx); const loaded = loadBasePolicy(ctx); - if (!('message' in loaded) && loaded.policy.train) return (await import('../crew/lib/ship-queue-train-cli')).readyMain(ctx, args, { pr, pregate: flag(args, '--pregate'), ...gate }); + if (!('message' in loaded) && loaded.policy.train) return (await import('../crew/lib/ship-queue-train-cli')).readyMain(ctx, args, { pr, pregate: flag(args, '--pregate'), trail: flag(args, '--trail'), ...gate }); if (unfetched) return finish('ready', { ok: false, lines: [], run: 'none', failure: unfetched }); if (['--screen', '--no-screen', '--broad'].some(f => args.includes(f))) process.stderr.write('gstack-ship-queue ready: --screen/--no-screen/--broad ignored: the base policy declares no train block\n'); - return finish('ready', ready(ctx, { pr, pregate: flag(args, '--pregate'), ...gate })); + return finish('ready', ready(ctx, { pr, pregate: flag(args, '--pregate'), trail: flag(args, '--trail'), ...gate })); } if (cmd === 'stamp') { const version = flag(args, '--version'); diff --git a/bin/gstack-ship-receipt b/bin/gstack-ship-receipt index 537624359..e226fd3e4 100755 --- a/bin/gstack-ship-receipt +++ b/bin/gstack-ship-receipt @@ -1071,10 +1071,11 @@ function postBody(rest: string[], pr: string | undefined, body: string): string if (bodyFile) { fs.writeFileSync(bodyFile, body); return null; } const repo = flag(rest, '--repo'); if (hostPublishes()) { - const view = gh(['repo', 'view', ...(repo ? [repo] : []), '--json', 'nameWithOwner,url']); + const target = repo ?? (process.env.GH_REPO?.trim() || undefined); + const view = gh(['repo', 'view', ...(target ? [target] : []), '--json', 'nameWithOwner,url']); let dest: { repo: string; host: string } | undefined; try { const v = JSON.parse(view.out); dest = { repo: String(v.nameWithOwner ?? ''), host: new URL(String(v.url)).host }; } catch { dest = undefined; } - if (!view.ok || !dest?.repo) return `cannot resolve the repository gh pr edit would have edited (gh repo view${repo ? ` ${repo}` : ''} --json nameWithOwner,url: ${view.err.split('\n')[0] || 'no repository'}); pass --repo , nothing was handed off`; + if (!view.ok || !dest?.repo) return `cannot resolve the repository gh pr edit would have edited (gh repo view${target ? ` ${target}` : ''} --json nameWithOwner,url: ${view.err.split('\n')[0] || 'no repository'}); pass --repo , nothing was handed off`; try { process.stdout.write(handOff({ op: 'pr-body', target: pr, ...dest, parts: [['body', body]] })); } catch (e) { return `cannot write the hand-off for the host's PR tool (${(e as Error).message}), nothing was handed off`; } return null; diff --git a/changelog.d/ship-tooling-small-fixes.md b/changelog.d/ship-tooling-small-fixes.md new file mode 100644 index 000000000..79bfc8113 --- /dev/null +++ b/changelog.d/ship-tooling-small-fixes.md @@ -0,0 +1,3 @@ +- **`gstack-ship-queue ready` now fills in the trial merges and the second-model trail read instead of printing lines to fill.** It lists the open PRs that change a file this PR changes and prints each one's `git merge-tree` result, and with `--trail ` it names the reader from the trail's newest `trail-read` row, under a train policy too; a gate, security, money, auth or data PR with no such row prints `MISSING: cross-family trail read`. +- **Five small ship-tool fixes.** `Plan: exempt:` accepts bug-fix wording such as "bug fix with failing-first tests", and ready uses the Plan line `/ship` finish resolved when the PR body has none. `gstack-approvals round-grant` refuses only gstack's own names, so "gstack-evals Captain" can grant a round. The Capy PR hand-off follows `GH_REPO` the way gh's own write does and refuses a PR URL that names another repository, and a pull request opened from a fork names its head as `owner:branch`. A targeted review read on a path with non-ASCII characters now carries across a later docs-only change. +- **A ruling the owner gives while a `/ship` run is open can be relayed.** `gstack-approvals rule --owner-ref :` records the owner's words with the message they came from and marks the ruling relayed in the record, the receipt and the PR body; without it the refusal now says `APPROVAL_RULING_RUN_OPEN`. `rule --not-security` lets the owner say a red-team finding is not a security finding, so its PR text shows the finding instead of "security finding, details recorded privately"; it is refused while a `/ship` run is open. diff --git a/crew/lib/ship-queue-train-cli.ts b/crew/lib/ship-queue-train-cli.ts index 722fa185b..44f166740 100644 --- a/crew/lib/ship-queue-train-cli.ts +++ b/crew/lib/ship-queue-train-cli.ts @@ -167,7 +167,7 @@ export async function trainMain(ctx: QueueContext, args: string[]): Promise { +export async function readyMain(ctx: QueueContext, args: string[], base: { pr: string; pregate?: string; trail?: string; gateExit?: number; gateLog?: string }): Promise { const screen = args.includes('--screen'); const noScreen = args.includes('--no-screen'); if (screen && noScreen) return usage('pass one of --screen or --no-screen'); diff --git a/crew/lib/ship-queue-train-ready.ts b/crew/lib/ship-queue-train-ready.ts index 7c7debe14..66a188e6e 100644 --- a/crew/lib/ship-queue-train-ready.ts +++ b/crew/lib/ship-queue-train-ready.ts @@ -32,12 +32,12 @@ import { extractReceipt } from '../../lib/ship-receipt'; import { loadReady, nowIso, persist, readyNoteUnpushed, readyPath, rebuildFromNotes, type ReadyReceipt, type ScreenChoice } from './ship-queue-train-record'; import { baseOverlap, fetchBase, mergeCommit, outOk, outPending, outRefused, trainEnv, type TrainEnv, type TrainOut } from './ship-queue-train'; import { checkWavePin } from './ship-queue-wave'; -import { readyPlan } from '../../lib/plan-record'; +import { finishPlanLine, readyPlan } from '../../lib/plan-record'; const Q = 'gstack-ship-queue'; export interface ReadyOptions { - pr: string; pregate?: string; gateExit?: number; gateLog?: string; screen?: 'screen' | 'no-screen'; broad: boolean; dryRun: boolean; + pr: string; pregate?: string; trail?: string; gateExit?: number; gateLog?: string; screen?: 'screen' | 'no-screen'; broad: boolean; dryRun: boolean; /** `--dispatch-ci`: run these workflows on the PR branch, wait, and clear the matching requires-remote pregate lanes before reading the head. */ dispatchCi?: { workflows: string[]; timeoutSec: number; pollMs: number }; /** `--base-red --fixer `: a conditional READY on a paused receipt, owned by the fixer PR (trains with gates only). */ @@ -198,7 +198,7 @@ const screenLine = (c: ScreenChoice) => `screen: ${c.choice}${c.policy ? ` polic /** The brief's Plan line resolved at ready, as non-train ready does (docs/ship-policy.md#plan-record); the receipt carries the record train land reads. */ function trainPlan(env: TrainEnv, body: string, baseSha: string, head: string, lines: string[]) { const changed = git(env.ctx.repoRoot, ['diff', '--name-only', `${baseSha}...${head}`]).out.split('\n').filter(Boolean); - const plan = readyPlan({ cwd: env.ctx.repoRoot, env: process.env, body, policyValue: env.policy.policy.plan_record, changed, fragmentsDir: env.policy.policy.changelog_fragments?.dir }); + const plan = readyPlan({ cwd: env.ctx.repoRoot, env: process.env, body, policyValue: env.policy.policy.plan_record, changed, fragmentsDir: env.policy.policy.changelog_fragments?.dir, finishLine: finishPlanLine(env.ctx.repoRoot, git(env.ctx.repoRoot, ['branch', '--show-current']).out.trim(), head) }); if (plan.line) lines.push(plan.line); return plan; } diff --git a/crew/test/ship-queue-ready-notes-push.test.ts b/crew/test/ship-queue-ready-notes-push.test.ts index 049beff12..36605a442 100644 --- a/crew/test/ship-queue-ready-notes-push.test.ts +++ b/crew/test/ship-queue-ready-notes-push.test.ts @@ -82,3 +82,25 @@ describe('ready refuses a READY note that never reached origin', () => { expect(remoteNotes(fx)).toBe(localNotes(fx)); }, 120_000); }); + +describe('ready under a train policy reads --trail and trial-merges non-ASCII paths (GST-3200 follow-up)', () => { + // Value: protects=gstack's own policy declares a train block, so its READY goes through the train route, which must carry + // --trail and compare sibling paths that git would C-quote; fails_when=the train route drops --trail and prints MISSING, or + // a sibling sharing café.txt reads as none share a file; seam=bin/gstack-ship-queue ready --no-screen with the train gh shim + test('the trail-read row names the reviewer and a sibling sharing café.txt is trial-merged', () => { + const fx = trainFixture(); + fixtures.push(fx); + const sibling = openPr(fx, '2', { file: 'café.txt', text: 'from #2\n', changelog: false }); + const head = openPr(fx, '1', { file: 'café.txt', text: 'from #1\n' }); + fx.write(d => { d.ci[head] = [{ status: 'completed', conclusion: 'success' }]; for (const n of ['1', '2']) (d.prs[n] as Record).files = [{ path: 'café.txt' }]; }); + const tree = runBin(fx.repo, 'gstack-wtree', []).out.trim(); + const pregate = path.join(fx.repo.root, 'pregate.json'); + fs.writeFileSync(pregate, JSON.stringify({ schema_version: 1, tree, head, verdict: 'pass', checks: FULL_CHECKS })); + const trail = path.join(fx.repo.root, 'decisions.tsv'); + fs.writeFileSync(trail, 'ts\tphase\tdecision\twhy\tevidence\tresult\n2026-11-19T00:00:00Z\tstart\trun x opens this trail\tno earlier rows\trun:x\topen\n2026-11-19T00:01:00Z\ttrail-read\topenai/gpt-6.2-sol (Subagent 4)\trule 27\tflags.md\tNo flags\n'); + const r = queue(fx, ['ready', '--pr', '1', '--pregate', pregate, '--no-screen', '--trail', trail]); + expect(r.out).toContain('reviewed by openai/gpt-6.2-sol (Subagent 4) ('); + expect(r.out).toContain('trail row 2)'); + expect(line(r.out, 'TRIAL_MERGES: ')).toStartWith(`TRIAL_MERGES: #2 ${sibling.slice(0, 12)} shares café.txt: `); + }, 120_000); +}); diff --git a/crew/test/ship-queue-train.test.ts b/crew/test/ship-queue-train.test.ts index 616fb0968..e53b0f949 100644 --- a/crew/test/ship-queue-train.test.ts +++ b/crew/test/ship-queue-train.test.ts @@ -177,6 +177,22 @@ describe('ready under a train policy: the screen choice', () => { expect(JSON.parse(fs.readFileSync(receipt, 'utf8')).plan).toMatchObject({ line: 'Plan: exempt: bug fix', state: 'exempt', reason: 'bug fix' }); }, 120_000); + + // Value: protects=train ready (gstack's own route) uses the Plan line /ship finish recorded for this branch and head when the + // body has none, as plain ready does; fails_when=trainPlan drops finishLine and warns or refuses PLAN_RECORD_MISSING after + // finish recorded Plan: exempt: bug fix (GSTA-649); seam=bin/gstack-ship-queue ready under a train policy + test('under GSTACK_PLAN_RECORD=require train ready takes the Plan line finish recorded when the body has none', () => { + const { fx, head, pregate } = readyFixture(); + const file = path.resolve(fx.repo.work, fx.repo.git('rev-parse', '--git-path', 'gstack-finish-plan.json')); + fs.writeFileSync(file, JSON.stringify({ schema_version: 2, branch: fx.repo.git('branch', '--show-current'), head, line: 'Plan: exempt: bug fix' }) + '\n'); + const ok = queue(fx, ['ready', '--pr', '1', '--pregate', pregate, '--no-screen'], { GSTACK_PLAN_RECORD: 'require' }); + expect([ok.status, ok.err]).toEqual([EXIT.ok, '']); + expect(ok.out.split('\n').filter(l => l.startsWith('PLAN:'))).toEqual(["PLAN: exempt bug fix (from /ship finish's plan record; the PR body has no Plan: line)"]); + const receipt = path.join(fx.state, 'ship-queue', 'ready', repoKey(fx), `1-${head}.json`); + expect(JSON.parse(fs.readFileSync(receipt, 'utf8')).plan).toMatchObject({ line: 'Plan: exempt: bug fix', from: 'finish' }); + }, 120_000); + + test("GSTA-67: a lane whose origin is another URL form of the repository (#3331's git.capy.ai) writes its receipt under the owner/repo key", () => { const { fx, head, pregate } = readyFixture(); githubOrigin(fx, 'https://git.capy.ai/fixture/repo.git'); diff --git a/docs/review-policy.md b/docs/review-policy.md index c9453130e..202b7f6a9 100644 --- a/docs/review-policy.md +++ b/docs/review-policy.md @@ -228,9 +228,10 @@ caught on another crew's PRs. 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. - gstack never grants itself a round: `--by` naming gstack (any name starting - with "gstack", so a Captain called GStack Minder writes "Captain GStack - Minder") and a grant from inside an open `/ship` run are refused, and `add` + 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 + grant) and a grant from inside an open `/ship` run are refused, and `add` refuses the scope. `--by` is otherwise the caller's own text, recorded and not checked: a lane that records a grant (or a ruling) from another checkout under its Captain's name can't be told apart from the Captain doing it, so the diff --git a/docs/ship-policy.md b/docs/ship-policy.md index 4564b9da5..54d65b3bf 100644 --- a/docs/ship-policy.md +++ b/docs/ship-policy.md @@ -1765,8 +1765,13 @@ and ask `ruled_note at : `, with the head's full sha two findings ruled with the same reason in one reply get two rows, and a ruling at a later head is a new row. Its `by` is the ruler and its `recorded_at` the time. `rule` refuses a `--head` that is not a commit in the repository, a reason with a -newline or control character, a `--by` naming gstack, and any ruling while this -checkout holds an open /ship run's marker (the lane's own runner). `add` refuses a +newline or control character, a `--by` naming gstack, and a ruling while this +checkout holds an open /ship run's marker (the lane's own runner) unless the lane +relays the owner's words with `--owner-ref :` +(on Capy the owner, a Captain, has no session on the lane's checkout). A relayed row's +source is `relayed:`, and its `RULED_NOTE:`, receipt entry and `Ruled note:` +line say `(relayed from )`, so a reader can check the words against that +message; without it the refusal is `APPROVAL_RULING_RUN_OPEN`. `add` refuses a `ruled_note` scope, so `rule` is the only path. A review-log field never makes a ruling: `ruled`, `action: "ruled"` or any other claim the lane writes on its own row is ignored. Step 16's `finish` reads the branch's rulings @@ -1814,6 +1819,12 @@ visibility lookup that can fail or change, and a private repository can go public with its PR history. As a backstop, `gstack-ship-receipt write` refuses a `--body` and `gstack-post` refuses any text that names a raw security fingerprint such as `src/x.ts:12:security`. Other findings print as before. +The red-team reviewer tags every finding `red-team`, a statistics or scoring +fix included, so the owner can rule one not security class with `gstack-approvals +rule --not-security` (only on a `path:line:red-team` fingerprint; a `security`, +`auth` or `secret` finding stays security class, and the flag is refused while a +/ship run is open on the checkout, so a run never lifts its own finding's redaction). +That ruling's lines show its reason and its location as `: (red-team, ruled not security class)`. **Gate dispositions (GST-2491).** A ruling never closes a gate finding (a loosened diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index 76d862b96..e4bff3d3a 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -2250,6 +2250,20 @@ empty or holds whitespace. `add` refuses a `ruled_note` or ruling or a test-lane exception is the owner's: record it from the owner's session, outside the lane's /ship run. + +### `gstack-approvals rule: ... (APPROVAL_RULING_RUN_OPEN)` + +**Meaning.** A /ship run is open on this checkout (its marker is in the git dir until +finish), and `rule` was given no `--owner-ref`. A ruling is the owner's, and the run's own +runner never rules on the findings it is stopped on. Exit 2. Nothing was written. + +**Fix.** On Capy the owner (a Captain) has no session on the lane's checkout, so the lane +relays the ruling: `gstack-approvals rule --finding --head --reason +--words "" --by "" --owner-ref :`. The row, the receipt and the PR body's Ruled note line say it was relayed +and from which message, so a reader can check the words against it. Otherwise record the +ruling after the run stops. + ### `gstack-approvals: ... (APPROVAL_RECORD_SECRET)` @@ -2407,8 +2421,9 @@ this check exists to catch (GST-1751). **Meaning.** `Plan: exempt: ` names a reason outside the list: `bug fix`, `s1`, `flaky`, `stamp`, `changelog-resolve`, `cap-repin`, `audited-list`, `read-only`, or `crew:` for an exemption a crew's rules file records. A trailing -parenthetical such as `(R65)` is ignored. A diff of changelog fragments only needs -no line. +parenthetical such as `(R65)` is ignored, and a reason that starts with bug-fix +wording (`bug fix with failing-first tests`, `bugfix`, `bug-fixes`) counts as +`bug fix`. A diff of changelog fragments only needs no line. **Fix.** Use the exemption the brief names. A change none of them covers is a feature and needs `Plan: required` and a plan run. diff --git a/docs/unattended.md b/docs/unattended.md index 947b57735..9d3371752 100644 --- a/docs/unattended.md +++ b/docs/unattended.md @@ -1090,8 +1090,13 @@ for that read. Every other PR skips it: the run's own audit is the review. The run's final report ends with an `Attention` section that opens with `reviewed by ` (risk class) or `self-audited` (every other PR) on its own line and lists each flag against its rows; `No flags` is a valid body, a missing -opening line is not. `gstack-ship-queue ready` prints the stub with the right -opening line for the receipt it bound. `decisions.jsonl` stays the typed record `gstack-artifact` validates; the +opening line is not. The reader's read is a trail row with phase `trail-read` +whose decision names the reader (`gstack-decision-trail trail-read +"openai/gpt-6.2-sol (Subagent 4)" `). +`gstack-ship-queue ready --trail ` prints the opening line from that row +for a risk-class receipt, or `MISSING: cross-family trail read` when the trail +has none, and one `TRIAL_MERGES` line per open PR that shares a file, from +`git merge-tree` at both heads. `decisions.jsonl` stays the typed record `gstack-artifact` validates; the trail is the plain one a person reads, and `column -s$'\t' -t decisions.tsv` renders it in a terminal. diff --git a/lib/gstack-post.ts b/lib/gstack-post.ts index 65a354754..91c67691d 100644 --- a/lib/gstack-post.ts +++ b/lib/gstack-post.ts @@ -56,6 +56,8 @@ export interface PostEnv { err(text: string): void; /** On Capy (GSTACK_CAPY=1): write the checked parts for the host's PR tool and return its HOST_PUBLISH: line; gh is never called to write (GST-3183). */ hostPublish?(op: Op, target: string | undefined, parts: Array<[Part, string]>, dest: HostDest): string; + /** GH_REPO: gh's PR and issue commands write there, but gh repo view ignores it, so the destination read names it. */ + ghRepo?: string; } /** Where the gh write would have gone, so the host's PR tool can send the hand-off to the same place. */ @@ -849,9 +851,16 @@ export function runPost(argv: string[], env: PostEnv, configBin = "gstack-config } let dest = { repo: remote.segments.join("/"), host: remote.host }; if (remote.kind === "github") { - const view = env.run("gh", ["repo", "view", "--json", "nameWithOwner,url"]); + const ghRepo = env.ghRepo?.trim(); + const view = env.run("gh", ["repo", "view", ...(ghRepo ? [ghRepo] : []), "--json", "nameWithOwner,url"]); try { const v = JSON.parse(view.stdout); dest = { repo: String(v.nameWithOwner ?? ""), host: new URL(String(v.url)).host }; } catch { dest = { repo: "", host: "" }; } - if (view.status !== 0 || !dest.repo) { env.err(`gstack-post: cannot resolve the repository gh would have written to (gh repo view --json nameWithOwner,url: ${view.stderr.trim().split("\n")[0] || "no repository"}); nothing was handed off\n`); return EXIT.cliFailed; } + if (view.status !== 0 || !dest.repo) { env.err(`gstack-post: cannot resolve the repository gh would have written to (gh repo view${ghRepo ? ` ${ghRepo}` : ""} --json nameWithOwner,url: ${view.stderr.trim().split("\n")[0] || "no repository"}); nothing was handed off\n`); return EXIT.cliFailed; } + const origin = remote.segments.join("/"); + if (req.target !== undefined && !/^[1-9][0-9]*$/.test(req.target) && origin.toLowerCase() !== dest.repo.toLowerCase()) { env.err(`gstack-post: target ${req.target} names ${origin}, but the hand-off goes to ${dest.repo}, the repository gh resolves (gh repo set-default or GH_REPO); pass the number of the ${dest.repo} pull request or issue; nothing was handed off\n`); return EXIT.usage; } + if (req.op === "pr-create" && head && !head.includes(":") && origin.toLowerCase() !== dest.repo.toLowerCase()) { + if (remote.host.toLowerCase() !== dest.host.toLowerCase() || remote.segments.length !== 2) { env.err(`gstack-post: pr-create from ${remote.host}/${origin} into ${dest.host}/${dest.repo}: the head branch is on another host or a nested namespace, so the host's PR tool cannot name it; pass --head :; nothing was handed off\n`); return EXIT.usage; } + head = `${remote.segments[0]}:${head}`; + } } let line: string; try { line = env.hostPublish(req.op, n, parts, { ...dest, to: req.to, base: req.base, head, draft: req.draft }); } diff --git a/lib/headless-artifacts.ts b/lib/headless-artifacts.ts index 00f98b612..97ca41146 100644 --- a/lib/headless-artifacts.ts +++ b/lib/headless-artifacts.ts @@ -131,7 +131,7 @@ export interface ShipReceipt { /** 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 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 }>; + 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). */ gate_dispositions?: Array<{ finding: string; gate_id: string; head: string; by: string; reason: string; words: string; at: string; approval: string }>; /** The `Mechanical retake: ()` lines /ship finish proved for this head's tree (lib/ship-mechanical.ts); the PR body lists each one word for word (GST-1560). */ @@ -284,7 +284,7 @@ export const ARTIFACT_SCHEMAS = { review_exclude: { type: 'object', required: ['source', 'patterns', 'applied', 'excluded', 'excluded_bytes', 'kept', 'gate_tagged', 'patterns_sha256', 'list_sha256', 'digest'], properties: { source: str, patterns: strList, applied: strList, excluded: { type: 'integer', minimum: 0 }, excluded_bytes: { type: 'integer', minimum: 0 }, kept: { type: 'integer', minimum: 0 }, gate_tagged: strList, patterns_sha256: str, list_sha256: str, digest: str } }, 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 } } } }, - 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 } } }, + 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, design: { type: 'object', required: ['mode', 'reason'], properties: { mode: { enum: ['static'] }, reason: str } }, diff --git a/lib/plan-record.ts b/lib/plan-record.ts index 18d38e299..be37d5537 100644 --- a/lib/plan-record.ts +++ b/lib/plan-record.ts @@ -38,7 +38,7 @@ export type PlanDecl = | { kind: 'required'; line: string } | { kind: 'approved'; line: string; token: string } | { kind: 'exempt'; line: string; reason: string }; -export interface PlanRecord { line: string; state: 'approved' | 'exempt'; ref?: string; row_id?: string; row_sha256?: string; reason?: string; resolver: number } +export interface PlanRecord { line: string; state: 'approved' | 'exempt'; ref?: string; row_id?: string; row_sha256?: string; reason?: string; resolver: number; from?: 'finish' } export interface PlanFailure { code: ResultCodeName; message: string; fix: string } export type PlanResolution = { ok: true; record: PlanRecord; summary: string } | { ok: false; failure: PlanFailure }; @@ -113,6 +113,7 @@ function planLineIn(text: string): PlanDecl | null { export function exemptReason(reason: string): string | null { const r = reason.replace(/\s*\([^)]*\)\s*$/, '').trim().toLowerCase(); if (/^crew:\s*\S/.test(r)) return r.replace(/^crew:\s*/, 'crew:'); + if (/^bug[\s-]?fix(?:es)?(?![a-z])/.test(r)) return 'bug fix'; return (EXEMPT_REASONS as readonly string[]).includes(r) ? r : null; } @@ -240,16 +241,19 @@ export function planLine(res: PlanResolution, mode: { mode: PlanMode; source: st } /** ready's plan step: the PLAN: line, the record for the READY note when it resolved, and the refusal under require. */ -export function readyPlan(o: { cwd: string; env: Env; body: string; policyValue?: PlanMode; changed: string[]; fragmentsDir?: string }): { line?: string; record?: PlanRecord; failure?: PlanFailure } { +export function readyPlan(o: { cwd: string; env: Env; body: string; policyValue?: PlanMode; changed: string[]; fragmentsDir?: string; finishLine?: string }): { line?: string; record?: PlanRecord; failure?: PlanFailure } { const mode = planMode(o.policyValue, o.env); - const decl = parsePlanLine(o.body); + const own = parsePlanLine(o.body); + const fromFinish = !own && o.finishLine ? parsePlanLine(o.finishLine) : null; + const decl = own ?? fromFinish; + const mark = (res: PlanResolution): PlanResolution => (fromFinish && res.ok ? { ok: true, record: { ...res.record, from: 'finish' }, summary: `${res.summary} (from /ship finish's plan record; the PR body has no Plan: line)` } : res); if (mode.mode === 'off') { const note = offNote(mode); const line = note ? { line: note } : {}; if (!decl) return line; - try { const res = resolvePlan(decl, { cwd: o.cwd, env: o.env, changed: o.changed, fragmentsDir: o.fragmentsDir }); return res.ok ? { ...line, record: res.record } : line; } catch { return line; } + try { const res = mark(resolvePlan(decl, { cwd: o.cwd, env: o.env, changed: o.changed, fragmentsDir: o.fragmentsDir })); return res.ok ? { ...line, record: res.record } : line; } catch { return line; } } - const res = resolvePlan(decl, { cwd: o.cwd, env: o.env, changed: o.changed, fragmentsDir: o.fragmentsDir }); + const res = mark(resolvePlan(decl, { cwd: o.cwd, env: o.env, changed: o.changed, fragmentsDir: o.fragmentsDir })); const line = planLine(res, mode); if (res.ok) return { line, record: res.record }; return mode.mode === 'require' ? { line, failure: res.failure } : { line }; @@ -261,14 +265,14 @@ export function landPlan(o: { env: Env; policyValue?: PlanMode; record?: PlanRec if (mode.mode === 'off') { const note = offNote(mode); return note ? { line: note } : {}; } const current = parsePlanLine(o.body)?.line ?? null; const why = !o.record ? 'the READY note carries no plan record' - : (current ?? 'Plan: exempt: changelog-only') !== o.record.line && !(current === null && o.record.reason === 'changelog-only') ? `the READY note recorded "${o.record.line}" but the PR body now says "${current ?? 'no Plan: line'}"` : null; + : (current ?? 'Plan: exempt: changelog-only') !== o.record.line && !(current === null && (o.record.reason === 'changelog-only' || o.record.from === 'finish')) ? `the READY note recorded "${o.record.line}" but the PR body now says "${current ?? 'no Plan: line'}"` : null; if (!why) return { line: `PLAN: ${o.record!.state} ${o.record!.ref ?? o.record!.reason}${o.record!.row_id ? ` row=${o.record!.row_id}` : ''} (from the READY note)` }; const failure: PlanFailure = { code: 'QUEUE_PLAN_MISMATCH', message: why, fix: 'the lane puts the brief\'s Plan line in the PR body (gstack-approvals render --plan) and reruns gstack-ship-queue ready --pr at the pin, which records any line that resolves whatever its own mode' }; return mode.mode === 'require' ? { line: `PLAN: refused ${why} (QUEUE_PLAN_MISMATCH)`, failure } : { line: `PLAN: warn ${why} (QUEUE_PLAN_MISMATCH) [mode ${mode.mode} from ${mode.source}]` }; } /** /ship finish's plan step (gstack-ship-release finish --plan ""): the same resolution ready makes, run before the stages. */ -export function finishPlan(cwd: string, base: string, line: string | undefined, env: Env = process.env): { line?: string; failure?: PlanFailure } { +export function finishPlan(cwd: string, base: string, line: string | undefined, env: Env = process.env): { line?: string; record?: PlanRecord; failure?: PlanFailure } { let policy: ShipPolicy | undefined; try { const loaded = loadPolicyFromBase(cwd, base); policy = isUnavailable(loaded) ? undefined : loaded.policy; } catch { policy = undefined; } const run = (args: string[]) => spawnSync('git', args, { cwd, encoding: 'utf8', timeout: 30_000 }); @@ -277,3 +281,25 @@ export function finishPlan(cwd: string, base: string, line: string | undefined, const body = line ? (/^\s*(\*\*)?Plan:/i.test(line) ? line.trim() : `Plan: ${line.trim()}`) : ''; return readyPlan({ cwd, env, body, policyValue: policy?.plan_record, changed, fragmentsDir: policy?.changelog_fragments?.dir }); } + +/** After finish's stages pass: the Plan line finish resolved, bound to the branch and the head finish left (its release commit included). */ +export function recordFinishPlan(cwd: string, record: PlanRecord | undefined): void { + const run = (args: string[]) => spawnSync('git', args, { cwd, encoding: 'utf8', timeout: 30_000 }).stdout?.trim(); + const file = run(['rev-parse', '--git-path', FINISH_PLAN_FILE]); + const branch = run(['branch', '--show-current']); + const head = run(['rev-parse', '--verify', '-q', 'HEAD']); + if (!file) return; + try { + if (record && branch && head) fs.writeFileSync(path.resolve(cwd, file), JSON.stringify({ schema_version: 2, branch, head, line: record.line }) + '\n'); + else fs.rmSync(path.resolve(cwd, file), { force: true }); + } catch { /* ready then reads the body only */ } +} + +const FINISH_PLAN_FILE = 'gstack-finish-plan.json'; + +/** The Plan line /ship finish resolved for `branch` at `head` on this checkout, which ready uses when the PR body has none. */ +export function finishPlanLine(cwd: string, branch: string | undefined, head: string): string | undefined { + if (!branch) return undefined; + const file = spawnSync('git', ['rev-parse', '--git-path', FINISH_PLAN_FILE], { cwd, encoding: 'utf8', timeout: 30_000 }).stdout?.trim(); + try { const r = JSON.parse(fs.readFileSync(path.resolve(cwd, file!), 'utf8')); return r?.schema_version === 2 && r.branch === branch && r.head === head && typeof r.line === 'string' ? r.line : undefined; } catch { return undefined; } +} diff --git a/lib/result-codes-capy.ts b/lib/result-codes-capy.ts index d42752d6f..7ff98b52e 100644 --- a/lib/result-codes-capy.ts +++ b/lib/result-codes-capy.ts @@ -15,6 +15,11 @@ export const CAPY_RESULT_CODES = { summary: 'an approval row is missing a required field, holds a value outside its enum, or exceeds a length cap', fix: 'rerun gstack-approvals add with every required flag (--ask, --words, --scope, --by) inside the caps it names; nothing was written', }, + APPROVAL_RULING_RUN_OPEN: { + anchor: 'approval-ruling-run-open', + summary: 'gstack-approvals rule ran on a checkout where a /ship run is open, with no --owner-ref, and a run\'s own runner never rules on its findings', + fix: 'relay the owner\'s ruling with --owner-ref : --by --words , or record it after the run stops; nothing was written', + }, APPROVAL_RECORD_SECRET: { anchor: 'approval-record-secret', summary: 'a field of the approval row matched the secret scanner, so the row was refused and nothing was written', diff --git a/lib/review-round-grant.ts b/lib/review-round-grant.ts index 51485809a..fc2937b4e 100644 --- a/lib/review-round-grant.ts +++ b/lib/review-round-grant.ts @@ -9,7 +9,7 @@ */ import { spawnSync } from './spawn-sync'; import { locate, readRecord, type ApprovalRow, type Env } from './approval-record'; -import { GSTACK_ACTOR } from './ruled-notes'; +import { isGstackActorName } from './ruled-notes'; export const ROUND_GRANT_KINDS = ['extra-round', 'fix-check'] as const; export type RoundGrantKind = (typeof ROUND_GRANT_KINDS)[number]; @@ -29,7 +29,7 @@ export function reviewRoundGrants(rows: readonly ApprovalRow[]): ReviewRoundGran const out: ReviewRoundGrant[] = []; for (const r of rows) { const s = SCOPE.exec(r.scope), a = ASK.exec(r.ask); - if (r.outcome !== 'approved' || !s || !a || GSTACK_ACTOR.test(r.by)) continue; + if (r.outcome !== 'approved' || !s || !a || isGstackActorName(r.by)) continue; if (a[1] !== s[3] || a[2] !== s[1] || a[3] !== s[2]) continue; const findings = s[5]?.split(','); if ((s[3] === 'fix-check') !== (s[4] !== undefined) || (s[4] !== undefined && (!STOP_RUN.test(s[4]) || !findings!.every(f => FINDING_ID.test(f))))) continue; diff --git a/lib/review-targeted.ts b/lib/review-targeted.ts index acd46efbc..63c77e5c7 100644 --- a/lib/review-targeted.ts +++ b/lib/review-targeted.ts @@ -84,7 +84,7 @@ export function targetedBriefSha(file = TARGETED_BRIEF_FILE): string { * or unreadable diff; neither proves what a reader read. Not the receipt's product_patch_id (that leaves tests out). */ export function targetedPatchId(root: string, mergeBase: string): string { - const git = (args: string[], input?: string) => spawnSync('git', args, { cwd: root, input, encoding: 'utf8', timeout: 60_000, maxBuffer: 256 * 1024 * 1024 }); + const git = (args: string[], input?: string) => spawnSync('git', ['-c', 'core.quotePath=false', ...args], { cwd: root, input, encoding: 'utf8', timeout: 60_000, maxBuffer: 256 * 1024 * 1024 }); if (git(['diff', '--quiet', 'HEAD', '--']).status !== 0 || git(['ls-files', '--others', '--exclude-standard']).stdout?.trim()) return 'uncommitted'; const diff = git(['diff', '--no-color', '--no-ext-diff', mergeBase, 'HEAD']); if (diff.status !== 0 || !diff.stdout.trim()) return 'none'; diff --git a/lib/ruled-notes.ts b/lib/ruled-notes.ts index f5b044491..f84cc2166 100644 --- a/lib/ruled-notes.ts +++ b/lib/ruled-notes.ts @@ -11,15 +11,23 @@ import * as path from 'node:path'; import { locate, readRecord, type ApprovalRow, type Env } from './approval-record'; import { isSecurityFinding, REDACTED_FINDING, REDACTED_REASON } from './security-findings'; -export interface RuledNote { finding: string; head: string; by: string; reason: string; at: string; approval: string } +export interface RuledNote { finding: string; head: string; by: string; reason: string; at: string; approval: string; relayed?: string; not_security?: true } const SCOPE = /^ruled_note (\S+) ([0-9a-f]{40})$/; const ASK = /^ruled_note (\S+) at ([0-9a-f]{40}): (\S(?:.*\S)?)$/; /** A ruler gstack names for itself (the no-stop default's `gstack no-stop default (K1)`) is no owner. */ export const GSTACK_ACTOR = /^gstack\b/i; +/** The names gstack itself writes as `by`, matched whole: `gstack-evals Captain` or `GStack Minder` is a person's crew, not gstack. */ +export const GSTACK_ACTOR_NAMES: readonly string[] = ['gstack', 'gstack no-stop default (K1)']; +export const isGstackActorName = (by: string) => GSTACK_ACTOR_NAMES.some(n => n.toLowerCase() === by.trim().toLowerCase()); export const RULED_NOTE_SCOPE = /^\s*ruled_note\b/; export const ruledNoteRow = (finding: string, head: string, reason: string) => ({ scope: `ruled_note ${finding} ${head}`, ask: `ruled_note ${finding} at ${head}: ${reason}` }); +/** Where a lane relays the owner's ruling from: `:`, a message a reader can look up. */ +export const OWNER_REF = /^[A-Z][A-Z0-9]*-[1-9]\d*:[A-Za-z0-9][\w.:+-]*$/; +const RED_TEAM = /:red-team$/i; +/** A ruling row's source: `relayed:` for a relayed ruling and `not-security` for a red-team finding the owner ruled not security class. */ +export const ruledNoteSource = (o: { ownerRef?: string; notSecurity?: boolean }) => [o.ownerRef ? `relayed:${o.ownerRef}` : '', o.notSecurity ? 'not-security' : ''].filter(Boolean).join(' ') || undefined; /** The approved ruling rows, one per finding and head (the newest wins). */ export function ruledNotes(rows: readonly ApprovalRow[]): RuledNote[] { @@ -29,7 +37,10 @@ export function ruledNotes(rows: readonly ApprovalRow[]): RuledNote[] { if (r.outcome !== 'approved' || !scope || !ask || ask[1] !== scope[1] || ask[2] !== scope[2] || GSTACK_ACTOR.test(r.by)) continue; const finding = scope[1]!, head = scope[2]!, key = `${finding} ${head}`; byFinding.delete(key); - byFinding.set(key, { finding, head, by: r.by, reason: ask[3]!, at: r.recorded_at, approval: r.id }); + const source = r.source.split(' '); + const relayed = source.find(t => t.startsWith('relayed:'))?.slice('relayed:'.length); + const notSecurity = source.includes('not-security') && RED_TEAM.test(finding); + byFinding.set(key, { finding, head, by: r.by, reason: ask[3]!, at: r.recorded_at, approval: r.id, ...(relayed && OWNER_REF.test(relayed) ? { relayed } : {}), ...(notSecurity ? { not_security: true as const } : {}) }); } return [...byFinding.values()]; } @@ -40,11 +51,17 @@ export function readRuledNotes(cwd: string, env: Env = process.env): RuledNote[] return 'code' in loc ? [] : ruledNotes(readRecord(loc).rows); } -/** The ruling as public text may carry it: a security-class finding's fingerprint and reason stay in the approval record (GST-3076). */ -export const publicRuledNote = (n: RuledNote): RuledNote => isSecurityFinding(n.finding) ? { ...n, finding: REDACTED_FINDING, reason: REDACTED_REASON } : n; +/** + * The ruling as public text may carry it: a security-class finding's fingerprint and reason stay in the approval record (GST-3076). + * A red-team finding the owner ruled not security class (gstack-evals #380: a statistics fix) shows its location and reason, + * written without the `:red-team` fingerprint tail the public-text guards refuse. + */ +export const publicRuledNote = (n: RuledNote): RuledNote => !isSecurityFinding(n.finding) ? n + : n.not_security && RED_TEAM.test(n.finding) ? { ...n, finding: n.finding.replace(RED_TEAM, ' (red-team, ruled not security class)') } + : { ...n, finding: REDACTED_FINDING, reason: REDACTED_REASON }; /** The one-line form finish prints after `RULED_NOTE: ` and the PR body carries after `Ruled note: `, from publicRuledNote. */ -export const ruledNoteText = (note: RuledNote) => { const n = publicRuledNote(note); return `${n.finding} at ${n.head.slice(0, 12)} ruled by ${n.by} at ${n.at}: ${n.reason} (approval ${n.approval})`; }; +export const ruledNoteText = (note: RuledNote) => { const n = publicRuledNote(note); return `${n.finding} at ${n.head.slice(0, 12)} ruled by ${n.by}${n.relayed ? ` (relayed from ${n.relayed})` : ''} at ${n.at}: ${n.reason} (approval ${n.approval})`; }; /** The /ship run open on this checkout (its marker in the git dir, which finish removes), if any. */ export function openShipRun(cwd: string): string | undefined { diff --git a/lib/ship-queue.ts b/lib/ship-queue.ts index 91ab44269..91df3ac05 100644 --- a/lib/ship-queue.ts +++ b/lib/ship-queue.ts @@ -32,10 +32,10 @@ import { CHECKS, pregateMirrorPath, readPregateFile, verifyPregate, PREGATE_OUT_ import { exceptionConsumerProblem, flakyExceptionLines } from './pregate/flaky-exception'; import { ensureTmpExcluded, restamp, versionAtRef } from './restamp'; import type { ResultCodeName } from './result-codes'; -import { extractReceipt, readyTailLines } from './ship-receipt'; +import { extractReceipt, readyTailLines, type ReadyTail } from './ship-receipt'; import { bindShippedReceipt } from './ship-receipt-depth'; import { isUnavailable, loadPolicyFromBase, type LoadedPolicy } from './ship-policy'; -import { readyPlan } from './plan-record'; +import { finishPlanLine, readyPlan } from './plan-record'; import { QUEUE_DIR_REL, applyStampPatch, commitForTree, currentAttempt, git, listAttempts, recomputeMergeTree, sha256, writeJsonAtomic, type AttemptRecord, type QueueFailure, @@ -292,8 +292,44 @@ export function refreshBase(ctx: QueueContext): QueueFailure | null { return { code: 'QUEUE_BASE_UNFETCHED', message: `cannot fetch origin/${ctx.base} (${fetched.err.trim().split('\n')[0]?.slice(0, 200) ?? ''}); ready reads the policy and checks the receipt against the current base, never a ref it did not refresh`, fix: `fix the fetch (git fetch origin ${ctx.base}), then rerun ready` }; } +/** + * TRIAL_MERGES (rule 14): each open PR into the base that changes a path this PR changes, trial-merged with this head by git + * merge-tree; one line per such PR, or a MISSING line when gh or the fetch cannot tell. + */ +export function trialMergeLines(ctx: QueueContext, pr: string, head: string, changed: readonly string[]): string[] { + const list = ctx.gh(['pr', 'list', '--state', 'open', '--base', ctx.base, '--limit', '200', '--json', 'number,headRefOid,files']); + let open: Array<{ number: number; headRefOid: string; files?: Array<{ path: string }> }> | undefined; + try { open = list.ok ? JSON.parse(list.out) : undefined; } catch { open = undefined; } + if (!Array.isArray(open)) return [`TRIAL_MERGES: MISSING: cannot list the open PRs into ${ctx.base} through gh (${(list.err ?? list.out).trim().split('\n')[0]?.slice(0, 160) || 'no JSON'}), so no trial merge ran (rule 14)`]; + const own = new Set(changed); + const others = open.filter(p => String(p.number) !== pr); + const siblings = others.map(p => ({ ...p, shared: (p.files ?? []).map(f => f.path).filter(f => own.has(f)) })).filter(p => p.shared.length); + if (!siblings.length) return [`TRIAL_MERGES: none share a file (${others.length} open PRs checked)`]; + const remote = ctx.remote ?? 'origin'; + return siblings.map(p => { + const at = `#${p.number} ${p.headRefOid.slice(0, 12)} shares ${p.shared.slice(0, 5).join(', ')}${p.shared.length > 5 ? ` (+${p.shared.length - 5} more)` : ''}`; + if (!git(ctx.repoRoot, ['cat-file', '-e', `${p.headRefOid}^{commit}`]).ok) git(ctx.repoRoot, ['fetch', '--no-tags', '-q', remote, `refs/pull/${p.number}/head`]); + if (!git(ctx.repoRoot, ['cat-file', '-e', `${p.headRefOid}^{commit}`]).ok) return `TRIAL_MERGES: ${at}: MISSING: its head is not in this clone after git fetch ${remote} refs/pull/${p.number}/head, so no trial merge ran`; + const m = git(ctx.repoRoot, ['merge-tree', '--write-tree', '--name-only', '--no-messages', head, p.headRefOid]); + const [tree, ...files] = m.out.split('\n').filter(Boolean); + if (m.status === 0) return `TRIAL_MERGES: ${at}: merge-tree clean (tree ${(tree ?? '').slice(0, 12)})`; + if (m.status === 1) return `TRIAL_MERGES: ${at}: CONFLICT in ${files.join(', ')}; the lane states the resolution`; + return `TRIAL_MERGES: ${at}: MISSING: git merge-tree failed (${m.err.split('\n')[0]})`; + }); +} + +/** The newest row of a decision trail (gstack-decision-trail) whose phase is trail-read: its row number and the reader it names. */ +export function trailReadRow(file: string | undefined): ReadyTail['trailRead'] { + if (!file) return { missing: 'ready got no --trail ' }; + let text: string; + try { text = fs.readFileSync(file, 'utf8'); } catch (e: any) { return { missing: `cannot read --trail ${file} (${e?.code ?? 'unreadable'})` }; } + const rows = text.split('\n').slice(1).filter(Boolean).map(l => l.split('\t')); + for (let i = rows.length - 1; i >= 0; i--) if (rows[i]![1]?.trim().toLowerCase() === 'trail-read' && rows[i]![2]?.trim()) return { row: i + 1, reader: rows[i]![2]!.trim() }; + return { missing: `${file} has no trail-read row` }; +} + /** READY: one block, identifiers first, about the exact pushed PR head. */ -export function ready(ctx: QueueContext, o: { pr: string; pregate?: string; gateExit?: number; gateLog?: string }): StepOutput { +export function ready(ctx: QueueContext, o: { pr: string; pregate?: string; gateExit?: number; gateLog?: string; trail?: string }): StepOutput { const run = PREGATE_OUT_REL; const unfetched = refreshBase(ctx); if (unfetched) return fail(unfetched, [], run); @@ -347,6 +383,7 @@ export function ready(ctx: QueueContext, o: { pr: string; pregate?: string; gate const receipt = bindShippedReceipt(ctx.repoRoot, `origin/${ctx.base}`, info.body ?? '', o.pr, acceptedReceiptHeads(ctx, policy, head, info.body ?? '')); const gates = receipt.ok ? gateAcceptance({ cwd: ctx.repoRoot, branch: info.headRefName ?? '', pin: head, body: info.body ?? '', receipt: receipt.receipt }) : null; const attempt = currentAttempt(ctx.repoRoot, o.pr); + const changed = git(ctx.repoRoot, ['-c', 'core.quotePath=false', 'diff', '--name-only', `${baseSha}...${head}`]).out.split('\n').filter(Boolean); const hint = conflictHint(info.mergeable, ci, info.headRefName, info.isCrossRepository === true, head); const lines = [ `READY #${o.pr} ${head} STAMP_VERSION=${version}`, @@ -364,7 +401,7 @@ export function ready(ctx: QueueContext, o: { pr: string; pregate?: string; gate ...(receipt.depthLine ? [receipt.depthLine] : []), ...(receipt.targetedLine ? [receipt.targetedLine] : []), ...(gates?.lines ?? []), - ...readyTailLines(receipt.ok ? { ...receipt.receipt, gate_dispositions: undefined } : undefined), + ...readyTailLines(receipt.ok ? { ...receipt.receipt, gate_dispositions: undefined } : undefined, { trialMerges: trialMergeLines(ctx, o.pr, head, changed), trailRead: trailReadRow(o.trail) }), ]; const gate = policy.policy.full_e2e ? gateEvidence(ctx, o.pr, head, attempt, o.gateExit, o.gateLog) : null; if (gate) lines.push(gate.line); @@ -373,8 +410,7 @@ export function ready(ctx: QueueContext, o: { pr: string; pregate?: string; gate if (gate && !gate.ok) return fail({ code: 'QUEUE_GATE_MISSING', message: `full_e2e is set and no passing gate is bound to ${head.slice(0, 12)}: ${gate.line}` }, lines, run); if (!receipt.ok) return fail({ code: receipt.code, message: receipt.message }, lines, run); if (gates?.failure) return fail(gates.failure, lines, run); - const changed = git(ctx.repoRoot, ['diff', '--name-only', `${baseSha}...${head}`]).out.split('\n').filter(Boolean); - const plan: ReturnType = policy.policy.train ? {} : readyPlan({ cwd: ctx.repoRoot, env: process.env, body: info.body ?? '', policyValue: policy.policy.plan_record, changed, fragmentsDir: policy.policy.changelog_fragments?.dir }); + const plan: ReturnType = policy.policy.train ? {} : readyPlan({ cwd: ctx.repoRoot, env: process.env, body: info.body ?? '', policyValue: policy.policy.plan_record, changed, fragmentsDir: policy.policy.changelog_fragments?.dir, finishLine: finishPlanLine(ctx.repoRoot, info.headRefName, head) }); if (plan.line) lines.push(plan.line); if (plan.failure) return fail(plan.failure, lines, run); if (!policy.policy.train && policy.policy.changelog_fragments) { diff --git a/lib/ship-receipt.ts b/lib/ship-receipt.ts index d2e2ae0d3..eb2c17bd4 100644 --- a/lib/ship-receipt.ts +++ b/lib/ship-receipt.ts @@ -229,24 +229,31 @@ export function receiptSummaryLine(r: ShipReceipt): string { /** A risk-class PR (R51): the receipt's review depth has class gate or a risk class. Only these get the cross-family trail read. */ export const riskClassReceipt = (r: ShipReceipt | undefined) => r?.review_depth?.class === 'gate' || !!r?.review_depth?.risk?.length; +/** What ready found for the READY tail: its TRIAL_MERGES lines and the decision trail's cross-family read, or why there is none. */ +export interface ReadyTail { trialMerges: string[]; trailRead: { row: number; reader: string } | { missing: string } } + /** - * The rest of the READY block (GSTA-258 E1: the ready output is the whole READY): the receipt's review loop, the trial-merge - * line the lane fills, and the Attention stub, whose opening line follows the receipt's risk class (docs/unattended.md). + * The rest of the READY block (GSTA-258 E1: the ready output is the whole READY): the receipt's review loop, ready's trial + * merges, and the Attention section, whose opening line follows the receipt's risk class and the trail's cross-family read + * (docs/unattended.md): a risk-class PR with no trail-read row prints MISSING instead of a line to fill in. */ -export function readyTailLines(r: ShipReceipt | undefined): string[] { +export function readyTailLines(r: ShipReceipt | undefined, t: ReadyTail = { trialMerges: [], trailRead: { missing: 'ready did not look for one' } }): string[] { const loop = parseReviewLoop(r?.review_loop); const opt = (k: keyof ReviewLoopReceipt) => (loop?.[k] ? ` ${k}=${loop[k]}` : ''); const risk = riskClassReceipt(r); const legacy = !!r && !r.review_depth; + const cls = legacy ? 'risk class unknown: the receipt records no review_depth' : `risk class: ${oneLine([r?.review_depth?.class === 'gate' ? 'gate' : '', ...(r?.review_depth?.risk ?? [])].filter(Boolean).join(', '))}`; + const reviewer = !legacy && !risk ? 'self-audited (not a risk class: no cross-family trail read)' + : 'row' in t.trailRead ? `reviewed by ${oneLine(t.trailRead.reader)} (${cls}; rule 27 cross-family trail read, trail row ${t.trailRead.row})` + : `MISSING: cross-family trail read (${cls}; rule 27): ${oneLine(t.trailRead.missing)}; have a reader on another model family read the trail and transcript, record it with gstack-decision-trail trail-read "" , then rerun ready with --trail `; return [ loop ? `REVIEW_LOOP: passes=${loop.passes} blocking_found=${loop.blocking_found} deferred=${loop.deferred} noted=${loop.noted ?? 0} fixed=${loop.fixed ?? 0}${opt('unrecorded')}${opt('unbound')}${opt('fix_checks')}` : 'REVIEW_LOOP: none in the receipt', ...(r?.ruled_notes ?? []).map(n => `RULED_NOTE: ${oneLine(ruledNoteText(n))}`), ...(r?.gate_dispositions ?? []).map(d => `GATE_DISPOSITION: ${oneLine(gateDispositionText(d))}`), ...laneExceptionBodyLines(r?.ci_carried).map(l => `TEST_LANE_EXCEPTION: ${oneLine(l.slice('Test-lane exception: '.length))}`), - 'TRIAL_MERGES: ', + ...(t.trialMerges.length ? t.trialMerges : ['TRIAL_MERGES: MISSING: ready did not check the open PRs that share a file (rule 14)']), 'Attention:', - legacy ? 'reviewed by (risk class unknown: the receipt records no review_depth; rule 27 cross-family trail read)' - : risk ? `reviewed by (risk class: ${oneLine([r?.review_depth?.class === 'gate' ? 'gate' : '', ...(r?.review_depth?.risk ?? [])].filter(Boolean).join(', '))}; rule 27 cross-family trail read)` : 'self-audited (not a risk class: no cross-family trail read)', + reviewer, '', ]; } diff --git a/lib/ship-release.ts b/lib/ship-release.ts index 8de60aa8f..78c97354f 100644 --- a/lib/ship-release.ts +++ b/lib/ship-release.ts @@ -35,7 +35,7 @@ import { bumpVersion, cmpVersion, fmtVersion, parseVersion, versionWidth, type B import { waitForRun } from './ci-carry'; import { MIN_POLL_MS } from './gh-poll'; import { lanesOnlyHeadPolicy } from './pregate/head-policy'; -import { finishPlan } from './plan-record'; +import { finishPlan, recordFinishPlan } from './plan-record'; import { PREPUSH_CHECK_IDS } from './pregate/index'; import { checkBranch, loadPlainTitlePolicy, type PlainFinding } from './plain-title'; import { buildRunCheck } from './pregate/run-check'; @@ -577,6 +577,7 @@ export async function finish(argv: readonly string[], cwd: string): Promise { expect(out.status, out.stderr).toBe(0); expect(destinations(out.stdout)).toEqual([{ op, target: '7', repo: 'upstream/fx' }]); } + const byUrl = r.run('gstack-post', ['pr-comment', 'https://github.com/forker/fx/pull/7', '--body-file', comment]); + expect(byUrl.status).toBe(64); + expect(byUrl.stdout).not.toContain('HOST_PUBLISH:'); + expect(byUrl.stderr).toContain('upstream/fx'); expect(r.gh.writes()).toEqual([]); }); @@ -318,3 +323,74 @@ describe('on Capy, gstack-ship-receipt carry calls no gh write (GST-3183)', () = expect(h!.body).toContain(head); }); }); + +/** The real gh on PATH (on a Capy machine the wrapper's gh.real), pointed at a fake GitHub API on a unix socket it owns. */ +const REAL_GH = Bun.which('gh.real') ?? Bun.which('gh'); +async function fakeGithub() { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gh-')); + const sock = path.join(dir, 's'); + const cfg = path.join(dir, 'cfg'); + fs.mkdirSync(cfg); + fs.writeFileSync(path.join(cfg, 'config.yml'), `http_unix_socket: ${sock}\n`); + fs.writeFileSync(path.join(dir, 'srv.ts'), [ + 'Bun.serve({ unix: process.argv[2], async fetch(req) {', + ' let v = {}; try { v = JSON.parse(await req.text()).variables || {}; } catch {}', + ' const owner = v.owner, name = v.name || v.repo;', + " return Response.json({ data: { repository: { id: 'R', name, owner: { login: owner }, nameWithOwner: owner + '/' + name, url: 'https://github.com/' + owner + '/' + name, pullRequest: { id: 'P', number: v.pr_number || 7, body: 'Fixes a thing.\\n' } } } });", + '} });', '', + ].join('\n')); + const bin = path.join(dir, 'bin'); + fs.mkdirSync(bin); + fs.symlinkSync(REAL_GH!, path.join(bin, 'gh')); + const server = Bun.spawn([process.execPath, path.join(dir, 'srv.ts'), sock], { stdout: 'ignore', stderr: 'ignore' }); + for (let i = 0; i < 100 && !fs.existsSync(sock); i++) await Bun.sleep(50); + const env = { PATH: `${bin}:${process.env.PATH}`, GH_CONFIG_DIR: cfg, GH_TOKEN: 'fake', GH_HOST: 'github.com', GH_ENTERPRISE_TOKEN: '', GH_NO_UPDATE_NOTIFIER: '1', GH_PROMPT_DISABLED: '1' }; + return { env, stop: () => { server.kill(); fs.rmSync(dir, { recursive: true, force: true }); } }; +} + +describe('GH_REPO and fork heads on the HOST_PUBLISH hand-off (#4518 follow-up)', () => { + // Value: protects=with GH_REPO set, both hand-off paths name the repository gh's own write would have used, as real gh + // resolves it (gh repo view ignores GH_REPO; gh pr view and edit honour it); fails_when=the destination read drops GH_REPO + // and names origin's repository; seam=bin/gstack-post and bin/gstack-ship-receipt with real gh over a fake API socket + test.skipIf(!REAL_GH || process.platform === 'win32')('real gh: gstack-post and stub name GH_REPO, not origin', async () => { + const r = capyRepo(); + r.githubOrigin(); + r.f.git('remote', 'set-url', 'origin', 'https://github.com/forker/fx.git'); + const gh = await fakeGithub(); + try { + const comment = path.join(r.f.root, 'c.md'); + fs.writeFileSync(comment, 'A plain comment.\n'); + const post = r.run('gstack-post', ['pr-comment', '7', '--body-file', comment], { ...gh.env, GH_REPO: 'upstream/fx' }); + expect(post.status, post.stderr).toBe(0); + expect(destinations(post.stdout)).toEqual([{ op: 'pr-comment', target: '7', repo: 'upstream/fx' }]); + const stub = r.run('gstack-ship-receipt', ['stub', '--pr', '7', '--run', 'r1'], { ...gh.env, GH_REPO: 'upstream/fx' }); + expect(stub.status, stub.stderr).toBe(0); + expect(destinations(stub.stdout)).toEqual([{ op: 'pr-body', target: '7', repo: 'upstream/fx' }]); + } finally { gh.stop(); } + }); + + // Value: protects=a pr-create hand-off from a fork checkout names owner:branch, as gh pr create would, and refuses when the + // fork is on another host; fails_when=head= is the bare branch, which the base repository reads as its own; seam=bin/gstack-post + test('a fork pr-create names the head as origin-owner:branch, or refuses across hosts', () => { + const title = (r: ReturnType) => { const t = path.join(r.f.root, 't.txt'); fs.writeFileSync(t, 'Add a thing for users\n'); return t; }; + const body = (r: ReturnType) => { const b = path.join(r.f.root, 'b.md'); fs.writeFileSync(b, 'Adds a thing for users.\n\n## Why\n\nBecause.\n'); return b; }; + const r = capyRepo({ nameWithOwner: 'upstream/fx', url: 'https://github.com/upstream/fx' }); + r.githubOrigin(); + r.f.git('remote', 'set-url', 'origin', 'https://github.com/forker/fx.git'); + const branch = r.f.git('branch', '--show-current').stdout.trim(); + const n = r.run('gstack-post', ['pr-create', '--base', 'main', '--title-file', title(r), '--body-file', body(r)]); + expect(n.status, n.stderr).toBe(0); + expect(destinations(n.stdout)).toEqual([{ op: 'pr-create', target: 'new', repo: 'upstream/fx', base: 'main', head: `forker:${branch}` }]); + const named = r.run('gstack-post', ['pr-create', '--base', 'main', '--head', 'someone:topic', '--title-file', title(r), '--body-file', body(r)]); + expect(destinations(named.stdout)).toEqual([{ op: 'pr-create', target: 'new', repo: 'upstream/fx', base: 'main', head: 'someone:topic' }]); + const far = capyRepo({ nameWithOwner: 'upstream/fx', url: 'https://github.acme.test/upstream/fx' }); + far.githubOrigin(); + far.f.git('remote', 'set-url', 'origin', 'https://github.com/forker/fx.git'); + const refused = far.run('gstack-post', ['pr-create', '--base', 'main', '--title-file', title(far), '--body-file', body(far)]); + expect(refused.status).toBe(64); + expect(refused.stdout).not.toContain('HOST_PUBLISH:'); + expect(refused.stderr).toContain('pass --head :'); + expect([...r.gh.writes(), ...far.gh.writes()]).toEqual([]); + }); +}); + diff --git a/test/gstack-ship-queue.test.ts b/test/gstack-ship-queue.test.ts index 310bb6a47..717d46965 100644 --- a/test/gstack-ship-queue.test.ts +++ b/test/gstack-ship-queue.test.ts @@ -789,3 +789,48 @@ describe('printed gate-ahead command (review #3235 P2-1)', () => { expect(line(r.stdout, 'GATE_RECORD:')).toMatch(new RegExp(`^GATE_RECORD: pr=2 attempt=${p.attempt} exit=0 `)); }, 180_000); }); + +describe('the READY tail ready fills in: TRIAL_MERGES and the cross-family trail read (GST-3200)', () => { + // Value: protects=READY carries a computed trial-merge line per open PR sharing a file and a reviewer line read from the trail, + // or MISSING, never a template line a lane can cut; fails_when=ready prints the TRIAL_MERGES or reviewed by + // placeholder (three gate-class PRs skipped the rule 27 read on 11-19); seam=bin/gstack-ship-queue ready with a gh shim + test('one line per sibling from git merge-tree, and the reviewer from the trail-read row, else MISSING', () => { + const repo = fixture(); + const sibling = (branch: string, files: Record, pr: string) => { + repo.git('checkout', '-q', 'origin/main', '-b', branch); + for (const [f, text] of Object.entries(files)) fs.writeFileSync(path.join(repo.work, f), text); + repo.git('add', '-A'); repo.git('commit', '-q', '-m', branch); + publish(repo, pr); + return repo.git('rev-parse', 'HEAD'); + }; + const conflict = sibling('pr-b', { 'pr-a.txt': 'other\n' }, '2'); + const clean = sibling('pr-c', { 'pr-a.txt': 'pr-a\n', 'c.txt': 'c\n' }, '3'); + const apart = sibling('pr-d', { 'd.txt': 'd\n' }, '4'); + const head = makePr(repo, 'pr-a', { changelog: false }); + const tree = runBin(repo, 'gstack-wtree', []).out.trim(); + const pregate = path.join(repo.root, 'pregate.json'); + fs.writeFileSync(pregate, JSON.stringify({ schema_version: 1, tree, head, verdict: 'pass', checks: FULL_CHECKS })); + const files = (...p: string[]) => p.map(f => ({ path: f })); + const list = [{ number: 1, headRefOid: head, files: files('pr-a.txt') }, { number: 2, headRefOid: conflict, files: files('pr-a.txt') }, { number: 3, headRefOid: clean, files: files('pr-a.txt', 'c.txt') }, { number: 4, headRefOid: apart, files: files('d.txt') }]; + const green = { check_runs: [{ status: 'completed', conclusion: 'success' }] }; + const prs = { '1': { headRefOid: head, body: shippedBody('1', head), headRefName: 'pr-a' } }; + const trail = path.join(repo.root, 'decisions.tsv'); + fs.writeFileSync(trail, 'ts\tphase\tdecision\twhy\tevidence\tresult\n2026-11-19T00:00:00Z\tstart\trun x opens this trail\tno earlier rows\trun:x\topen\n2026-11-19T00:01:00Z\ttrail-read\topenai/gpt-6.2-sol (Subagent 4)\trule 27\tflags.md\tNo flags\n'); + const r = queue(repo, ['ready', '--pr', '1', '--pregate', pregate, '--trail', trail], ghQueueShim(repo, { prs, checks: { [head]: green }, list })); + expect(r.status, r.err).toBe(EXIT.ok); + const cleanTree = repo.git('merge-tree', '--write-tree', head, clean); + expect(r.out.split('\n').filter(l => l.startsWith('TRIAL_MERGES: '))).toEqual([ + `TRIAL_MERGES: #2 ${conflict.slice(0, 12)} shares pr-a.txt: CONFLICT in pr-a.txt; the lane states the resolution`, + `TRIAL_MERGES: #3 ${clean.slice(0, 12)} shares pr-a.txt: merge-tree clean (tree ${cleanTree.slice(0, 12)})`, + ]); + expect(line(r.out, 'Attention:')).toBe('Attention:'); + expect(r.out).toContain('\nreviewed by openai/gpt-6.2-sol (Subagent 4) (risk class unknown: the receipt records no review_depth; rule 27 cross-family trail read, trail row 2)\n'); + expect(r.out).not.toContain(''); + const bare = queue(repo, ['ready', '--pr', '1', '--pregate', pregate], ghQueueShim(repo, { prs, checks: { [head]: green } })); + expect(line(bare.out, 'TRIAL_MERGES: ')).toStartWith('TRIAL_MERGES: MISSING: cannot list the open PRs into main through gh'); + expect(line(bare.out, 'MISSING: cross-family')).toStartWith('MISSING: cross-family trail read (risk class unknown: the receipt records no review_depth; rule 27): ready got no --trail ;'); + const alone = queue(repo, ['ready', '--pr', '1', '--pregate', pregate], ghQueueShim(repo, { prs, checks: { [head]: green }, list: [list[0], list[3]] })); + expect(line(alone.out, 'TRIAL_MERGES: ')).toBe('TRIAL_MERGES: none share a file (1 open PRs checked)'); + }, 240_000); +}); + diff --git a/test/helpers/ship-queue-fixture.ts b/test/helpers/ship-queue-fixture.ts index 3d5f666c3..829c0c776 100644 --- a/test/helpers/ship-queue-fixture.ts +++ b/test/helpers/ship-queue-fixture.ts @@ -83,15 +83,16 @@ export function gbrainPairRepo(): { repo: FixtureRepo; pair: GbrainPair; gated: * entry has no commit-status contexts, as on GitHub. A check run marked * earlier_attempt belongs to a superseded workflow-run attempt: like GitHub's * default filter=latest, the shim hides it unless the call asks for filter=all. - * workflowRuns answers actions/runs?head_sha= the same way (none by default). + * workflowRuns answers actions/runs?head_sha= the same way (none by default). list answers gh pr list (a failure when absent). */ -export function ghQueueShim(repo: FixtureRepo, data: { prs: Record; checks: Record; statuses?: Record; workflowRuns?: Record }): { PATH: string } { +export function ghQueueShim(repo: FixtureRepo, data: { prs: Record; checks: Record; statuses?: Record; workflowRuns?: Record; list?: unknown[] }): { PATH: string } { const dir = path.join(repo.root, 'gh-queue-shim'); fs.mkdirSync(dir, { recursive: true }); fs.writeFileSync(path.join(dir, 'data.json'), JSON.stringify(data)); const js = [ "const d = require(process.argv[2]); const a = process.argv.slice(3);", "if (a[0] === 'pr' && a[1] === 'view') { const p = d.prs[a[2]]; if (!p) { console.error('no pull request found'); process.exit(1); } console.log(JSON.stringify(p)); process.exit(0); }", + "if (a[0] === 'pr' && a[1] === 'list') { if (!d.list) { console.error('gh shim: no pr list'); process.exit(1); } console.log(JSON.stringify(d.list)); process.exit(0); }", "const paged = (c, key, page) => { if (c.pages) return c.pages[page - 1] || { total_count: c.pages.reduce((n, p) => n + p[key].length, 0), [key]: [] }; const total = c.total_count ?? c[key].length; return page === 1 ? { total_count: total, ...c } : { total_count: total, [key]: [] }; };", "const latestOnly = (c, url) => /[?&]filter=all(&|$)/.test(url) || !c || !Array.isArray(c.check_runs) || !c.check_runs.some(r => r.earlier_attempt) ? c : { check_runs: c.check_runs.filter(r => !r.earlier_attempt) };", "if (a[0] === 'api') { const w = /actions\\/runs\\?head_sha=([0-9a-f]+).*page=(\\d+)/.exec(a[1] || ''); if (w) { console.log(JSON.stringify(paged((d.workflowRuns || {})[w[1]] || { workflow_runs: [] }, 'workflow_runs', Number(w[2])))); process.exit(0); } }", diff --git a/test/helpers/ship-queue-train-fixture.ts b/test/helpers/ship-queue-train-fixture.ts index d893a5a78..ade30d8e7 100644 --- a/test/helpers/ship-queue-train-fixture.ts +++ b/test/helpers/ship-queue-train-fixture.ts @@ -249,7 +249,7 @@ function shimSource(): string { "}", "if (a[0] === 'pr' && a[1] === 'comment') { const p = d.prs[a[2]]; if (!p) fail('no pull request found'); p.comments = [...(p.comments || []), { body: opt('--body') }]; out({}); }", "if (a[0] === 'pr' && a[1] === 'close') { const p = d.prs[a[2]]; if (!p) fail('no pull request found'); p.state = 'CLOSED'; out({}); }", - "if (a[0] === 'pr' && a[1] === 'list') { const head = opt('--head'); const st = opt('--state'); out(Object.entries(d.prs).filter(([, p]) => (!head || p.headRefName === head) && (st !== 'open' || p.state === 'OPEN')).map(([n, p]) => ({ number: Number(n), state: p.state, headRefOid: p.headRefOid, baseRefName: p.baseRefName || 'main', mergeCommit: p.mergeCommit || null }))); }", + "if (a[0] === 'pr' && a[1] === 'list') { const head = opt('--head'); const st = opt('--state'); out(Object.entries(d.prs).filter(([, p]) => (!head || p.headRefName === head) && (st !== 'open' || p.state === 'OPEN')).map(([n, p]) => ({ number: Number(n), state: p.state, headRefOid: p.headRefOid, baseRefName: p.baseRefName || 'main', mergeCommit: p.mergeCommit || null, files: p.files || [] }))); }", "fail('gh shim: unsupported ' + a.join(' '));", ].join('\n') + '\n'; } diff --git a/test/plan-record.test.ts b/test/plan-record.test.ts index 703617265..97ab98259 100644 --- a/test/plan-record.test.ts +++ b/test/plan-record.test.ts @@ -9,7 +9,7 @@ import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; import { buildRow, locate, type ApprovalRow } from '../lib/approval-record'; -import { exemptReason, finishPlan, landPlan, parsePlanLine, planMode, planRecordId, publicPlanLine, readyPlan, resolvePlan } from '../lib/plan-record'; +import { exemptReason, finishPlan, finishPlanLine, landPlan, parsePlanLine, planMode, planRecordId, publicPlanLine, readyPlan, recordFinishPlan, resolvePlan } from '../lib/plan-record'; import { planBinding } from '../lib/ship-audit'; import { loadReady, persist, repoIdentity } from '../crew/lib/ship-queue-train-record'; @@ -407,3 +407,33 @@ describe('public repos: the record-keyed Plan line and the machine-local key (GS expect(config('get', 'plan_record').stdout.trim()).toBe('warn'); }); }); + +describe('bug-fix exemption wording and the plan finish recorded (GSTA-649, GSTA-617)', () => { + // Value: protects=a stated bug-fix exemption resolves whatever its wording, and a PR whose body has no Plan line takes the line + // /ship finish resolved on this checkout, which land then accepts; fails_when=ready warns PLAN_EXEMPT_UNKNOWN or + // PLAN_RECORD_MISSING after finish recorded Plan: exempt: bug fix; seam=exemptReason, finishPlan, readyPlan, landPlan + test('bug fix variants are the bug fix exemption', () => { + for (const r of ['bug fix with failing-first tests', 'Bugfix', 'bug-fix: retry backoff', 'bug fixes (R65)']) expect(exemptReason(r)).toBe('bug fix'); + expect(exemptReason('bugfixing everything')).toBeNull(); + }); + test('ready reads the Plan line finish resolved when the body has none, and land accepts it', () => { + const f = fixture(); + const env = { ...f.env, GSTACK_PLAN_RECORD: 'require' }; + spawnSync('git', ['-c', 'user.name=Fixture', '-c', 'user.email=fixture@example.com', 'commit', '-q', '--allow-empty', '-m', 'seed'], { cwd: f.cwd, timeout: 30_000 }); + const head = spawnSync('git', ['rev-parse', 'HEAD'], { cwd: f.cwd, encoding: 'utf8', timeout: 30_000 }).stdout.trim(); + const fin = finishPlan(f.cwd, 'main', 'Plan: exempt: bug fix', env); + expect(fin.line).toBe('PLAN: exempt bug fix'); + recordFinishPlan(f.cwd, fin.record); + const ready = readyPlan({ cwd: f.cwd, env, body: 'Fixes a thing.', changed: ['lib/x.ts'], finishLine: finishPlanLine(f.cwd, 'capy/feature', head) }); + expect(ready.failure).toBeUndefined(); + expect(ready.record).toMatchObject({ line: 'Plan: exempt: bug fix', state: 'exempt', reason: 'bug fix', from: 'finish' }); + expect(ready.line).toContain("from /ship finish's plan record"); + expect(landPlan({ env, record: ready.record, body: 'Fixes a thing.' }).failure).toBeUndefined(); + expect(finishPlanLine(f.cwd, 'other-branch', head)).toBeUndefined(); + expect(finishPlanLine(f.cwd, 'capy/feature', '0'.repeat(40))).toBeUndefined(); + expect(readyPlan({ cwd: f.cwd, env, body: 'Plan: exempt: flaky', changed: ['lib/x.ts'], finishLine: finishPlanLine(f.cwd, 'capy/feature', head) }).record).toMatchObject({ reason: 'flaky' }); + recordFinishPlan(f.cwd, undefined); + expect(finishPlanLine(f.cwd, 'capy/feature', head)).toBeUndefined(); + }); +}); + diff --git a/test/pr-round-cli.test.ts b/test/pr-round-cli.test.ts index e54622cc1..b4587695a 100644 --- a/test/pr-round-cli.test.ts +++ b/test/pr-round-cli.test.ts @@ -64,6 +64,15 @@ describe('gstack-approvals round-grant', () => { expect(r.run('gstack-approvals', ['round-grant', '--pr', '5', '--head', r.head, '--kind', 'more', '--reason', 'x', '--by', 'lane']).status).toBe(2); expect(r.run('gstack-approvals', ['add', '--ask', 'a', '--words', 'w', '--by', 'b', '--scope', `review_round_grant ${r.head} pr=5 kind=extra-round`]).status).toBe(2); }); + + // Value: protects=a Captain whose crew name starts with gstack can grant a round, while gstack's own names stay refused; + // fails_when=the self-grant check matches a prefix (gstack-evals Captain refused, #4518 follow-up); seam=bin/gstack-approvals + test('a --by that only starts with gstack is a crew, not gstack: gstack-evals Captain records a grant', () => { + const r = repo(); + for (const by of ['gstack', 'GStack', ' gstack no-stop default (K1) ']) expect(r.run('gstack-approvals', ['round-grant', '--pr', '5', '--head', r.head, '--kind', 'extra-round', '--reason', 'x', '--by', by]).status).toBe(2); + const ok = r.run('gstack-approvals', ['round-grant', '--pr', '5', '--head', r.head, '--kind', 'extra-round', '--reason', 'x', '--by', 'gstack-evals Captain']); + expect([ok.status, ok.stderr]).toEqual([0, '']); + }); }); describe('gstack-ship-receipt history and stub', () => { diff --git a/test/review-plan-targeted-delta.test.ts b/test/review-plan-targeted-delta.test.ts index e5d8f0b33..dffa3e57c 100644 --- a/test/review-plan-targeted-delta.test.ts +++ b/test/review-plan-targeted-delta.test.ts @@ -4,6 +4,8 @@ import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; import { parseReviewTargeted, plainDocsSince, targetedClassesSince } from '../lib/ship-receipt-depth'; +import { targetedPatchId } from '../lib/review-targeted'; +import { targetedDelta } from '../lib/review-targeted-delta'; const BIN = path.join(import.meta.dir, '..', 'bin'); const dirs: string[] = []; @@ -166,3 +168,18 @@ describe('GST-1598: a post-review docs delta that trips a targeted claim gets on expect(rendered.map(e => [e.reader, e.diff_base, e.head, e.classes])).toEqual([['targeted', mergeBase, r.git('rev-parse', 'HEAD'), ['money']]]); }); }); + +describe('a targeted read on a non-ASCII path (#4520 ruled note)', () => { + // Value: protects=the patch-id the targeted record stores and the one targetedDelta recomputes hash the same diff text when a + // path is non-ASCII, so a plain-docs follow-up carries the read; fails_when=targetedPatchId quotes the path (core.quotePath + // default) while the check does not, and the read never matches; seam=targetedPatchId and targetedDelta over a real git repo + test('a plain-docs change after the read carries it instead of refusing --targeted-ran', () => { + const r = reviewed({}, { 'src/caf\u00e9/billing.ts': MONEY_CODE }); + const read = r.git('rev-parse', 'HEAD'); + const ran = targetedPatchId(r.dir, r.git('merge-base', 'main', 'HEAD')); + expect(ran).toMatch(/^[0-9a-f]{40}$/); + r.commit({ 'docs/notes.md': '# Notes\n\nA plain paragraph.\n' }, 'docs'); + expect(targetedDelta(r.dir, 'main', read, ran)).toEqual({ state: 'skip', reason: expect.stringContaining('plain docs'), carried: true }); + }); +}); + diff --git a/test/review-round-grant.test.ts b/test/review-round-grant.test.ts index 913318f70..4fdecbea4 100644 --- a/test/review-round-grant.test.ts +++ b/test/review-round-grant.test.ts @@ -20,6 +20,7 @@ describe('review round grants', () => { test('only an approved row that gstack did not write counts, and it binds only its head and PR', () => { expect(reviewRoundGrants([row({ outcome: 'pending' as any })])).toEqual([]); expect(reviewRoundGrants([row({ by: 'gstack' })])).toEqual([]); + expect(reviewRoundGrants([row({ by: 'gstack-evals Captain' })]).map(g => g.by)).toEqual(['gstack-evals Captain']); const gs = reviewRoundGrants([row({})]); expect(grantAt(gs, 12, head)).toBeDefined(); expect(grantAt(gs, 13, head)).toBeUndefined(); diff --git a/test/security-finding-redaction.test.ts b/test/security-finding-redaction.test.ts index 191323a80..12feeee39 100644 --- a/test/security-finding-redaction.test.ts +++ b/test/security-finding-redaction.test.ts @@ -149,3 +149,39 @@ describe('the full approvals table', () => { expect(out).toContain(`ruled_note src/x.ts:1:naming at ${HEAD}: naming ships as a note`); }); }); + +// Value: protects=a red-team finding the owner ruled not security class (gstack-evals #380: a statistics fix) shows its location +// and reason in public text, the receipt validates and the public-text guards pass it, while security, auth and secret +// findings cannot take the exemption; fails_when=every red-team ruling prints "security finding, details recorded privately", +// or the exemption reaches a security-category finding; seam=gstack-approvals rule|rulings and gstack-ship-receipt write +describe('a red-team finding the owner ruled not security class (gstack-evals #380)', () => { + test.skipIf(process.platform === 'win32')('rule --not-security prints the finding; a security category refuses the flag', () => { + const f = shipFixture({ 'src/x.ts': 'export const x = 1;\n' }, { 'src/x.ts': 'export const x = 2;\n' }); + ships.push(f); + fs.writeFileSync(path.join(f.root, 'stub', 'gh'), '#!/bin/sh\ncase "$*" in *visibility*) echo PUBLIC ;; *) exit 1 ;; esac\n', { mode: 0o755 }); + const run = (bin: string, args: string[]) => f.run(path.join(BIN, bin), args, { GSTACK_APPROVALS_MIRROR: '0' }); + const head = f.git('rev-parse', 'HEAD').stdout.trim(); + const reason = 'the routing pilot picks its four extra tasks before the seed is fixed'; + const rule = (finding: string, extra: string[]) => run('gstack-approvals', ['rule', '--finding', finding, '--head', head, '--reason', reason, '--words', 'a note, fix it by a dated change', '--by', 'Fixture Owner', ...extra]); + expect(rule('src/x.ts:1:security', ['--not-security']).status).toBe(EXIT.usage); + const marker = path.resolve(f.work, f.git('rev-parse', '--git-path', 'gstack-ship-run').stdout.trim()); + fs.writeFileSync(marker, 'ship-run-1\n'); + const inRun = rule('src/x.ts:2:red-team', ['--not-security', '--owner-ref', 'GSTA-36:2026-11-19T12:29:59Z']); + expect(inRun.status).toBe(EXIT.usage); + expect(inRun.stderr).toContain('--not-security'); + fs.rmSync(marker); + expect(run('gstack-approvals', ['rulings']).stdout).not.toContain('src/x.ts:2'); + const ruled = rule('src/x.ts:1:red-team', ['--not-security']); + expect(ruled.status, ruled.stderr).toBe(0); + const line = run('gstack-approvals', ['rulings']).stdout.trim(); + expect(line).toStartWith(`Ruled note: src/x.ts:1 (red-team, ruled not security class) at ${head.slice(0, 12)} ruled by Fixture Owner at `); + expect(line).toContain(reason); + expect(securityFingerprints(line)).toEqual([]); + const body = path.join(f.root, 'body.md'); + fs.writeFileSync(body, `## Pre-Landing Review\n\n${line}\n`); + const write = f.run(path.join(BIN, 'gstack-ship-receipt'), ['write', '--pr', '7', '--base', 'main', '--version', '1.0.0', '--session-kind', 'unattended', '--body', body], { GSTACK_APPROVALS_MIRROR: '0' }); + expect(write.status, write.stderr).toBe(EXIT.ok); + expect(fs.readFileSync(body, 'utf8')).toContain('"not_security": true'); + }); +}); + diff --git a/test/ship-finish-ruled-notes.test.ts b/test/ship-finish-ruled-notes.test.ts index f29522abb..93988a759 100644 --- a/test/ship-finish-ruled-notes.test.ts +++ b/test/ship-finish-ruled-notes.test.ts @@ -492,3 +492,34 @@ describe('a granted fix-check that found new CRITICALs the owner accepted (harne expect(r.stdout).toContain('STOP: behavior, tests or build inputs changed since review (src/x.ts)'); }); }); + +// Value: protects=a ruling relayed into an open /ship run records the owner's words with a checkable source and says so in the +// row, the Ruled note line and the receipt, while a ruling with no owner reference still refuses under its own code; +// fails_when=the refusal reads APPROVAL_RECORD_INVALID and points at add (GBRA-108), or a relayed ruling cannot be recorded +// or is not marked relayed; seam=gstack-approvals rule|rulings|list and gstack-ship-receipt write +describe('a ruling relayed into an open /ship run (GBRA-108, gbrain #9762)', () => { + test('without --owner-ref it refuses as APPROVAL_RULING_RUN_OPEN; with one it records and marks the ruling relayed', () => { + const { f, passHead } = grantedFixCheck(QM3122); + const marker = path.resolve(f.work, f.git('rev-parse', '--git-path', 'gstack-ship-run').stdout.trim()); + fs.writeFileSync(marker, 'ship-9762-abc\n'); + const bare = rule(f, RACE, passHead, 'GBrain Minder (GBRA-108)'); + expect([bare.status, bare.stderr]).toEqual([EXIT.usage, expect.stringContaining('(APPROVAL_RULING_RUN_OPEN)')]); + expect(bare.stderr).not.toContain('APPROVAL_RECORD_INVALID'); + expect(bare.stderr).not.toContain('gstack-approvals add'); + const relay = (ref: string) => run(f, 'gstack-approvals', ['rule', '--finding', RACE, '--head', passHead, '--reason', 'ships as a disclosed note', '--words', 'B, note it', '--by', 'GBrain Minder (GBRA-108)', '--owner-ref', ref]); + expect(relay('just words').status).toBe(EXIT.usage); + const ok = relay('GBRA-108:2026-11-19T12:29:59Z'); + expect(ok.status, ok.stderr).toBe(0); + const rows = JSON.parse(run(f, 'gstack-approvals', ['list', '--json']).stdout).rows as Array<{ source: string; words: string }>; + expect(rows.find(r => r.source === 'relayed:GBRA-108:2026-11-19T12:29:59Z')?.words).toBe('B, note it'); + const line = run(f, 'gstack-approvals', ['rulings']).stdout.trim(); + expect(line).toContain('ruled by GBrain Minder (GBRA-108) (relayed from GBRA-108:2026-11-19T12:29:59Z) at '); + fs.rmSync(marker); + const body = path.join(f.root, 'relayed-body.md'); + fs.writeFileSync(body, `## Pre-Landing Review\n\n${line}\n`); + const write = f.run(path.join(BIN, 'gstack-ship-receipt'), ['write', '--pr', '7', '--base', 'main', '--version', '1.0.0', '--session-kind', 'unattended', '--body', body], { GSTACK_APPROVALS_MIRROR: '0' }); + expect(write.status, write.stderr).toBe(0); + expect(fs.readFileSync(body, 'utf8')).toContain('"relayed": "GBRA-108:2026-11-19T12:29:59Z"'); + }); +}); + diff --git a/test/ship-receipt-runs.test.ts b/test/ship-receipt-runs.test.ts index fb7bfd55c..1128acbc5 100644 --- a/test/ship-receipt-runs.test.ts +++ b/test/ship-receipt-runs.test.ts @@ -50,7 +50,8 @@ describe('READY tail (E1: the ready output is the whole READY)', () => { const depth = (cls: 'docs' | 'code' | 'gate', risk?: Array<'money' | 'auth' | 'secret' | 'security' | 'data'>) => ({ depth: 'full' as const, class: cls, runtime_lines: 10, rules: 'r', base: 'b', registry: null, gate_scan: { tagged: 0, head: 'h' }, reasons: [], ...(risk ? { risk } : {}) }); test('a risk-class receipt asks for the cross-family read; any other PR is self-audited', () => { - expect(readyTailLines({ ...receipt('f'.repeat(40)), review_depth: depth('gate') })[3]).toStartWith('reviewed by (risk class: gate;'); + expect(readyTailLines({ ...receipt('f'.repeat(40)), review_depth: depth('gate') })[3]).toStartWith('MISSING: cross-family trail read (risk class: gate; rule 27): ready did not look for one;'); + expect(readyTailLines({ ...receipt('f'.repeat(40)), review_depth: depth('gate') }, { trialMerges: ['TRIAL_MERGES: none share a file (3 open PRs checked)'], trailRead: { row: 7, reader: 'openai/gpt-6.2-sol' } }).slice(1, 4)).toEqual(['TRIAL_MERGES: none share a file (3 open PRs checked)', 'Attention:', 'reviewed by openai/gpt-6.2-sol (risk class: gate; rule 27 cross-family trail read, trail row 7)']); expect(readyTailLines({ ...receipt('f'.repeat(40)), review_depth: depth('code', ['money']) })[3]).toContain('risk class: money'); expect(readyTailLines({ ...receipt('f'.repeat(40)), review_depth: depth('docs') })[3]).toBe('self-audited (not a risk class: no cross-family trail read)'); }); @@ -59,7 +60,7 @@ describe('READY tail (E1: the ready output is the whole READY)', () => { expect(lines[0]).toBe('REVIEW_LOOP: passes=2 blocking_found=3 deferred=0 noted=0 fixed=2 unrecorded=1 unbound=1'); expect(lines.slice(1, 3)).toEqual([expect.stringMatching(/^TRIAL_MERGES: /), 'Attention:']); expect(readyTailLines(undefined)[0]).toBe('REVIEW_LOOP: none in the receipt'); - expect(readyTailLines(receipt('f'.repeat(40)))[3]).toStartWith('reviewed by (risk class unknown: the receipt records no review_depth'); + expect(readyTailLines(receipt('f'.repeat(40)))[3]).toStartWith('MISSING: cross-family trail read (risk class unknown: the receipt records no review_depth; rule 27)'); }); }); diff --git a/test/ship-release.test.ts b/test/ship-release.test.ts index c74bf309d..c68bde1f1 100644 --- a/test/ship-release.test.ts +++ b/test/ship-release.test.ts @@ -6,6 +6,7 @@ import { afterEach, describe, expect, setDefaultTimeout, test } from 'bun:test'; import * as fs from 'node:fs'; import * as path from 'node:path'; +import { finishPlanLine } from '../lib/plan-record'; import { RESULT_CODES } from '../lib/result-codes'; import { BUMP_NEVER_KEY_VERSION } from '../lib/ship-policy'; import { lineOf, RELEASE, shipFixture, type ShipFx } from './helpers/ship-bin-fixture'; @@ -191,6 +192,7 @@ describe('finish (Steps 15-16)', () => { expect(ok.stdout.split('\n')[0]).toBe('PLAN: exempt bug fix'); expect(ok.stdout).toMatch(/^COMMIT: /m); expect(ok.status).toBe(0); + expect(finishPlanLine(f.work, f.git('branch', '--show-current').stdout.trim(), f.git('rev-parse', 'HEAD').stdout.trim())).toBe('Plan: exempt: bug fix'); }); // Value: protects=under changelog_fragments the branch's own fragment is release metadata: version writes nothing and names it in NEXT, finish commits it as the release commit and the route counts it as metadata, and another fragment is still a feature file; fails_when=finish stops on changelog.d/.md or routes it to re-review (/ship #3648 fix-check 4, CRITICAL);