READY prints real trial merges and the second-model trail read, plus six small ship-tool fixes (GST-3200) (#4529)

READY now prints each open PR's trial-merge result and the reader of the
second-model trail read, or a loud MISSING line, instead of lines left
to fill in.

Why: agents dropped those lines as noise and skipped the trail read on
three gate-class PRs. Six more small ship-tool bugs from 2026-11-19
reports are fixed here too.

Nothing to do: pass `--trail ` to `gstack-ship-queue ready` on
risk-class PRs.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
Review-Finding: p1/outside-voice#1 reader=outside-voice
Review-Finding: p1/outside-voice#2 reader=outside-voice
Review-Finding: p1/outside-voice#3 reader=outside-voice
Review-Finding: p1/outside-voice#4 reader=outside-voice
Review-Finding: p1/outside-voice#5 reader=outside-voice
Review-Finding: p1/red-team#1 reader=red-team
Review-Finding: p1/adversarial-native#4 reader=adversarial-native
This commit is contained in:
Garry Tanandcapy-ai[bot] authored and GitHub committed 2026-11-19 17:05:16 +00:00
1 parent 50cc282273
commit 2714e9f7f3
36 files changed
+503 -68

No files matched your search

+11 -2
View File
@@ -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 <owner>:<branch>; 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 }); }
+2 -2
View File
@@ -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: <path> (<what>)` 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 } },
+33 -7
View File
@@ -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 <n> 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 brief's Plan line>"): 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; }
}
+5
View File
@@ -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 <thread code>:<message id or timestamp> --by <the owner> --words <their exact 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',
+2 -2
View File
@@ -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;
+1 -1
View File
@@ -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';
+22 -5
View File
@@ -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: `<thread code>:<message id or timestamp>`, 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:<owner ref>` 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 {
+42 -6
View File
@@ -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 <decisions.tsv>' };
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<typeof readyPlan> = 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<typeof readyPlan> = 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) {
+13 -6
View File
@@ -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> trail-read "<reader model>" <why> <evidence> <flags>, then rerun ready with --trail <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: <one line per open sibling pin that shares a file: its git merge-tree result and the resolution, or "none share a file">',
...(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 <model on another family> (risk class unknown: the receipt records no review_depth; rule 27 cross-family trail read)'
: risk ? `reviewed by <model on another family> (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,
'<flags against decision-trail row numbers, or No flags>',
];
}
+2 -1
View File
@@ -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<Repo
if (plan.failure) return new Report().add(plan.line!).stop(`${plan.failure.message} (${plan.failure.code}); fix: ${plan.failure.fix}`);
const r = await finishStages(argv, cwd);
if (plan.line) r.lines.unshift(plan.line);
if (r.exit === 0) recordFinishPlan(cwd, flag('--plan') ? plan.record : undefined);
const marker = r.exit === 0 && shipRunMarker(cwd);
if (marker) fs.rmSync(marker, { force: true });
return r;