Fix ready notes, landing decisions, release PR descriptions and squash messages (GST-3343) (#4596)

Landing a ready PR now reads its gate decisions from the PR's ready
note, and the ready note, a reopened release PR and a stacked PR's
squash message now say the right thing.

Each of these stopped a landing or left a wrong public record until
someone fixed it by hand; the goal is unattended shipping that lands on
its own.

Nothing to do as a reader.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
Review-Finding: p1/red-team#1 reader=red-team
This commit is contained in:
Garry Tanandcapy-ai[bot] authored and GitHub committed 2026-11-21 08:52:11 +00:00
1 parent b281effa07
commit 7fe1900f8b
18 files changed
+304 -42

No files matched your search

+1
View File
@@ -0,0 +1 @@
**Landing a ready PR no longer depends on a hand-copied gate decision, and the ready note, release PR and squash message say the right thing.** `gstack-ship-queue ready` now writes the signed, applied, non-security gate decisions into the PR's ready note, and landing reads them from there, so a decision recorded on the /ship machine reaches the landing machine without a hand copy; `--accept` still decides what lands. The ready note shows the decision trail's flags from its trail-read row instead of a placeholder, and calls a PR from a fork an outside PR rather than a sibling it trial-merged. Reopening a release PR now rewrites its description. When /ship's finish step left no plan line, the ready note writes the plan's public form, without the plan record's row. A stacked PR's squash message no longer repeats its parent's trailers. docs/ship-budget.md now says how to restart the budget meter for a stopped run whose ledger closed.
+3
View File
@@ -15,6 +15,7 @@ import { redactFindingSpans } from '../../lib/redact-engine';
import { git, sha256, writeJsonAtomic } from './ship-queue-gate';
import { resolveStateRoot } from '../../lib/state-root';
import type { PlanRecord } from '../../lib/plan-record';
import type { ApprovalRow } from '../../lib/approval-record';
export const TRAIN_SCHEMA = 1;
export const NOTES_REF = 'refs/notes/gstack-trains';
@@ -120,6 +121,8 @@ export interface ReadyReceipt {
base_red?: BaseRedCondition; fixes_base_red?: string[];
/** The PR body's Plan line as ready resolved it (lib/plan-record.ts); absent before plan_record or when it did not resolve. */
plan?: PlanRecord;
/** The signed non-security gate disposition rows ready's store applied at the head, for a lander on another machine (lib/gate-dispositions.ts). */
gate_dispositions?: ApprovalRow[];
}
/** One release-gate bisect round (crew/lib/release-gate.ts): the prefixes it dispatched on release-gate/<id> and what each case did there. */
export interface ReleaseBisectRound { nonce: string; ref: string; run: { id: number; url: string } | null; prefixes: Array<{ sha: string; results: Record<string, PrefixResult> }> }
+16
View File
@@ -309,6 +309,22 @@ change `resume --run <id>` restores both. A corrupt ledger
([BUDGET_LEDGER_INVALID](troubleshooting.md#budget-ledger-invalid)) is rebuilt from the
record's block with `--rebuild-from-record`; open reservations are then charged as unknown.
### A stopped run whose ledger is closed
A /ship run that stopped after its ledger closed (the run's last step closes it) can't be resumed:
`resume` refuses with `run <id> is closed`. To continue that run's remaining steps, open a new
observe ledger on the same record:
```bash
gstack-ship-budget start --record <record> --mode observe --reading <cost.tokens>
```
`start` reuses a record's ledger only while it is open, so on a closed one it mints a new run id
and ledger for the same record and prints its `BUDGET_RUN:` line. The new ledger meters from its own
first reading: spend under the closed ledger stays in that ledger and is not carried into the new
one, so add the two when you report what the run cost. On Capy, `--reading` is the thread's
`cost.tokens`; without a reading the start is unmetered.
### Successor handoff
When another thread takes over a /ship run (a successor handoff, routine under the 75%-of-hard-stop
+10 -2
View File
@@ -1961,8 +1961,16 @@ merges one only when the lander passes `--accept-gate-disposition <approval id>`
for it.
Land works the dispositions out again at the pin from the PR branch's approval
store: the local record and its mirror. A lander on another machine reads the
mirror the owner recorded into, so set `GSTACK_APPROVALS_DIR` to that directory
store: the local record and its mirror, plus the rows `ready` copied into the
READY note. The store lives on the machine that recorded the row, often the
/ship machine, so `ready` copies each disposition it applies at the head into the
READY note on `refs/notes/gstack-trains`, signed and whole, and land on any
machine reads those rows beside its own store under the same checks: the
writer's fields, the digest, the PR's branch and the head in the pin's history.
An edited note row counts for nothing, and the lander still accepts each one
explicitly (#4581). A security-class disposition stays out of the note, because
the notes ref is public, so for one of those a lander on another machine reads
the mirror the owner recorded into: set `GSTACK_APPROVALS_DIR` to that directory
when it isn't the default. Land counts every disposition whose head the pin
contains. In a full clone, a row whose head commit is gone (the branch was
rewritten and garbage-collected, or the name reused) doesn't apply, because the
+5 -3
View File
@@ -6360,9 +6360,11 @@ receipt's `gate_dispositions`, or the PR body's `Gate disposition:` lines, diffe
from the store (`ready` refuses those too). Nothing was merged. The
`GATE_DISPOSITION:` lines above the refusal are what the store holds at the pin;
the receipt and the body aren't trusted for this, because the lane writes them.
A receipt id the store lacks usually means this lander reads another
`GSTACK_STATE_ROOT` or approvals mirror than the owner recorded into, or that the row
was removed after the receipt was written. A pin missing from the clone, a shallow
Land also reads the signed non-security rows `ready` copied into the READY note at
the pin, under the same checks. A receipt id the store lacks usually means this
lander reads another `GSTACK_STATE_ROOT` or approvals mirror than the owner recorded
into (security-class rows never go in the note), or that the row was removed after
the receipt was written. A pin missing from the clone, a shallow
clone that can't prove whether a row's head is in the pin's history, and any other
git error while checking a head also refuse here. In a full clone, a row whose head
commit is gone after a rewrite and gc just doesn't apply.
+4 -2
View File
@@ -1097,9 +1097,11 @@ opening line is not. The reader's read is a trail row with phase `trail-read`
whose decision names the reader (`gstack-decision-trail <file> trail-read
"openai/gpt-6.2-sol (Subagent 4)" <why> <evidence> <flags>`).
`gstack-ship-queue ready --trail <file>` prints the opening line from that row
for a risk-class receipt, or `MISSING: cross-family trail read` when the trail
for a risk-class receipt, then that row's flags (`Flags (trail row <n>): …`, or
`No flags (trail row <n>)`), 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
`git merge-tree` at both heads. A PR from a fork is labelled as an outside PR
and never fetched or merged. `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.
+15 -9
View File
@@ -10,7 +10,9 @@
* the writer's hash reproduces) and its `digest` over those fields, so a hand-typed or edited row is ignored. The digest catches
* edits; it is not authentication: a same-user lane can compute it too. What authorizes a disposition is the lander's explicit
* `--accept-gate-disposition <id>` (`gateAcceptance`, run by `gstack-ship-queue land --pin` and `verify --pin`), re-derived from
* the store at the pin, never from the receipt or the PR body (docs/ship-policy.md#gate-dispositions).
* the store at the pin, never from the receipt or the PR body (docs/ship-policy.md#gate-dispositions). A store lives on the machine
* that recorded the row, so `ready` also copies each applied non-security row, signed and whole, into the READY note on the
* notes ref, and a lander on another machine reads those rows beside its own store under the same checks (#4581).
*/
import { createHash } from 'node:crypto';
import { spawnSync } from './spawn-sync';
@@ -80,7 +82,7 @@ export function readGateDispositions(cwd: string, env: Env = process.env): GateD
* full clone a row whose head commit is gone (a rewritten and collected branch, a reused name) is not applied: the pin's history
* is all present, so a missing commit cannot be in it.
*/
export function appliedGateDispositions(cwd: string, o: { branch?: string; pin: string; env?: Env }): { applied: GateDisposition[]; loc: StoreLocation } {
export function appliedGateDispositions(cwd: string, o: { branch?: string; pin: string; env?: Env; noted?: readonly ApprovalRow[] }): { applied: GateDisposition[]; rows: ApprovalRow[]; loc: StoreLocation } {
const loc = locate({ cwd, env: o.env ?? process.env, branch: o.branch });
if ('code' in loc) throw new Error(loc.message);
const git = (...args: string[]) => spawnSync('git', args, { cwd, encoding: 'utf8', timeout: 10_000 });
@@ -94,7 +96,10 @@ export function appliedGateDispositions(cwd: string, o: { branch?: string; pin:
if (r.status === 1 || git('cat-file', '-e', `${head}^{commit}`).status !== 0) return false;
throw new Error(`git merge-base --is-ancestor ${head.slice(0, 12)} ${o.pin.slice(0, 12)} failed (${(r.stderr ?? r.error?.message ?? '').trim().slice(0, 120) || `exit ${r.status}`})`);
};
return { applied: gateDispositions(readRecord(loc).rows, loc.branch).filter(d => contains(d.head)), loc };
const byId = new Map([...(o.noted ?? []), ...readRecord(loc).rows].map(r => [r.id, r]));
const rows = [...byId.values()].sort((a, b) => String(a.recorded_at).localeCompare(String(b.recorded_at)));
const applied = gateDispositions(rows, loc.branch).filter(d => contains(d.head));
return { applied, rows: applied.map(d => byId.get(d.approval)!), loc };
}
/**
@@ -158,18 +163,19 @@ export type GateAcceptanceCode = Extract<ResultCodeName, 'QUEUE_GATE_DISPOSITION
* receipt's gate_dispositions or the PR body's `Gate disposition:` lines differ from them, and, with `accepted` (land and
* verify; ready passes none), when an applied disposition is not accepted or an accepted id is not applied.
*/
export function gateAcceptance(o: { cwd: string; branch: string; pin: string; body: string; receipt?: ShipReceipt; accepted?: readonly string[]; env?: Env }):
{ lines: string[]; applied: GateDisposition[]; failure?: { code: GateAcceptanceCode; message: string; fix: string } } {
export function gateAcceptance(o: { cwd: string; branch: string; pin: string; body: string; receipt?: ShipReceipt; accepted?: readonly string[]; env?: Env; noted?: readonly ApprovalRow[] }):
{ lines: string[]; applied: GateDisposition[]; noteRows?: ApprovalRow[]; failure?: { code: GateAcceptanceCode; message: string; fix: string } } {
const fix = 'the lander reads each GATE_DISPOSITION line and reruns with --accept-gate-disposition <approval id> for each one it accepts; a receipt or body that differs from the store is rewritten by /ship at the pin (docs/troubleshooting.md#queue-gate-disposition)';
let got: ReturnType<typeof appliedGateDispositions>;
try { got = appliedGateDispositions(o.cwd, o); }
catch (e: any) { return { lines: [], applied: [], failure: { code: 'QUEUE_GATE_DISPOSITION', message: `the gate dispositions for ${o.branch} at the pin cannot be derived (${e.message}); an unreadable store or a git error refuses, never reads as none`, fix } }; }
const { applied, loc } = got;
const noteRows = got.rows.filter(r => !isSecurityFinding(SCOPE.exec(r.scope)![1]!));
const recorded = o.receipt?.gate_dispositions;
const listed = recorded ?? [];
const where = `the store at ${loc.mirror ?? loc.file}`;
const where = `the store at ${loc.mirror ?? loc.file}${o.noted?.length ? ' with the READY note\'s rows' : ''}`;
const lines = applied.map(d => `GATE_DISPOSITION: ${gateDispositionText(d)}`);
if (!applied.length && !listed.length && !o.accepted?.length) return { lines, applied };
if (!applied.length && !listed.length && !o.accepted?.length) return { lines, applied, noteRows };
const problems: string[] = [];
for (const d of applied) {
const r = listed.find(l => l.approval === d.approval);
@@ -182,8 +188,8 @@ export function gateAcceptance(o: { cwd: string; branch: string; pin: string; bo
for (const d of applied) if (!o.accepted.includes(d.approval)) problems.push(`disposition ${d.approval} is not accepted (--accept-gate-disposition ${d.approval})`);
for (const id of o.accepted) if (!applied.some(d => d.approval === id)) problems.push(`--accept-gate-disposition ${id} names no disposition the store applies at ${o.pin.slice(0, 12)}`);
}
lines.push(`GATE_DISPOSITIONS: applied=${applied.map(d => d.approval).join(',') || 'none'}${o.accepted ? ` accepted=${o.accepted.join(',') || 'none'}` : ''} store=${loc.mirror ?? loc.file}`);
return problems.length ? { lines, applied, failure: { code: 'QUEUE_GATE_DISPOSITION', message: problems.join('; '), fix } } : { lines, applied };
lines.push(`GATE_DISPOSITIONS: applied=${applied.map(d => d.approval).join(',') || 'none'}${o.accepted ? ` accepted=${o.accepted.join(',') || 'none'}` : ''} store=${loc.mirror ?? loc.file}${o.noted?.length ? ` ready_note_rows=${o.noted.length}` : ''}`);
return problems.length ? { lines, applied, noteRows, failure: { code: 'QUEUE_GATE_DISPOSITION', message: problems.join('; '), fix } } : { lines, applied, noteRows };
}
/** The disposition as public text may carry it: a security-class finding's fingerprint, reason and owner words stay in the approval record (GST-3076). */
+8 -1
View File
@@ -246,7 +246,14 @@ export function readyPlan(o: { cwd: string; env: Env; body: string; policyValue?
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);
const mark = (res: PlanResolution): PlanResolution => {
if (!fromFinish || !res.ok) return res;
const { row_id, ...rest } = res.record;
const record: PlanRecord = rest.state === 'approved'
? { ...rest, line: publicPlanLine(fromFinish, res), ref: RECORD_ID.test(rest.ref ?? '') ? rest.ref : planRecordId(row_id!), from: 'finish' }
: { ...rest, line: `Plan: exempt: ${rest.reason}`, from: 'finish' };
return { ok: true, record, summary: `${res.summary} (from /ship finish's plan record; the PR body has no Plan: line)` };
};
if (mode.mode === 'off') {
const note = offNote(mode);
const line = note ? { line: note } : {};
+15 -3
View File
@@ -123,7 +123,7 @@ const defaultGh = (args: string[], cwd: string) => {
/**
* Stamp a fresh worktree of origin/<base> with gstack-restamp --release, commit only the stamped files (detached, so no
* local branch is left behind), force-push the commit to release/<version> (a reopen after RELEASE_STAMP_INVALID
* replaces the old release branch) and open the release PR. The Captain lands it with gstack-ship-queue land --pr <n> --pin <head> once its
* replaces the old release branch) and open the release PR, or on a reopen rewrite the open PR's body to the new stamp's. The Captain lands it with gstack-ship-queue land --pr <n> --pin <head> once its
* checks are green; the stable cut then tags the new version. --dry-run stamps and prints the diff, and creates nothing.
*/
export function openRelease(o: OpenOptions): OpenResult {
@@ -168,7 +168,8 @@ export function openRelease(o: OpenOptions): OpenResult {
].join('\n'));
const posted = foldSections(body);
const open = gh(['pr', 'list', '--head', branch, '--state', 'open', '--json', 'url,isCrossRepository', '--jq', '[.[] | select(.isCrossRepository | not)][0].url // ""'], dir);
if (!(open.ok && open.out.trim()) && hostPublishes(o.env)) {
const reopened = open.ok && !!open.out.trim();
if (!reopened && hostPublishes(o.env)) {
const view = gh(['repo', 'view', '--json', 'nameWithOwner,url'], dir);
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; }
@@ -176,8 +177,19 @@ export function openRelease(o: OpenOptions): OpenResult {
lines.push(handOff({ op: 'pr-create', ...dest, base: o.base, head: branch, parts: [['title', `v${version} release`], ['body', posted]], env: o.env }).trimEnd(), `NEXT: gstack-ship-queue land --pr <n> --pin ${head} once the PR the host opens has green checks`);
return { ok: true, version, branch, head, lines };
}
const pr = open.ok && open.out.trim() ? open : gh(['pr', 'create', '--base', o.base, '--head', branch, '--title', `v${version} release`, '--body', posted], dir);
const pr = reopened ? open : gh(['pr', 'create', '--base', o.base, '--head', branch, '--title', `v${version} release`, '--body', posted], dir);
if (!pr.ok) return fail('RELEASE_STAMP_INVALID', `gh pr create failed (${pr.err.trim().split('\n')[0]}); ${branch} is pushed, so open its PR by hand`);
if (reopened && hostPublishes(o.env)) {
const view = gh(['repo', 'view', '--json', 'nameWithOwner,url'], dir);
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 fail('RELEASE_STAMP_INVALID', `cannot resolve the repository the release PR belongs to (gh repo view --json nameWithOwner,url: ${view.err.trim().split('\n')[0] || 'no repository'}); ${branch} is pushed with the new stamp, but its PR still has the old body, so replace the body with the host's PR tool`);
const target = /\/pull\/(\d+)/.exec(pr.out.trim().split('\n').pop() ?? '')?.[1];
lines.push(handOff({ op: 'pr-body', target, ...dest, parts: [['body', posted]], env: o.env }).trimEnd());
} else if (reopened) {
const edit = gh(['pr', 'edit', pr.out.trim().split('\n').pop() ?? '', '--body', posted], dir);
if (!edit.ok) return fail('RELEASE_STAMP_INVALID', `gh pr edit failed (${edit.err.trim().split('\n')[0]}); ${branch} is pushed with the new stamp, but its PR still has the old body, so replace the body by hand`);
}
const url = pr.out.trim().split('\n').pop() ?? '';
const n = /\/pull\/(\d+)/.exec(url)?.[1];
lines.push(`RELEASE_PR: ${n ? `#${n} ` : ''}${url}`, `NEXT: gstack-ship-queue land --pr ${n ?? '<n>'} --pin ${head} once its checks are green`);
+6 -3
View File
@@ -37,14 +37,16 @@ export interface DirectOptions { pr: string; pin: string; body?: string; dryRun?
/**
* The pin's /ship receipt bound to it, and every owner gate disposition the approval store applies at the pin accepted by the
* lander (lib/gate-dispositions.ts gateAcceptance, re-derived from the store, never from the receipt or the body): the one
* check land --pin and verify --pin share, so the two cannot drift (docs/ship-policy.md#gate-dispositions).
* lander (lib/gate-dispositions.ts gateAcceptance, re-derived from the store and the signed rows ready copied into the READY note at
* the pin, never from the receipt or the body): the one check land --pin and verify --pin share, so the two cannot drift
* (docs/ship-policy.md#gate-dispositions).
*/
export function pinAcceptance(ctx: QueueContext, info: Pick<DirectPr, 'body' | 'headRefName'>, pr: string, pin: string, accepted: readonly string[]): { lines: string[]; failure?: QueueFailure } {
const receipt = bindShippedReceipt(ctx.repoRoot, `origin/${ctx.base}`, info.body ?? '', pr, [pin]);
const lines = [receipt.line, ...(receipt.depthLine ? [receipt.depthLine] : []), ...(receipt.targetedLine ? [receipt.targetedLine] : [])];
if (!receipt.ok) return { lines, failure: { code: receipt.code, message: receipt.message, fix: `run /ship at the pin, then gstack-ship-queue ready --pr ${pr}` } };
const gates = gateAcceptance({ cwd: ctx.repoRoot, branch: info.headRefName, pin, body: info.body ?? '', receipt: receipt.receipt, accepted });
const noted = loadReady(repoIdentity(ctx.repoRoot).keys, pr, pin)?.gate_dispositions;
const gates = gateAcceptance({ cwd: ctx.repoRoot, branch: info.headRefName, pin, body: info.body ?? '', receipt: receipt.receipt, accepted, noted });
return { lines: [...lines, ...gates.lines], ...(gates.failure ? { failure: gates.failure } : {}) };
}
@@ -64,6 +66,7 @@ export function verifyPin(ctx: QueueContext, o: { pr: string; pin: string; accep
if (info.state !== 'OPEN') return fail(lines, { code: 'QUEUE_NOT_READY', message: `#${o.pr} is ${info.state}` });
if (info.headRefOid !== o.pin) return fail(lines, { code: 'QUEUE_LAND_PIN_MOVED', message: `#${o.pr}'s head is ${info.headRefOid.slice(0, 12)}, not the pin ${o.pin.slice(0, 12)}` });
if (!havePin(root, o.pr, o.pin, info.headRefName)) return fail(lines, { code: 'QUEUE_NOT_READY', message: `cannot fetch the pin ${o.pin.slice(0, 12)} from ${info.headRefName} or refs/pull/${o.pr}/head`, fix: 'fix the fetch, then rerun verify' });
rebuildFromNotes(root, ctx.remote ?? 'origin');
const accepted = pinAcceptance(ctx, info, o.pr, o.pin, o.acceptGateDispositions);
lines.push(...accepted.lines);
if (accepted.failure) return fail(lines, accepted.failure);
+8 -6
View File
@@ -294,11 +294,12 @@ export function refreshBase(ctx: QueueContext): QueueFailure | null {
/**
* 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.
* merge-tree; one line per such PR, or a MISSING line when gh or the fetch cannot tell. A PR from a fork is an outside
* contribution, not a sibling lane: it is labelled and never fetched or merged (outside code is read as text only).
*/
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;
const list = ctx.gh(['pr', 'list', '--state', 'open', '--base', ctx.base, '--limit', '200', '--json', 'number,headRefOid,files,isCrossRepository']);
let open: Array<{ number: number; headRefOid: string; files?: Array<{ path: string }>; isCrossRepository?: boolean }> | 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);
@@ -308,6 +309,7 @@ export function trialMergeLines(ctx: QueueContext, pr: string, head: string, cha
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 (p.isCrossRepository) return `TRIAL_MERGES: ${at}: outside PR from a fork, not a sibling lane; not trial-merged (rule 19)`;
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]);
@@ -318,13 +320,13 @@ export function trialMergeLines(ctx: QueueContext, pr: string, head: string, cha
});
}
/** The newest row of a decision trail (gstack-decision-trail) whose phase is trail-read: its row number and the reader it names. */
/** The newest row of a decision trail (gstack-decision-trail) whose phase is trail-read: its row number, the reader it names and its result, the reader's flags. */
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() };
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(), flags: rows[i]![5]?.trim() ?? '' };
return { missing: `${file} has no trail-read row` };
}
@@ -417,7 +419,7 @@ export function ready(ctx: QueueContext, o: { pr: string; pregate?: string; gate
const repo = repoIdentity(ctx.repoRoot);
const now = nowIso();
const remote = ctx.remote ?? 'origin';
const p = persist(ctx.repoRoot, [{ schema: 1, kind: 'ready', repo_key: repo.key, pr: o.pr, head, base_sha: baseSha, ready_at: now, screen: { choice: 'no-screen', policy: null, nonce: null, run: null, merge_sha: null }, updated_at: now, ...(plan.record ? { plan: plan.record } : {}) }], { remote });
const p = persist(ctx.repoRoot, [{ schema: 1, kind: 'ready', repo_key: repo.key, pr: o.pr, head, base_sha: baseSha, ready_at: now, screen: { choice: 'no-screen', policy: null, nonce: null, run: null, merge_sha: null }, updated_at: now, ...(plan.record ? { plan: plan.record } : {}), ...(gates?.noteRows?.length ? { gate_dispositions: gates.noteRows } : {}) }], { remote });
lines.push(`READY_RECEIPT: ${readyPath(repo.key, o.pr, head)} (${p.detail})`);
if (!p.pushed) return fail({ ...readyNoteUnpushed(o.pr, head, remote, p.detail), fix: `fix the notes push to ${remote} (the READY_RECEIPT line ends with its error), then rerun gstack-ship-queue ready --pr ${o.pr} with the same flags` }, lines, run);
}
+10 -7
View File
@@ -230,12 +230,13 @@ export function receiptSummaryLine(r: ShipReceipt): string {
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 } }
export interface ReadyTail { trialMerges: string[]; trailRead: { row: number; reader: string; flags?: string } | { missing: string } }
/**
* 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.
* (docs/unattended.md): a risk-class PR with no trail-read row prints MISSING instead of a line to fill in. Its flags line is the
* trail-read row's result, and with no such row there is none: the lane lists its own audit's flags, never a template line.
*/
export function readyTailLines(r: ShipReceipt | undefined, t: ReadyTail = { trialMerges: [], trailRead: { missing: 'ready did not look for one' } }): string[] {
const loop = parseReviewLoop(r?.review_loop);
@@ -254,7 +255,7 @@ export function readyTailLines(r: ShipReceipt | undefined, t: ReadyTail = { tria
...(t.trialMerges.length ? t.trialMerges : ['TRIAL_MERGES: MISSING: ready did not check the open PRs that share a file (rule 14)']),
'Attention:',
reviewer,
'<flags against decision-trail row numbers, or No flags>',
...((legacy || risk) && 'row' in t.trailRead ? [/^(none|no flags?)?\.?$/i.test(t.trailRead.flags?.trim() ?? '') ? `No flags (trail row ${t.trailRead.row})` : `Flags (trail row ${t.trailRead.row}): ${oneLine(t.trailRead.flags!)}`] : []),
];
}
@@ -442,16 +443,18 @@ export const STACK_PARENT_WALK = 100;
* that squash-merged (or merged) into the base after the receipt was written against the base (GST-1199). A commit with no
* product change of its own (a test-first commit) is no parent, since any base trivially holds it, and neither is a commit
* rangeBase already held: a parent that landed before the review is part of the reviewed base, so measuring from it drops
* nothing and compares the wrong range (yc-software/qm#3457, GST-3315). Null when no
* commit within STACK_PARENT_WALK qualifies or git cannot tell; a conflicted product path is never held.
* nothing and compares the wrong range (yc-software/qm#3457, GST-3315). That last skip is for a reviewed range (the receipt check
* and Step 11.5); `reviewedRange` false drops it, for land's commit message, whose range starts at a merge base the child's merge of
* the base moved past its parent's squash. Null when no commit within STACK_PARENT_WALK qualifies or git cannot tell; a conflicted
* product path is never held.
*/
export function landedStackParent(repoRoot: string, s: { rangeBase: string; reviewed: string; currentBase: string }, product: readonly string[]): string | null {
export function landedStackParent(repoRoot: string, s: { rangeBase: string; reviewed: string; currentBase: string }, product: readonly string[], reviewedRange = true): string | null {
const run = (args: string[]) => spawnSync('git', args, { cwd: repoRoot, encoding: 'utf8', timeout: 120_000, maxBuffer: 64 * 1024 * 1024 });
const commits = run(['rev-list', '--topo-order', `--max-count=${STACK_PARENT_WALK + 1}`, `${s.rangeBase}..${s.reviewed}`]);
if (commits.status !== 0) return null;
for (const commit of commits.stdout.split('\n').filter(c => c && c !== s.reviewed)) {
if (run(['diff', '--quiet', s.rangeBase, commit, '--', ...product]).status !== 1) continue;
if (heldBy(repoRoot, commit, s.currentBase, product) && !heldBy(repoRoot, commit, s.rangeBase, product)) return commit;
if (heldBy(repoRoot, commit, s.currentBase, product) && !(reviewedRange && heldBy(repoRoot, commit, s.rangeBase, product))) return commit;
}
return null;
}
+7 -6
View File
@@ -33,11 +33,12 @@ export function openingLines(body: string): string {
return out.map(wrap).join('\n\n');
}
/** Every distinct trailer git's own parser finds on the non-merge commits in from..to, oldest first (the first spelling wins); null when git cannot read the range. */
export function branchTrailers(root: string, from: string, to: string): string[] | null {
const r = git(root, ['log', '--reverse', '--no-merges', '--format=%(trailers:only,unfold)', `${from}..${to}`]);
/** Every distinct trailer git's own parser finds on the non-merge commits reachable from `to` and from none of `from`, oldest first (the first spelling wins); null when git cannot read the range. */
export function branchTrailers(root: string, from: string | readonly string[], to: string): string[] | null {
const range = [...[from].flat().map(f => `^${f}`), to];
const r = git(root, ['log', '--reverse', '--no-merges', '--format=%(trailers:only,unfold)', ...range]);
if (r.status !== 0) return null;
const authors = git(root, ['log', '--reverse', '--no-merges', '--format=%an <%ae>', `${from}..${to}`]);
const authors = git(root, ['log', '--reverse', '--no-merges', '--format=%an <%ae>', ...range]);
if (authors.status !== 0) return null;
const others = authors.stdout.split('\n').filter(Boolean).filter((a, _, all) => a !== all[0]).map(a => `Co-authored-by: ${a}`);
const seen = new Map<string, string>();
@@ -61,8 +62,8 @@ export function landMethod(root: string, policy: Pick<ShipPolicy, 'history' | 'l
* Refuses (error) when git cannot read the branch's commits or the message holds a HIGH redaction finding.
*/
export function landMessage(root: string, o: { pr: string; title: string; prBody: string; mergeBase: string; pin: string; tip: string; policy: Pick<ShipPolicy, 'history' | 'land'>; override?: string; visibility?: RepoVisibility }): LandMessage | { error: string } {
const parent = landedStackParent(root, { rangeBase: o.mergeBase, reviewed: o.pin, currentBase: o.tip }, ['.']);
const trailers = branchTrailers(root, parent ?? o.mergeBase, o.pin);
const parent = landedStackParent(root, { rangeBase: o.mergeBase, reviewed: o.pin, currentBase: o.tip }, ['.'], false);
const trailers = branchTrailers(root, parent ? [o.mergeBase, parent] : o.mergeBase, o.pin);
if (!o.title.trim()) return { error: `#${o.pr} has no title to use as the commit subject` };
if (!trailers) return { error: `git cannot read #${o.pr}'s commits ${(parent ?? o.mergeBase).slice(0, 12)}..${o.pin.slice(0, 12)}` };
const subject = `${o.title.trim()} (#${o.pr})`;
+17
View File
@@ -416,6 +416,23 @@ describe('bug-fix exemption wording and the plan finish recorded (GSTA-649, GSTA
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();
});
// Value: protects=the READY note, which rides a public notes ref, never carries finish's raw --plan text: an approved line keeps only
// the opaque record id, an exempt line only its listed reason; fails_when=a local run path, a row id or a note in parentheses
// reaches the note's plan record; why_new=#4529 final review (GST-1955 family); seam=readyPlan's finish fallback, landPlan
test('the plan record finish supplies is redacted before it reaches the READY note (#4529)', () => {
const f = fixture({ y: [{ ask: 'R41 A1: cut a skill' }] });
const env = { ...f.env, GSTACK_PLAN_RECORD: 'require' };
const rowId = f.ids['R41 A1: cut a skill']!;
const approved = readyPlan({ cwd: f.cwd, env, body: 'Fixes a thing.', changed: ['lib/x.ts'], finishLine: `Plan: approved: ${rowId}` });
expect(approved.record).toMatchObject({ line: `Plan: approved (record ${planRecordId(rowId)})`, ref: planRecordId(rowId), state: 'approved', from: 'finish' });
expect(JSON.stringify(approved.record)).not.toContain(rowId);
expect(landPlan({ env, record: approved.record, body: 'Fixes a thing.' }).failure).toBeUndefined();
const exempt = readyPlan({ cwd: f.cwd, env, body: 'Fixes a thing.', changed: ['lib/x.ts'], finishLine: 'Plan: exempt: bug fix (see /home/user/.capy/work/ship-4529/run)' });
expect(exempt.record).toMatchObject({ line: 'Plan: exempt: bug fix', reason: 'bug fix', from: 'finish' });
expect(JSON.stringify(exempt.record)).not.toContain('/home/user');
const own = readyPlan({ cwd: f.cwd, env, body: `Plan: approved: ${rowId}`, changed: ['lib/x.ts'] });
expect(own.record).toMatchObject({ line: `Plan: approved: ${rowId}`, row_id: rowId });
});
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' };
+35
View File
@@ -204,6 +204,41 @@ describe('gstack-release-stamp open', () => {
expect(repo.git('branch', '--list', 'release/*')).toBe('');
});
// Value: protects=a reopen that force-pushes a new stamp also rewrites the open release PR's body, so its change count, notes, base and
// land pin match the pushed head; fails_when=the open PR keeps the old body (GSTA-677 on #4573); seam=openRelease with a gh stub
test('reopening at a moved base rewrites the open release PR\'s body to the new stamp', () => {
const repo = landed();
const calls: string[][] = [];
const r = openRelease({ repoRoot: repo.work, base: 'main', gh: (args) => { calls.push(args); return { ok: true, out: 'https://github.com/o/r/pull/44\n', err: '' }; } });
expect(r.ok).toBe(true);
if (!r.ok) return;
expect(calls.map(a => a.slice(0, 3))).toEqual([['pr', 'list', '--head'], ['pr', 'edit', 'https://github.com/o/r/pull/44']]);
const body = calls[1]![calls[1]!.indexOf('--body') + 1]!;
expect(body).toContain(`--pin ${r.head}`);
expect(sectionText(body, 'Release notes')).toBe('- a change\n- b feature');
const refused = openRelease({ repoRoot: repo.work, base: 'main', now: new Date('2030-01-02T00:00:00Z'), gh: (args) => (args[1] === 'edit' ? { ok: false, out: '', err: 'HTTP 502' } : { ok: true, out: 'https://github.com/o/r/pull/44\n', err: '' }) });
expect(refused).toMatchObject({ ok: false, code: 'RELEASE_STAMP_INVALID' });
});
test('on Capy, a reopen hands the new body to the host tool without gh pr edit', () => {
const repo = landed();
const state = fs.mkdtempSync(path.join(repo.work, '..', 'state-'));
const calls: string[][] = [];
const r = openRelease({ repoRoot: repo.work, base: 'main', env: { GSTACK_CAPY: '1', GSTACK_STATE_ROOT: state }, gh: (args) => {
calls.push(args);
if (args[0] === 'repo') return { ok: true, out: JSON.stringify({ nameWithOwner: 'o/r', url: 'https://github.com/o/r' }), err: '' };
return { ok: true, out: 'https://github.com/o/r/pull/44\n', err: '' };
} });
expect(r.ok).toBe(true);
if (!r.ok) return;
expect(calls.map(a => a.slice(0, 2).join(' '))).toEqual(['pr list', 'repo view']);
const handed = r.lines.find(l => l.startsWith('HOST_PUBLISH: '))!;
expect(handed).toStartWith('HOST_PUBLISH: pr-body 44 repo=o/r');
const body = fs.readFileSync(/ body-file=(\S+)/.exec(handed)![1]!, 'utf8');
expect(body).toContain(`--pin ${r.head}`);
expect(r.lines).toContain('RELEASE_PR: #44 https://github.com/o/r/pull/44');
});
test('--dry-run creates nothing; an empty base is refused', () => {
const repo = landed();
const dry = openRelease({ repoRoot: repo.work, base: 'main', dryRun: true, gh: () => { throw new Error('no gh in a dry run'); } });
+59
View File
@@ -1329,6 +1329,65 @@ describe('land --pin and verify --pin accept owner gate dispositions (GST-2491)'
expect(gateLines(landed.out)[1]).toContain(`accepted=${id}`);
}, 180_000);
// Value: protects=a disposition recorded on the /ship machine reaches a lander on another machine through the READY note, still
// only by the lander's explicit acceptance, and a note row edited after ready wrote it counts for nothing; fails_when=land on a
// machine without the store refuses QUEUE_GATE_DISPOSITION (#4581 needed GSTACK_APPROVALS_DIR pointed at a hand copy), lands an
// unaccepted disposition, or trusts an edited note row; seam=ready's note and pinAcceptance; no_claim=a security-class row, which
// stays store-only so the public notes ref never carries its words
test('#4581: land on a machine without the store reads the signed row ready copied into the READY note', () => {
const fx = prep();
const head = openPr(fx, '44', { ready: false });
fx.repo.git('checkout', '-q', 'pr-44');
const rec = record(fx, '44', head);
expect(rec.status, rec.err).toBe(0);
const id = rec.out.split(' ')[1]!;
const ds = applied(fx, '44', head);
setBody(fx, '44', bodyWith('44', head, ds));
const pregate = path.join(fx.repo.root, 'pregate.json');
fs.writeFileSync(pregate, JSON.stringify({ schema_version: 1, tree: runBin(fx.repo, 'gstack-wtree', []).out.trim(), head, verdict: 'pass', checks: FULL_CHECKS }));
const ready = runBin(fx.repo, 'gstack-ship-queue', ['ready', '--pr', '44', '--pregate', pregate, '--base', 'main'], fx.env);
expect(ready.status, ready.out + ready.err).toBe(EXIT.ok);
fx.repo.git('checkout', '-q', '--detach', 'origin/main');
const elsewhere = { ...fx.env, GSTACK_STATE_ROOT: path.join(fx.repo.root, 'lander-state') };
const landAt = (env: Record<string, string>, extra: string[] = []) => runBin(fx.repo, 'gstack-ship-queue', ['land', '--pr', '44', '--pin', head, '--base', 'main', ...extra], env);
expect(appliedGateDispositions(fx.repo.work, { branch: 'pr-44', pin: head, env: { ...storeEnv(fx), GSTACK_STATE_ROOT: elsewhere.GSTACK_STATE_ROOT } }).applied).toEqual([]);
const bare = landAt(elsewhere);
expect([bare.status, bare.err]).toEqual([EXIT.refused, expect.stringContaining(`disposition ${id} is not accepted`)]);
expect(gateLines(bare.out)[0]).toBe(`GATE_DISPOSITION: ${gateDispositionText(ds[0]!)}`);
expect(gateLines(bare.out)[1]).toContain('ready_note_rows=1');
const landed = landAt(elsewhere, ['--accept-gate-disposition', id]);
expect(landed.status, landed.out + landed.err).toBe(EXIT.ok);
expect(landed.out).toContain('MERGED: #44 as ');
}, 180_000);
test('#4581: an edited READY note row counts for nothing, so land elsewhere still refuses', () => {
const fx = prep();
const head = openPr(fx, '45', { ready: false });
const rec = record(fx, '45', head);
expect(rec.status, rec.err).toBe(0);
const loc = locate({ cwd: fx.repo.work, env: storeEnv(fx), branch: 'pr-45' }) as StoreLocation;
const row = JSON.parse(fs.readFileSync(loc.file, 'utf8').trim().split('\n').at(-1)!) as ApprovalRow;
const edited = { ...row, ask: row.ask.replace(REASON, 'the gate is fine') };
const env = { ...storeEnv(fx), GSTACK_STATE_ROOT: path.join(fx.repo.root, 'lander-state') };
expect(appliedGateDispositions(fx.repo.work, { branch: 'pr-45', pin: head, env, noted: [edited] }).applied).toEqual([]);
expect(appliedGateDispositions(fx.repo.work, { branch: 'pr-45', pin: head, env, noted: [row] }).applied.map(d => d.approval)).toEqual([row.id]);
const other = appliedGateDispositions(fx.repo.work, { branch: 'pr-46', pin: head, env, noted: [row] }).applied;
expect(other).toEqual([]);
}, 120_000);
test('#4581: a newer store row for the same finding wins over an older READY note row', () => {
const fx = prep();
const head = openPr(fx, '47', { ready: false });
expect(record(fx, '47', head).status).toBe(0);
const loc = locate({ cwd: fx.repo.work, env: storeEnv(fx), branch: 'pr-47' }) as StoreLocation;
const older = JSON.parse(fs.readFileSync(loc.file, 'utf8').trim().split('\n').at(-1)!) as ApprovalRow;
const again = runBin(fx.repo, 'gstack-approvals', ['gate', '--branch', 'pr-47', '--finding', F, '--gate-id', G, '--head', head, '--reason', 'owner re-ruled after ready', '--words', 'Do it', '--by', 'Founderstar Captain (FOUN-1)'], fx.env);
expect(again.status, again.err).toBe(0);
const newer = JSON.parse(fs.readFileSync(loc.file, 'utf8').trim().split('\n').at(-1)!) as ApprovalRow;
expect(newer.id).not.toBe(older.id);
expect(appliedGateDispositions(fx.repo.work, { branch: 'pr-47', pin: head, env: storeEnv(fx), noted: [older] }).applied.map(d => d.approval)).toEqual([newer.id]);
}, 120_000);
test('a row the lane appends to the store by hand, digest and all, still needs the lander: land refuses and prints it, a wrong id refuses, and the accepted id lands', () => {
const fx = prep();
const head = openPr(fx, '42');
+64
View File
@@ -0,0 +1,64 @@
/**
* The READY tail's last two template gaps (#4529, #4575, #4578): the Attention section printed
* "<flags against decision-trail row numbers, or No flags>" for the lane to fill, and TRIAL_MERGES listed outside fork PRs such as
* #4499 as conflicts a lane must resolve. The flags line now comes from the trail-read row's result, and a fork PR is labelled and
* never fetched or merged.
*/
import { afterEach, describe, expect, test } from 'bun:test';
import { spawnSync } from 'node:child_process';
import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
import { trailReadRow, trialMergeLines } from '../lib/ship-queue';
import type { ShipReceipt } from '../lib/headless-artifacts';
import { readyTailLines } from '../lib/ship-receipt';
const dirs: string[] = [];
afterEach(() => { while (dirs.length) fs.rmSync(dirs.pop()!, { recursive: true, force: true }); });
const tmp = () => { const d = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-ready-tail-')); dirs.push(d); return d; };
const HEADER = 'ts\tphase\tdecision\twhy\tevidence\tresult\n';
const trail = (rows: string[]) => { const f = path.join(tmp(), 'decisions.tsv'); fs.writeFileSync(f, HEADER + rows.map(r => r + '\n').join('')); return f; };
const READ = (flags: string) => `2026-11-20T00:01:00Z\ttrail-read\topenai/gpt-6.2-sol (Subagent 4)\trule 27\tflags.md\t${flags}`;
const GATE = { review_depth: { class: 'gate', risk: [] } } as unknown as ShipReceipt;
const CODE = { review_depth: { class: 'code', risk: [] } } as unknown as ShipReceipt;
const attention = (r: ShipReceipt, file?: string) => { const l = readyTailLines(r, { trialMerges: ['TRIAL_MERGES: none share a file (0 open PRs checked)'], trailRead: trailReadRow(file) }); return l.slice(l.indexOf('Attention:') + 1); };
describe('the Attention flags line comes from the trail (#4529)', () => {
// Value: protects=READY never prints the flags placeholder: a risk-class PR prints the trail-read row's flags against its row number
// and a self-audited PR prints only its opener; fails_when=the placeholder line comes back or a flag is dropped; why_new=lanes
// pasted the placeholder on #4529, #4575 and #4578; seam=trailReadRow and readyTailLines as ready calls them
test('a trail-read row\'s flags, or No flags, against its row; no line without a row or on a self-audited PR', () => {
expect(attention(GATE, trail([READ('rows 4 and 7: retry claimed without a log')]))).toEqual([
'reviewed by openai/gpt-6.2-sol (Subagent 4) (risk class: gate; rule 27 cross-family trail read, trail row 1)',
'Flags (trail row 1): rows 4 and 7: retry claimed without a log',
]);
for (const none of ['No flags', 'none', '']) expect(attention(GATE, trail([READ(none)]))[1]).toBe('No flags (trail row 1)');
expect(attention(GATE)).toHaveLength(1);
expect(attention(GATE)[0]).toStartWith('MISSING: cross-family trail read');
expect(attention(CODE, trail([READ('row 2')]))).toEqual(['self-audited (not a risk class: no cross-family trail read)']);
for (const r of [GATE, CODE]) expect(readyTailLines(r).join('\n')).not.toContain('<flags against');
});
});
describe('TRIAL_MERGES labels an outside fork PR instead of merging it (#4499)', () => {
// Value: protects=an outside PR from a fork that shares a file is named as outside and never fetched or merged, while a sibling lane
// is still trial-merged; fails_when=a fork PR is listed as a CONFLICT the lane must resolve, or its head is fetched; why_new=#4529,
// #4575 and #4578 listed #4499 as a real conflict; seam=trialMergeLines with a gh stub
test('a fork PR sharing a file is labelled; a sibling sharing the same file is still merged', () => {
const root = tmp();
const git = (...a: string[]) => { const r = spawnSync('git', ['-c', 'user.name=Fx', '-c', 'user.email=fx@example.com', ...a], { cwd: root, encoding: 'utf8', timeout: 30_000 }); if (r.status !== 0) throw new Error(r.stderr); return r.stdout.trim(); };
git('init', '-q', '-b', 'main');
fs.writeFileSync(path.join(root, 'a.txt'), 'a\n'); git('add', '-A'); git('commit', '-q', '-m', 'base');
const branch = (name: string, text: string) => { git('checkout', '-q', '-b', name, 'main'); fs.writeFileSync(path.join(root, 'a.txt'), text); git('commit', '-q', '-am', name); return git('rev-parse', 'HEAD'); };
const sibling = branch('sib', 'sibling\n');
const head = branch('mine', 'mine\n');
const calls: string[][] = [];
const list = [{ number: 1, headRefOid: head, files: [{ path: 'a.txt' }] }, { number: 2, headRefOid: sibling, files: [{ path: 'a.txt' }] }, { number: 4499, headRefOid: 'f'.repeat(40), files: [{ path: 'a.txt' }], isCrossRepository: true }];
const lines = trialMergeLines({ repoRoot: root, base: 'main', gh: a => { calls.push(a); return { ok: true, out: JSON.stringify(list) }; } }, '1', head, ['a.txt']);
expect(lines).toEqual([
`TRIAL_MERGES: #2 ${sibling.slice(0, 12)} shares a.txt: CONFLICT in a.txt; the lane states the resolution`,
`TRIAL_MERGES: #4499 ${'f'.repeat(12)} shares a.txt: outside PR from a fork, not a sibling lane; not trial-merged (rule 19)`,
]);
expect(calls[0]).toContain('number,headRefOid,files,isCrossRepository');
});
});
+21
View File
@@ -92,6 +92,27 @@ describe('the commit message', () => {
expect(m).toMatchObject({ skippedParent: parent, body: 'Co-authored-by: Erin <erin@example.com>' });
expect(branchTrailers(r.root, r.base, pin)).toEqual(['Co-authored-by: Dan <dan@example.com>', 'Co-authored-by: Erin <erin@example.com>']);
});
// Value: protects=a stacked child that merged main after its parent squash-landed still leaves out the parent's credit lines, and
// main's own; fails_when=land measures the parent with the reviewed-range rule (a parent the merge base already holds is no
// parent, GST-3315) or reads the trailers from the parent alone; why_new=#4580 note: the child's squash body repeated the parent's
// trailers; seam=landMessage as land calls it, with the merge base of the pin and main's tip
test('a stacked child that merged main after its parent landed leaves out the parent\'s and main\'s trailers', () => {
const r = repo();
r.git(['checkout', '-q', '-b', 'stack']);
const parent = r.commit('src/parent.ts', 'parent\n\nCo-authored-by: Dan <dan@example.com>');
r.commit('src/child.ts', 'child\n\nCo-authored-by: Erin <erin@example.com>');
r.git(['checkout', '-q', 'main']);
r.git(['checkout', '-q', parent, '--', 'src/parent.ts']);
r.git(['commit', '-q', '-m', 'Parent PR (#4)\n\nReview-Finding: p1/red-team#1 reader=red-team']);
r.commit('docs/other.md', 'Other PR (#5)\n\nCo-authored-by: Fay <fay@example.com>');
const tip = r.git(['rev-parse', 'HEAD']);
r.git(['checkout', '-q', 'stack']);
r.git(['merge', '-q', '--no-edit', 'main']);
const pin = r.git(['rev-parse', 'HEAD']);
const mergeBase = r.git(['merge-base', pin, tip]);
const m = landMessage(r.root, { pr: '6', title: 'Child', prBody: '', mergeBase, pin, tip, policy: SQUASH });
expect(m).toMatchObject({ skippedParent: parent, body: 'Co-authored-by: Erin <erin@example.com>' });
});
});
describe('the merge method', () => {