/ship counts a clean base merge as reviewed (GST-3562) (#4754)

When you merge main into a reviewed branch and your own lines, file
modes and symlink targets come through byte-identical, /ship now treats
the head as reviewed and lets CI check it, instead of asking for another
reader.

Why: these routine merges cost a reader stop on almost every PR that sat
a day, and the reader only ever re-read lines that had not changed.

Part of the /ship simplification Garry approved (items G and H); nothing
for readers to do.

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/red-team#1 reader=red-team
Review-Finding: p1/red-team#2 reader=red-team
Review-Finding: p1/targeted#1 reader=targeted
Review-Finding: p1/adversarial-native#1 reader=adversarial-native
Review-Finding: p1/adversarial-native#4 reader=adversarial-native
This commit is contained in:
Garry Tanandcapy-ai[bot] authored and GitHub committed 2026-11-24 02:41:52 +00:00
1 parent e78a1bfe32
commit 6ef3861302
14 files changed
+423 -228

No files matched your search

+16 -13
View File
@@ -753,14 +753,15 @@ function cmdCarry(rest: string[], json: boolean): number {
const changedProduct: string[] = [];
let walkCut = false;
const contextPaths: string[] = [];
const baseContext: string[] = [];
const stampOnly: string[] = [];
if (retarget && reviewed !== current) changedProduct.push(`HEAD's product diff against ${base} is not the one reviewed against ${reviewedBase} (the parent has not fully landed on ${base}, or the branch changed since)`);
else if (productFrom !== productHead && !retarget) {
// planCarry names at most CARRY_NAMED_PATHS differing paths, so the walk stops there, and it reads only the paths the
// branch itself touched against the base at either head: a base merge brings in every path the base changed, none of
// which can differ between the two base diffs. A touched path with the same blob at both heads and at both bases has
// the same patch, so only paths that moved on one side are compared (GST-448: 6000 touched paths). A path whose only difference is base context next to unchanged hunks
// (lib/ship-patch.ts) needs a scoped review instead of the loop.
// the same patch, so only paths that moved on one side are compared (GST-448: 6000 touched paths). A spliced path (comparePath) needs a scoped review, and a path whose only difference is base context next to its unchanged hunks counts as reviewed
// (lib/ship-patch.ts, GST-3562 G).
const sides = { reviewedBase: rangeBase, reviewed: from, currentBase: headBase, current: head };
const moved = [touchedPaths(repoRoot, from, head), touchedPaths(repoRoot, rangeBase, headBase)];
if (moved.some(l => !l)) return refused('RECEIPT_CARRY_REFUSED', `git could not list the paths the branch touched against ${base}; run /ship on ${head.slice(0, 12)}`);
@@ -784,9 +785,10 @@ function cmdCarry(rest: string[], json: boolean): number {
if (cls !== 'product') continue;
const verdict = comparePath(repoRoot, sides, p);
if (verdict === 'changed') changedProduct.push(p);
else if (verdict === 'context') contextPaths.push(p);
else if (verdict === 'spliced') contextPaths.push(p);
else if (verdict === 'context') baseContext.push(p);
}
const left = [...contextPaths, ...stampOnly];
const left = [...contextPaths, ...baseContext, ...stampOnly];
if (!changedProduct.length && !left.length) changedProduct.push('(a product path outside the branch\'s touched files; compare the two base diffs)');
else if (!changedProduct.length) {
const rest = [...spec.product, ...left.map(p => `:(exclude,literal)${p}`)];
@@ -802,8 +804,8 @@ function cmdCarry(rest: string[], json: boolean): number {
if (packetBody && !changedProduct.length) {
const record = flag(rest, '--scoped-review');
if (!record && rest.includes('--dry-run')) {
scopedDryRun = `base context moved next to the reviewed hunks in ${contextPaths.join(', ')}: carry without --dry-run writes the scoped-review packet for one fix-check reviewer, then carry --scoped-review <record.json>; nothing written`;
scopedReview = `base context moved (scoped review pending: ${contextPaths.join(', ')})`;
scopedDryRun = `the base merge spliced lines into the reviewed hunks in ${contextPaths.join(', ')}: carry without --dry-run writes the scoped-review packet for one fix-check reviewer, then carry --scoped-review <record.json>; nothing written`;
scopedReview = `spliced hunks (scoped review pending: ${contextPaths.join(', ')})`;
} else if (!record) {
const gitPath = git(['rev-parse', '--git-path', `gstack/scoped-review-${head.slice(0, 12)}.md`], repoRoot);
const packet = path.resolve(repoRoot, gitPath ?? `.git/gstack/scoped-review-${head.slice(0, 12)}.md`);
@@ -811,14 +813,14 @@ function cmdCarry(rest: string[], json: boolean): number {
fs.mkdirSync(path.dirname(packet), { recursive: true });
fs.writeFileSync(packet, packetBody.text);
} catch (e) {
return refused('RECEIPT_CARRY_REFUSED', `base context moved next to the reviewed hunks in ${contextPaths.join(', ')}, but the scoped-review packet ${packet} cannot be written (${(e as Error).message.split('\n')[0]}); make its directory writable, then rerun carry`);
return refused('RECEIPT_CARRY_REFUSED', `the base merge spliced lines into the reviewed hunks in ${contextPaths.join(', ')}, but the scoped-review packet ${packet} cannot be written (${(e as Error).message.split('\n')[0]}); make its directory writable, then rerun carry`);
}
return refused('RECEIPT_CARRY_SCOPED_REVIEW', `base context moved next to the reviewed hunks in ${contextPaths.join(', ')}: one fix-check reviewer reads ${packet}, then rerun carry with --scoped-review <record.json> ({"head":"${head}","paths":[…],"reviewer":"<model>","verdict":"clean"}); a blocking finding means /ship on ${head.slice(0, 12)}`);
return refused('RECEIPT_CARRY_SCOPED_REVIEW', `the base merge spliced lines into the reviewed hunks in ${contextPaths.join(', ')}: one fix-check reviewer reads ${packet}, then rerun carry with --scoped-review <record.json> ({"head":"${head}","paths":[…],"reviewer":"<model>","verdict":"clean"}); a blocking finding means /ship on ${head.slice(0, 12)}`);
}
if (record) {
const review = readScopedReview(record, { head }, contextPaths);
if (!review.ok) return refused('RECEIPT_CARRY_REFUSED', `--scoped-review: ${review.message}`);
scopedReview = `base context moved (scoped review by ${review.review.reviewer}: ${contextPaths.join(', ')})`;
scopedReview = `spliced hunks (scoped review by ${review.review.reviewer}: ${contextPaths.join(', ')})`;
}
}
const mergeCommits = (git(['rev-list', '--merges', '--count', `${from}..${head}`], repoRoot) ?? '0').trim();
@@ -832,10 +834,11 @@ function cmdCarry(rest: string[], json: boolean): number {
const fullRange = rangeRaw.status === 0 && inter?.status === 0 ? `${rangeRaw.stdout.trim()}\n${inter.stdout.trim()}` : null;
const numstat = named.length ? spawnSync('git', ['diff', '--numstat', from, head, '--', ...named.map(p => `:(literal)${p}`)], { cwd: repoRoot, encoding: 'utf8', timeout: 30_000, maxBuffer: 16 * 1024 * 1024 }) : null;
const binary = numstat?.status !== 0 || (numstat?.stdout ?? '').split('\n').some(l => l.startsWith('-\t-\t'));
// Moved base context composes into the same packet, bound to range_base (GST-1561).
const context = contextPaths.length ? contextPacket(repoRoot, { reviewedBase: rangeBase, reviewed: from, currentBase: headBase, current: head }, contextPaths) : undefined;
// Moved base context and spliced hunks compose into the same advisory packet, bound to range_base (GST-1561).
const advisory = [...contextPaths, ...baseContext].sort();
const context = advisory.length ? contextPacket(repoRoot, { reviewedBase: rangeBase, reviewed: from, currentBase: headBase, current: head }, advisory) : undefined;
const bound = context ? { rangeBase, context: context.text } : {};
const r = planRecheck({ code: 'RECEIPT_CARRY_PRODUCT_CHANGED', ancestor, retarget, rangeDiff: fullRange, unnamedPaths: named.length !== changedProduct.length, legacy: !receipt.review_depth, walkCut, contextPaths: contextPaths.length, context, binary });
const r = planRecheck({ code: 'RECEIPT_CARRY_PRODUCT_CHANGED', ancestor, retarget, rangeDiff: fullRange, unnamedPaths: named.length !== changedProduct.length, legacy: !receipt.review_depth, walkCut, contextPaths: advisory.length, context, binary });
if (!r.ok) process.stderr.write(`RECHECK: not eligible (${r.reason}); run /ship on ${head.slice(0, 12)}\n`);
else {
let where = 'not written (dry run)';
@@ -847,7 +850,7 @@ function cmdCarry(rest: string[], json: boolean): number {
process.stderr.write(`RECHECK: advisory range_diff_lines=${r.lines} range_diff_sha256=${r.sha256} packet=${where}; one reader may read it for advice, but it never carries the receipt (GST-2673): run /ship on ${head.slice(0, 12)} for the merge head's full review (docs/review-policy.md#rounds-per-pull-request)\n`);
}
}
plan = planCarry({ from, head, changed, productPatchId: { from: reviewed as string, head: current as string }, testPatchId: { from: testFrom, head: testHead }, changedProduct, mergeCommits: Number(mergeCommits) || 0, rangeDiff, ...(retarget ? { retargetedFrom: reviewedBase } : {}), ...(stackParent ? { stackParent } : {}), ...(scopedReview ? { scopedReview } : {}), ...(stampedRows.length ? { stampedRows } : {}) });
plan = planCarry({ from, head, changed, productPatchId: { from: reviewed as string, head: current as string }, testPatchId: { from: testFrom, head: testHead }, changedProduct, mergeCommits: Number(mergeCommits) || 0, rangeDiff, ...(retarget ? { retargetedFrom: reviewedBase } : {}), ...(stackParent ? { stackParent } : {}), ...(scopedReview ? { scopedReview } : {}), ...(!changedProduct.length && baseContext.length ? { baseContext } : {}), ...(stampedRows.length ? { stampedRows } : {}) });
}
if (!plan.ok) return refused(plan.code, plan.message);
// Eligibility is not publication: a receipt that recorded a pregate is rebound only with a pregate current for HEAD,
@@ -0,0 +1 @@
**/ship no longer asks for an extra reader when you merge the base branch next to code that was already reviewed.** If merging main leaves your own added and removed lines, file modes and symlink targets exactly as they were reviewed, /ship treats the head as reviewed and lets CI on the merged head check it. A merge that splices main's change into the same lines you changed, or that has to choose the order of your inserted lines against lines main inserted at the same spot, still gets one scoped reader, and a mode flip, a symlink retarget or a conflict resolution that edits your own lines still needs a full review.
+9 -6
View File
@@ -2353,13 +2353,14 @@ receipt when the base moves:
| What changed since /ship | The receipt |
|---|---|
| a merge of the base, product diff unchanged (tests, release metadata, registered outputs the pregate's regen check proved) | carries; no review reruns |
| a merge of the base that edited lines next to the branch's unchanged hunks (the branch's +/- lines identical and in the same places) | carries after one fix-check reviewer reads the hunks and comes back clean (`RECEIPT_CARRY_SCOPED_REVIEW`, then `carry --scoped-review <record.json>`) |
| a merge of the base that edited lines next to the branch's unchanged hunks (the branch's +/- lines, file modes and symlink targets identical and in the same places) | carries with no reader; CI on the merged head is the check (reason `base context moved next to unchanged own lines`, GST-3562) |
| a merge of the base that spliced lines into one of the branch's hunks (the base replaced the very lines the branch replaces and the merge kept both, GST-2975) | carries after one scoped reader reads the hunks and comes back clean (`RECEIPT_CARRY_SCOPED_REVIEW`, then `carry --scoped-review <record.json>`) |
| a merge of the base that only re-records the harness pin of a product file (`scripts/harness-pins/<file>.json`; a pinned test or metadata file's pin stays product): at both heads the pin is a regular file (not a symlink), both pinned files resolve, the pin's `blob` is its file's blob, its other fields are the reviewed ones, and `scripts/harness-version.json`'s version and patterns did not move; the pinned file itself still counts as product | carries (reason `regenerated outputs`, GSTA-749) |
| a merge of the base whose resolution changed product code, or moved the branch's lines elsewhere | a fresh /ship (`RECEIPT_CARRY_PRODUCT_CHANGED`) |
| a rebase or force-push onto a tree the receipt covers, product diff against the new base unchanged | carries (`carry.ancestry: rewritten`) |
| any other rebase or force-push | a fresh /ship (`RECEIPT_CARRY_TREE_MISMATCH`) |
| a stacked PR whose parent landed (squash or merge), retargeted to the base with the base merged in, HEAD's product diff exactly the one reviewed against the parent branch | carries (reason `stack parent <branch> landed`) |
| a stacked PR whose receipt was written against the base, after its parent landed and the base was merged in, HEAD's product diff exactly the reviewed range from the parent's head | carries (reason `stack parent <sha12> landed`); base context next to the child's hunks is `RECEIPT_CARRY_SCOPED_REVIEW` |
| a stacked PR whose receipt was written against the base, after its parent landed and the base was merged in, HEAD's product diff exactly the reviewed range from the parent's head | carries (reason `stack parent <sha12> landed`); base context next to the child's unchanged hunks carries too, and a spliced hunk is `RECEIPT_CARRY_SCOPED_REVIEW` |
| a stamp on the branch's own rows in a stamp file the branch also changed as product: every changed line at a branch-added position, the file's mode unchanged, the base not touching it, the rest of the product diff unchanged | carries (reason `a stamp on the branch's own rows (<file>)`) |
| a stamp file the branch changes, against each head's base, by no more than a stamp (back at the base's content after a changelog-fragment conversion, or only its version field moved), whatever else the base changed in it | carries (reason `release metadata`, GST-1210) |
@@ -2398,7 +2399,8 @@ every path whose content at the reviewed head is the base's (a base merge the
child made before its receipt brought it in) unless HEAD changed it against the
base (GST-1214): an equal
patch-id carries with reason `stack parent <sha12> landed`, base context next
to the child's unchanged hunks is `RECEIPT_CARRY_SCOPED_REVIEW`, and any other
to the child's unchanged hunks carries too, a spliced hunk is
`RECEIPT_CARRY_SCOPED_REVIEW`, and any other
difference refuses with `RECEIPT_CARRY_PRODUCT_CHANGED`. When merging the commit
into the current base conflicts because the base edited the landed lines
afterwards, the base commits since the fork that touched every path of its
@@ -2494,7 +2496,7 @@ along the receipt's own history, `rewritten` once any hop was a rebase;
skill=ship status=complete` line, and its summary line ends with
`carried_from=<old12>`. `CARRY: current` means the receipt already names HEAD;
`--dry-run` prints `CARRY: would carry …` and writes nothing. When the only
difference is base context next to the branch's unchanged hunks and none of
difference is a hunk the base merge spliced and none of
carry's other checks would refuse, `--dry-run` refuses
`RECEIPT_CARRY_SCOPED_REVIEW` without writing the packet; carry without
`--dry-run` writes it.
@@ -2502,7 +2504,8 @@ carry's other checks would refuse, `--dry-run` refuses
A changed product path, or a product patch-id that differs, is
[`RECEIPT_CARRY_PRODUCT_CHANGED`](troubleshooting.md#receipt-carry-product-changed)
(exit 3; the refusal names the paths), except when the only difference is
base context next to the branch's unchanged hunks, which is
base context next to the branch's unchanged hunks, which carries with no
reader (GST-3562), or a hunk the base merge spliced, which is
[`RECEIPT_CARRY_SCOPED_REVIEW`](troubleshooting.md#receipt-carry-scoped-review)
until one fix-check reviewer clears the packet; a working tree with uncommitted
changes is [`RECEIPT_CARRY_REFUSED`](troubleshooting.md#receipt-carry-refused).
@@ -2543,7 +2546,7 @@ generated skill file whose only branch-side difference after a base merge is
that id compares as unchanged. A reviewed line that the base also replaced,
where the current line is the base's new line plus exactly the tokens the
branch added to the reviewed line (both sides appended an entry to one
expected-value list), is base context: it goes to the one scoped reader, never
expected-value list), is a spliced hunk: it goes to the one scoped reader, never
through silently. A resolution that drops, invents or rewrites anything on the
branch's own lines stays a changed path.
+15 -12
View File
@@ -7886,30 +7886,33 @@ landed on the base, a stamp on the branch's own rows in a stamp file it also
changed as product (every changed line at a branch-added position, the mode
unchanged, the base not touching the file), a stamp file the branch changes by
no more than a stamp against each head's base (a changelog-fragment conversion
that puts `package.json` back at the base's content), or base context next to unchanged
hunks after a clean scoped review ([`RECEIPT_CARRY_SCOPED_REVIEW`](#receipt-carry-scoped-review)), which the
that puts `package.json` back at the base's content), base context next to unchanged
hunks, or hunks the base merge spliced after a clean scoped review ([`RECEIPT_CARRY_SCOPED_REVIEW`](#receipt-carry-scoped-review)), which the
`carry` object in the carried receipt records with the product patch-id and
the range-diff evidence ([unattended.md](unattended.md#the-terminal-line)).
<a id="receipt-carry-scoped-review"></a>
### `RECEIPT_CARRY_SCOPED_REVIEW`
**Meaning.** Every product path the branch touches has the reviewed +/- lines
in the same places, but the base edited context lines next to some of them, so
the 3-line patches differ (GST-384: main reworded the line above the PR's
hunk). A hunk whose added lines are unchanged but whose removed lines changed with
the base (the base took `SAVE_VERSION := 83` under the branch's `:= 84`) doesn't
count: the PR's own removed lines changed, so it's `RECEIPT_CARRY_PRODUCT_CHANGED`
and a full review (GST-2706). The merge may have spliced the two, as in a JSON entry where the branch
changed one key and the base the next, so the receipt does not carry silently.
**Meaning.** The base replaced the very lines one of the branch's hunks
replaces, and the merge kept both: each current line is the base's new line
plus exactly the tokens the branch added, as when both sides appended an entry
to one expected-value list (GST-2975). The branch's own lines are not the
reviewed bytes, so the receipt does not carry silently. Base context that only
moved next to the branch's unchanged hunks (GST-384: main reworded the line
above the PR's hunk) no longer stops here: when the branch's +/- lines, file
modes and symlink targets are the reviewed ones, the carry passes and CI on the
merged head is the check (GST-3562). A hunk whose added lines are unchanged but
whose removed lines changed with the base (the base took `SAVE_VERSION := 83`
under the branch's `:= 84`) is `RECEIPT_CARRY_PRODUCT_CHANGED` and a full
review (GST-2706).
The refusal names the paths and a packet file with the hunks that differ and
the base's own change. The same lines moved somewhere else are
`RECEIPT_CARRY_PRODUCT_CHANGED`, not this code. A packet section with over
200 of the branch's own +/- lines takes the full loop instead. Nothing else
counts toward that limit: the context lines and headers of the branch's hunks,
which a base merge can move (GST-2229), and the base's own change, already
merged at base (GST-1226), are shown and not counted, so a large base edit next
to the branch's hunks still gets the scoped read. A base change over 2,000 lines
merged at base (GST-1226), are shown and not counted. A base change over 2,000 lines
in one file counts in full again and takes the full loop.
**Fix.** Dispatch one fix-check reviewer
+2 -2
View File
@@ -311,8 +311,8 @@ now names HEAD with a `carry` object holding the `git range-diff` evidence, and
`ship-run.json` gains `carried_from` and `carry_reason`; the `review_loop`
counters are kept, because the reviewed product diff is unchanged or its only
difference passed a scoped review. `CARRY: current` means nothing moved.
`CARRY: refused (RECEIPT_CARRY_SCOPED_REVIEW)` means the base edited context
next to reviewed hunks. Carry without `--dry-run` writes the packet the
`CARRY: refused (RECEIPT_CARRY_SCOPED_REVIEW)` means the base merge spliced
lines into reviewed hunks (moved context next to unchanged hunks carries). Carry without `--dry-run` writes the packet the
refusal names (a dry run writes none), one fix-check reviewer reads it, and a
clean record reruns carry with `--scoped-review <record.json>`
([troubleshooting](troubleshooting.md#receipt-carry-scoped-review)). `CARRY: refused (RECEIPT_CARRY_PRODUCT_CHANGED)`,
+2 -2
View File
@@ -443,7 +443,7 @@ export const RELEASE_RESULT_CODES = {
RECEIPT_CARRY_PRODUCT_CHANGED: {
anchor: 'receipt-carry-product-changed',
summary: 'the product diff against the base changed between the receipt\'s head and HEAD (a product file differs beyond a base merge, a test-only fix, release metadata or a regenerated output), so the reviewed verdict does not cover HEAD',
fix: 'run /ship on the new head; the receipt carries only when every changed path is a test, release metadata, a registered output the pregate regen check proved, or the base merge, and the product patch-id is unchanged; base context next to unchanged reviewed hunks is RECEIPT_CARRY_SCOPED_REVIEW instead (one scoped fix-check, no /ship)',
fix: 'run /ship on the new head; the receipt carries only when every changed path is a test, release metadata, a registered output the pregate regen check proved, or the base merge, and the product patch-id is unchanged; base context next to unchanged reviewed hunks carries as the base merge, and a hunk the base merge spliced is RECEIPT_CARRY_SCOPED_REVIEW instead (one scoped reader, no /ship)',
},
STOP_UNBOUND: {
anchor: 'stop-unbound',
@@ -472,7 +472,7 @@ export const RELEASE_RESULT_CODES = {
},
RECEIPT_CARRY_SCOPED_REVIEW: {
anchor: 'receipt-carry-scoped-review',
summary: 'the branch\'s own +/- lines are the reviewed ones, but the base edited context next to them, so the merge may have spliced the two (GST-384); the receipt carries only after a scoped review of those hunks',
summary: 'the base replaced the very lines one of the branch\'s hunks replaces and the merge kept both (GST-2975), so the branch\'s own lines are not the reviewed bytes; the receipt carries only after a scoped review of those hunks',
fix: 'dispatch one fix-check reviewer on the packet the refusal names, write its clean verdict as { head, paths, reviewer, verdict } and rerun carry with --scoped-review <record.json>; a blocking finding means /ship on the new head',
},
RECEIPT_DOCS_AUDIT_READ: {
+1 -1
View File
@@ -39,7 +39,7 @@ export function targetedDelta(root: string, base: string, rangeBase: string, ran
const now = touchedPaths(root, headBase, head);
if (!before || !now) return skip('git could not list the branch patch at range_base or at HEAD');
const sides = { reviewedBase: readBase, reviewed: read, currentBase: headBase, current: head };
const paths = [...new Set([...before, ...now])].filter(p => !['same', 'context'].includes(comparePath(root, sides, p))).sort();
const paths = [...new Set([...before, ...now])].filter(p => !['same', 'context', 'spliced'].includes(comparePath(root, sides, p))).sort();
if (!paths.length) return skip(`the branch patch is unchanged since range_base ${read.slice(0, 12)}`);
const change = docsChangeSince(root, read, head, base);
if (!change) return skip(`git could not build the PR's own change since range_base ${read.slice(0, 12)}`);
+32 -15
View File
@@ -13,10 +13,17 @@
* A hunk whose added lines match but whose removed lines changed with the base (founderstar#563:
* the base took SAVE_VERSION 83 under the branch's 84, GST-1561) is changed: the PR's own added
* and removed lines must both be the reviewed bytes for a head to count as reviewed (GST-2673).
* The merge may still have spliced the two (a JSON entry where the branch changed one key and
* the base the next), so a context path needs a scoped review of its hunks, never a silent pass;
* - changed: anything else, including the same lines moved to another place, a file-mode change, and any path whose
* patches cannot be read (an empty patch on both sides of a path the branch touches). A binary, empty or mode-only
* A context path counts as reviewed (GST-3562 G): its own added and removed lines, file modes
* at both heads and symlink targets are the reviewed bytes, and CI on the merged head checks the
* base context next to them;
* - spliced: the base replaced the very lines one of the branch's hunks replaces and the merge kept
* both (GST-2975: each current line is the base's new line plus the tokens the branch added), or
* the base added or replaced lines at the very spot a branch insertion sits, so the merge chose
* the order of the two (GST-3562); the path needs a scoped review of its hunks;
* - changed: anything else, including the same lines moved to another place, a file-mode change (in either patch, or
* between the reviewed and current heads of a context or spliced path), a diff git printed as bytes that are not
* UTF-8 (two such bytes decode to the same character, so their comparison is lossy), and any path whose patches
* cannot be read (an empty patch on both sides of a path the branch touches). A binary, empty or mode-only
* patch has no hunks to place, so it is same when its patch-id matches and changed otherwise.
* Diffs skip external drivers and textconv, so a configured filter cannot hide a line.
* Paths reach git as literal pathspecs from NUL-separated listings, so quoted names and glob
@@ -38,7 +45,7 @@ import { headPolicyDiff } from './pregate/head-policy';
import { CHECK_IDS } from './pregate/index';
export interface PatchSides { reviewedBase: string; reviewed: string; currentBase: string; current: string }
export type PathVerdict = 'same' | 'context' | 'changed';
export type PathVerdict = 'same' | 'context' | 'spliced' | 'changed';
function git(repoRoot: string, args: string[], input?: string): string | null {
const r = spawnSync('git', ['-c', 'core.quotepath=off', ...args], { cwd: repoRoot, encoding: 'utf8', input, timeout: 120_000, maxBuffer: 256 * 1024 * 1024 });
@@ -98,18 +105,24 @@ function mapper(base: ZeroHunk[]): (line: number) => number | null {
};
}
/** Whether a branch hunk at the reviewed base's position lands where the current branch hunk sits. */
function sameSpot(r: ZeroHunk, c: ZeroHunk, map: (line: number) => number | null): boolean {
/**
* Where a branch hunk at the reviewed base's position lands against the current branch hunk: 'exact' when it sits at the one
* place the base's change maps it to, 'among' when it is an insertion that sits between the same surviving neighbours but the
* base added or replaced lines there too, so the merge chose its order against them (GST-3562), and false otherwise.
*/
function sameSpot(r: ZeroHunk, c: ZeroHunk, map: (line: number) => number | null): 'exact' | 'among' | false {
if (r.oldCount > 0) {
for (let k = 0; k < r.oldCount; k++) if (map(r.oldStart + k) !== c.oldStart + k) return false;
return true;
return 'exact';
}
let below = r.oldStart;
while (below > 0 && map(below) === null) below--;
let above = r.oldStart + 1;
for (let guard = 0; map(above) === null && guard < 100_000; guard++) above++;
const low = below > 0 ? map(below)! : 0;
return c.oldStart >= low && c.oldStart <= map(above)! - 1;
const high = map(above)! - 1;
if (c.oldStart < low || c.oldStart > high) return false;
return high > low ? 'among' : 'exact';
}
/**
@@ -155,7 +168,7 @@ function sideDiffs(repoRoot: string, s: PatchSides, rel: string): { diff: (from:
export function comparePath(repoRoot: string, s: PatchSides, rel: string): PathVerdict {
const r3 = pathDiff(repoRoot, s.reviewedBase, s.reviewed, rel, 3);
const c3 = pathDiff(repoRoot, s.currentBase, s.current, rel, 3);
if (r3 === null || c3 === null || (!r3.trim() && !c3.trim())) return 'changed';
if (r3 === null || c3 === null || (!r3.trim() && !c3.trim()) || r3.includes('\uFFFD') || c3.includes('\uFFFD')) return 'changed';
const modes = (d: string) => d.split('\n').filter(l => /^(old mode|new mode|new file mode|deleted file mode) /.test(l)).join('\n');
if (modes(r3) !== modes(c3)) return 'changed';
const sides = sideDiffs(repoRoot, s, rel);
@@ -173,11 +186,15 @@ export function comparePath(repoRoot: string, s: PatchSides, rel: string): PathV
const map = mapper(b0);
let spliced = false;
for (const [i, h] of r0.entries()) {
if (h.body === c0[i]!.body && sameSpot(h, c0[i]!, map)) continue;
if (!splicedHunk(h, c0[i]!, b0)) return 'changed';
const spot = h.body === c0[i]!.body ? sameSpot(h, c0[i]!, map) : false;
if (spot === 'exact') continue;
if (spot !== 'among' && !splicedHunk(h, c0[i]!, b0)) return 'changed';
spliced = true;
}
return ids[0] === ids[1] && !spliced ? 'same' : 'context';
if (ids[0] === ids[1] && !spliced) return 'same';
const mode = (ref: string) => git(repoRoot, ['ls-tree', '--full-tree', ref, '--', rel])?.split(' ')[0];
if (mode(s.reviewed) !== mode(s.current)) return 'changed';
return spliced ? 'spliced' : 'context';
} finally {
sides.done();
}
@@ -197,7 +214,7 @@ function insertedTokens(from: string, to: string): string[] | null {
* A hunk the base merge spliced (GST-2975, ghome#16): the base replaced exactly the lines the branch's hunk replaces, line
* for line, and each current line is the base's new line with the very tokens the branch added to the reviewed line, as
* when both sides appended an entry to one expected-value list. The branch removes nothing on those lines, so its own change
* is the reviewed one and the merge only kept both; the caller still routes the path to a scoped reader (context), never
* is the reviewed one and the merge only kept both; the caller still routes the path to a scoped reader (spliced), never
* through silently.
*/
function splicedHunk(r: ZeroHunk, c: ZeroHunk, base: ZeroHunk[]): boolean {
@@ -266,7 +283,7 @@ export function contextPacket(repoRoot: string, s: PatchSides, paths: readonly s
const late = Object.keys(bounded).sort();
const sides = `reviewed ${s.reviewed.slice(0, 12)} against ${s.reviewedBase.slice(0, 12)}; current ${s.current.slice(0, 12)} against ${s.currentBase.slice(0, 12)}.`;
const parts = [paths.length || !late.length
? `# Scoped review: base context moved next to the reviewed hunks\n\n${sides} The branch's added lines are unchanged, and a removed line differs only where the base edited the line the branch replaces; read whether the merge kept their meaning next to the base's edit (a version or number the base also took). Report clean, or findings at the blocking floor.\n`
? `# Scoped review: the base merge changed the reviewed hunks\n\n${sides} The branch added the same tokens it added at review, and the merge kept them beside the base's edit to the same or nearby lines; read whether the merge kept their meaning next to the base's edit (an entry, a version or a number the base also took). Report clean, or findings at the blocking floor.\n`
: `# Scoped review: edits that landed after the review bound\n\n${sides}\n`];
if (late.length) parts.push(`Bounded edits since review in ${late.map(p => `${p} (${bounded[p]})`).join(', ')}: each landed after the review bound, and its kind was proven from the diff; this one read replaces another review round (docs/review-policy.md#bounded-post-review-edits). Read every line under "Changed since review" as gate code. Audit prose is policy text agents follow: flag any change to what a gate, cap, reviewer, approval or exception does. A lanes edit maps files to tests: flag a glob that marks files covered by tests that do not exercise them. A bookkeeping row is an exemption or a limit: flag a row that moves an exemption onto code it should not cover, or raises a limit without a reason in the diff. Read them through the targeted brief at the end for money, gate, auth and secret wording. Report clean, or findings at the blocking floor.\n`);
if (tests.length) parts.push(`Test code changed since review in ${tests.join(', ')}: read whether each test still checks what it did (no weakened or bypassed assertion, early return, new exemption, skip or mock). Report clean, or findings at the blocking floor.\n`);
+7 -4
View File
@@ -301,8 +301,10 @@ export interface CarryPlanInput {
retargetedFrom?: string;
/** A commit inside the reviewed range whose product change the base already holds (a stack parent that squash-merged under a receipt written against the base, GST-1199): productPatchId.from is then the range from it. */
stackParent?: string;
/** A clean scoped review of product paths whose only difference is base context next to unchanged hunks (lib/ship-patch.ts, GST-384): the carry reason it adds. */
/** A clean scoped review of product paths the base merge spliced (comparePath 'spliced', lib/ship-patch.ts, GST-2975): the carry reason it adds. */
scopedReview?: string;
/** Product paths whose own added and removed lines, modes and symlink targets are the reviewed bytes and whose only difference is base context next to them (comparePath 'context', GST-3562 G): reviewed, with CI on HEAD as the check. */
baseContext?: string[];
/** Stamp files the branch changed as product whose only change since the reviewed head is a stamp on the branch's own rows, the base untouched, and without which the two product patches match (GST-980). */
stampedRows?: string[];
}
@@ -368,18 +370,19 @@ export function classifyCarryPath(rel: string, extra: { metadata?: readonly stri
* against the base has the same patch-id at both heads, which is what a
* conflict-only base merge, a test-only fix or a release-metadata change
* leaves behind. A product patch that differs is RECEIPT_CARRY_PRODUCT_CHANGED,
* whatever else changed, unless every difference is base context next to unchanged hunks
* and a scoped review of those hunks came back clean (`scopedReview`), or a stamp on the
* whatever else changed, unless every difference is base context next to byte-identical own hunks
* (`baseContext`, GST-3562 G), a spliced hunk whose scoped review came back clean (`scopedReview`), or a stamp on the
* branch's own rows in a stamp file the branch also changed as product (`stampedRows`, GST-980).
*/
export function planCarry(input: CarryPlanInput): CarryPlan {
if (input.productPatchId.from !== input.productPatchId.head && (input.changedProduct.length || (!input.scopedReview && !input.stampedRows?.length))) {
if (input.productPatchId.from !== input.productPatchId.head && (input.changedProduct.length || (!input.scopedReview && !input.stampedRows?.length && !input.baseContext?.length))) {
const named = input.changedProduct.slice(0, CARRY_NAMED_PATHS);
return { ok: false, code: 'RECEIPT_CARRY_PRODUCT_CHANGED', message: `product diff changed between ${input.from.slice(0, 12)} and ${input.head.slice(0, 12)}: ${named.join(', ') || 'patch-id differs'}${input.changedProduct.length > named.length ? ` (+${input.changedProduct.length - named.length} more)` : ''}` };
}
const parent = input.retargetedFrom ?? input.stackParent?.slice(0, 12);
const reasons: string[] = parent ? [`stack parent ${parent} landed`] : [];
if (input.mergeCommits > 0) reasons.push(input.mergeCommits === 1 ? 'base merge' : `${input.mergeCommits} base merges`);
if (input.baseContext?.length && input.productPatchId.from !== input.productPatchId.head) reasons.push(`base context moved next to unchanged own lines (${input.baseContext.slice(0, CARRY_NAMED_PATHS).join(', ')}${input.baseContext.length > CARRY_NAMED_PATHS ? ` (+${input.baseContext.length - CARRY_NAMED_PATHS} more)` : ''}; CI at head checks it)`);
if (input.scopedReview && input.productPatchId.from !== input.productPatchId.head) reasons.push(input.scopedReview);
if (input.stampedRows?.length && input.productPatchId.from !== input.productPatchId.head) reasons.push(`a stamp on the branch's own rows (${input.stampedRows.join(', ')})`);
if (input.testPatchId.from !== input.testPatchId.head) reasons.push('test-only change');
+4 -4
View File
@@ -54,7 +54,7 @@ export const RELEASE_HELP = `gstack-ship-release — /ship Steps 12 and 15-17 (s
[--docs-requested <path>... --docs-result <the audit's result JSON>] [--review-loop-exception <json|@file>]
Step 15's release commit, Step 16 stages 1-4 (your builds, the reviewed-tree route, docs freshness,
each lane's receipt run once if stale) and the pregate on the stamped tree; --reviewed-base (the merge base
saved with the reviewed tree, or a stack parent's head once the parent landed: REVIEWED_BASE:) routes paths only the base moved as base=, and an adjacent base edit as context=;
saved with the reviewed tree, or a stack parent's head once the parent landed: REVIEWED_BASE:) routes paths only the base moved, or whose own hunks are unchanged next to moved base context, as base=, and a hunk the base merge spliced as context=;
--review-loop-exception (the record write takes) routes paths the branch touched at fix_check.head (narrowed to fix_check.files when listed) and changed since as accepted=
A lane the base branch maps in .gstack/pregate.json ship_lanes_from is carried from a verified CI run at this exact
tree, else deferred (EVIDENCE: DEFERRED): the pregate then runs its preflight stage here and its tests stage in accept
@@ -406,9 +406,9 @@ function route(cwd: string, base: string, reviewed: string, reviewedBase: Review
const baseSide = new Set<string>();
for (const p of [...changedSet, ...onlyShipped].sort()) {
const verdict = sides ? (!touched.has(p) || (parent && !shipped.has(p) && baseHolds(cwd, sides, p)) ? 'same' : comparePath(cwd, sides, p)) : 'changed';
if (verdict === 'context') baseSide.add(p);
if (verdict === 'context' || verdict === 'spliced') baseSide.add(p);
const metadata = isMetadata(p);
by[verdict === 'same' ? 'base' : metadata ? 'metadata' : sides && isTestCode(p, opts.testCode) ? 'tests' : classifyPath(p, cwd) === 'docs' && !matchesAny(opts.bookkeeping, p) ? 'docs' : verdict === 'context' ? 'context' : 'behavior'].push(p);
by[verdict === 'same' || verdict === 'context' ? 'base' : metadata ? 'metadata' : sides && isTestCode(p, opts.testCode) ? 'tests' : classifyPath(p, cwd) === 'docs' && !matchesAny(opts.bookkeeping, p) ? 'docs' : verdict === 'spliced' ? 'context' : 'behavior'].push(p);
}
const shippedTests = by.tests.filter(p => onlyShipped.has(p));
const gated = new Set([...(gateEditedPaths(cwd, reviewed, now, by.tests.filter(p => !onlyShipped.has(p) && !baseSide.has(p))) ?? by.tests), ...(gateEditedPaths(cwd, sides?.currentBase ?? reviewed, now, shippedTests) ?? shippedTests)]);
@@ -468,7 +468,7 @@ function route(cwd: string, base: string, reviewed: string, reviewedBase: Review
const packet = path.resolve(cwd, git(cwd, ['rev-parse', '--git-path', `gstack/scoped-review-${now.slice(0, 12)}.md`]).stdout.trim() || `.git/gstack/scoped-review-${now.slice(0, 12)}.md`);
const built = contextPacket(cwd, sides, by.context, by.tests, late());
if (!opts.contextReviewed) {
const why = [by.context.length ? `base context moved next to the reviewed hunks in ${short(by.context)}` : '', by.tests.length ? `test code changed since review in ${short(by.tests)}` : '',
const why = [by.context.length ? `the base merge spliced lines into the reviewed hunks in ${short(by.context)}` : '', by.tests.length ? `test code changed since review in ${short(by.tests)}` : '',
by.bounded.length ? `bounded edits since review in ${by.bounded.map(p => `${p} (${bounded.kinds[p]})`).join(', ')}` : ''].filter(Boolean).join('; ');
try {
fs.mkdirSync(path.dirname(packet), { recursive: true });
+117 -7
View File
@@ -2,13 +2,15 @@
* GST-2975: /ship finish stopped with "behavior, tests or build inputs changed since review" after a base merge whose only
* effect on the branch's files was base-side: the shared-preamble hash id in regenerated skill files (#4383, 94 files), and
* main's new entry spliced into an expected-value list the branch also appended to (ghome#16). Both now compare with the
* base-side difference masked; the spliced list goes to the scoped reader, and a real change to the branch's own lines
* still stops.
* base-side difference masked; the spliced list goes to the scoped reader, moved base context next to unchanged own lines
* counts as reviewed (GST-3562 G), and a real change to the branch's own lines still stops.
*/
import { afterEach, describe, expect, setDefaultTimeout, test } from 'bun:test';
import * as fs from 'node:fs';
import * as path from 'node:path';
import { EXIT } from '../lib/headless-artifacts';
import { comparePath } from '../lib/ship-patch';
import { extractReceipt, placeReceipt } from '../lib/ship-receipt';
import { lineOf, RELEASE, shipFixture, type ShipFx } from './helpers/ship-bin-fixture';
setDefaultTimeout(90_000);
@@ -59,15 +61,15 @@ describe('regenerated skill files whose only base-side change is the shared-prea
// Value: protects=#4383: a main merge that only moved the shared-preamble hash id in the branch's regenerated files is a
// base merge, not a behavior change; fails_when=finish stops with behavior=N for the id lines; seam=comparePath via finish;
// no_claim=a hash id outside the two generated forms
test('the id lines are masked: the paths route as base or context and finish never stops for a behavior change', () => {
test('the id lines are masked: both paths route as base and finish never stops for a behavior change', () => {
const { f, reviewed, reviewedBase, post } = preambleMerge();
const sides = sidesOf(f, reviewed, reviewedBase);
expect(comparePath(f.work, sides, SKILL)).toBe('same');
expect(comparePath(f.work, sides, PREAMBLE)).toBe('context');
const r = finish(f, reviewed, post, reviewedBase);
expect(lineOf(r.stdout, 'ROUTE')).toMatch(/ behavior=0 .* base=1 context=1$/);
expect(lineOf(r.stdout, 'ROUTE')).toMatch(/ behavior=0 .* base=2 context=0$/);
expect(r.stdout).not.toContain('behavior, tests or build inputs changed since review');
expect(r.stdout).toContain(`STOP: base context moved next to the reviewed hunks in ${PREAMBLE}`);
expect(r.stdout).not.toContain('STOP:');
});
// Value: protects=#4383's own files: a branch that edits the shared preamble changes every generated file by its id alone, and
@@ -120,9 +122,9 @@ describe('an expected-value list the base merge spliced (ghome#16)', () => {
// Value: protects=ghome#16: a resolved line that is main's line plus exactly the entry the branch added goes to the scoped
// reader of its test hunks, not to an owner grant; fails_when=gateEditedPaths sends it to behavior (the owner-grant stop) or
// it passes with no reader; seam=comparePath + finish route; no_claim=the scoped reader's verdict
test('the union is context: finish stops for the scoped reader, never for a behavior change', () => {
test('the union is spliced: finish stops for the scoped reader, never for a behavior change', () => {
const { f, reviewed, reviewedBase, post } = listMerge(methods([...BASE_METHODS, 'ghome.talk.target', 'ghome.brief']));
expect(comparePath(f.work, sidesOf(f, reviewed, reviewedBase), LIST)).toBe('context');
expect(comparePath(f.work, sidesOf(f, reviewed, reviewedBase), LIST)).toBe('spliced');
const r = finish(f, reviewed, post, reviewedBase);
expect(lineOf(r.stdout, 'ROUTE')).toMatch(/ behavior=0 .*tests=1 /);
expect(r.stdout).not.toContain('behavior, tests or build inputs changed since review');
@@ -149,3 +151,111 @@ describe('an expected-value list the base merge spliced (ghome#16)', () => {
}
});
});
const ROWS = 'src/rows.ts';
const RUN = 'bin/run.sh';
const LINK = 'src/link.ts';
const rows = (edit: Record<number, string> = {}) => Array.from({ length: 12 }, (_, i) => edit[i + 1] ?? `export const r${i + 1} = ${i + 1};`).join('\n') + '\n';
const OWN = { 6: 'export const r6 = 600;' };
/**
* GST-3562 G: the branch edits rows.ts, a script it marks executable and a symlink it adds; the base edits the line next to
* the branch's hunk, so the merge conflicts and the resolution decides what the head holds. `resolve` runs on the merged
* working tree before the merge commit.
*/
function noLossMerge(resolve: (work: string) => void) {
const f = fx({ [ROWS]: rows(), [RUN]: '#!/bin/sh\necho base\n' }, { [ROWS]: rows(OWN), [RUN]: '#!/bin/sh\necho branch\n' });
fs.chmodSync(path.join(f.work, RUN), 0o755);
fs.symlinkSync('rows.ts', path.join(f.work, LINK));
f.commit('feat: executable script and link');
const reviewed = wtree(f);
const reviewedBase = mergeBase(f);
const reviewedHead = f.git('rev-parse', 'HEAD').stdout.trim();
const post = snapshot(f);
f.advanceBase({ [ROWS]: rows({ 5: 'export const r5 = 50;' }) });
f.git('fetch', '-q', 'origin');
f.git('merge', '-q', '--no-commit', '--no-edit', 'origin/main');
f.write({ [ROWS]: rows({ 5: 'export const r5 = 50;', ...OWN }) });
resolve(f.work);
f.commit('merge main');
const body = path.join(f.root, 'body.md');
fs.writeFileSync(body, placeReceipt('## Summary\n\nProse.\n', { schema_version: 1, pr: 9, head: reviewedHead, base: 'main', queue_mode: 'stamp-at-merge' } as any));
const carry = () => f.run(path.join(BIN, 'gstack-ship-receipt'), ['carry', '--body', body, '--base', 'main']);
return { f, sides: sidesOf(f, reviewed, reviewedBase), finish: () => finish(f, reviewed, post, reviewedBase), carry, body };
}
describe('a base merge counts as reviewed only when the branch\'s own lines, modes and symlink targets are unchanged (GST-3562 G)', () => {
// Value: protects=no review is lost by G: a base merge whose resolution keeps the branch's own lines, file modes and symlink
// targets byte-identical counts as reviewed in finish and carry, and a mode flip, a symlink retarget or a resolution that
// edits the branch's own line inside the conflict never does; fails_when=any adversarial resolution routes as base or
// carries, or the identical one asks for a reader; seam=comparePath via finish and carry; no_claim=CI's verdict at the head
test('byte-identical own lines, modes and symlink targets route as base in finish and carry with no reader', () => {
const x = noLossMerge(() => {});
expect([ROWS, RUN, LINK].map(p => comparePath(x.f.work, x.sides, p))).toEqual(['context', 'same', 'same']);
const r = x.finish();
expect([r.status, lineOf(r.stdout, 'ROUTE')], r.stdout).toEqual([0, expect.stringMatching(/ behavior=0 .* base=1 context=0$/)]);
const c = x.carry();
expect(c.status, c.stderr).toBe(EXIT.ok);
expect(extractReceipt(fs.readFileSync(x.body, 'utf8')).receipt!.carry!.reason).toContain(`base context moved next to unchanged own lines (${ROWS}; CI at head checks it)`);
});
test('a mode flip, a symlink retarget and a resolution inside the branch\'s own line are changed: finish stops and carry refuses', () => {
const cases: [string, (work: string) => void][] = [
[RUN, work => fs.chmodSync(path.join(work, RUN), 0o644)],
[LINK, work => { fs.unlinkSync(path.join(work, LINK)); fs.symlinkSync('a.ts', path.join(work, LINK)); }],
[ROWS, work => fs.writeFileSync(path.join(work, ROWS), rows({ 5: 'export const r5 = 50;', 6: 'export const r6 = 6000;' }))],
];
for (const [p, resolve] of cases) {
const x = noLossMerge(resolve);
expect([p, comparePath(x.f.work, x.sides, p)]).toEqual([p, 'changed']);
const r = x.finish();
expect([p, r.status, r.stdout.includes('behavior, tests or build inputs changed since review')], r.stdout).toEqual([p, 3, true]);
const c = x.carry();
expect([p, c.status, c.stdout.trim().split('\n')[0]], c.stderr).toEqual([p, EXIT.refused, 'CARRY: refused (RECEIPT_CARRY_PRODUCT_CHANGED)']);
expect(c.stderr).toContain(p);
}
});
});
describe('a merge that chose its own order, a base mode flip, or bytes that are not UTF-8 never count as reviewed (GST-3562 G)', () => {
const P = 'src/tool.sh';
/** Four sides in one repository: A, the reviewed branch R on A, the base B on A, and the merge C of R and B with `resolved`. */
const sides = (base: string | Buffer, reviewed: string | Buffer, baseSide: string | Buffer, resolved: string | Buffer, baseExec = false) => {
const f = fx();
const put = (text: string | Buffer) => fs.writeFileSync(path.join(f.work, P), text);
fs.mkdirSync(path.join(f.work, 'src'), { recursive: true });
put(base); f.commit('A');
const A = f.git('rev-parse', 'HEAD').stdout.trim();
put(reviewed); f.commit('R');
const R = f.git('rev-parse', 'HEAD').stdout.trim();
f.git('checkout', '-q', '-b', 'side', A);
put(baseSide); if (baseExec) fs.chmodSync(path.join(f.work, P), 0o755); f.commit('B');
const B = f.git('rev-parse', 'HEAD').stdout.trim();
f.git('checkout', '-q', '-b', 'merged', R);
f.git('merge', '-q', '--no-commit', '--no-edit', B);
put(resolved); if (baseExec) fs.chmodSync(path.join(f.work, P), 0o755); f.commit('C');
return comparePath(f.work, { reviewedBase: A, reviewed: R, currentBase: B, current: f.git('rev-parse', 'HEAD').stdout.trim() }, P);
};
const at = (edit: Record<number, string[]>) => rows().trimEnd().split('\n').flatMap((l, i) => [edit[i + 1]?.[0] ?? l, ...(edit[i + 1]?.slice(1) ?? [])]).join('\n') + '\n';
const GUARD = 'export const guard = 1;';
const [X1, X2] = ['export const x1 = 1;', 'export const x2 = 2;'];
const R3 = 'export const r3 = 3;';
// Value: protects=no review is lost by G: an insertion whose place against lines the base inserted or replaced at the same
// spot was chosen by the merge, a base exec-bit flip on a file the branch edits, and a diff of bytes that are not UTF-8 all
// leave the reviewed state; fails_when=any compares as context (no reader) or the controls lose their verdicts;
// seam=comparePath; no_claim=the routes, which the cases above cover for spliced and changed
test('same-spot insertions are spliced in either order; a base exec-bit flip and non-UTF-8 bytes are changed', () => {
expect(sides(rows(), at({ 3: [R3, GUARD] }), at({ 3: [R3, X1, X2] }), at({ 3: [R3, X1, GUARD, X2] }))).toBe('spliced');
expect(sides(rows(), at({ 3: [R3, GUARD] }), at({ 3: [R3, X1, X2] }), at({ 3: [R3, GUARD, X1, X2] }))).toBe('spliced');
expect(sides(rows(), at({ 3: [R3, GUARD] }), at({ 3: ['export const r3 = 30;'] }), at({ 3: ['export const r3 = 30;', GUARD] }))).toBe('spliced');
expect(sides(rows(), at({ 3: [R3, GUARD] }), at({ 10: ['export const r10 = 100;'] }), at({ 3: [R3, GUARD], 10: ['export const r10 = 100;'] }))).toBe('same');
expect(sides(rows(), rows(OWN), rows({ 5: 'export const r5 = 50;' }), rows({ 5: 'export const r5 = 50;', ...OWN }))).toBe('context');
expect(sides(rows(), rows(OWN), rows({ 5: 'export const r5 = 50;' }), rows({ 5: 'export const r5 = 50;', ...OWN }), true)).toBe('changed');
const latin = (own: number, five = 'r5 = 5') => Buffer.concat([Buffer.from(rows({ 5: `export const ${five};` }).split('export const r6 = 6;')[0]!), Buffer.from('export const r6 = "caf'), Buffer.from([own]), Buffer.from('";\n'), Buffer.from(rows().split('export const r6 = 6;\n')[1]!)]);
const plain = rows({ 6: 'export const r6 = "cafe";' });
expect(sides(rows(), latin(0xe9), rows({ 5: 'export const r5 = 50;' }), latin(0xe9, 'r5 = 50'))).toBe('changed');
expect(sides(rows(), latin(0xe9), rows({ 5: 'export const r5 = 50;' }), latin(0xe8, 'r5 = 50'))).toBe('changed');
expect(sides(rows(), plain, rows({ 5: 'export const r5 = 50;' }), rows({ 5: 'export const r5 = 50;', 6: 'export const r6 = "cafe";' }))).toBe('context');
});
});
+40 -13
View File
@@ -13,7 +13,7 @@ import * as fs from 'node:fs';
import * as path from 'node:path';
import { EXIT } from '../lib/headless-artifacts';
import { comparePath } from '../lib/ship-patch';
import { bindReceipt, extractReceipt } from '../lib/ship-receipt';
import { bindReceipt, CARRY_NAMED_PATHS, extractReceipt, placeReceipt, planCarry } from '../lib/ship-receipt';
import { RECHECK_RANGE_DIFF_CAP } from '../crew/lib/ship-recheck';
import { lineOf, RELEASE, shipFixture, type ShipFx } from './helpers/ship-bin-fixture';
@@ -155,7 +155,7 @@ describe('carry: a changed path plus context paths compose into one bounded re-c
expect(eligible(r.stderr)).toBeNull();
});
test('changed-only keeps J1 as it is; context-only keeps the scoped review', () => {
test('changed-only keeps J1 as it is; context-only carries with no reader (GST-3562 G)', () => {
const changed = reviewedBranch({ [SCORE]: 'var score := 1\n' }, { [SCORE]: 'var score := 2\n' });
changed.f.write({ [SCORE]: 'var score := 3\n' }); changed.f.commit('fix: score 3');
const c = changed.carry();
@@ -168,25 +168,22 @@ describe('carry: a changed path plus context paths compose into one bounded re-c
context.f.advanceBase({ [VESTING]: vesting(BASE_VESTING) });
mergeMain(context.f, { [VESTING]: vesting({ ...BASE_VESTING, ...BRANCH_VESTING }) });
const s = context.carry();
expect([s.status, s.stdout.trim().split('\n')[0]]).toEqual([EXIT.refused, 'CARRY: refused (RECEIPT_CARRY_SCOPED_REVIEW)']);
expect(s.status, s.stderr).toBe(EXIT.ok);
expect(s.stderr).not.toContain('RECHECK:');
expect(extractReceipt(fs.readFileSync(context.body, 'utf8')).receipt!.carry!.reason).toContain(`base context moved next to unchanged own lines (${VESTING}; CI at head checks it)`);
});
});
describe('finish: the founderstar#563 shape takes the scoped reader too', () => {
test('ROUTE sends nothing to behavior, and one clean scoped record lets finish go on', () => {
describe('finish: the founderstar#563 shape needs no reader (GST-3562 G)', () => {
test('ROUTE sends nothing to behavior or context: the moved base context next to unchanged own lines counts as reviewed', () => {
const x = founderstar();
const post = path.join(x.f.root, 'post.json');
expect(x.f.run(path.join(BIN, 'gstack-docs-candidate'), ['snapshot', '--out', post, '--audit-id', 'a1', '--mode', 'edit', '--base', 'main', '--docs', 'README.md']).status).toBe(0);
const finish = (extra: string[] = []) => x.f.run(RELEASE, ['finish', '--base', 'main', '--reviewed-tree', x.reviewedTree, '--docs-post', post, '--lane', LANE, '--reviewed-base', x.reviewedBase, ...extra]);
const ask = finish();
expect([ask.status, lineOf(ask.stdout, 'ROUTE')], ask.stdout).toEqual([3, expect.stringMatching(/ behavior=0 .* context=[12]$/)]);
const packet = /reads (\S+\.md)[ ,]/.exec(ask.stdout)?.[1];
expect(fs.readFileSync(packet!, 'utf8')).toContain('moved by the base');
const tree = x.f.run(path.join(BIN, 'gstack-wtree'), []).stdout.trim();
const ok = finish(['--context-reviewed', recordAt(x.f, 'ctx.json', { tree, paths: [GAME, VESTING], reviewer: READER, verdict: 'clean' })]);
expect(lineOf(ok.stdout, 'SCOPED_REVIEW'), ok.stdout).toStartWith(`SCOPED_REVIEW: clean by ${READER} (`);
expect(ok.stdout).not.toContain('STOP: behavior');
const ok = finish();
expect([ok.status, lineOf(ok.stdout, 'ROUTE')], ok.stdout).toEqual([0, expect.stringMatching(/ behavior=0 .* base=[12] context=0$/)]);
expect(ok.stdout).not.toContain('SCOPED_REVIEW');
expect(ok.stdout).not.toContain('STOP:');
});
});
@@ -231,3 +228,33 @@ describe('a receipt a scoped re-check carried never carries on or lands (GST-270
}
});
});
describe('a receipt that records only what binding needs (GST-3562 H)', () => {
// Value: protects=/ship's receipt no longer needs the docs, review-loop, issue or budget records: a write with none of them
// binds at its head, and a receipt from before H that carries them still binds; fails_when=write or bindReceipt starts
// requiring one of those records again, or rejects an older receipt that has them; seam=gstack-ship-receipt write +
// bindReceipt; no_claim=the queue's other ready checks
test('a slim receipt writes and binds, and an older receipt with every record still binds', () => {
const x = reviewedBranch({ [VESTING]: vesting() }, { [VESTING]: vesting(BRANCH_VESTING) });
const body = fs.readFileSync(x.body, 'utf8');
const slim = extractReceipt(body).receipt!;
expect(['review_loop', 'calls', 'spend_usd', 'docs_audit_read'].filter(k => k in slim)).toEqual([]);
expect(bindReceipt(body, '5', [x.from], { base: 'main' })).toMatchObject({ ok: true, head: x.from });
const older = placeReceipt('## Summary\n', { ...slim, review_loop: { passes: 2, blocking_found: 1, deferred: 1, fixed: 1, rounds: 2 }, calls: 14, spend_usd: 3.25, docs_audit_read: { paths: ['README.md'], reviewer: READER, packet_sha256: 'a'.repeat(64) } } as any);
expect(bindReceipt(older, '5', [x.from], { base: 'main' })).toMatchObject({ ok: true, head: x.from });
});
});
describe('the carry reason names at most CARRY_NAMED_PATHS moved-context paths (GST-3562 G)', () => {
// Value: protects=a PR that merges main often keeps its receipt line bounded: the reason names at most CARRY_NAMED_PATHS
// paths and counts the rest; fails_when=every path is named on every hop and the PR body grows past GitHub's limit;
// seam=planCarry; no_claim=none
test('25 context paths name 20 and count 5', () => {
const paths = Array.from({ length: 25 }, (_, i) => `src/f${String(i).padStart(2, '0')}.ts`);
const plan = planCarry({ from: 'a'.repeat(40), head: 'b'.repeat(40), changed: [], productPatchId: { from: 'p1', head: 'p2' }, testPatchId: { from: '', head: '' }, changedProduct: [], mergeCommits: 1, rangeDiff: '', baseContext: paths });
expect(plan.ok).toBe(true);
const reason = plan.ok ? plan.carry.reason : '';
expect(reason).toContain(`(${paths.slice(0, CARRY_NAMED_PATHS).join(', ')} (+5 more); CI at head checks it)`);
expect(reason).not.toContain(paths[CARRY_NAMED_PATHS]!);
});
});
+19 -19
View File
@@ -215,17 +215,16 @@ describe('carry after a stack parent squash-merges, receipt written against main
expect(receiptIn(s.body).head).toBe(s.child);
}, 120_000);
// Value: protects=a base change next to the child's reviewed hunks gets one fix-check reviewer, not a carry and not a full
// /ship; fails_when=the landed-parent comparison ignores base context or refuses it outright; seam=none; no_claim=-
test('a base change next to the child\'s reviewed hunks routes to RECEIPT_CARRY_SCOPED_REVIEW', () => {
// Value: protects=GST-3562 G: a base change next to the child's unchanged reviewed hunks carries with no reader and the
// reason names the file, not a full /ship; fails_when=the landed-parent comparison ignores base context (the reason
// says only "base merge") or refuses it; seam=none; no_claim=-
test('a base change next to the child\'s reviewed hunks carries and names the moved context', () => {
const repo = makeFixtureRepo({ baseFiles: { 'lib/config.js': CONFIG } }); repos.push(repo);
const { child, body } = stack(repo, undefined, { 'lib/config.js': configWith({ 'd = 4': 'd = 40' }) }, 'main');
const { body } = stack(repo, undefined, { 'lib/config.js': configWith({ 'd = 4': 'd = 40' }) }, 'main');
landOnMain(repo, { 'lib/util.js': SUB, 'lib/config.js': configWith({ 'f = 6': 'f = 60' }) });
const out = carry(repo, body);
expect(out.status).toBe(EXIT.refused);
expect(out.out).toContain('CARRY: refused (RECEIPT_CARRY_SCOPED_REVIEW)');
expect(out.err).toContain('lib/config.js');
expect(receiptIn(body).head).toBe(child);
expect(out.status, out.err).toBe(EXIT.ok);
expect(receiptIn(body).carry!.reason).toContain('base context moved next to unchanged own lines (lib/config.js; CI at head checks it)');
}, 90_000);
// Value: protects=the receipt never names a stack parent that does not exist; fails_when=a test-first commit with no
@@ -338,26 +337,27 @@ function landedFirst(files: Record<string, string>) {
}
describe('a stack parent the reviewed base already held is no landed parent (qm#3457, GST-3315)', () => {
// Value: protects=qm#3457: base context moved beside the child's own hunk takes one scoped review of that file, not a
// refusal naming the parent's files; fails_when=landedStackParent counts a parent the reviewed base already held and the
// carry measures from it; seam=gstack-ship-receipt carry; no_claim=the scoped review itself
test('#3457: context moved next to the child\'s hunk routes to a scoped review of that file alone', () => {
// Value: protects=qm#3457: base context moved beside the child's own hunk carries naming that file alone (GST-3562 G), not
// a refusal naming the parent's files; fails_when=landedStackParent counts a parent the reviewed base already held and the
// carry measures from it; seam=gstack-ship-receipt carry; no_claim=-
test('#3457: context moved next to the child\'s hunk carries naming that file alone', () => {
const { repo, reviewed, rangeBase, body } = landedFirst({ 'lib/config.js': configWith({ 'f = 6': 'f = 60' }) });
expect(landedStackParent(repo.work, { rangeBase, reviewed, currentBase: repo.git('merge-base', 'origin/main', 'HEAD') }, ['.', ':(exclude,glob)test/**'])).toBeNull();
const out = carry(repo, body);
expect([out.status, out.out]).toEqual([EXIT.refused, expect.stringContaining('CARRY: refused (RECEIPT_CARRY_SCOPED_REVIEW)')]);
expect(out.err).toContain('lib/config.js');
expect(out.err).not.toContain('lib/util.js');
expect(receiptIn(body).head).toBe(reviewed);
expect(out.status, out.err).toBe(EXIT.ok);
const reason = receiptIn(body).carry!.reason;
expect(reason).toContain('base context moved next to unchanged own lines (lib/config.js; CI at head checks it)');
expect(reason).not.toContain('lib/util.js');
}, 90_000);
// Value: protects=the patch-id keeps three lines of context whatever the user's git config says; fails_when=diff.context=0
// drops the moved context from both hashes and the carry passes unread base edits; seam=patchId; no_claim=-
test('diff.context=0 in the user\'s git config still routes moved context to a scoped review', () => {
// drops the moved context from both hashes and the carry calls it a plain base merge; seam=patchId; no_claim=-
test('diff.context=0 in the user\'s git config still sees the moved context', () => {
const { repo, body } = landedFirst({ 'lib/config.js': configWith({ 'f = 6': 'f = 60' }) });
repo.git('config', 'diff.context', '0');
const out = carry(repo, body);
expect([out.status, out.out]).toEqual([EXIT.refused, expect.stringContaining('CARRY: refused (RECEIPT_CARRY_SCOPED_REVIEW)')]);
expect(out.status, out.err).toBe(EXIT.ok);
expect(receiptIn(body).carry!.reason).toContain('base context moved next to unchanged own lines (lib/config.js; CI at head checks it)');
}, 90_000);
test('an unrelated main change carries', () => {
+158 -130
View File
@@ -301,35 +301,21 @@ describe('a restamp after a lost slot (GST-895, GBRA-218, gbrain #8134)', () =>
});
describe('adjacent base edits (GST-384, #3631, founderstar#441)', () => {
// Value: protects=a base edit next to the branch's unchanged hunk asks for a scoped review of only those hunks (finish
// context=N, carry RECEIPT_CARRY_SCOPED_REVIEW), and a clean scoped review lets it through; fails_when=it forces the
// full loop (RECEIPT_CARRY_PRODUCT_CHANGED, behavior=1) or passes silently with no review; seam=lib/ship-patch.ts;
// no_claim=the scoped reviewer's judgment
test('finish stops for a scoped review of the spliced JSON entry, then continues with a clean record', () => {
// Value: protects=GST-3562 G: a base edit next to the branch's unchanged hunk (the JSON entry where the branch changed one
// key and the base the next, an inserted guard() under a base-edited line) counts as reviewed, with CI on the merged head
// as the check; a hunk the merge spliced still stops for one scoped reader and a clean record lets it through;
// fails_when=the adjacent edit forces the full loop (behavior=1) or a reader, or a spliced hunk passes silently;
// seam=lib/ship-patch.ts via finish; no_claim=the scoped reviewer's judgment
test('finish routes an adjacent base edit as base, and stops for a scoped review of a spliced hunk', () => {
const f = fx({ 'data/flavor.json': FLAVOR('old', 'old') }, { 'data/flavor.json': FLAVOR('Bright and new', 'old') });
const reviewed = wtree(f);
const reviewedBase = mergeBase(f);
const post = snapshot(f);
f.advanceBase({ 'data/flavor.json': FLAVOR('old', 'pat-pat') });
mergeMain(f, { 'data/flavor.json': FLAVOR('Bright and new', 'pat-pat') });
const r = finish(f, reviewed, post, ['--reviewed-base', reviewedBase]);
expect(lineOf(r.stdout, 'ROUTE')).toMatch(/ behavior=0 .* context=1$/);
expect(r.status).toBe(3);
const packet = /STOP: base context moved next to the reviewed hunks in data\/flavor\.json: .* reads (\S+),/.exec(r.stdout)?.[1];
expect(packet).toBeDefined();
const text = fs.readFileSync(packet!, 'utf8');
expect(text).toContain('"pat": "pat-pat"');
expect(text).toContain('"headline": "Bright and new"');
const record = path.join(f.root, 'scoped.json');
fs.writeFileSync(record, JSON.stringify({ tree: wtree(f), paths: ['data/flavor.json'], reviewer: 'anthropic/claude-opus-5-5', verdict: 'blocking' }));
expect(finish(f, reviewed, post, ['--reviewed-base', reviewedBase, '--context-reviewed', record]).stdout).toContain('STOP: --context-reviewed: the scoped review is "blocking"');
fs.writeFileSync(record, JSON.stringify({ tree: reviewed, paths: ['data/flavor.json'], reviewer: 'anthropic/claude-opus-5-5', verdict: 'clean' }));
expect(finish(f, reviewed, post, ['--reviewed-base', reviewedBase, '--context-reviewed', record]).stdout).toContain(`STOP: --context-reviewed: the scoped review is for tree ${reviewed.slice(0, 12)}`);
fs.writeFileSync(record, JSON.stringify({ tree: wtree(f), paths: [], reviewer: 'anthropic/claude-opus-5-5', verdict: 'clean' }));
expect(finish(f, reviewed, post, ['--reviewed-base', reviewedBase, '--context-reviewed', record]).stdout).toContain('STOP: --context-reviewed: the scoped review does not cover data/flavor.json');
fs.writeFileSync(record, JSON.stringify({ tree: wtree(f), paths: ['data/flavor.json'], reviewer: 'anthropic/claude-opus-5-5', verdict: 'clean' }));
const ok = finish(f, reviewed, post, ['--reviewed-base', reviewedBase, '--context-reviewed', record]);
expect([ok.status, ok.stdout.includes('NEXT: Step 16 stage 5')]).toEqual([0, true]);
const adjacent = finish(f, reviewed, post, ['--reviewed-base', reviewedBase]);
expect([adjacent.status, lineOf(adjacent.stdout, 'ROUTE')], adjacent.stdout).toEqual([0, expect.stringMatching(/ behavior=0 .* base=1 context=0$/)]);
expect(adjacent.stdout).toContain('NEXT: Step 16 stage 5');
const guard = (text: string) => text.replace('export const l5 = 5;\n', 'export const l5 = 5;\nguard();\n');
const inserted = fx({ 'src/m.ts': lines(9) }, { 'src/m.ts': guard(lines(9)) });
@@ -339,28 +325,70 @@ describe('adjacent base edits (GST-384, #3631, founderstar#441)', () => {
inserted.advanceBase({ 'src/m.ts': lines(9, { 4: 'export const l4 = 40;' }) });
mergeMain(inserted, { 'src/m.ts': guard(lines(9, { 4: 'export const l4 = 40;' })) });
const i = finish(inserted, reviewed2, post2, ['--reviewed-base', base2]);
expect([i.status, lineOf(i.stdout, 'ROUTE')]).toEqual([3, expect.stringMatching(/ behavior=0 .* context=1$/)]);
expect([i.status, lineOf(i.stdout, 'ROUTE')], i.stdout).toEqual([0, expect.stringMatching(/ behavior=0 .* base=1 context=0$/)]);
const list = (entries: string) => `export const METHODS = [${entries}];\n`;
const s = fx({ 'src/methods.ts': list('"prep"') }, { 'src/methods.ts': list('"prep", "brief"') });
const reviewed3 = wtree(s);
const base3 = mergeBase(s);
const post3 = snapshot(s);
s.advanceBase({ 'src/methods.ts': list('"prep", "talk"') });
mergeMain(s, { 'src/methods.ts': list('"prep", "talk", "brief"') });
const r = finish(s, reviewed3, post3, ['--reviewed-base', base3]);
expect([r.status, lineOf(r.stdout, 'ROUTE')], r.stdout).toEqual([3, expect.stringMatching(/ behavior=0 .* context=1$/)]);
const packet = /STOP: the base merge spliced lines into the reviewed hunks in src\/methods\.ts: .* reads (\S+),/.exec(r.stdout)?.[1];
expect(packet).toBeDefined();
expect(fs.readFileSync(packet!, 'utf8')).toContain('"prep", "talk", "brief"');
const record = path.join(s.root, 'scoped.json');
fs.writeFileSync(record, JSON.stringify({ tree: wtree(s), paths: ['src/methods.ts'], reviewer: 'anthropic/claude-opus-5-5', verdict: 'blocking' }));
expect(finish(s, reviewed3, post3, ['--reviewed-base', base3, '--context-reviewed', record]).stdout).toContain('STOP: --context-reviewed: the scoped review is "blocking"');
fs.writeFileSync(record, JSON.stringify({ tree: reviewed3, paths: ['src/methods.ts'], reviewer: 'anthropic/claude-opus-5-5', verdict: 'clean' }));
expect(finish(s, reviewed3, post3, ['--reviewed-base', base3, '--context-reviewed', record]).stdout).toContain(`STOP: --context-reviewed: the scoped review is for tree ${reviewed3.slice(0, 12)}`);
fs.writeFileSync(record, JSON.stringify({ tree: wtree(s), paths: [], reviewer: 'anthropic/claude-opus-5-5', verdict: 'clean' }));
expect(finish(s, reviewed3, post3, ['--reviewed-base', base3, '--context-reviewed', record]).stdout).toContain('STOP: --context-reviewed: the scoped review does not cover src/methods.ts');
fs.writeFileSync(record, JSON.stringify({ tree: wtree(s), paths: ['src/methods.ts'], reviewer: 'anthropic/claude-opus-5-5', verdict: 'clean' }));
const ok = finish(s, reviewed3, post3, ['--reviewed-base', base3, '--context-reviewed', record]);
expect([ok.status, ok.stdout.includes('NEXT: Step 16 stage 5')], ok.stdout).toEqual([0, true]);
});
// Value: protects=same as above, for the receipt carry; and the same added line moved to another function is
// RECEIPT_CARRY_PRODUCT_CHANGED; fails_when=carry refuses the adjacent edit outright, carries it silently, or carries
// a moved hunk; seam=lib/ship-patch.ts; no_claim=gh pr edit (--body stands in)
test('carry asks for a scoped review of an adjacent base edit, carries with a clean one, and refuses a moved hunk', () => {
const repo = makeFixtureRepo({ prefix: 'ship-rereview-' }); repos.push(repo);
// Value: protects=GST-3562 G for the receipt carry: an adjacent base edit next to the branch's unchanged hunk carries with
// no reader (CI at head checks it); a hunk the merge spliced asks for one scoped review and carries with a clean one; the
// same added line moved to another function is RECEIPT_CARRY_PRODUCT_CHANGED; fails_when=carry refuses the adjacent edit,
// carries a spliced hunk silently, or carries a moved hunk; seam=lib/ship-patch.ts; no_claim=gh pr edit (--body stands in)
test('carry passes an adjacent base edit, asks for a scoped review of a spliced hunk, and refuses a moved hunk', () => {
const src = (edit: Record<number, string> = {}) => Array.from({ length: 12 }, (_, i) => edit[i + 1] ?? `exports.v${i + 1} = ${i + 1};`).join('\n') + '\n';
repo.git('checkout', '-q', 'main');
write(repo.work, 'lib/rows.js', src()); repo.git('add', '-A'); repo.git('commit', '-qm', 'rows'); repo.git('push', '-q', 'origin', 'main');
repo.git('checkout', '-q', 'feature'); repo.git('merge', '-q', '--no-edit', 'main');
write(repo.work, 'lib/rows.js', src({ 6: 'exports.v6 = 600;' })); repo.git('commit', '-qam', 'feat: v6');
const reviewed = repo.git('rev-parse', 'HEAD');
const body = path.join(repo.root, 'body.md');
fs.writeFileSync(body, placeReceipt('## Summary\n\nProse.\n', { schema_version: 1, pr: 9, head: reviewed, base: 'main', queue_mode: 'stamp-at-merge' } as any));
repo.git('checkout', '-q', 'main');
write(repo.work, 'lib/rows.js', src({ 5: 'exports.v5 = "five";' })); repo.git('commit', '-qam', 'main: v5'); repo.git('push', '-q', 'origin', 'main');
repo.git('checkout', '-q', 'feature');
spawnMerge(repo, { 'lib/rows.js': src({ 5: 'exports.v5 = "five";', 6: 'exports.v6 = 600;' }) });
const head = repo.git('rev-parse', 'HEAD');
const carry = (extra: string[] = []) => runBin(repo, 'gstack-ship-receipt', ['carry', '--body', body, '--base', 'main', ...extra]);
const setup = (reviewedEdit: Record<number, string>, baseEdit: Record<number, string>, merged: Record<number, string>) => {
const repo = makeFixtureRepo({ prefix: 'ship-rereview-' }); repos.push(repo);
repo.git('checkout', '-q', 'main');
write(repo.work, 'lib/rows.js', src()); repo.git('add', '-A'); repo.git('commit', '-qm', 'rows'); repo.git('push', '-q', 'origin', 'main');
repo.git('checkout', '-q', 'feature'); repo.git('merge', '-q', '--no-edit', 'main');
write(repo.work, 'lib/rows.js', src(reviewedEdit)); repo.git('commit', '-qam', 'feat: v6');
const reviewed = repo.git('rev-parse', 'HEAD');
const body = path.join(repo.root, 'body.md');
fs.writeFileSync(body, placeReceipt('## Summary\n\nProse.\n', { schema_version: 1, pr: 9, head: reviewed, base: 'main', queue_mode: 'stamp-at-merge' } as any));
repo.git('checkout', '-q', 'main');
write(repo.work, 'lib/rows.js', src(baseEdit)); repo.git('commit', '-qam', 'main: edit'); repo.git('push', '-q', 'origin', 'main');
repo.git('checkout', '-q', 'feature');
spawnMerge(repo, { 'lib/rows.js': src(merged) });
const carry = (extra: string[] = []) => runBin(repo, 'gstack-ship-receipt', ['carry', '--body', body, '--base', 'main', ...extra]);
return { repo, reviewed, head: repo.git('rev-parse', 'HEAD'), body, carry };
};
const adjacent = setup({ 6: 'exports.v6 = 600;' }, { 5: 'exports.v5 = "five";' }, { 5: 'exports.v5 = "five";', 6: 'exports.v6 = 600;' });
const passed = adjacent.carry();
expect(passed.status, passed.err).toBe(EXIT.ok);
expect(extractReceipt(fs.readFileSync(adjacent.body, 'utf8')).receipt!.carry!.reason).toContain('base context moved next to unchanged own lines (lib/rows.js; CI at head checks it)');
const guard = (text: string, after: string) => text.replace('authorize();\n', '').replace(after + '\n', after + '\nauthorize();\n');
const rows = () => fs.readFileSync(path.join(adjacent.repo.work, 'lib/rows.js'), 'utf8');
write(adjacent.repo.work, 'lib/rows.js', guard(rows(), 'exports.v2 = 2;')); adjacent.repo.git('commit', '-qam', 'feat: guard v2');
fs.writeFileSync(adjacent.body, placeReceipt('## Summary\n\nProse.\n', { schema_version: 1, pr: 9, head: adjacent.repo.git('rev-parse', 'HEAD'), base: 'main', queue_mode: 'stamp-at-merge' } as any));
write(adjacent.repo.work, 'lib/rows.js', guard(rows(), 'exports.v4 = 4;')); adjacent.repo.git('commit', '-qam', 'feat: move the guard');
const moved = adjacent.carry();
expect(moved.status).toBe(EXIT.refused);
expect(moved.out).toContain('RECEIPT_CARRY_PRODUCT_CHANGED');
expect(moved.err).toContain('lib/rows.js');
const { repo, reviewed, head, body, carry } = setup({ 6: 'exports.v6 = 6 + 60;' }, { 6: 'exports.v6 = 6 + 7;' }, { 6: 'exports.v6 = 6 + 7 + 60;' });
fs.writeFileSync(path.join(repo.work, '.git', 'gstack'), 'not a directory');
const blocked = carry();
expect([blocked.status, blocked.out.includes('RECEIPT_CARRY_REFUSED'), blocked.err.includes('cannot be written')]).toEqual([EXIT.refused, true, true]);
@@ -378,24 +406,15 @@ describe('adjacent base edits (GST-384, #3631, founderstar#441)', () => {
fs.writeFileSync(record, JSON.stringify({ head, paths: ['lib/rows.js'], reviewer: 'anthropic/claude-opus-5-5', verdict: 'clean' }));
const ok = carry(['--scoped-review', record]);
expect(ok.status).toBe(EXIT.ok);
expect(extractReceipt(fs.readFileSync(body, 'utf8')).receipt!.carry!.reason).toBe('base merge + base context moved (scoped review by anthropic/claude-opus-5-5: lib/rows.js)');
const guard = (text: string, after: string) => text.replace('authorize();\n', '').replace(after + '\n', after + '\nauthorize();\n');
const rows = () => fs.readFileSync(path.join(repo.work, 'lib/rows.js'), 'utf8');
write(repo.work, 'lib/rows.js', guard(rows(), 'exports.v2 = 2;')); repo.git('commit', '-qam', 'feat: guard v2');
fs.writeFileSync(body, placeReceipt('## Summary\n\nProse.\n', { schema_version: 1, pr: 9, head: repo.git('rev-parse', 'HEAD'), base: 'main', queue_mode: 'stamp-at-merge' } as any));
write(repo.work, 'lib/rows.js', guard(rows(), 'exports.v4 = 4;')); repo.git('commit', '-qam', 'feat: move the guard');
const moved = carry();
expect(moved.status).toBe(EXIT.refused);
expect(moved.out).toContain('RECEIPT_CARRY_PRODUCT_CHANGED');
expect(moved.err).toContain('lib/rows.js');
expect(extractReceipt(fs.readFileSync(body, 'utf8')).receipt!.carry!.reason).toBe('base merge + spliced hunks (scoped review by anthropic/claude-opus-5-5: lib/rows.js)');
});
});
describe('carry with a context path and a gap elsewhere (GST-407 cycle 5)', () => {
// Value: protects=a scoped review of the context paths carries only when the rest of the product diff is unchanged;
// fails_when=a product path the walk skips (a stamp_files sibling whose glob a base edit demoted, here plugin/b.json,
// whose branch edit also landed on main) drops out of the product patch-id unnamed and the receipt carries under a
// scoped review that never saw it; seam=bin/gstack-ship-receipt cmdCarry; no_claim=none
// Value: protects=a context path carries only when the rest of the product diff is unchanged, and once it is, a large
// context path carries with no reader (GST-3562 G); fails_when=a product path the walk skips (a stamp_files sibling
// whose glob a base edit demoted, here plugin/b.json, whose branch edit also landed on main) drops out of the product
// patch-id unnamed and the receipt carries without it; seam=bin/gstack-ship-receipt cmdCarry; no_claim=none
test('carry refuses a product patch-id gap outside the context paths', () => {
const repo = makeFixtureRepo({ prefix: 'ship-rereview-gap-' }); repos.push(repo);
const src = (edit: Record<number, string> = {}) => Array.from({ length: 12 }, (_, i) => edit[i + 1] ?? `exports.v${i + 1} = ${i + 1};`).join('\n') + '\n';
@@ -424,7 +443,8 @@ describe('carry with a context path and a gap elsewhere (GST-407 cycle 5)', () =
repo.git('checkout', '-q', 'feature');
spawnMerge(repo, { 'lib/rows.js': src({ 5: 'exports.v5 = "5";', 6: 'exports.v6 = 600;' }) + Array.from({ length: 220 }, (_, i) => `exports.w${i} = ${i};\n`).join('') });
const big = runBin(repo, 'gstack-ship-receipt', ['carry', '--body', body, '--base', 'main']);
expect([big.status, big.out.trim().split('\n')[0], big.err.includes('too large for the scoped review')]).toEqual([EXIT.refused, 'CARRY: refused (RECEIPT_CARRY_PRODUCT_CHANGED)', true]);
expect(big.status, big.err).toBe(EXIT.ok);
expect(extractReceipt(fs.readFileSync(body, 'utf8')).receipt!.carry!.reason).toContain('base context moved next to unchanged own lines (lib/rows.js; CI at head checks it)');
});
});
@@ -605,16 +625,17 @@ describe('test-only and audit-requested edits after the docs audit (GST-391, gbr
});
});
describe('preflight carry route for an adjacent base edit (GST-442)', () => {
// Value: protects=/ship Step 1's carry check offers the scoped review when the base edited context next to a reviewed hunk,
// instead of treating the refusal as "run the full loop", and its dry run writes nothing; fails_when=preflight acts only on
// 'CARRY: would carry' or carry --dry-run writes the packet; seam=gstack-ship-receipt carry --dry-run; no_claim=the reviewer
describe('preflight carry route for a spliced hunk (GST-442)', () => {
// Value: protects=/ship Step 1's carry check offers the scoped review when the base merge spliced lines into a reviewed hunk
// (GST-3562 G: an adjacent base edit alone now carries), instead of treating the refusal as "run the full loop", and its
// dry run writes nothing; fails_when=preflight acts only on 'CARRY: would carry' or carry --dry-run writes the packet;
// seam=gstack-ship-receipt carry --dry-run; no_claim=the reviewer
test('preflight routes RECEIPT_CARRY_SCOPED_REVIEW to one scoped review, and the dry run writes no packet', () => {
const src = (edit: Record<number, string> = {}) => Array.from({ length: 12 }, (_, i) => edit[i + 1] ?? `exports.v${i + 1} = ${i + 1};`).join('\n') + '\n';
const f = fx({ 'lib/rows.js': src() }, { 'lib/rows.js': src({ 6: 'exports.v6 = 600;' }) });
const f = fx({ 'lib/rows.js': src() }, { 'lib/rows.js': src({ 6: 'exports.v6 = 6 + 60;' }) });
const reviewed = f.git('rev-parse', 'HEAD').stdout.trim();
f.advanceBase({ 'lib/rows.js': src({ 5: 'exports.v5 = "five";' }) });
mergeMain(f, { 'lib/rows.js': src({ 5: 'exports.v5 = "five";', 6: 'exports.v6 = 600;' }) });
f.advanceBase({ 'lib/rows.js': src({ 6: 'exports.v6 = 6 + 7;' }) });
mergeMain(f, { 'lib/rows.js': src({ 6: 'exports.v6 = 6 + 7 + 60;' }) });
const head = f.git('rev-parse', 'HEAD').stdout.trim();
const view = path.join(f.root, 'view.json');
fs.writeFileSync(view, JSON.stringify({ body: placeReceipt('## Summary\n\nProse.\n', { schema_version: 1, pr: 9, head: reviewed, base: 'main', queue_mode: 'stamp-at-merge' } as any), headRefOid: head }));
@@ -650,10 +671,10 @@ describe('preflight carry route for an adjacent base edit (GST-442)', () => {
// round 2); fails_when=the dry run returns the scoped refusal before the receipt's other carry checks; seam=gh; no_claim=none
test('a dry run that the receipt would refuse anyway names that refusal, not the scoped route', () => {
const src = (edit: Record<number, string> = {}) => Array.from({ length: 12 }, (_, i) => edit[i + 1] ?? `exports.v${i + 1} = ${i + 1};`).join('\n') + '\n';
const f = fx({ 'lib/rows.js': src() }, { 'lib/rows.js': src({ 6: 'exports.v6 = 600;' }) });
const f = fx({ 'lib/rows.js': src() }, { 'lib/rows.js': src({ 6: 'exports.v6 = 6 + 60;' }) });
const reviewed = f.git('rev-parse', 'HEAD').stdout.trim();
f.advanceBase({ 'lib/rows.js': src({ 5: 'exports.v5 = "five";' }) });
mergeMain(f, { 'lib/rows.js': src({ 5: 'exports.v5 = "five";', 6: 'exports.v6 = 600;' }) });
f.advanceBase({ 'lib/rows.js': src({ 6: 'exports.v6 = 6 + 7;' }) });
mergeMain(f, { 'lib/rows.js': src({ 6: 'exports.v6 = 6 + 7 + 60;' }) });
const head = f.git('rev-parse', 'HEAD').stdout.trim();
const view = path.join(f.root, 'view.json');
fs.writeFileSync(view, JSON.stringify({ body: placeReceipt('## Summary\n\nProse.\n', { schema_version: 1, pr: 9, head: reviewed, base: 'main', queue_mode: 'stamp-at-merge', gstack_version: '1.0.0' } as any), headRefOid: head }));
@@ -947,17 +968,19 @@ describe('finish after a completed fix-check (GST-1130, GEVA-218)', () => {
});
});
// Value: protects=a base merge that puts lines already merged at base next to the branch's reviewed, unchanged hunk reaches
// the scoped read even when those base lines push a packet section past PACKET_SECTION_CAP (founderstar#515, #3923); only the
// branch's own lines count toward the cap; fails_when=finish forces the behavior route for a section that is over only
// because of base lines, or lets a section the branch's own lines push over reach the scoped read; seam=contextPacket's count
describe('base lines do not count toward the scoped-review cap (GST-1226, founderstar#515, #3923)', () => {
// Value: protects=GST-3562 G: a base merge that puts lines next to the branch's reviewed, unchanged hunk counts as reviewed
// however large either side is (founderstar#515, #3923 once needed a scoped read), with CI on the merged head as the check;
// the scoped-review cap now applies to hunks the merge spliced, where only the branch's own lines count;
// fails_when=finish asks for a reader or the behavior route for unchanged own lines, or lets a spliced section the branch's
// own lines push over the cap reach the scoped read; seam=comparePath + contextPacket's count
describe('base lines next to unchanged own lines need no reader; the cap binds spliced hunks (GST-1226, GST-3562 G)', () => {
const block = (name: string, n: number) => Array.from({ length: n }, (_, i) => `export const ${name}${i + 1} = ${i + 1};`);
const join = (rows: string[]) => rows.join('\n') + '\n';
const at = (n: number, after: number, add: string[]) => { const rows = lines(n).trimEnd().split('\n'); rows.splice(after, 0, ...add); return rows; };
const scoped = (r: { status: number | null; stdout: string }) => [r.status, lineOf(r.stdout, 'ROUTE').replace(/^.* behavior=/, 'behavior='), r.stdout.includes('STOP: base context moved next to the reviewed hunks in src/shots.ts'), r.stdout.includes('SCOPED_REVIEW: too large')];
const routed = (r: { status: number | null; stdout: string }) => [r.status, lineOf(r.stdout, 'ROUTE').replace(/^.* behavior=/, 'behavior='), r.stdout.includes('STOP: the base merge spliced lines into the reviewed hunks in src/shots.ts'), r.stdout.includes('SCOPED_REVIEW: too large')];
const reviewedAsBase = [0, 'behavior=0 docs=0 metadata=0 tests=0 base=1 context=0', false, false];
test('210 lines another PR merged at base next to the branch\'s 76 reviewed lines reach the scoped read', () => {
test('210 lines another PR merged at base next to the branch\'s 76 reviewed lines count as reviewed', () => {
const pr = block('pr', 76), other = block('other', 210);
const f = fx({ 'src/shots.ts': lines(20) }, { 'src/shots.ts': join(at(20, 10, pr)) });
const reviewed = wtree(f), reviewedBase = mergeBase(f), post = snapshot(f);
@@ -965,10 +988,10 @@ describe('base lines do not count toward the scoped-review cap (GST-1226, founde
const merged = at(20, 11, other); merged.splice(10, 0, ...pr);
mergeMain(f, { 'src/shots.ts': join(merged) });
expect(f.git('show', 'HEAD:src/shots.ts').stdout).toBe(join(merged));
expect(scoped(finish(f, reviewed, post, ['--reviewed-base', reviewedBase]))).toEqual([3, 'behavior=0 docs=0 metadata=0 tests=0 base=0 context=1', true, false]);
expect(routed(finish(f, reviewed, post, ['--reviewed-base', reviewedBase]))).toEqual(reviewedAsBase);
});
test('a changed trailing context line with the same +/- lines reaches the scoped read beside a 221-line base rewrite', () => {
test('a changed trailing context line with the same +/- lines beside a 221-line base rewrite counts as reviewed', () => {
const pr = block('pr', 76);
const f = fx({ 'src/shots.ts': lines(300) }, { 'src/shots.ts': join(at(300, 10, pr)) });
const reviewed = wtree(f), reviewedBase = mergeBase(f), post = snapshot(f);
@@ -978,39 +1001,43 @@ describe('base lines do not count toward the scoped-review cap (GST-1226, founde
const merged = lines(300, edits).trimEnd().split('\n'); merged.splice(10, 0, ...pr);
mergeMain(f, { 'src/shots.ts': join(merged) });
expect(f.git('show', 'HEAD:src/shots.ts').stdout).toBe(join(merged));
expect(scoped(finish(f, reviewed, post, ['--reviewed-base', reviewedBase]))).toEqual([3, 'behavior=0 docs=0 metadata=0 tests=0 base=0 context=1', true, false]);
expect(routed(finish(f, reviewed, post, ['--reviewed-base', reviewedBase]))).toEqual(reviewedAsBase);
});
test('a section the branch\'s own 230 lines push past the cap still takes the behavior route', () => {
const pr = block('pr', 230), other = block('other', 5);
const f = fx({ 'src/shots.ts': lines(20) }, { 'src/shots.ts': join(at(20, 10, pr)) });
const reviewed = wtree(f), reviewedBase = mergeBase(f), post = snapshot(f);
f.advanceBase({ 'src/shots.ts': join(at(20, 11, other)) });
const merged = at(20, 11, other); merged.splice(10, 0, ...pr);
mergeMain(f, { 'src/shots.ts': join(merged) });
const r = finish(f, reviewed, post, ['--reviewed-base', reviewedBase]);
expect(scoped(r)).toEqual([3, 'behavior=1 docs=0 metadata=0 tests=0 base=0 context=0', false, true]);
expect(r.stdout.includes('STOP: behavior, tests or build inputs changed since review (src/shots.ts)')).toBe(true);
test('the branch\'s own 230 unchanged lines and a base change past BASE_SECTION_CEILING count as reviewed', () => {
for (const [own, base] of [[230, 5], [76, 2100]]) {
const pr = block('pr', own), other = block('other', base);
const f = fx({ 'src/shots.ts': lines(20) }, { 'src/shots.ts': join(at(20, 10, pr)) });
const reviewed = wtree(f), reviewedBase = mergeBase(f), post = snapshot(f);
f.advanceBase({ 'src/shots.ts': join(at(20, 11, other)) });
const merged = at(20, 11, other); merged.splice(10, 0, ...pr);
mergeMain(f, { 'src/shots.ts': join(merged) });
expect(routed(finish(f, reviewed, post, ['--reviewed-base', reviewedBase]))).toEqual(reviewedAsBase);
}
});
test('a base change past BASE_SECTION_CEILING counts in full again and takes the behavior route', () => {
const pr = block('pr', 76), other = block('other', 2100);
const f = fx({ 'src/shots.ts': lines(20) }, { 'src/shots.ts': join(at(20, 10, pr)) });
const reviewed = wtree(f), reviewedBase = mergeBase(f), post = snapshot(f);
f.advanceBase({ 'src/shots.ts': join(at(20, 11, other)) });
const merged = at(20, 11, other); merged.splice(10, 0, ...pr);
mergeMain(f, { 'src/shots.ts': join(merged) });
expect(scoped(finish(f, reviewed, post, ['--reviewed-base', reviewedBase]))).toEqual([3, 'behavior=1 docs=0 metadata=0 tests=0 base=0 context=0', false, true]);
test('20 spliced lines reach the scoped read; 120 spliced lines pass the cap and take the behavior route', () => {
const spliced = (n: number) => {
const edit = (v: (i: number) => string) => Object.fromEntries(Array.from({ length: n }, (_, i) => [i + 3, `export const l${i + 3} = ${v(i + 3)};`]));
const f = fx({ 'src/shots.ts': lines(n + 10) }, { 'src/shots.ts': lines(n + 10, edit(i => `${i} + 1000`)) });
const reviewed = wtree(f), reviewedBase = mergeBase(f), post = snapshot(f);
f.advanceBase({ 'src/shots.ts': lines(n + 10, edit(i => `${i} + 7`)) });
mergeMain(f, { 'src/shots.ts': lines(n + 10, edit(i => `${i} + 7 + 1000`)) });
return finish(f, reviewed, post, ['--reviewed-base', reviewedBase]);
};
expect(routed(spliced(20))).toEqual([3, 'behavior=0 docs=0 metadata=0 tests=0 base=0 context=1', true, false]);
const big = spliced(120);
expect(routed(big)).toEqual([3, 'behavior=1 docs=0 metadata=0 tests=0 base=0 context=0', false, true]);
expect(big.stdout).toContain('STOP: behavior, tests or build inputs changed since review (src/shots.ts)');
});
});
// Value: protects=a base merge that only changes context lines inside the branch's own unchanged hunks reaches the carry's
// scoped read even when those context lines and hunk headers push a section past PACKET_SECTION_CAP (founderstar#802: 22
// hunks, +66/-11, a section of about 205 lines); a branch whose own +/- lines pass the cap is still refused;
// fails_when=carry counts base context lines (in the branch's hunks or in the base's change) toward the cap and refuses
// with RECEIPT_CARRY_PRODUCT_CHANGED, or lets a section the branch's own lines push over reach the scoped read;
// seam=contextPacket's count; no_claim=the scoped reviewer's judgment
describe('only the branch\'s own +/- lines count toward the scoped-review cap in carry (GST-2229, founderstar#802)', () => {
// Value: protects=GST-3562 G for the carry: a base merge that only changes context lines inside or next to the branch's own
// unchanged hunks carries with no reader however large the sections are (founderstar#802 once needed a scoped read); the
// scoped-review cap binds spliced hunks, counting only the branch's own +/- lines; fails_when=carry refuses unchanged own
// lines, or lets a spliced section the branch's own lines push over the cap reach the scoped read;
// seam=bin/gstack-ship-receipt cmdCarry + contextPacket's count; no_claim=the scoped reviewer's judgment
describe('carry passes moved context next to unchanged own lines; the cap binds spliced hunks (GST-2229, GST-3562 G)', () => {
const row = (at: number, v: string | number = at) => `exports.v${at} = ${v};`;
/** `hunks` branch hunks 15 lines apart, alternating a 1-to-3 replacement and a 3-line insertion; the base edits the line two below each of the first `edits` spots, inside a branch hunk's context where there is one. */
const file = (hunks: number, edits: number, pr: boolean, base: boolean) => Array.from({ length: 15 * Math.max(hunks, edits) + 10 }, (_, i) => {
@@ -1020,46 +1047,47 @@ describe('only the branch\'s own +/- lines count toward the scoped-review cap in
const added = [0, 1, 2].map(j => `exports.pr${at}_${j} = ${j};`);
return k % 2 ? [line, ...added] : added;
}).flat().join('\n') + '\n';
const carry = (hunks: number, edits = hunks) => {
const carryOf = (main: string, branch: string, base: string, merged: string) => {
const repo = makeFixtureRepo({ prefix: 'ship-rereview-own-' }); repos.push(repo);
repo.git('checkout', '-q', 'main');
write(repo.work, 'lib/game.js', file(hunks, edits, false, false)); repo.git('add', '-A'); repo.git('commit', '-qm', 'game'); repo.git('push', '-q', 'origin', 'main');
write(repo.work, 'lib/game.js', main); repo.git('add', '-A'); repo.git('commit', '-qm', 'game'); repo.git('push', '-q', 'origin', 'main');
repo.git('checkout', '-q', 'feature'); repo.git('merge', '-q', '--no-edit', 'main');
write(repo.work, 'lib/game.js', file(hunks, edits, true, false)); repo.git('commit', '-qam', 'feat: game');
write(repo.work, 'lib/game.js', branch); repo.git('commit', '-qam', 'feat: game');
const body = path.join(repo.root, 'body.md');
fs.writeFileSync(body, placeReceipt('## Summary\n\nProse.\n', { schema_version: 1, pr: 9, head: repo.git('rev-parse', 'HEAD'), base: 'main', queue_mode: 'stamp-at-merge' } as any));
repo.git('checkout', '-q', 'main');
write(repo.work, 'lib/game.js', file(hunks, edits, false, true)); repo.git('commit', '-qam', 'main: context'); repo.git('push', '-q', 'origin', 'main');
write(repo.work, 'lib/game.js', base); repo.git('commit', '-qam', 'main: context'); repo.git('push', '-q', 'origin', 'main');
repo.git('checkout', '-q', 'feature');
spawnMerge(repo, { 'lib/game.js': file(hunks, edits, true, true) });
expect(fs.readFileSync(path.join(repo.work, 'lib/game.js'), 'utf8')).toBe(file(hunks, edits, true, true));
return runBin(repo, 'gstack-ship-receipt', ['carry', '--body', body, '--base', 'main']);
spawnMerge(repo, { 'lib/game.js': merged });
expect(fs.readFileSync(path.join(repo.work, 'lib/game.js'), 'utf8')).toBe(merged);
return { r: runBin(repo, 'gstack-ship-receipt', ['carry', '--body', body, '--base', 'main']), body };
};
const carry = (hunks: number, edits = hunks) => carryOf(file(hunks, edits, false, false), file(hunks, edits, true, false), file(hunks, edits, false, true), file(hunks, edits, true, true));
const spliced = (n: number) => {
const text = (v: (i: number) => string) => Array.from({ length: n + 10 }, (_, i) => row(i + 1, i >= 2 && i < n + 2 ? v(i + 1) : i + 1)).join('\n') + '\n';
return carryOf(text(i => String(i)), text(i => `${i} + 1000`), text(i => `${i} + 7`), text(i => `${i} + 7 + 1000`)).r;
};
const section = (text: string, label: string) => (new RegExp(`^${label}\\n\`\`\`diff\\n([\\s\\S]*?)\\n\`\`\`$`, 'm').exec(text)?.[1] ?? '').split('\n');
const packet = (r: { status: number | null; out: string; err: string }) => {
expect([r.status, r.out.trim().split('\n')[0]], r.err).toEqual([EXIT.refused, 'CARRY: refused (RECEIPT_CARRY_SCOPED_REVIEW)']);
const at = /reads (\S+), then/.exec(r.err)?.[1];
expect(at).toBeDefined();
return fs.readFileSync(at!, 'utf8');
};
const own = (rows: string[]) => rows.filter(l => /^[+-]/.test(l)).length;
test('22 unchanged branch hunks whose base context moved reach the scoped read with their sections over 200 lines', () => {
const text = packet(carry(22));
const current = section(text, 'Current hunks'), reviewed = section(text, 'Reviewed hunks');
expect([current.length > 200, own(current), reviewed.length > 200, own(reviewed)]).toEqual([true, 77, true, 77]);
expect(text).toContain('+exports.pr10_0 = 0;');
expect(text).toContain(' exports.v12 = "base 12";');
test('22 or 60 unchanged branch hunks and 30 scattered base edits carry with no reader', () => {
for (const [hunks, edits] of [[22, 22], [60, 60], [4, 30]]) {
const { r, body } = carry(hunks, edits);
expect(r.status, r.err).toBe(EXIT.ok);
expect(r.err).not.toContain('SCOPED_REVIEW');
expect(extractReceipt(fs.readFileSync(body, 'utf8')).receipt!.carry!.reason).toContain('base context moved next to unchanged own lines (lib/game.js; CI at head checks it)');
}
});
test('30 scattered base edits whose context lines pass 200 next to 4 unchanged branch hunks reach the scoped read', () => {
const base = section(packet(carry(4, 30)), "The base's change");
expect([base.length - own(base) > 200, own(base)]).toEqual([true, 60]);
});
test('60 branch hunks whose own +/- lines pass 200 are still too large for the scoped review', () => {
const r = carry(60);
expect([r.status, r.out.trim().split('\n')[0], r.err.includes('lib/game.js (too large for the scoped review: over 200 lines in a section)')]).toEqual([EXIT.refused, 'CARRY: refused (RECEIPT_CARRY_PRODUCT_CHANGED)', true]);
test('20 spliced lines reach the scoped read with only their own lines counted; 120 are too large for it', () => {
const ask = spliced(20);
expect([ask.status, ask.out.trim().split('\n')[0]], ask.err).toEqual([EXIT.refused, 'CARRY: refused (RECEIPT_CARRY_SCOPED_REVIEW)']);
const at = /reads (\S+), then/.exec(ask.err)?.[1];
expect(at).toBeDefined();
const text = fs.readFileSync(at!, 'utf8');
expect([own(section(text, 'Current hunks')), own(section(text, 'Reviewed hunks'))]).toEqual([40, 40]);
expect(text).toContain('+exports.v3 = 3 + 7 + 1000;');
const big = spliced(120);
expect([big.status, big.out.trim().split('\n')[0], big.err.includes('lib/game.js (too large for the scoped review: over 200 lines in a section)')]).toEqual([EXIT.refused, 'CARRY: refused (RECEIPT_CARRY_PRODUCT_CHANGED)', true]);
});
});