Skip to content

Use Garry Tan's exact Claude Code setup: 23 opinionated tools that serve as CEO, Designer, Eng Manager, Release Manager, Doc Engineer, and QA

TypeScript

ship finish: a declared mechanical version retake after a base merge binds without a new review (GST-1560) (#4053)

Garry Tan8d712d63ddb8
diff --git a/bin/gstack-review-plan b/bin/gstack-review-plan
index b5c87d80c..71522415a 100755
--- a/bin/gstack-review-plan
+++ b/bin/gstack-review-plan
@@ -5,7 +5,7 @@
* gstack-review-plan --base <ref> [--pass <full passes run>] [--last none|full|fix-check] [--fixed-blocking] [--fixed-below]
* [--blocking-open] [--touched-gate] [--critical-found] [--adversarial-ran] [--gate-tagged <n>] [--gated a,b] [--force a,b|all]
* [--reviewed-numbers <fingerprint>] [--depth-floor standard|full] [--range-base <sha>] [--pass1-depth light|standard|full] [--no-tiers]
- * [--targeted-ran <targeted_patch_id>] [--grant <approval id>] [--fix-checks <n>] [--pr <n>] [--json]
+ * [--targeted-ran <targeted_patch_id>] [--grant <approval id>] [--fix-checks <n>] [--post-review] [--pr <n>] [--json]
* gstack-review-plan --fix-check-prompt --fix-list <file> --hunks <file> --tests <file> [--callers <file>]
*
* Reads the diff against the merge base with <ref> (committed, tracked uncommitted
@@ -75,6 +75,10 @@ const HELP = `gstack-review-plan — the review depth of the next /ship step (do
gate-class edit plans that fix-check instead; a fix-check never earns another; any other row is refused (exit 3)
--fix-checks <n> fix-checks already run in this invocation: the owner's grant adds one only after the first, in the lean
loop and after a round-2 fix-check in the full loop (GEVA-223)
+ --post-review plan the Step 9 that /ship Step 16 stage 2.1 inserted for edits after the review bound (finish's
+ behavior STOP): they plan as a fix to a gate-class path, never a note, so below the round cap
+ it is a pass on the range (lean: a fix-check), and at the cap it stops for the owner, whose
+ --grant adds one scoped fix-check; pass --pass, --last and --fix-checks as the loop left them
--pr <n> the PR whose platform review counts under review.platform on (default: this branch's PR)
--declare-risk <classes> risk classes the lane declares for the diff (comma list of ${RISK_CLASSES.join(', ')}): they join
the detected classes and only raise the depth; RISK_DECLARED: prints both (GST-1129)
@@ -215,11 +219,13 @@ function main(): number {
const targeted = targetedClasses({ ...collected, ...(active ? { paths: paths.filter(p => !active.excluded.has(p)), added: kept(added), removed: kept(collected.removed) } : {}), scope, gateTagged });
const patch = collected.mergeBase ? targetedPatchId(process.cwd(), collected.mergeBase) : 'none';
const brief = targetedBriefSha();
+ const postReview = has('--post-review');
const plan = planReview({
...collected, ...exclusionInput, ...riskPaths, declared: declared as RiskClass[], shape: { panel: review.panel, readerModel: review.reader_model, platform: review.platform, head, platformReview: platform?.ok ? platform.review : null }, scope, gateTagged, targeted: { classes: targeted.classes, ran: !['uncommitted', 'none'].includes(patch) && flag('--targeted-ran') === patch }, numbers: scanNumbers(kept(added)), force, gated: list('--gated'), floor, tiers: auditEffort !== 'host',
criticalFound: has('--critical-found'), adversarialRan: has('--adversarial-ran'), reviewedNumbers: flag('--reviewed-numbers'),
- history: { fullPasses: pass, last, fixedBlocking: has('--fixed-blocking'), fixedBelow: has('--fixed-below') && last !== 'fix-check', blockingOpen: has('--blocking-open'), touchedGate: has('--touched-gate') || !!fixRange?.touched_gate, pass1Depth, rangeRuntimeLines: fixRange?.runtime_lines, granted: grant, fixChecks: has('--fix-checks') ? fixChecks : undefined },
+ history: { fullPasses: pass, last, fixedBlocking: has('--fixed-blocking'), fixedBelow: (has('--fixed-below') || (postReview && pass > 0)) && last !== 'fix-check', blockingOpen: has('--blocking-open'), touchedGate: has('--touched-gate') || !!fixRange?.touched_gate || (postReview && pass > 0), pass1Depth, rangeRuntimeLines: fixRange?.runtime_lines, granted: grant, fixChecks: has('--fix-checks') ? fixChecks : undefined },
});
+ if (postReview && pass > 0) plan.next.reason = `edits after the review bound (Step 16 stage 2.1) plan as a fix to a gate-class path, never a note: ${plan.next.reason}`;
const selection = policySelection(active && { state: 'active', specs: active.specs, keep: active.keep, excerpt: active.excerpt }, readers);
plan.dispatches.forEach((d, i) => { if (d.role !== 'fix-check') plan.dispatches[i] = selectFor(d, selection); });
const gateScan = { tagged: gateTagged, head };
diff --git a/bin/gstack-ship-receipt b/bin/gstack-ship-receipt
index 04369c030..50c73537b 100755
--- a/bin/gstack-ship-receipt
+++ b/bin/gstack-ship-receipt
@@ -57,6 +57,7 @@ import { checkReceiptProse, proseLine } from '../lib/ship-receipt-prose';
import { resolveStateRoot } from '../lib/state-root';
import { readPause, receiptBaseRed } from '../lib/base-red';
import { readRuledNotes, ruledNoteText } from '../lib/ruled-notes';
+import { readMechanicalLines } from '../lib/ship-mechanical';
import { isRegistryUnavailable, loadRegistryFromBase } from '../lib/regen';
const HELP = `gstack-ship-receipt — the \`\`\`gstack-ship-receipt\`\`\` block (docs/ship-policy.md#ship-receipt)
@@ -264,6 +265,9 @@ function cmdWrite(rest: string[], json: boolean): number {
const ruledNotes = readRuledNotes(repoRoot);
const unlisted = bodyFile ? ruledNotes.map(n => `Ruled note: ${ruledNoteText(n)}`).find(l => !bodyText.split(/\r?\n/).some(b => b.trim() === l)) : undefined;
if (unlisted) { process.stderr.write(resultLine('gstack-ship-receipt write', 'RECEIPT_INVALID', `${bodyFile} does not list ruled note ${JSON.stringify(unlisted)} (gstack-approvals rulings prints each line the body carries); nothing written`) + '\n'); return EXIT.fail; }
+ const mechanical = readMechanicalLines(repoRoot, git(['rev-parse', `${head}^{tree}`], repoRoot) ?? '');
+ const unlistedRetake = bodyFile ? mechanical.find(l => !bodyText.split(/\r?\n/).some(b => b.trim() === l)) : undefined;
+ if (unlistedRetake) { process.stderr.write(resultLine('gstack-ship-receipt write', 'RECEIPT_INVALID', `${bodyFile} does not list ${JSON.stringify(unlistedRetake)} (finish's MECHANICAL: lines; the body carries each as one line); nothing written`) + '\n'); return EXIT.fail; }
const declared = (flag(rest, '--declare-risk') ?? '').split(',').map(s => s.trim()).filter(Boolean);
if (rest.includes('--declare-risk') && (!declared.length || declared.some(c => !(RISK_CLASSES as readonly string[]).includes(c)))) { process.stderr.write(resultLine('gstack-ship-receipt write', 'RECEIPT_INVALID', `--declare-risk ${flag(rest, '--declare-risk') ?? ''}: each class is one of ${RISK_CLASSES.join(', ')}; nothing written`) + '\n'); return EXIT.fail; }
const review = receiptReviewAtHead(repoRoot, base, path.dirname(Bun.fileURLToPath(import.meta.url)), headSha ?? head, declared as RiskClass[]);
@@ -319,7 +323,7 @@ function cmdWrite(rest: string[], json: boolean): number {
policy: flag(rest, '--policy') ?? tree?.policy, queue_mode: flag(rest, '--queue-mode'), preregistration: flag(rest, '--preregistration'), history: flag(rest, '--history'),
...pregate, issues: issuesFile ? receiptIssuesFrom(issuesFile) : undefined, approval: approval.kind === 'ok' ? approval.approval : undefined,
review_loop: reviewLoop, ...(docs?.ok ? { docs: docs.docs } : {}), ...product,
- gstack_version: installedGstackVersion(), review_depth: reviewDepth, review_loop_exception: loopException?.ok ? loopException.exception : undefined, ruled_notes: ruledNotes.length ? ruledNotes : undefined, review_targeted: targeted?.ok ? targeted.targeted : undefined,
+ gstack_version: installedGstackVersion(), review_depth: reviewDepth, review_loop_exception: loopException?.ok ? loopException.exception : undefined, ruled_notes: ruledNotes.length ? ruledNotes : undefined, mechanical: mechanical.length ? mechanical : undefined, review_targeted: targeted?.ok ? targeted.targeted : undefined,
base_red: pause ? receiptBaseRed(pause) : undefined,
review_exclude: receiptExclude(review.exclude),
no_stop: noStopArg(flag(rest, '--no-stop')),
diff --git a/changelog.d/capy-gst-1560-mechanical-retake.md b/changelog.d/capy-gst-1560-mechanical-retake.md
new file mode 100644
index 000000000..cd306ab55
--- /dev/null
+++ b/changelog.d/capy-gst-1560-mechanical-retake.md
@@ -0,0 +1 @@
+- **/ship's finish routes a declared version or rules-number retake after a base merge as mechanical, with no review round.** founderstar#563 merged its base after two full passes and retook its rules number 80 → 81: one line in `scripts/core/game.gd`, `save_version` in 8 save fixtures and one golden. finish routed all 10 paths as behavior and said to insert Steps 5–11.5, while `gstack-review-plan` at the round cap said `done`, so the only exit was a fresh /ship. A base policy can now declare the constant under `mechanical_retake` (its file and one-line template, the fixture fields that carry the value, and the `.gstack/generated.json` entries that rebuild its goldens). finish proves each changed path from the diff. It needs one literal on the constant's line, a value above the reviewed one and the base's, the same new value in every changed field, goldens that regenerate byte-identically, and nothing else changed. It prints `MECHANICAL:` per path and `mechanical=<n>` on `ROUTE:`. Any other edit in those files, a value that doesn't match or a golden that doesn't regenerate keeps its old route with a `ROUTE_MECHANICAL_REFUSED:` reason. The receipt lists the paths as `Mechanical retake: …` lines, and receipt write refuses a PR body missing one. finish's behavior STOP now names `gstack-review-plan --post-review`, which plans that Step 9 as a fix to a gate-class path: a pass on the range below the round cap, and a stop for the owner's grant of one scoped fix-check at the cap, never `done`. Prior art: #3966 (GSTA-167's `carry_mechanical`). (GST-1560)
diff --git a/docs/ship-policy.md b/docs/ship-policy.md
index 9e2d9b26f..2746ffbf0 100644
--- a/docs/ship-policy.md
+++ b/docs/ship-policy.md
@@ -69,6 +69,7 @@ refuses the file (`POLICY_GSTACK_TOO_OLD`). `validate` ends with
| `land` | `{ merged_checks }` or `null` | `null` | Under `merge: direct`, the shell commands (1 to 16, one line of at most 512 characters each, 15 minutes each) [`land --pin`](#land-direct) runs on the pin merged onto the base tip when the base moved past the pin's merge base; it lands only when every one exits 0. They are repo commands, so land runs them only with `--allow-repo-commands`, never under `--dry-run`. `null` lands a stale base untested with a `STALE_BASE: warn` line. Read from the base revision only. Needs `min_gstack_version`. |
| `release_gate` | `{ cadence_hours, gate_workflow, branch, stable_ref, check_name, on_red, bisect_spend_cap_usd }` or `null` | `null` | One full paid gate on main every `cadence_hours` (8 to 168) instead of the per-push main backstop, feeding the stable release; see [release_gate](#release-gate). Every field is required: `on_red` is `hold-release`, `bisect_spend_cap_usd` 0 to 500 (0 skips the bisect). `null` keeps the per-push backstop. Needs `min_gstack_version`. |
| `bookkeeping` | glob list | `[]` | <a id="bookkeeping"></a>Root-anchored globs of bookkeeping tables a verify or ratchet step rewrites (size baselines, serial lists, limits), each ending in `.tsv`, `.csv` or `.txt` and never under `.gstack/` or `.github/` (`["scripts/*-baseline.tsv"]`). A matching file changed at most 20 lines after review binds, first touched or not, takes finish's [one scoped reader](review-policy.md#bounded-post-review-edits) instead of Steps 5–11.5; the reader still reads every changed row. Read from the base revision only. Needs `min_gstack_version`. |
+| `mechanical_retake` | `[{ path, template, fields, regen }]` | `[]` | A version or rules constant a branch may have to retake after a base merge, next to `bookkeeping`'s bounded kind: `path` is one literal file, `template` the whole line with one `{n}` (`const RULE_NUMBERS := {n}`), `fields` the `{ glob, field }` fixture fields that carry the same value, and `regen` the [`.gstack/generated.json`](pregate.md#generated) entry ids whose command regenerates its goldens. A post-review edit finish proves to be only that retake routes as `mechanical=`, with no reader and no review round; see [mechanical retakes](#mechanical-retake). At most 8 constants and 16 fields or ids each; no glob, `..`, `.gstack/` or `.github/` path. Read from the base revision only. Needs `min_gstack_version`. |
| `base_red` | `{ setup, select, timeout_sec }` or `null` | `null` | How `/ship` Step 5 proves a failure is the base branch's own before pausing on it; see [base_red](#base-red). Read from the base revision only. Needs `min_gstack_version`. |
| `changelog_fragments` | `{ dir, required_checks? }` or `null` | `null` | PRs carry unversioned [CHANGELOG fragments](#changelog-fragments) in `dir` (one flat, repo-relative directory, no `..`) and the merge step ([`land`](#land)) assigns the version (under `merge: direct`, the [release PR](#release-stamp) does). `required_checks` (up to 50 distinct names) are the checks [`train land`](#stamped-trains-under-changelog_fragments-train-land) requires present and green on a stamp commit. `null` keeps `[Unreleased]` sections and per-PR stamps. Needs `min_gstack_version`. |
@@ -1717,6 +1718,67 @@ merged with the new base in a scratch worktree and, when every lane passes,
rewrites the receipt without `base_red`.
<a id="receipt-carry"></a>
+<a id="mechanical-retake"></a>
+## `mechanical_retake`: a version or rules number retaken after a base merge
+
+Some repositories number things in one constant: a save version, a rules
+number, a schema version. Two branches can take the same next number. When
+the base lands the other one first, the branch merges the base and takes the
+number after it: one literal on the constant's line, the same value in every
+save fixture, and goldens rebuilt from the generator. founderstar#563 did
+this after two full review passes (rules number 80 to 81 in
+`scripts/core/game.gd`, `save_version` in 8 fixtures under `fixtures/`, one
+golden). `finish` routed all 10 paths as behavior and said to insert Steps
+5–11.5, while `gstack-review-plan` at the round cap said `done`, so the only
+way out was a fresh /ship (GST-1560).
+
+A base policy that declares the constant lets `finish` prove the retake
+instead:
+
+```json
+"mechanical_retake": [{
+ "path": "scripts/core/game.gd",
+ "template": "const RULE_NUMBERS := {n}",
+ "fields": [{ "glob": "fixtures/saves/*.json", "field": "save_version" }],
+ "regen": ["rules-golden"]
+}]
+```
+
+`finish` runs with `--reviewed-base` and checks each declared path that
+changed since review:
+
+| Path | Proof |
+|---|---|
+| the constant (`path`) | Exactly one line matches `template` at the reviewed base, the reviewed tree, the current base and now. The reviewed branch took the number (its value differs from the reviewed base's), and the current value is above both the reviewed value and the current base's. With that one line masked on every side, the file's patch is the reviewed patch (the same comparison base paths use). |
+| a fixture (`fields`) | A matching file holds the same number of `field` lines (`field: n`, `field = n` or `"field": n,`) at the reviewed tree and now. Each one either kept its value or moved from the constant's reviewed value to its current value. With those lines masked, its patch is the reviewed patch. |
+| a golden (`regen`) | An output of a named entry in the base's `.gstack/generated.json` that the entry's command recreates byte-identically in a scratch worktree (the pregate `regen` check's proof run). |
+
+Each proven path prints `MECHANICAL: <path> (<what>)` and counts as
+`mechanical=<n>` on `ROUTE:`. It needs no reader and no review round, and
+the docs audit carries it like a base path. A declared path that fails its
+proof keeps its route from before, and `finish` prints
+`ROUTE_MECHANICAL_REFUSED: <path> <reason>`
+([troubleshooting](troubleshooting.md#route-mechanical-refused)). That covers
+any other edit in the constant's file, a fixture value that doesn't match, a
+golden that doesn't regenerate, a constant the reviewed branch never took, a
+gate path and a landed stack parent. A fixture or golden whose constant isn't a
+proven retake is refused too. Nothing is inferred: an undeclared file never
+routes as mechanical.
+
+`finish` records the proven paths for the tree it routed, and
+`gstack-ship-receipt write` copies them into the receipt's `mechanical` list
+as `Mechanical retake: <path> (<what>)`. With `--body` it refuses a PR body
+that doesn't carry each of those lines word for word.
+
+**When the route still says behavior at the round cap.** `finish`'s behavior
+STOP tells the lane to plan the inserted Step 9 with `gstack-review-plan
+--post-review` (plus `--pass`, `--last` and `--fix-checks` as the loop left
+them). Edits after the review bound plan as a fix to a gate-class path, never
+as a note. Below the round cap that's a pass on the range (a fix-check under
+the lean panel). At the cap it stops for the owner, whose recorded grant
+(`--grant`) adds one scoped fix-check, never `done`. So `finish` never asks for
+a step the planner refuses.
+
## Carrying a receipt across a base merge or a test-only fix
**Merge main into a reviewed branch; never rebase it.** What happens to the
diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md
index 60dc35525..7ccc0bfa2 100644
--- a/docs/troubleshooting.md
+++ b/docs/troubleshooting.md
@@ -3166,6 +3166,28 @@ lane change removed (a `[]` declaration lands on the base first). Or take
Steps 5–11.5 for the edit. Never shrink an edit to get under the cap by
moving its lines into another file.
+<a id="route-mechanical-refused"></a>
+### `ROUTE_MECHANICAL_REFUSED: <path> <reason>`
+
+**Meaning.** `gstack-ship-release finish` found a post-review edit to a path
+the base policy's `mechanical_retake` declares (the constant's file, a fixture
+field or a golden) that failed its proof, so the path keeps its old route,
+usually behavior ([ship-policy.md#mechanical-retake](ship-policy.md#mechanical-retake)).
+The reason names the failed proof: `needs --reviewed-base`, `is a gate path
+or under .gstack/ or .github/`, `does not hold exactly one line matching
+<template> at <side>`, `the reviewed branch did not take the constant`,
+`retakes <a> as <b>, not above the reviewed <a> and the base's <c>`,
+`changes more than the declared values since review`, `its constant <path>
+is not a proven retake`, `does not hold the same number of <field> lines`,
+`writes <v> into <field> where it held <w>, not the constant's <a> → <b>`,
+`changes no <field> value`, or `does not regenerate byte-identically from
+<regen id> (<status>)`.
+
+**Fix.** Keep the retake to the declared values: undo any other edit in those
+files (or ship it through Steps 5–11.5), write the constant's new value into
+every changed field, and rerun the regen entry's command and commit its output.
+A behavior STOP that remains is planned with `gstack-review-plan --post-review`.
+
<a id="policy-source-unavailable"></a>
### `policy source unavailable — fix: git fetch origin <base> --depth=1 (POLICY_SOURCE_UNAVAILABLE)`
diff --git a/lib/headless-artifacts.ts b/lib/headless-artifacts.ts
index c908d0a9d..3a684717e 100644
--- a/lib/headless-artifacts.ts
+++ b/lib/headless-artifacts.ts
@@ -125,6 +125,8 @@ export interface ShipReceipt {
review_loop_exception?: { accepted_by: string; date: string; via: string; reason: string; fix_check?: { head: string; findings: number; files?: string[] }; second_pass?: { head: string; deferred: string[] } };
/** The owner's rulings that a finding ships as a disclosed note (gstack-approvals rule, lib/ruled-notes.ts); the PR body lists each one word for word (GST-1537). */
ruled_notes?: Array<{ finding: string; head: string; by: string; reason: string; at: string; approval: string }>;
+ /** The `Mechanical retake: <path> (<what>)` lines /ship finish proved for this head's tree (lib/ship-mechanical.ts); the PR body lists each one word for word (GST-1560). */
+ mechanical?: string[];
/** The targeted pass on money, gate, auth and secret code (lib/review-targeted.ts), bound to the receipt's product_patch_id; `done` only with its output collected. */
review_targeted?: { classes: string[]; rules: string; brief_sha: string; product_patch_id: string; status: 'done' | 'failed' | 'not-run'; findings: number; raised_by: string };
/** Step 5 failures gstack-base-red proved are the base's own (lib/base-red.ts): a conditional receipt the queue refuses until /ship --resume rewrites it without this block. */
@@ -270,6 +272,7 @@ export const ARTIFACT_SCHEMAS = {
review_exclude: { type: 'object', required: ['source', 'patterns', 'applied', 'excluded', 'excluded_bytes', 'kept', 'gate_tagged', 'patterns_sha256', 'list_sha256', 'digest'], properties: { source: str, patterns: strList, applied: strList, excluded: { type: 'integer', minimum: 0 }, excluded_bytes: { type: 'integer', minimum: 0 }, kept: { type: 'integer', minimum: 0 }, gate_tagged: strList, patterns_sha256: str, list_sha256: str, digest: str } },
review_loop_exception: { type: 'object', required: ['accepted_by', 'date', 'via', 'reason'], properties: { accepted_by: str, date: str, via: str, reason: str, fix_check: { type: 'object', required: ['head', 'findings'], properties: { head: str, findings: { type: 'integer', minimum: 0 }, files: strList } }, second_pass: { type: 'object', required: ['head', 'deferred'], properties: { head: str, deferred: strList } } } },
ruled_notes: { type: 'array', items: { type: 'object', required: ['finding', 'head', 'by', 'reason', 'at', 'approval'], properties: { finding: str, head: str, by: str, reason: str, at: str, approval: str } } },
+ mechanical: strList,
no_stop: { type: 'array', items: { type: 'object', required: ['class', 'reason', 'evidence'], properties: { class: { enum: [...NO_STOP_CLASSES] }, reason: str, evidence: str } } },
issues: { type: 'object', properties: { fixes: { type: 'array', items: { type: 'integer' } }, refs: { type: 'array', items: { type: 'integer' } }, flakes: { type: 'array', items: { type: 'object', required: ['issue', 'run'], properties: { issue: { type: 'integer' }, run: str } } }, related: { type: 'array', items: { type: 'object', required: ['pr', 'author', 'closes'], properties: { pr: { type: 'integer' }, repo: str, author: str, closes: { type: 'array', items: { type: 'integer' } }, supersedes: { type: 'boolean' }, credit: { type: 'boolean' } } } } } },
},
diff --git a/lib/ship-mechanical.ts b/lib/ship-mechanical.ts
new file mode 100644
index 000000000..a333eb5cf
--- /dev/null
+++ b/lib/ship-mechanical.ts
@@ -0,0 +1,161 @@
+/**
+ * Mechanical retakes after review (GST-1560, docs/ship-policy.md#mechanical-retake). After a base merge a branch may
+ * have to retake a version or rules number the base just took (founderstar#563: RULE_NUMBERS 80 to 81 in one line, the
+ * same value in 8 save fixtures, one regenerated golden). /ship finish routes such paths as mechanical, with no reader,
+ * only when the base policy's `mechanical_retake` declares them and the diff proves each one:
+ * - the constant: exactly one line matching its template on each side, a value the reviewed branch took (not the
+ * reviewed base's), a current value above both the reviewed one and the current base's, and the file's patch with
+ * that line masked is the reviewed patch (lib/ship-patch.ts comparePath);
+ * - a fixture field: the masked patch is the reviewed one, and each field line either kept its value or moved from the
+ * constant's reviewed value to its current value;
+ * - a golden: a base .gstack/generated.json entry the constant names regenerates it byte-identically (lib/regen.ts).
+ * A declared path that fails its proof is refused with the reason and stays behavior; nothing is inferred.
+ */
+import { spawnSync } from 'node:child_process';
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+import { isGatePath } from './review-depth';
+import { isRegistryUnavailable, loadRegistryFromBase, runRegen } from './regen';
+import { comparePath, type PatchSides } from './ship-patch';
+import { matchesAny } from './ship-policy';
+import { constantValue, fieldValue, VALUE_SLOT, type MechanicalConstant } from './ship-policy-mechanical';
+
+export interface MechanicalRefusal { path: string; reason: string }
+export interface MechanicalInput { sides?: PatchSides; base: string; candidates: readonly string[]; declared: readonly MechanicalConstant[] }
+const SIDES = ['reviewedBase', 'reviewed', 'currentBase', 'current'] as const;
+type Side = typeof SIDES[number];
+
+function git(cwd: string, args: string[], env: NodeJS.ProcessEnv = process.env, input?: string): string | null {
+ const r = spawnSync('git', ['--literal-pathspecs', ...args], { cwd, encoding: 'latin1', input: input === undefined ? undefined : Buffer.from(input, 'latin1'), timeout: 120_000, maxBuffer: 256 * 1024 * 1024, env });
+ return r.status === 0 ? r.stdout : null;
+}
+
+/** The four sides with `rel` rewritten by `mask` (an absent file stays absent), and each side's masked blob; a string says why not. */
+function maskedSides(cwd: string, s: PatchSides, rel: string, mask: (text: string) => string): { sides: PatchSides; blobs: Record<Side, string | null> } | string {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-mechanical-'));
+ const env = { ...process.env, GIT_INDEX_FILE: path.join(dir, 'index') };
+ try {
+ const sides = { ...s };
+ const blobs = {} as Record<Side, string | null>;
+ for (const side of SIDES) {
+ const ls = git(cwd, ['ls-tree', s[side], '--', rel], env);
+ if (ls === null) return `git could not read it at ${side} ${s[side].slice(0, 12)}`;
+ if (!ls.trim()) { blobs[side] = null; continue; }
+ const entry = /^(100644|100755) blob ([0-9a-f]{40,64})\t/.exec(ls);
+ const text = entry && git(cwd, ['cat-file', 'blob', entry[2]!], env);
+ if (!entry || text === null) return `is not a regular file at ${side} ${s[side].slice(0, 12)}`;
+ const blob = git(cwd, ['hash-object', '-w', '--stdin'], env, mask(text))?.trim();
+ const tree = blob && git(cwd, ['read-tree', s[side]], env) !== null && git(cwd, ['update-index', '--cacheinfo', `${entry[1]},${blob},${rel}`], env) !== null ? git(cwd, ['write-tree'], env)?.trim() : undefined;
+ if (!tree) return `git could not build its masked tree at ${side}`;
+ sides[side] = tree;
+ blobs[side] = `${entry[1]} ${blob}`;
+ }
+ return { sides, blobs };
+ } finally {
+ fs.rmSync(dir, { recursive: true, force: true });
+ }
+}
+
+/** Why the branch's patch to `rel`, with `mask` applied on every side, is not the reviewed patch; null when it is. */
+function maskedChange(cwd: string, s: PatchSides, rel: string, mask: (text: string) => string): string | null {
+ const m = maskedSides(cwd, s, rel, mask);
+ if (typeof m === 'string') return m;
+ if (m.blobs.reviewedBase === m.blobs.reviewed && m.blobs.currentBase === m.blobs.current) return null;
+ return comparePath(cwd, m.sides, rel) === 'same' ? null : 'changes more than the declared values since review (the masked patch is not the reviewed one)';
+}
+
+/**
+ * The declared paths among `candidates` whose post-review change is a proven mechanical retake (path -> what moved),
+ * and each declared candidate that failed its proof with the reason. Paths no declaration names are neither.
+ */
+export function mechanicalPaths(cwd: string, i: MechanicalInput): { proven: Record<string, string>; refused: MechanicalRefusal[] } {
+ const proven: Record<string, string> = Object.create(null);
+ const refused: MechanicalRefusal[] = [];
+ const retaken = new Map<MechanicalConstant, { from: number; to: number }>();
+ const s = i.sides;
+ const refuse = (p: string, reason: string) => refused.push({ path: p, reason });
+ const gate = (p: string) => isGatePath(p) || /^\.(gstack|github)\//.test(p);
+ const text = (side: Side, rel: string) => s && git(cwd, ['show', `${s[side]}:${rel}`]);
+ for (const c of i.declared.filter(d => i.candidates.includes(d.path))) {
+ if (!s) { refuse(c.path, 'needs --reviewed-base'); continue; }
+ if (gate(c.path)) { refuse(c.path, 'is a gate path or under .gstack/ or .github/'); continue; }
+ const values = SIDES.map(side => (text(side, c.path) ?? '').split('\n').map(l => constantValue(l, c.template)).filter((v): v is number => v !== null));
+ const odd = SIDES.find((_, k) => values[k]!.length !== 1);
+ if (odd) { refuse(c.path, `does not hold exactly one line matching ${JSON.stringify(c.template)} at ${odd}`); continue; }
+ const [rb, rv, cb, cv] = values.map(v => v[0]!) as [number, number, number, number];
+ if (rv === rb) { refuse(c.path, `the reviewed branch did not take the constant (${rv} at the reviewed base too), so a new take is behavior`); continue; }
+ if (!(cv > rv && cv > cb)) { refuse(c.path, `retakes ${rv} as ${cv}, not above the reviewed ${rv} and the base's ${cb}`); continue; }
+ const why = maskedChange(cwd, s, c.path, t => t.split('\n').map(l => (constantValue(l, c.template) === null ? l : c.template)).join('\n'));
+ if (why) { refuse(c.path, why); continue; }
+ proven[c.path] = `constant ${rv} → ${cv}`;
+ retaken.set(c, { from: rv, to: cv });
+ }
+ const rest = i.candidates.filter(p => !i.declared.some(d => d.path === p));
+ const goldens: string[] = [];
+ for (const p of rest) {
+ const c = i.declared.find(d => d.fields.some(f => matchesAny([f.glob], p)));
+ if (!c) { if (i.declared.some(d => d.regen.length)) goldens.push(p); continue; }
+ const take = retaken.get(c);
+ if (!take || !s) { refuse(p, `its constant ${c.path} is not a proven retake`); continue; }
+ if (gate(p)) { refuse(p, 'is a gate path or under .gstack/ or .github/'); continue; }
+ const fields = c.fields.filter(f => matchesAny([f.glob], p)).map(f => f.field);
+ const valueOf = (l: string) => fields.map(f => fieldValue(l, f)).find(v => v !== null) ?? null;
+ const [was, now] = (['reviewed', 'current'] as const).map(side => text(side, p)?.split('\n').map(valueOf).filter((v): v is number => v !== null) ?? null);
+ if (!was || !now || !now.length || was.length !== now.length) { refuse(p, `does not hold the same number of ${fields.join(', ')} lines at the reviewed and the current tree`); continue; }
+ const bad = now.findIndex((v, k) => v !== was[k] && !(was[k] === take.from && v === take.to));
+ if (bad >= 0) { refuse(p, `writes ${now[bad]} into ${fields.join(', ')} where it held ${was[bad]}, not the constant's ${take.from} → ${take.to}`); continue; }
+ if (now.every((v, k) => v === was[k])) { refuse(p, `changes no ${fields.join(', ')} value`); continue; }
+ const why = maskedChange(cwd, s, p, t => t.split('\n').map(l => (valueOf(l) === null ? l : l.replace(/\d+(\s*,?\s*\r?)$/, `${VALUE_SLOT}$1`))).join('\n'));
+ if (why) { refuse(p, why); continue; }
+ proven[p] = `${fields.join(', ')} ${take.from} → ${take.to}`;
+ }
+ if (!goldens.length) return { proven, refused };
+ const load = loadRegistryFromBase(cwd, i.base);
+ const registry = isRegistryUnavailable(load) || load.errors.length ? { entries: [] } : load.registry;
+ const entries = registry.entries.filter(e => e.command);
+ const named = (p: string, cs: readonly MechanicalConstant[]) => entries.filter(e => cs.some(c => c.regen.includes(e.id)) && matchesAny(e.outputs, p));
+ const claimed = goldens.filter(p => named(p, i.declared).length);
+ const ids = [...new Set(claimed.flatMap(p => named(p, [...retaken.keys()]).map(e => e.id)))];
+ const results = ids.length && claimed.some(p => !gate(p)) ? runRegen({ repoRoot: cwd, registry, mode: 'check', only: ids, prove: claimed }).results : [];
+ for (const p of claimed) {
+ const by = named(p, [...retaken.keys()]);
+ if (!by.length) { refuse(p, 'its constant is not a proven retake'); continue; }
+ if (gate(p)) { refuse(p, 'is a gate path or under .gstack/ or .github/'); continue; }
+ const ok = results.find(r => by.some(e => e.id === r.id) && r.status === 'fresh' && r.proven?.includes(p));
+ if (!ok) { refuse(p, `does not regenerate byte-identically from ${by.map(e => e.id).join(', ')} (${results.filter(r => by.some(e => e.id === r.id)).map(r => r.status).join(', ') || 'not run'})`); continue; }
+ proven[p] = `golden, regenerated by ${ok.id}`;
+ }
+ return { proven, refused };
+}
+
+/** The PR body and receipt line for one mechanical path. */
+export const mechanicalLine = (p: string, what: string) => `Mechanical retake: ${p} (${what})`;
+
+function recordFile(cwd: string, tree: string): string {
+ const rel = spawnSync('git', ['rev-parse', '--git-path', `gstack/mechanical-${tree.slice(0, 12)}.json`], { cwd, encoding: 'utf8', timeout: 30_000 }).stdout?.trim();
+ return path.resolve(cwd, rel || `.git/gstack/mechanical-${tree.slice(0, 12)}.json`);
+}
+
+/** Saves finish's mechanical paths for the tree it routed, for gstack-ship-receipt write; the error message when it cannot. */
+export function writeMechanicalRecord(cwd: string, tree: string, proven: Readonly<Record<string, string>>): string | null {
+ const file = recordFile(cwd, tree);
+ try {
+ fs.mkdirSync(path.dirname(file), { recursive: true });
+ fs.writeFileSync(file, JSON.stringify({ tree, paths: proven }) + '\n');
+ return null;
+ } catch (e) {
+ return `${file}: ${(e as Error).message.split('\n')[0]}`;
+ }
+}
+
+/** The mechanical lines finish recorded for exactly this tree; none when it recorded none. */
+export function readMechanicalLines(cwd: string, tree: string): string[] {
+ try {
+ const v = JSON.parse(fs.readFileSync(recordFile(cwd, tree), 'utf8'));
+ if (v?.tree !== tree || !v.paths || typeof v.paths !== 'object') return [];
+ return Object.entries(v.paths).filter(([, w]) => typeof w === 'string').map(([p, w]) => mechanicalLine(p, w as string)).sort();
+ } catch {
+ return [];
+ }
+}
diff --git a/lib/ship-policy-keys.ts b/lib/ship-policy-keys.ts
index 6a19e469f..472b74aa4 100644
--- a/lib/ship-policy-keys.ts
+++ b/lib/ship-policy-keys.ts
@@ -46,6 +46,7 @@ export const MERGE_KEY_VERSION = '1.95.0.0';
export const LAND_KEY_VERSION = '1.96.0.0';
export const READERS_KEY_VERSION = '1.96.0.0';
export const BOOKKEEPING_KEY_VERSION = '1.96.0.0';
+export const MECHANICAL_RETAKE_KEY_VERSION = '1.96.1.0';
export const POLICY_KEY_INTRODUCED: Record<PolicyKey, string> = {
bump: '1.91.73.0', queue_mode: '1.91.73.0', release_tool: '1.91.73.0', release_outputs: '1.91.73.0', stamp_paths: '1.91.73.0',
changelog: '1.91.73.0', mirror: '1.91.73.0', history: '1.91.73.0', preregistration_shas: '1.91.73.0', stamp_sensitive_gates: '1.91.73.0',
@@ -55,5 +56,5 @@ export const POLICY_KEY_INTRODUCED: Record<PolicyKey, string> = {
changelog_fragments: CHANGELOG_FRAGMENTS_KEY_VERSION,
base_red: BASE_RED_KEY_VERSION, review_exclude_paths: REVIEW_EXCLUDE_KEY_VERSION, review: REVIEW_POLICY_KEY_VERSION, release_gate: RELEASE_GATE_KEY_VERSION,
stamp_placeholders: STAMP_PLACEHOLDERS_KEY_VERSION, merge: MERGE_KEY_VERSION, land: LAND_KEY_VERSION, readers: READERS_KEY_VERSION,
- bookkeeping: BOOKKEEPING_KEY_VERSION,
+ bookkeeping: BOOKKEEPING_KEY_VERSION, mechanical_retake: MECHANICAL_RETAKE_KEY_VERSION,
};
diff --git a/lib/ship-policy-mechanical.ts b/lib/ship-policy-mechanical.ts
new file mode 100644
index 000000000..f616839f4
--- /dev/null
+++ b/lib/ship-policy-mechanical.ts
@@ -0,0 +1,63 @@
+/**
+ * The `mechanical_retake` key of .gstack/ship-policy.json (GST-1560, docs/ship-policy.md#mechanical-retake): a version or
+ * rules constant a branch takes and may have to retake after a base merge, the fixture fields that carry the same value,
+ * and the .gstack/generated.json entries that regenerate its goldens. /ship finish proves a retake from these
+ * declarations (lib/ship-mechanical.ts); nothing is inferred. Kept beside lib/ship-policy.ts, which stays under the
+ * module-size ratchet and must not be imported from here (`glob` is its globError).
+ */
+export const VALUE_SLOT = '{n}';
+export interface MechanicalField { glob: string; field: string }
+export interface MechanicalConstant { path: string; template: string; fields: MechanicalField[]; regen: string[] }
+
+const MAX_CONSTANTS = 8, MAX_TEMPLATE = 128, MAX_LIST = 16;
+const FIELD_RE = /^[A-Za-z_][A-Za-z0-9_.-]{0,63}$/;
+const REGEN_ID_RE = /^[a-z0-9][a-z0-9_.-]{0,63}$/;
+const DIGITS = /^\d{1,15}$/;
+
+/** What `gstack-ship-policy init --explain` prints for the key. */
+export const MECHANICAL_EXPLANATION = 'Array of { path, template, fields, regen }: a version or rules constant a branch may retake after a base merge (GST-1560). path is one literal repository file, template the whole line with one {n} for the value (\'const SAVE_VERSION := {n}\'), fields the { glob, field } fixture fields that carry the same value (a line holding only field: n, field = n or "field": n), regen the .gstack/generated.json entry ids whose command regenerates the goldens. A post-review edit that only retakes the constant (one literal, a higher value), writes the same value into declared fields and leaves goldens those commands regenerate byte-identically routes as mechanical in /ship finish, with no reader; any other edit in those files routes as behavior. Read from the base branch only. Empty (default) declares none (docs/ship-policy.md#mechanical-retake).';
+
+/** Every error in the key at its path; `glob` is lib/ship-policy.ts's globError. */
+export function mechanicalErrors(value: unknown, out: Array<{ code: 'POLICY_INVALID' | 'POLICY_CONTAINMENT'; path: string; message: string }> | any[], glob: (g: string) => string | null): void {
+ const at = 'mechanical_retake';
+ if (!Array.isArray(value)) { out.push({ code: 'POLICY_INVALID', path: at, message: 'must be an array of { path, template, fields, regen }' }); return; }
+ if (value.length > MAX_CONSTANTS) out.push({ code: 'POLICY_CONTAINMENT', path: at, message: `more than ${MAX_CONSTANTS} constants` });
+ value.forEach((c, i) => {
+ const here = `${at}[${i}]`;
+ const e = c as Record<string, unknown> | null;
+ if (!e || typeof e !== 'object' || Array.isArray(e) || Object.keys(e).sort().join() !== 'fields,path,regen,template') { out.push({ code: 'POLICY_INVALID', path: here, message: 'must be exactly { path, template, fields, regen }' }); return; }
+ const p = e.path;
+ const pathWhy = typeof p !== 'string' ? 'must be a string' : glob(p) ?? (/[*?[\]{}]/.test(p) ? 'must be one literal file, not a glob' : /^\.(gstack|github)\//.test(p) ? 'must not name a path under .gstack/ or .github/' : null);
+ if (pathWhy) out.push({ code: 'POLICY_CONTAINMENT', path: `${here}.path`, message: `${JSON.stringify(p)} ${pathWhy}` });
+ const t = e.template;
+ if (typeof t !== 'string' || t.split(VALUE_SLOT).length !== 2 || !t.replace(VALUE_SLOT, '').trim()) out.push({ code: 'POLICY_INVALID', path: `${here}.template`, message: `must hold exactly one ${VALUE_SLOT} beside literal text` });
+ else if (t.length > MAX_TEMPLATE || /[\0\r\n]/.test(t)) out.push({ code: 'POLICY_CONTAINMENT', path: `${here}.template`, message: `must be one line of at most ${MAX_TEMPLATE} characters` });
+ const list = (key: 'fields' | 'regen', check: (v: unknown) => string | null) => {
+ const v = e[key];
+ if (!Array.isArray(v)) { out.push({ code: 'POLICY_INVALID', path: `${here}.${key}`, message: 'must be an array' }); return; }
+ if (v.length > MAX_LIST) out.push({ code: 'POLICY_CONTAINMENT', path: `${here}.${key}`, message: `more than ${MAX_LIST} entries` });
+ v.forEach((x, j) => { const why = check(x); if (why) out.push({ code: 'POLICY_INVALID', path: `${here}.${key}[${j}]`, message: why }); });
+ };
+ list('fields', f => {
+ const o = f as Record<string, unknown> | null;
+ if (!o || typeof o !== 'object' || Array.isArray(o) || Object.keys(o).sort().join() !== 'field,glob' || typeof o.glob !== 'string' || typeof o.field !== 'string') return 'must be exactly { glob, field } strings';
+ return glob(o.glob) ?? (/^\.(gstack|github)\//.test(o.glob) ? 'glob must not name a path under .gstack/ or .github/' : FIELD_RE.test(o.field) ? null : `field ${JSON.stringify(o.field)} must be a plain key name`);
+ });
+ list('regen', id => typeof id === 'string' && REGEN_ID_RE.test(id) ? null : `${JSON.stringify(id)} must be a .gstack/generated.json entry id`);
+ });
+}
+
+/** The value on a line that is exactly the template with digits in its slot (a trailing CR ignored); null otherwise. */
+export function constantValue(line: string, template: string): number | null {
+ const [pre, post] = template.split(VALUE_SLOT) as [string, string];
+ const l = line.replace(/\r$/, '');
+ if (l.length <= pre.length + post.length || !l.startsWith(pre) || !l.endsWith(post)) return null;
+ const v = l.slice(pre.length, l.length - post.length);
+ return DIGITS.test(v) ? Number(v) : null;
+}
+
+/** The value on a line holding only the field and a number (`field: n`, `field = n`, `"field": n,`); null otherwise. */
+export function fieldValue(line: string, field: string): number | null {
+ const m = new RegExp(`^\\s*(["']?)${field.replace(/[.-]/g, '\\$&')}\\1\\s*[:=]\\s*(\\d{1,15})\\s*,?\\s*$`).exec(line.replace(/\r$/, ''));
+ return m ? Number(m[2]) : null;
+}
diff --git a/lib/ship-policy.ts b/lib/ship-policy.ts
index f9fc428c4..1558ea338 100644
--- a/lib/ship-policy.ts
+++ b/lib/ship-policy.ts
@@ -25,6 +25,7 @@ import { cmpVersion, parseVersion } from './version-source';
import { POLICY_COMPAT_FLOOR, BUMP_NEVER_KEY_VERSION, TRAIN_GATES_KEY_VERSION, POLICY_KEY_INTRODUCED } from './ship-policy-keys';
import { placeholderErrors, templateErrors } from './ship-policy-stamps';
import { bookkeepingGlobError, globError } from './ship-policy-bookkeeping';
+import { MECHANICAL_EXPLANATION, mechanicalErrors, type MechanicalConstant } from './ship-policy-mechanical';
export { VERSION_SLOT } from './ship-policy-stamps';
export const SHIP_POLICY_PATH = '.gstack/ship-policy.json';
@@ -95,6 +96,7 @@ export interface ShipPolicy {
/** The release gate on the base branch (docs/ship-policy.md#release-gate); null keeps the per-push main backstop. */
release_gate: ReleaseGatePolicy | null;
/** Bookkeeping tables (`.tsv`, `.csv`, `.txt` globs) whose small post-review edits take /ship finish's scoped reader (docs/ship-policy.md#bookkeeping); read from the base only. */ bookkeeping: string[];
+ /** Constants a branch may retake after a base merge, with their fixture fields and golden regen ids (docs/ship-policy.md#mechanical-retake); read from the base only. */ mechanical_retake: MechanicalConstant[];
/** `direct` lands each READY PR at its own green head (`land --pin`, docs/ship-policy.md#land-direct); `train` keeps merge trains. */ merge: 'direct' | 'train';
/** What `land --pin` runs on the pin merged onto a base that moved past its merge base (lib/land-merged-checks.ts); null lands a stale base untested with a STALE_BASE: warn line. */ land: LandPolicy | null;
}
@@ -187,7 +189,7 @@ export const DEFAULT_POLICY: ShipPolicy = {
min_gstack_version: null,
train: null,
docs: null,
- base_red: null, merge: 'train', land: null, bookkeeping: [],
+ base_red: null, merge: 'train', land: null, bookkeeping: [], mechanical_retake: [],
release_gate: null, readers: { forbid_fetch: [], forbid_paths: [], brief_note: null },
};
@@ -226,6 +228,7 @@ export const POLICY_EXPLANATIONS: Record<PolicyKey, string> = {
release_gate: RELEASE_GATE_EXPLANATION,
land: LAND_EXPLANATION,
bookkeeping: 'Root-anchored globs of bookkeeping tables, each ending in .tsv, .csv or .txt and never under .gstack/ or .github/, for example ["scripts/*-baseline.tsv"]. An edit of at most 20 lines to a matching file after review binds, first touched or not, takes /ship finish\'s scoped reader instead of Steps 5–11.5; the reader still reads every changed row. Read from the base branch only. Empty (default) declares none.',
+ mechanical_retake: MECHANICAL_EXPLANATION,
merge: 'train (default) | direct. direct: the Captain lands each READY PR at its own green head with `gstack-ship-queue land --pr <n> --pin <sha>` (no train, no stamp commit; the PR leaves VERSION, the manifest version and the CHANGELOG at the base and the release stamps them), and train build refuses. train: merge trains as before (docs/ship-policy.md#land-direct).',
min_gstack_version: 'The oldest gstack that may read this file. Any key newer than 1.91.98.0 set to a non-default value requires it at that key’s introducing version (validate prints each); a gstack older than it refuses the file (POLICY_GSTACK_TOO_OLD).',
};
@@ -466,6 +469,7 @@ export function validatePolicy(raw: unknown, opts: { gstackVersion?: string } =
if ('stamp_patterns' in obj) templateErrors(obj.stamp_patterns, errors);
if ('stamp_placeholders' in obj) placeholderErrors(obj.stamp_placeholders, errors);
if ('bookkeeping' in obj) listErrors('bookkeeping', obj.bookkeeping, errors, g => globError(g) ?? bookkeepingGlobError(g));
+ if ('mechanical_retake' in obj) mechanicalErrors(obj.mechanical_retake, errors, globError);
if ('restamp_command' in obj && obj.restamp_command !== null) {
const t = obj.restamp_command;
if (typeof t !== 'string' || !t.trim()) errors.push({ code: 'POLICY_INVALID', path: 'restamp_command', message: 'must be a non-empty string or null' });
diff --git a/lib/ship-receipt-prose.ts b/lib/ship-receipt-prose.ts
index 411b194b5..0e39fe3cd 100644
--- a/lib/ship-receipt-prose.ts
+++ b/lib/ship-receipt-prose.ts
@@ -96,7 +96,7 @@ function withoutApprovalsBlocks(body: string): string {
/**
* The body without the exception lines the receipt's own exceptions require: the `Review-loop exception: …` line
- * (GST-977), the `Documentation exception: …` line (GST-983) and each `Ruled note: …` line (GST-1537). write and the receipt check want each word for word,
+ * (GST-977), the `Documentation exception: …` line (GST-983) and each `Ruled note: …` and `Mechanical retake: …` line (GST-1537, GST-1560). write and the receipt check want each word for word,
* and each quotes the owner's reason (`outside 1 and 2 skip detector`), not this PR's counters. Only a line whose
* trimmed text is a rendered line, the test write applies, is left out; the same words inside a longer line stay
* prose. A marker line takes its place so the text on either side never joins into a claim.
@@ -109,6 +109,7 @@ function withoutExceptionLines(body: string, receipt: Record<string, unknown>):
const docsLine = docs?.ok ? docsExceptionLine(docs.docs) : null;
if (docsLine) lines.add(docsLine);
if (Array.isArray(receipt.ruled_notes)) for (const n of receipt.ruled_notes) lines.add(`Ruled note: ${ruledNoteText(n as RuledNote)}`);
+ if (Array.isArray(receipt.mechanical)) for (const l of receipt.mechanical) if (typeof l === 'string') lines.add(l);
if (!lines.size) return body;
return body.split(/(?<=\n)/).map(l => (lines.has(l.trim()) ? '(exception line)\n' : l)).join('');
}
diff --git a/lib/ship-receipt.ts b/lib/ship-receipt.ts
index 6319d5a04..58d9e5e38 100644
--- a/lib/ship-receipt.ts
+++ b/lib/ship-receipt.ts
@@ -21,7 +21,7 @@ const KEY_ORDER: Array<keyof ShipReceipt | 'docs'> = [
'schema_version', 'pr', 'head', 'version', 'base', 'gated_tree', 'predecessor', 'tree', 'gate_reuse', 'gate', 'ci', 'ci_carried', 'spend_usd',
'session_kind', 'artifacts_consumed', 'run', 'thread', 'policy', 'queue_mode', 'preregistration', 'history',
'head_tree', 'product_patch_id', 'gstack_version', 'review_depth', 'pregate', 'requires_remote', 'issues', 'approval', 'docs', 'review_loop',
- 'review_loop_exception', 'ruled_notes', 'review_targeted', 'review_exclude', 'carry', 'base_red', 'flaky_exception', 'no_stop',
+ 'review_loop_exception', 'ruled_notes', 'mechanical', 'review_targeted', 'review_exclude', 'carry', 'base_red', 'flaky_exception', 'no_stop',
];
/** Keys in the fixed order so identifiers lead; undefined values are dropped. */
diff --git a/lib/ship-release.ts b/lib/ship-release.ts
index 585efd88b..e1555cd1f 100644
--- a/lib/ship-release.ts
+++ b/lib/ship-release.ts
@@ -18,6 +18,8 @@ import { matchesAny } from './ship-policy';
import { baseHolds, boundedPaths, comparePath, contextPacket, gateEditedPaths, isTestCode, PACKET_SECTION_CAP, readScopedReview, touchedPaths, type BoundedKind, type PatchSides } from './ship-patch';
import { heldBy } from './ship-receipt';
import { locate, readRecord } from './approval-record';
+import { mechanicalPaths, writeMechanicalRecord } from './ship-mechanical';
+import type { MechanicalConstant } from './ship-policy-mechanical';
import { reviewFreshness } from './review-evidence';
import { readRuledNotes, ruledNoteText } from './ruled-notes';
import { parseReviewLoopException, type ReviewLoopException } from './ship-receipt-depth';
@@ -203,9 +205,9 @@ function harnessRepin(cwd: string, from: string, to: string, p: string): boolean
* prints as RULED_NOTE (GST-1537). Authored docs keep the stage 2.2 recheck.
*/
type FixCheckException = ReviewLoopException & { fix_check: NonNullable<ReviewLoopException['fix_check']> };
-type Routed = Record<'behavior' | 'docs' | 'metadata' | 'tests' | 'base' | 'context' | 'bounded' | 'accepted' | 'fix_checked', string[]>;
+type Routed = Record<'behavior' | 'docs' | 'metadata' | 'tests' | 'base' | 'context' | 'bounded' | 'mechanical' | 'accepted' | 'fix_checked', string[]>;
type ReviewedBase = { commit: string; parent: boolean };
-type RouteOpts = { docsRechecked: boolean; contextReviewed?: string; loop?: FixCheckException; audited: Record<string, string | null> | null; bookkeeping: readonly string[]; baseRelease?: string[] };
+type RouteOpts = { docsRechecked: boolean; contextReviewed?: string; loop?: FixCheckException; audited: Record<string, string | null> | null; bookkeeping: readonly string[]; mechanical: readonly MechanicalConstant[]; baseRelease?: string[] };
/**
* The --reviewed-base commit: one on the base, or a landed stack parent (GST-1399). A child reviewed against its parent
@@ -257,7 +259,7 @@ function route(cwd: string, base: string, reviewed: string, reviewedBase: Review
touched = new Set([...a, ...b]);
shipped = b;
}
- const by: Routed = { behavior: [], docs: [], metadata: [], tests: [], base: [], context: [], bounded: [], accepted: [], fix_checked: [] };
+ const by: Routed = { behavior: [], docs: [], metadata: [], tests: [], base: [], context: [], bounded: [], mechanical: [], accepted: [], fix_checked: [] };
const onlyShipped = new Set(parent ? [...shipped].filter(p => !changedSet.has(p)) : []);
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';
@@ -268,6 +270,9 @@ function route(cwd: string, base: string, reviewed: string, reviewedBase: Review
const gated = new Set([...(gateEditedPaths(cwd, reviewed, now, by.tests.filter(p => !onlyShipped.has(p))) ?? by.tests), ...(gateEditedPaths(cwd, sides?.currentBase ?? reviewed, now, shippedTests) ?? shippedTests)]);
by.behavior.push(...by.tests.filter(p => gated.has(p)));
by.tests = by.tests.filter(p => !gated.has(p));
+ const mech = mechanicalPaths(cwd, { sides, base, candidates: parent ? [] : [...by.behavior, ...by.tests, ...by.docs], declared: opts.mechanical });
+ by.mechanical = Object.keys(mech.proven).sort();
+ for (const k of ['behavior', 'tests', 'docs'] as const) by[k] = by[k].filter(p => !Object.hasOwn(mech.proven, p));
const bounded = boundedPaths(cwd, { sides, reviewed, now, base: baseRef, candidates: parent ? [] : by.behavior, audited: opts.audited, bookkeeping: opts.bookkeeping });
by.bounded = Object.keys(bounded.kinds).sort();
by.behavior = by.behavior.filter(p => !by.bounded.includes(p));
@@ -323,10 +328,14 @@ function route(cwd: string, base: string, reviewed: string, reviewedBase: Review
by.behavior = by.behavior.filter(p => !by.accepted.includes(p));
by.docs = by.docs.filter(p => !by.accepted.includes(p));
}
- r.add(`ROUTE: reviewed=${reviewed.slice(0, 12)} current=${now.slice(0, 12)} behavior=${by.behavior.length} docs=${by.docs.length} metadata=${by.metadata.length} tests=${by.tests.length} base=${sides ? by.base.length : 'unknown'} context=${by.context.length}${by.bounded.length ? ` bounded=${by.bounded.length}` : ''}${counted ? ` fix_checked=${by.fix_checked.length}` : ''}${loop ? ` accepted=${by.accepted.length}` : ''}`);
+ r.add(`ROUTE: reviewed=${reviewed.slice(0, 12)} current=${now.slice(0, 12)} behavior=${by.behavior.length} docs=${by.docs.length} metadata=${by.metadata.length} tests=${by.tests.length} base=${sides ? by.base.length : 'unknown'} context=${by.context.length}${by.bounded.length ? ` bounded=${by.bounded.length}` : ''}${by.mechanical.length ? ` mechanical=${by.mechanical.length}` : ''}${counted ? ` fix_checked=${by.fix_checked.length}` : ''}${loop ? ` accepted=${by.accepted.length}` : ''}`);
if (loop) r.add(`REVIEW_LOOP_EXCEPTION: accepted ${by.accepted.length ? short(by.accepted) : 'none'} (changed since fix-check ${loop.fix_check.head.slice(0, 12)}; accepted by ${loop.accepted_by} ${loop.date} via ${loop.via})`);
for (const x of bounded.refused) if (by.behavior.includes(x.path)) r.add(`ROUTE_BOUNDED_REFUSED: ${x.path} ${x.reason} (fix: ${x.fix}; docs/troubleshooting.md#route-bounded-refused)`);
- if (by.behavior.length) { r.stop(`behavior, tests or build inputs changed since review (${short(by.behavior.sort())}): insert 5–11.5 → 12–14 → 16 before Step 17 (stage 2.1)`); return null; }
+ for (const p of by.mechanical) r.add(`MECHANICAL: ${p} (${mech.proven[p]})`);
+ for (const x of mech.refused) r.add(`ROUTE_MECHANICAL_REFUSED: ${x.path} ${x.reason} (docs/troubleshooting.md#route-mechanical-refused)`);
+ if (by.behavior.length) { r.stop(`behavior, tests or build inputs changed since review (${short(by.behavior.sort())}): insert 5–11.5 → 12–14 → 16 before Step 17; plan that Step 9 with gstack-review-plan --post-review, which at the round cap stops for the owner's grant of one scoped fix-check (stage 2.1)`); return null; }
+ const kept = by.mechanical.length ? writeMechanicalRecord(cwd, now, mech.proven) : null;
+ if (kept) { r.stop(`the mechanical paths cannot be recorded for gstack-ship-receipt write (${kept}): make that directory writable, then rerun finish (stage 2.1)`); return null; }
const scoped = [...by.context, ...by.tests, ...by.bounded].sort();
if (scoped.length && sides) {
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`);
@@ -478,14 +487,15 @@ async function finishStages(argv: readonly string[], cwd: string): Promise<Repor
let audited: Record<string, string | null> | null = null;
try { const h = JSON.parse(fs.readFileSync(flag('--docs-post')!, 'utf8')).hashes; audited = h && typeof h === 'object' && !Array.isArray(h) ? h : null; } catch { audited = null; }
const bookkeeping = Array.isArray(policy?.bookkeeping) ? policy!.bookkeeping.filter((g: unknown): g is string => typeof g === 'string') : [];
+ const mechanical: MechanicalConstant[] = Array.isArray(policy?.mechanical_retake) ? policy!.mechanical_retake : [];
const reviewedBaseArg = flag('--reviewed-base');
const fragments = typeof policy?.changelog_fragments?.dir === 'string' ? [`:(top,exclude,glob)${policy.changelog_fragments.dir.replace(/\/+$/, '')}/*.md`] : [];
const reviewedBase = reviewedBaseArg === undefined ? undefined : reviewedBaseCommit(cwd, `origin/${base.replace(/^origin\//, '')}`, reviewedBaseArg, [...releasePaths(policy, cwd, flag('--reviewed-tree')!, base, true).map(p => `:(top,exclude,literal)${p}`), ...fragments], r);
if (reviewedBase === null) return r;
const baseRelease = reviewedBase?.parent ? releasePaths(policy, cwd, git(cwd, ['merge-base', `origin/${base.replace(/^origin\//, '')}`, 'HEAD']).stdout.trim(), base, true) : undefined;
- const routed = route(cwd, base, flag('--reviewed-tree')!, reviewedBase, release, { docsRechecked: has('--docs-rechecked'), contextReviewed: flag('--context-reviewed'), loop, audited, bookkeeping, baseRelease }, r);
+ const routed = route(cwd, base, flag('--reviewed-tree')!, reviewedBase, release, { docsRechecked: has('--docs-rechecked'), contextReviewed: flag('--context-reviewed'), loop, audited, bookkeeping, mechanical, baseRelease }, r);
if (!routed) return r;
- if (!docsFresh(cwd, base, flag('--docs-post')!, [...routed.base, ...routed.context, ...stampedFiles(policy, cwd, flag('--reviewed-tree')!, base)], all('--docs-requested'), flag('--docs-result'), loop ? routed.accepted : undefined, reviewedBase?.parent ? reviewedBase.commit : undefined, r)) return r;
+ if (!docsFresh(cwd, base, flag('--docs-post')!, [...routed.base, ...routed.context, ...routed.mechanical, ...stampedFiles(policy, cwd, flag('--reviewed-tree')!, base)], all('--docs-requested'), flag('--docs-result'), loop ? routed.accepted : undefined, reviewedBase?.parent ? reviewedBase.commit : undefined, r)) return r;
if (!list.length && !has('--no-lanes-approved')) return r.stop('no test lanes: require Step 5\'s explicit untested-scope approval (rerun with --no-lanes-approved) or run Steps 5-15');
const allow = evidenceExempt(release).join(',');
const check = (l: { label: string; command: string }) => bin(cwd, 'gstack-evidence', ['check', '--label', l.label, '--expect-cmd', l.command, '--max-age', '24', '--allow-paths', allow], 60_000).stdout;
diff --git a/scripts/lib/windows-curation.ts b/scripts/lib/windows-curation.ts
index 2d6141c0b..857c5b016 100644
--- a/scripts/lib/windows-curation.ts
+++ b/scripts/lib/windows-curation.ts
@@ -407,6 +407,10 @@ export const KNOWN_WINDOWS_INCOMPATIBLE: Array<{ file: string; reason: string }>
file: 'test/ship-finish-ruled-notes.test.ts',
reason: 'drives bin/gstack-ship-release, gstack-approvals, gstack-docs-candidate and gstack-wtree (shebangs) through test/helpers/ship-bin-fixture.ts like test/ship-rereview-triggers.test.ts; windows-latest fails every case at the first bin spawn (windows-scoped-shard, run 42139467391)',
},
+ {
+ file: 'test/ship-mechanical-retake.test.ts',
+ reason: 'drives bin/gstack-ship-release, gstack-review-plan, gstack-ship-receipt, gstack-docs-candidate and gstack-wtree (shebangs) through test/helpers/ship-bin-fixture.ts like test/ship-finish-stack-parent.test.ts; windows-latest fails every case at the first bin spawn (windows-scoped-shard, run 42156939158)',
+ },
];
// Force-include overrides: files a WINDOWS_FRAGILE_PATTERNS regex excludes for
diff --git a/ship/SKILL.md b/ship/SKILL.md
index 769833bd7..847810c4e 100644
--- a/ship/SKILL.md
+++ b/ship/SKILL.md
@@ -665,21 +665,19 @@ also makes Step 15's item-3 commit and runs the pregate (`--docs-rechecked`,
### 1. Finish writers and prepare outputs
-Before `finish`, inspect writer handles, including the docs child. Confirm completion or
-termination before another writer runs; timeout or cancellation acknowledgment
-alone means STOP until confirmed.
-
-Find declared generation/build commands in project instructions, manifests, build
-files and CI. Pass each to `finish` as `--build`. If none exists, record not applicable and
-the inspected sources. A missing prerequisite or failed build stops shipping:
-report **Build failed or prerequisite missing**, with the command, error and needed
-repair. Never invent a substitute command.
+Before `finish`, confirm every writer (the docs child too) completed or terminated;
+an acknowledged timeout or cancellation alone means STOP until confirmed.
+
+Pass each declared generation/build command (instructions, manifests, build files, CI)
+as `--build`; with none, record N/A and the sources inspected.
+A missing prerequisite or failed build stops shipping: report **Build failed or prerequisite
+missing** with the command, error and repair. Never invent a substitute command.
**If blocked:** repair it, repeat stage 1, then continue to stage 2: a content repair is behavior there.
### 2. Choose the change route
-`finish` runs `git diff <reviewed-tree> <current-tree>` (`--reviewed-tree`, saved before Step 12,
-against `~/.claude/skills/gstack/bin/gstack-wtree`) and prints `ROUTE:`. No saved tree: pass `review_binding.end_wtree` from Step 11.5's bound Step 9 record;
+`finish` runs `git diff <reviewed-tree> <current-tree>` (`--reviewed-tree`, saved before Step 12
+by `~/.claude/skills/gstack/bin/gstack-wtree`) and prints `ROUTE:`. No saved tree: pass `review_binding.end_wtree` from Step 11.5's bound Step 9 record;
with none, insert `9 → 10 → 11 → 11.5`.
Its `STOP:` names the route:
@@ -687,11 +685,12 @@ Its `STOP:` names the route:
1. **Behavior, tests or build inputs changed:** Prompts/templates count as behavior.
Insert `5–11.5 → 12–14 → 16` before the pending Step 17. It excludes Step 14.5 (a rebuild
can change generated docs; compare before stage 3) and Step 15 (`finish` STOPs on an uncommitted
- non-release file: commit it by Step 15's rules, then rerun). A STOP naming a scoped-review packet
+ non-release file: commit it per Step 15, rerun). Its Step 9 plans with `gstack-review-plan --post-review`
+ (at the cap: a stop for the owner). A STOP naming a scoped-review packet
instead takes one reader (no round) and `--context-reviewed` rerun; a blocker is this item.
2. **Only authored docs or release metadata changed:** Keep Step 8's original child
- report and counts. Recheck affected plan items using their recorded verification
- and append current evidence to the invocation record. If a classification is no
+ report and counts. Recheck affected plan items by their recorded verification and
+ log current evidence. If a classification is no
longer supported, run Step 8's audit and decision gates only, then return to
Step 16 stage 1; else rerun with `--docs-rechecked`. Never edit the child's counts yourself.
3. **No changes, or the docs-only checks still support the plan:** `finish` continues to
diff --git a/ship/SKILL.md.tmpl b/ship/SKILL.md.tmpl
index 10f2071fe..a18af4768 100644
--- a/ship/SKILL.md.tmpl
+++ b/ship/SKILL.md.tmpl
@@ -386,21 +386,19 @@ also makes Step 15's item-3 commit and runs the pregate (`--docs-rechecked`,
### 1. Finish writers and prepare outputs
-Before `finish`, inspect writer handles, including the docs child. Confirm completion or
-termination before another writer runs; timeout or cancellation acknowledgment
-alone means STOP until confirmed.
-
-Find declared generation/build commands in project instructions, manifests, build
-files and CI. Pass each to `finish` as `--build`. If none exists, record not applicable and
-the inspected sources. A missing prerequisite or failed build stops shipping:
-report **Build failed or prerequisite missing**, with the command, error and needed
-repair. Never invent a substitute command.
+Before `finish`, confirm every writer (the docs child too) completed or terminated;
+an acknowledged timeout or cancellation alone means STOP until confirmed.
+
+Pass each declared generation/build command (instructions, manifests, build files, CI)
+as `--build`; with none, record N/A and the sources inspected.
+A missing prerequisite or failed build stops shipping: report **Build failed or prerequisite
+missing** with the command, error and repair. Never invent a substitute command.
**If blocked:** repair it, repeat stage 1, then continue to stage 2: a content repair is behavior there.
### 2. Choose the change route
-`finish` runs `git diff <reviewed-tree> <current-tree>` (`--reviewed-tree`, saved before Step 12,
-against `~/.claude/skills/gstack/bin/gstack-wtree`) and prints `ROUTE:`. No saved tree: pass `review_binding.end_wtree` from Step 11.5's bound Step 9 record;
+`finish` runs `git diff <reviewed-tree> <current-tree>` (`--reviewed-tree`, saved before Step 12
+by `~/.claude/skills/gstack/bin/gstack-wtree`) and prints `ROUTE:`. No saved tree: pass `review_binding.end_wtree` from Step 11.5's bound Step 9 record;
with none, insert `9 → 10 → 11 → 11.5`.
Its `STOP:` names the route:
@@ -408,11 +406,12 @@ Its `STOP:` names the route:
1. **Behavior, tests or build inputs changed:** Prompts/templates count as behavior.
Insert `5–11.5 → 12–14 → 16` before the pending Step 17. It excludes Step 14.5 (a rebuild
can change generated docs; compare before stage 3) and Step 15 (`finish` STOPs on an uncommitted
- non-release file: commit it by Step 15's rules, then rerun). A STOP naming a scoped-review packet
+ non-release file: commit it per Step 15, rerun). Its Step 9 plans with `gstack-review-plan --post-review`
+ (at the cap: a stop for the owner). A STOP naming a scoped-review packet
instead takes one reader (no round) and `--context-reviewed` rerun; a blocker is this item.
2. **Only authored docs or release metadata changed:** Keep Step 8's original child
- report and counts. Recheck affected plan items using their recorded verification
- and append current evidence to the invocation record. If a classification is no
+ report and counts. Recheck affected plan items by their recorded verification and
+ log current evidence. If a classification is no
longer supported, run Step 8's audit and decision gates only, then return to
Step 16 stage 1; else rerun with `--docs-rechecked`. Never edit the child's counts yourself.
3. **No changes, or the docs-only checks still support the plan:** `finish` continues to
diff --git a/ship/sections/pr-body.md b/ship/sections/pr-body.md
index 349a27c4c..45011a426 100644
--- a/ship/sections/pr-body.md
+++ b/ship/sections/pr-body.md
@@ -103,7 +103,7 @@ ZERO-RUN lane never reaches this body unresolved.>
## Pre-Landing Review
<findings from Step 9 code review, or "No issues found."; then Step 9.4's `REVIEW_LOOP:` line.>
<Each `Ruled note: …` line `gstack-approvals rulings` prints, verbatim: a finding the owner ruled a disclosed note,
-with its ruler and reason. `gstack-ship-receipt write --body` refuses a body missing one.>
+with its ruler and reason; finish's `MECHANICAL: x` as `Mechanical retake: x`. `gstack-ship-receipt write --body` refuses a body missing one.>
<Gate edits: Step 9's latest `Gate edits:` line verbatim — `none detected (...)`,
`N listed, M read, K findings — J kept, R restored, O open`, `partial (...)` or
`UNAVAILABLE — ...`; never `none detected` for partial or UNAVAILABLE. Under it, each
diff --git a/ship/sections/pr-body.md.tmpl b/ship/sections/pr-body.md.tmpl
index 3590ebec7..097923aaa 100644
--- a/ship/sections/pr-body.md.tmpl
+++ b/ship/sections/pr-body.md.tmpl
@@ -94,7 +94,7 @@ ZERO-RUN lane never reaches this body unresolved.>
## Pre-Landing Review
<findings from Step 9 code review, or "No issues found."; then Step 9.4's `REVIEW_LOOP:` line.>
<Each `Ruled note: …` line `gstack-approvals rulings` prints, verbatim: a finding the owner ruled a disclosed note,
-with its ruler and reason. `gstack-ship-receipt write --body` refuses a body missing one.>
+with its ruler and reason; finish's `MECHANICAL: x` as `Mechanical retake: x`. `gstack-ship-receipt write --body` refuses a body missing one.>
<Gate edits: Step 9's latest `Gate edits:` line verbatim — `none detected (...)`,
`N listed, M read, K findings — J kept, R restored, O open`, `partial (...)` or
`UNAVAILABLE — ...`; never `none detected` for partial or UNAVAILABLE. Under it, each
diff --git a/test/fixtures/golden/agy-ship-SKILL.md b/test/fixtures/golden/agy-ship-SKILL.md
index cfec5b43e..e240b0923 100644
--- a/test/fixtures/golden/agy-ship-SKILL.md
+++ b/test/fixtures/golden/agy-ship-SKILL.md
@@ -666,21 +666,19 @@ also makes Step 15's item-3 commit and runs the pregate (`--docs-rechecked`,
### 1. Finish writers and prepare outputs
-Before `finish`, inspect writer handles, including the docs child. Confirm completion or
-termination before another writer runs; timeout or cancellation acknowledgment
-alone means STOP until confirmed.
-
-Find declared generation/build commands in project instructions, manifests, build
-files and CI. Pass each to `finish` as `--build`. If none exists, record not applicable and
-the inspected sources. A missing prerequisite or failed build stops shipping:
-report **Build failed or prerequisite missing**, with the command, error and needed
-repair. Never invent a substitute command.
+Before `finish`, confirm every writer (the docs child too) completed or terminated;
+an acknowledged timeout or cancellation alone means STOP until confirmed.
+
+Pass each declared generation/build command (instructions, manifests, build files, CI)
+as `--build`; with none, record N/A and the sources inspected.
+A missing prerequisite or failed build stops shipping: report **Build failed or prerequisite
+missing** with the command, error and repair. Never invent a substitute command.
**If blocked:** repair it, repeat stage 1, then continue to stage 2: a content repair is behavior there.
### 2. Choose the change route
-`finish` runs `git diff <reviewed-tree> <current-tree>` (`--reviewed-tree`, saved before Step 12,
-against `~/.gemini/antigravity-cli/skills/gstack/bin/gstack-wtree`) and prints `ROUTE:`. No saved tree: pass `review_binding.end_wtree` from Step 11.5's bound Step 9 record;
+`finish` runs `git diff <reviewed-tree> <current-tree>` (`--reviewed-tree`, saved before Step 12
+by `~/.gemini/antigravity-cli/skills/gstack/bin/gstack-wtree`) and prints `ROUTE:`. No saved tree: pass `review_binding.end_wtree` from Step 11.5's bound Step 9 record;
with none, insert `9 → 10 → 11 → 11.5`.
Its `STOP:` names the route:
@@ -688,11 +686,12 @@ Its `STOP:` names the route:
1. **Behavior, tests or build inputs changed:** Prompts/templates count as behavior.
Insert `5–11.5 → 12–14 → 16` before the pending Step 17. It excludes Step 14.5 (a rebuild
can change generated docs; compare before stage 3) and Step 15 (`finish` STOPs on an uncommitted
- non-release file: commit it by Step 15's rules, then rerun). A STOP naming a scoped-review packet
+ non-release file: commit it per Step 15, rerun). Its Step 9 plans with `gstack-review-plan --post-review`
+ (at the cap: a stop for the owner). A STOP naming a scoped-review packet
instead takes one reader (no round) and `--context-reviewed` rerun; a blocker is this item.
2. **Only authored docs or release metadata changed:** Keep Step 8's original child
- report and counts. Recheck affected plan items using their recorded verification
- and append current evidence to the invocation record. If a classification is no
+ report and counts. Recheck affected plan items by their recorded verification and
+ log current evidence. If a classification is no
longer supported, run Step 8's audit and decision gates only, then return to
Step 16 stage 1; else rerun with `--docs-rechecked`. Never edit the child's counts yourself.
3. **No changes, or the docs-only checks still support the plan:** `finish` continues to
diff --git a/test/fixtures/golden/claude-ship-SKILL.md b/test/fixtures/golden/claude-ship-SKILL.md
index 769833bd7..847810c4e 100644
--- a/test/fixtures/golden/claude-ship-SKILL.md
+++ b/test/fixtures/golden/claude-ship-SKILL.md
@@ -665,21 +665,19 @@ also makes Step 15's item-3 commit and runs the pregate (`--docs-rechecked`,
### 1. Finish writers and prepare outputs
-Before `finish`, inspect writer handles, including the docs child. Confirm completion or
-termination before another writer runs; timeout or cancellation acknowledgment
-alone means STOP until confirmed.
-
-Find declared generation/build commands in project instructions, manifests, build
-files and CI. Pass each to `finish` as `--build`. If none exists, record not applicable and
-the inspected sources. A missing prerequisite or failed build stops shipping:
-report **Build failed or prerequisite missing**, with the command, error and needed
-repair. Never invent a substitute command.
+Before `finish`, confirm every writer (the docs child too) completed or terminated;
+an acknowledged timeout or cancellation alone means STOP until confirmed.
+
+Pass each declared generation/build command (instructions, manifests, build files, CI)
+as `--build`; with none, record N/A and the sources inspected.
+A missing prerequisite or failed build stops shipping: report **Build failed or prerequisite
+missing** with the command, error and repair. Never invent a substitute command.
**If blocked:** repair it, repeat stage 1, then continue to stage 2: a content repair is behavior there.
### 2. Choose the change route
-`finish` runs `git diff <reviewed-tree> <current-tree>` (`--reviewed-tree`, saved before Step 12,
-against `~/.claude/skills/gstack/bin/gstack-wtree`) and prints `ROUTE:`. No saved tree: pass `review_binding.end_wtree` from Step 11.5's bound Step 9 record;
+`finish` runs `git diff <reviewed-tree> <current-tree>` (`--reviewed-tree`, saved before Step 12
+by `~/.claude/skills/gstack/bin/gstack-wtree`) and prints `ROUTE:`. No saved tree: pass `review_binding.end_wtree` from Step 11.5's bound Step 9 record;
with none, insert `9 → 10 → 11 → 11.5`.
Its `STOP:` names the route:
@@ -687,11 +685,12 @@ Its `STOP:` names the route:
1. **Behavior, tests or build inputs changed:** Prompts/templates count as behavior.
Insert `5–11.5 → 12–14 → 16` before the pending Step 17. It excludes Step 14.5 (a rebuild
can change generated docs; compare before stage 3) and Step 15 (`finish` STOPs on an uncommitted
- non-release file: commit it by Step 15's rules, then rerun). A STOP naming a scoped-review packet
+ non-release file: commit it per Step 15, rerun). Its Step 9 plans with `gstack-review-plan --post-review`
+ (at the cap: a stop for the owner). A STOP naming a scoped-review packet
instead takes one reader (no round) and `--context-reviewed` rerun; a blocker is this item.
2. **Only authored docs or release metadata changed:** Keep Step 8's original child
- report and counts. Recheck affected plan items using their recorded verification
- and append current evidence to the invocation record. If a classification is no
+ report and counts. Recheck affected plan items by their recorded verification and
+ log current evidence. If a classification is no
longer supported, run Step 8's audit and decision gates only, then return to
Step 16 stage 1; else rerun with `--docs-rechecked`. Never edit the child's counts yourself.
3. **No changes, or the docs-only checks still support the plan:** `finish` continues to
diff --git a/test/fixtures/golden/codex-ship-SKILL.md b/test/fixtures/golden/codex-ship-SKILL.md
index b94c81878..f30493591 100644
--- a/test/fixtures/golden/codex-ship-SKILL.md
+++ b/test/fixtures/golden/codex-ship-SKILL.md
@@ -668,21 +668,19 @@ also makes Step 15's item-3 commit and runs the pregate (`--docs-rechecked`,
### 1. Finish writers and prepare outputs
-Before `finish`, inspect writer handles, including the docs child. Confirm completion or
-termination before another writer runs; timeout or cancellation acknowledgment
-alone means STOP until confirmed.
-
-Find declared generation/build commands in project instructions, manifests, build
-files and CI. Pass each to `finish` as `--build`. If none exists, record not applicable and
-the inspected sources. A missing prerequisite or failed build stops shipping:
-report **Build failed or prerequisite missing**, with the command, error and needed
-repair. Never invent a substitute command.
+Before `finish`, confirm every writer (the docs child too) completed or terminated;
+an acknowledged timeout or cancellation alone means STOP until confirmed.
+
+Pass each declared generation/build command (instructions, manifests, build files, CI)
+as `--build`; with none, record N/A and the sources inspected.
+A missing prerequisite or failed build stops shipping: report **Build failed or prerequisite
+missing** with the command, error and repair. Never invent a substitute command.
**If blocked:** repair it, repeat stage 1, then continue to stage 2: a content repair is behavior there.
### 2. Choose the change route
-`finish` runs `git diff <reviewed-tree> <current-tree>` (`--reviewed-tree`, saved before Step 12,
-against `$GSTACK_ROOT/bin/gstack-wtree`) and prints `ROUTE:`. No saved tree: pass `review_binding.end_wtree` from Step 11.5's bound Step 9 record;
+`finish` runs `git diff <reviewed-tree> <current-tree>` (`--reviewed-tree`, saved before Step 12
+by `$GSTACK_ROOT/bin/gstack-wtree`) and prints `ROUTE:`. No saved tree: pass `review_binding.end_wtree` from Step 11.5's bound Step 9 record;
with none, insert `9 → 10 → 11 → 11.5`.
Its `STOP:` names the route:
@@ -690,11 +688,12 @@ Its `STOP:` names the route:
1. **Behavior, tests or build inputs changed:** Prompts/templates count as behavior.
Insert `5–11.5 → 12–14 → 16` before the pending Step 17. It excludes Step 14.5 (a rebuild
can change generated docs; compare before stage 3) and Step 15 (`finish` STOPs on an uncommitted
- non-release file: commit it by Step 15's rules, then rerun). A STOP naming a scoped-review packet
+ non-release file: commit it per Step 15, rerun). Its Step 9 plans with `gstack-review-plan --post-review`
+ (at the cap: a stop for the owner). A STOP naming a scoped-review packet
instead takes one reader (no round) and `--context-reviewed` rerun; a blocker is this item.
2. **Only authored docs or release metadata changed:** Keep Step 8's original child
- report and counts. Recheck affected plan items using their recorded verification
- and append current evidence to the invocation record. If a classification is no
+ report and counts. Recheck affected plan items by their recorded verification and
+ log current evidence. If a classification is no
longer supported, run Step 8's audit and decision gates only, then return to
Step 16 stage 1; else rerun with `--docs-rechecked`. Never edit the child's counts yourself.
3. **No changes, or the docs-only checks still support the plan:** `finish` continues to
diff --git a/test/fixtures/golden/factory-ship-SKILL.md b/test/fixtures/golden/factory-ship-SKILL.md
index 24e3df64c..83930fe0a 100644
--- a/test/fixtures/golden/factory-ship-SKILL.md
+++ b/test/fixtures/golden/factory-ship-SKILL.md
@@ -670,21 +670,19 @@ also makes Step 15's item-3 commit and runs the pregate (`--docs-rechecked`,
### 1. Finish writers and prepare outputs
-Before `finish`, inspect writer handles, including the docs child. Confirm completion or
-termination before another writer runs; timeout or cancellation acknowledgment
-alone means STOP until confirmed.
-
-Find declared generation/build commands in project instructions, manifests, build
-files and CI. Pass each to `finish` as `--build`. If none exists, record not applicable and
-the inspected sources. A missing prerequisite or failed build stops shipping:
-report **Build failed or prerequisite missing**, with the command, error and needed
-repair. Never invent a substitute command.
+Before `finish`, confirm every writer (the docs child too) completed or terminated;
+an acknowledged timeout or cancellation alone means STOP until confirmed.
+
+Pass each declared generation/build command (instructions, manifests, build files, CI)
+as `--build`; with none, record N/A and the sources inspected.
+A missing prerequisite or failed build stops shipping: report **Build failed or prerequisite
+missing** with the command, error and repair. Never invent a substitute command.
**If blocked:** repair it, repeat stage 1, then continue to stage 2: a content repair is behavior there.
### 2. Choose the change route
-`finish` runs `git diff <reviewed-tree> <current-tree>` (`--reviewed-tree`, saved before Step 12,
-against `$GSTACK_ROOT/bin/gstack-wtree`) and prints `ROUTE:`. No saved tree: pass `review_binding.end_wtree` from Step 11.5's bound Step 9 record;
+`finish` runs `git diff <reviewed-tree> <current-tree>` (`--reviewed-tree`, saved before Step 12
+by `$GSTACK_ROOT/bin/gstack-wtree`) and prints `ROUTE:`. No saved tree: pass `review_binding.end_wtree` from Step 11.5's bound Step 9 record;
with none, insert `9 → 10 → 11 → 11.5`.
Its `STOP:` names the route:
@@ -692,11 +690,12 @@ Its `STOP:` names the route:
1. **Behavior, tests or build inputs changed:** Prompts/templates count as behavior.
Insert `5–11.5 → 12–14 → 16` before the pending Step 17. It excludes Step 14.5 (a rebuild
can change generated docs; compare before stage 3) and Step 15 (`finish` STOPs on an uncommitted
- non-release file: commit it by Step 15's rules, then rerun). A STOP naming a scoped-review packet
+ non-release file: commit it per Step 15, rerun). Its Step 9 plans with `gstack-review-plan --post-review`
+ (at the cap: a stop for the owner). A STOP naming a scoped-review packet
instead takes one reader (no round) and `--context-reviewed` rerun; a blocker is this item.
2. **Only authored docs or release metadata changed:** Keep Step 8's original child
- report and counts. Recheck affected plan items using their recorded verification
- and append current evidence to the invocation record. If a classification is no
+ report and counts. Recheck affected plan items by their recorded verification and
+ log current evidence. If a classification is no
longer supported, run Step 8's audit and decision gates only, then return to
Step 16 stage 1; else rerun with `--docs-rechecked`. Never edit the child's counts yourself.
3. **No changes, or the docs-only checks still support the plan:** `finish` continues to
diff --git a/test/ship-bounded-route.test.ts b/test/ship-bounded-route.test.ts
index 0c56e1c6b..57e639c98 100644
--- a/test/ship-bounded-route.test.ts
+++ b/test/ship-bounded-route.test.ts
@@ -26,7 +26,7 @@ const snapshot = (f: ShipFx, docs = ['README.md'], out = path.join(f.root, 'post
return out;
};
const finish = (f: ShipFx, reviewed: string, post: string, extra: string[] = []) => f.run(RELEASE, ['finish', '--base', 'main', '--reviewed-tree', reviewed, '--docs-post', post, '--lane', LANE, ...extra]);
-const behaviorStop = (p: string) => `STOP: behavior, tests or build inputs changed since review (${p}): insert 5–11.5 → 12–14 → 16 before Step 17 (stage 2.1)`;
+const behaviorStop = (p: string) => `STOP: behavior, tests or build inputs changed since review (${p}): insert 5–11.5 → 12–14 → 16 before Step 17; plan that Step 9 with gstack-review-plan --post-review, which at the round cap stops for the owner's grant of one scoped fix-check (stage 2.1)`;
const packetOf = (out: string) => /reads (\S+\.md)[ ,]/.exec(out)?.[1] ?? '';
const record = (f: ShipFx, paths: string[], packet: string | null, extra: Record<string, unknown> = {}) => {
const file = path.join(f.root, 'bounded-reviewed.json');
diff --git a/test/ship-finish-stack-parent.test.ts b/test/ship-finish-stack-parent.test.ts
index 1c676ccaf..3195f7df1 100644
--- a/test/ship-finish-stack-parent.test.ts
+++ b/test/ship-finish-stack-parent.test.ts
@@ -23,7 +23,7 @@ const wtree = (f: ShipFx) => f.run(path.join(BIN, 'gstack-wtree'), []).stdout.tr
const head = (f: ShipFx) => f.git('rev-parse', 'HEAD').stdout.trim();
const finish = (f: ShipFx, reviewed: string, post: string, extra: string[] = []) => f.run(RELEASE, ['finish', '--base', 'main', '--reviewed-tree', reviewed, '--docs-post', post, '--lane', LANE, ...extra]);
const lines = (n: number, edit: Record<number, string> = {}) => Array.from({ length: n }, (_, i) => edit[i + 1] ?? `export const l${i + 1} = ${i + 1};`).join('\n') + '\n';
-const behaviorStop = (paths: string) => `STOP: behavior, tests or build inputs changed since review (${paths}): insert 5–11.5 → 12–14 → 16 before Step 17 (stage 2.1)`;
+const behaviorStop = (paths: string) => `STOP: behavior, tests or build inputs changed since review (${paths}): insert 5–11.5 → 12–14 → 16 before Step 17; plan that Step 9 with gstack-review-plan --post-review, which at the round cap stops for the owner's grant of one scoped fix-check (stage 2.1)`;
const TEST_V0 = "import { expect, test } from 'bun:test';\ntest('lands', () => { expect(1).toBe(1); });\n";
const TEST_V1 = "import { expect, test } from 'bun:test';\ntest('lands direct', () => { expect(1).toBe(1); });\n";
diff --git a/test/ship-mechanical-retake.test.ts b/test/ship-mechanical-retake.test.ts
new file mode 100644
index 000000000..d4bc0ce26
--- /dev/null
+++ b/test/ship-mechanical-retake.test.ts
@@ -0,0 +1,145 @@
+/**
+ * Mechanical retakes after review (GST-1560, founderstar#563). After two full passes a branch merged its base (7 base-only
+ * paths) and retook its rules number 80 -> 81: one line in scripts/core/game.gd, save_version in 8 save fixtures under
+ * fixtures/, and one golden. finish said "insert 5–11.5" while gstack-review-plan at the round cap said "done". A
+ * retake the base policy declares under mechanical_retake, proven from the diff, now routes as mechanical with no review;
+ * anything else in those files still routes as behavior, and the behavior STOP names the planner flag that agrees with it.
+ */
+import { afterEach, describe, expect, setDefaultTimeout, test } from 'bun:test';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import { readMechanicalLines } from '../lib/ship-mechanical';
+import { MECHANICAL_RETAKE_KEY_VERSION } from '../lib/ship-policy';
+import { orderReceipt, validateReceipt } from '../lib/ship-receipt';
+import { lineOf, RELEASE, shipFixture, type ShipFx } from './helpers/ship-bin-fixture';
+
+setDefaultTimeout(180_000);
+const ROOT = path.resolve(import.meta.dir, '..');
+const BIN = path.dirname(RELEASE);
+const LANE = 'tests=printf " 3 pass\\n 0 fail\\nRan 3 tests across 1 file. [5.00ms]\\n"';
+const ships: ShipFx[] = [];
+afterEach(() => { while (ships.length) ships.pop()!.cleanup(); });
+
+const GAME = (n: number, { top = '', bottom = '', ready = 'pass' } = {}) => ['extends Node', top, ...Array.from({ length: 8 }, (_, i) => `# rules note ${i + 1}`), `const RULE_NUMBERS := ${n}`,
+ ...Array.from({ length: 8 }, (_, i) => `# engine note ${i + 1}`), `func _ready(): ${ready}`, bottom].filter(l => l !== '').join('\n') + '\n';
+const SAVES = (n: number, odd: Record<number, number> = {}) => Object.fromEntries(Array.from({ length: 8 }, (_, i) => [`fixtures/saves/s${i + 1}.json`, `{\n "name": "s${i + 1}",\n "save_version": ${odd[i + 1] ?? n}\n}\n`]));
+const GOLDEN = 'test/golden/rules.golden';
+const REGEN = JSON.stringify({ entries: [{ id: 'rules-golden', command: `sed -n 's/^const RULE_NUMBERS := //p' scripts/core/game.gd | sed 's/^/rules=/' > ${GOLDEN}`, outputs: [GOLDEN], inputs: ['scripts/core/game.gd'] }] }) + '\n';
+const POLICY = JSON.stringify({ mechanical_retake: [{ path: 'scripts/core/game.gd', template: 'const RULE_NUMBERS := {n}', fields: [{ glob: 'fixtures/saves/*.json', field: 'save_version' }], regen: ['rules-golden'] }], min_gstack_version: MECHANICAL_RETAKE_KEY_VERSION }) + '\n';
+const behaviorStop = (p: string) => `STOP: behavior, tests or build inputs changed since review (${p}): insert 5–11.5 → 12–14 → 16 before Step 17; plan that Step 9 with gstack-review-plan --post-review, which at the round cap stops for the owner's grant of one scoped fix-check (stage 2.1)`;
+
+/**
+ * founderstar#563: the branch took 80 and was reviewed; the base then took 80 for another rule and added 7 files; the
+ * branch merged the base and retook 81. `retake` overrides what the retake commit writes.
+ */
+function founderstar(retake: { game?: string; saves?: Record<string, string>; golden?: string } = {}, policy = true) {
+ const f = shipFixture({ ...(policy ? { '.gstack/ship-policy.json': POLICY } : {}), '.gstack/generated.json': REGEN, 'scripts/core/game.gd': GAME(79), ...SAVES(79), [GOLDEN]: 'rules=79\n' },
+ { 'scripts/core/game.gd': GAME(80, { bottom: 'func rule_80(): pass' }), ...SAVES(80), [GOLDEN]: 'rules=80\n' });
+ ships.push(f);
+ const reviewed = f.run(path.join(BIN, 'gstack-wtree'), []).stdout.trim();
+ const reviewedBase = f.git('merge-base', 'origin/main', 'HEAD').stdout.trim();
+ const post = path.join(f.root, 'post.json');
+ expect(f.run(path.join(BIN, 'gstack-docs-candidate'), ['snapshot', '--out', post, '--audit-id', 'a1', '--mode', 'edit', '--base', 'main', '--docs', 'README.md']).status).toBe(0);
+ f.advanceBase({ 'scripts/core/game.gd': GAME(80, { top: 'func rule_other(): pass' }), ...SAVES(80), [GOLDEN]: 'rules=80\n', ...Object.fromEntries(Array.from({ length: 7 }, (_, i) => [`base/p${i + 1}.ts`, `export const p${i + 1} = ${i};\n`])) });
+ expect(f.git('fetch', '-q', 'origin').status).toBe(0);
+ const merged = f.git('merge', '-q', '--no-edit', 'origin/main');
+ expect(merged.status, merged.stderr).toBe(0);
+ f.write({ 'scripts/core/game.gd': retake.game ?? GAME(81, { top: 'func rule_other(): pass', bottom: 'func rule_80(): pass' }), ...SAVES(81), ...(retake.saves ?? {}), [GOLDEN]: retake.golden ?? 'rules=81\n' });
+ f.commit('retake the rules number: 80 -> 81');
+ const run = (extra: string[] = []) => f.run(RELEASE, ['finish', '--base', 'main', '--reviewed-tree', reviewed, '--reviewed-base', reviewedBase, '--docs-post', post, '--lane', LANE, ...extra]);
+ return { f, run };
+}
+
+describe('a declared mechanical retake after a base merge (GST-1560: founderstar#563)', () => {
+ test('the base merge, the constant, 8 save fixtures and the golden bind without a new review, and the receipt lists them', () => {
+ const { f, run } = founderstar();
+ const r = run();
+ expect(lineOf(r.stdout, 'ROUTE'), r.stdout).toMatch(/ behavior=0 docs=0 metadata=0 tests=0 base=7 context=0 mechanical=10$/);
+ expect(r.stdout).not.toContain('STOP: behavior');
+ expect(r.stdout).not.toContain('scoped reader');
+ const lines = r.stdout.split('\n').filter(l => l.startsWith('MECHANICAL: '));
+ expect(lines).toContain('MECHANICAL: scripts/core/game.gd (constant 80 → 81)');
+ expect(lines).toContain('MECHANICAL: fixtures/saves/s8.json (save_version 80 → 81)');
+ expect(lines).toContain(`MECHANICAL: ${GOLDEN} (golden, regenerated by rules-golden)`);
+ expect(lines).toHaveLength(10);
+ expect(lineOf(r.stdout, 'DOCS')).toContain('fresh');
+
+ const body = path.join(f.root, 'body.md');
+ fs.writeFileSync(body, '## Summary\n\nRetake.\n');
+ const unlisted = f.run(path.join(BIN, 'gstack-ship-receipt'), ['write', '--pr', '563', '--base', 'main', '--body', body]);
+ expect(unlisted.status).not.toBe(0);
+ expect(unlisted.stderr).toContain('does not list "Mechanical retake: fixtures/saves/s1.json (save_version 80 → 81)"');
+ fs.writeFileSync(body, '## Summary\n\n' + lines.map(l => `Mechanical retake: ${l.slice('MECHANICAL: '.length)}`).join('\n') + '\n');
+ const listed = f.run(path.join(BIN, 'gstack-ship-receipt'), ['write', '--pr', '563', '--base', 'main', '--body', body, '--json']);
+ expect(listed.stderr).not.toContain('Mechanical retake');
+ const recorded = readMechanicalLines(f.work, f.git('rev-parse', 'HEAD^{tree}').stdout.trim());
+ expect(recorded).toEqual(lines.map(l => `Mechanical retake: ${l.slice('MECHANICAL: '.length)}`).sort());
+ const receipt = orderReceipt({ schema_version: 1, head: 'a'.repeat(40), base: 'main', mechanical: recorded });
+ expect(Object.keys(receipt).indexOf('mechanical')).toBeGreaterThan(0);
+ expect(validateReceipt(receipt).filter(e => e.path.includes('mechanical'))).toEqual([]);
+ expect(validateReceipt({ ...receipt, mechanical: [5] }).some(e => e.path.includes('mechanical'))).toBe(true);
+ f.write({ 'README.md': '# Fx\n\nedited after finish\n' }); f.commit('docs: an edit after finish');
+ expect(readMechanicalLines(f.work, f.git('rev-parse', 'HEAD^{tree}').stdout.trim())).toEqual([]);
+ });
+
+ test('one extra non-literal edit in the constant file routes as behavior, and so do the fixtures that hang on it', () => {
+ const { run } = founderstar({ game: GAME(81, { top: 'func rule_other(): pass', bottom: 'func rule_80(): pass', ready: 'return' }) });
+ const r = run();
+ expect(r.status).toBe(3);
+ expect(lineOf(r.stdout, 'ROUTE'), r.stdout).toMatch(/ behavior=10 .* base=7 context=0$/);
+ expect(r.stdout).toContain('ROUTE_MECHANICAL_REFUSED: scripts/core/game.gd changes more than the declared values since review');
+ expect(r.stdout).toContain('ROUTE_MECHANICAL_REFUSED: fixtures/saves/s1.json its constant scripts/core/game.gd is not a proven retake');
+ expect(lineOf(r.stdout, 'STOP')).toStartWith('STOP: behavior, tests or build inputs changed since review (');
+ });
+
+ test('a fixture holding a value other than the retaken constant routes as behavior; the rest stay mechanical', () => {
+ const { run } = founderstar({ saves: SAVES(81, { 3: 82 }) });
+ const r = run();
+ expect(lineOf(r.stdout, 'ROUTE'), r.stdout).toMatch(/ behavior=1 .* base=7 context=0 mechanical=9$/);
+ expect(r.stdout).toContain("ROUTE_MECHANICAL_REFUSED: fixtures/saves/s3.json writes 82 into save_version where it held 80, not the constant's 80 → 81");
+ expect([r.status, lineOf(r.stdout, 'STOP')]).toEqual([3, behaviorStop('fixtures/saves/s3.json')]);
+ });
+
+ test('an undeclared file named like an Object.prototype key still routes as behavior beside a proven retake', () => {
+ const { run } = founderstar({ saves: { constructor: '#!/bin/sh\necho changed after review\n' } });
+ const r = run();
+ expect(lineOf(r.stdout, 'ROUTE'), r.stdout).toMatch(/ behavior=1 .* base=7 context=0 mechanical=10$/);
+ expect([r.status, lineOf(r.stdout, 'STOP')]).toEqual([3, behaviorStop('constructor')]);
+ });
+
+ test('a golden its declared command does not regenerate byte-identically routes as behavior', () => {
+ const { run } = founderstar({ golden: 'rules=81 (edited by hand)\n' });
+ const r = run();
+ expect(r.stdout).toContain(`ROUTE_MECHANICAL_REFUSED: ${GOLDEN} does not regenerate byte-identically from rules-golden (stale)`);
+ expect([r.status, lineOf(r.stdout, 'STOP')]).toEqual([3, behaviorStop(GOLDEN)]);
+ });
+
+ test('without the base policy declaration the same retake routes as behavior, exactly as before', () => {
+ const { run } = founderstar({}, false);
+ const r = run();
+ expect(lineOf(r.stdout, 'ROUTE'), r.stdout).toMatch(/ behavior=10 .* base=7 context=0$/);
+ expect(r.stdout).not.toContain('MECHANICAL');
+ });
+
+ test('a policy that declares a glob, two slots or a .gstack/ path as the constant is refused at load', () => {
+ const f = shipFixture({ '.gstack/ship-policy.json': JSON.stringify({ mechanical_retake: [{ path: 'scripts/*.gd', template: 'const A := {n} {n}', fields: [{ glob: '.gstack/x.json', field: 'v' }], regen: [] }], min_gstack_version: MECHANICAL_RETAKE_KEY_VERSION }) + '\n' });
+ ships.push(f);
+ const v = f.run(path.join(BIN, 'gstack-ship-policy'), ['validate', '--json']);
+ expect(v.status).not.toBe(0);
+ for (const why of ['must be one literal file, not a glob', 'must hold exactly one {n}', 'glob must not name a path under .gstack/ or .github/']) expect(v.stdout + v.stderr).toContain(why);
+ });
+});
+
+describe('finish and gstack-review-plan agree at the round cap (GST-1560)', () => {
+ test('the behavior STOP names --post-review, and the planner then plans the owner\'s exit at the cap, never done', () => {
+ const { f, run } = founderstar({ game: GAME(81, { top: 'func rule_other(): pass', bottom: 'func rule_80(): pass', ready: 'return' }) });
+ expect(lineOf(run().stdout, 'STOP')).toContain('plan that Step 9 with gstack-review-plan --post-review, which at the round cap stops for the owner\'s grant of one scoped fix-check');
+ const plan = (...a: string[]) => lineOf(f.run(path.join(BIN, 'gstack-review-plan'), ['--base', 'main', '--adversarial-ran', ...a]).stdout, 'NEXT');
+ expect(plan('--pass', '2', '--last', 'full')).toStartWith('NEXT: done');
+ expect(plan('--pass', '2', '--last', 'full', '--post-review')).toStartWith('NEXT: stop (edits after the review bound (Step 16 stage 2.1)');
+ expect(plan('--pass', '1', '--last', 'fix-check', '--fix-checks', '1', '--post-review')).toStartWith('NEXT: stop (edits after the review bound');
+ expect(plan('--pass', '1', '--last', 'full', '--post-review')).toMatch(/^NEXT: (full|fix-check) \(edits after the review bound/);
+ const stage2 = fs.readFileSync(path.join(ROOT, 'ship/SKILL.md.tmpl'), 'utf8').split('### 2. Choose the change route')[1]!.split('### 3.')[0]!;
+ expect(stage2).toContain('--post-review');
+ });
+});
diff --git a/test/ship-rereview-triggers.test.ts b/test/ship-rereview-triggers.test.ts
index 274dcceb7..99f9967b2 100644
--- a/test/ship-rereview-triggers.test.ts
+++ b/test/ship-rereview-triggers.test.ts
@@ -178,7 +178,7 @@ describe('finish route after a base merge (GST-407 #1, GBRA-108 #7739)', () => {
expect(comparePath(f.work, sides(), 'assets/x.bin')).toBe('changed');
f.write({ 'assets/x.bin': 'a\u0000b\n', 'src/auth.ts': 'export const authRequired = false;\nexport const a = 2;\n' }); f.commit('flip');
const r = finish(f, reviewed, post, ['--reviewed-base', reviewedBase]);
- expect([r.status, lineOf(r.stdout, 'STOP')]).toEqual([3, 'STOP: behavior, tests or build inputs changed since review (src/auth.ts): insert 5–11.5 → 12–14 → 16 before Step 17 (stage 2.1)']);
+ expect([r.status, lineOf(r.stdout, 'STOP')]).toEqual([3, 'STOP: behavior, tests or build inputs changed since review (src/auth.ts): insert 5–11.5 → 12–14 → 16 before Step 17; plan that Step 9 with gstack-review-plan --post-review, which at the round cap stops for the owner\'s grant of one scoped fix-check (stage 2.1)']);
});
});
@@ -197,7 +197,7 @@ describe('a version stamp after review (GBRA-251, gbrain #8095)', () => {
const post = snapshot(f);
f.write({ VERSION: '1.0.1.0\n', 'plugin.json': pluginAfter, 'docs/guide.md': guide('1.0.1.0') }); f.commit('stamp');
const r = finish(f, reviewed, post, ['--reviewed-base', mergeBase(f)]);
- if (stops) expect([name, r.status, lineOf(r.stdout, 'STOP')]).toEqual([name, 3, 'STOP: behavior, tests or build inputs changed since review (plugin.json): insert 5–11.5 → 12–14 → 16 before Step 17 (stage 2.1)']);
+ if (stops) expect([name, r.status, lineOf(r.stdout, 'STOP')]).toEqual([name, 3, 'STOP: behavior, tests or build inputs changed since review (plugin.json): insert 5–11.5 → 12–14 → 16 before Step 17; plan that Step 9 with gstack-review-plan --post-review, which at the round cap stops for the owner\'s grant of one scoped fix-check (stage 2.1)']);
else expect([name, lineOf(r.stdout, 'ROUTE')]).toEqual([name, expect.stringMatching(/ behavior=0 docs=0 metadata=3 tests=0 /)]);
}
});
@@ -220,7 +220,7 @@ describe('a restamp after a lost slot (GST-895, GBRA-218, gbrain #8134)', () =>
mergeMain(f, { VERSION: '1.0.2.0\n', 'src/notice.ts': notice(['0.9.0.0', 'old'], ['1.0.1.0', 'theirs'], [ownRow, 'mine']) });
return { f, reviewed: wtree(f), reviewedBase: mergeBase(f), post: snapshot(f) };
};
- const behaviorStop = 'STOP: behavior, tests or build inputs changed since review (src/notice.ts): insert 5–11.5 → 12–14 → 16 before Step 17 (stage 2.1)';
+ const behaviorStop = 'STOP: behavior, tests or build inputs changed since review (src/notice.ts): insert 5–11.5 → 12–14 → 16 before Step 17; plan that Step 9 with gstack-review-plan --post-review, which at the round cap stops for the owner\'s grant of one scoped fix-check (stage 2.1)';
test('the moved stale stamp is metadata; a moved base row or pre-fork row stops', () => {
const own = lostSlot('1.0.1.0');
@@ -472,7 +472,7 @@ describe('test-only and audit-requested edits after the docs audit (GST-391, gbr
const plong = snapshot(long);
long.write({ 'test/b.test.ts': spec('b') + Array.from({ length: 250 }, (_, i) => `test('case ${i}', () => expect(${i}).toBe(${i}));\n`).join('') }); long.commit('test: 250 cases');
const tooLong = finish(long, rlong, plong, ['--reviewed-base', mergeBase(long)]);
- expect([tooLong.status, lineOf(tooLong.stdout, 'STOP')]).toEqual([3, 'STOP: behavior, tests or build inputs changed since review (test/b.test.ts): insert 5–11.5 → 12–14 → 16 before Step 17 (stage 2.1)']);
+ expect([tooLong.status, lineOf(tooLong.stdout, 'STOP')]).toEqual([3, 'STOP: behavior, tests or build inputs changed since review (test/b.test.ts): insert 5–11.5 → 12–14 → 16 before Step 17; plan that Step 9 with gstack-review-plan --post-review, which at the round cap stops for the owner\'s grant of one scoped fix-check (stage 2.1)']);
expect(tooLong.stdout).toContain('too large for the scoped review (over 200 lines in a section): test/b.test.ts');
for (const [rel, route] of [['src/main/java/ABTest.java', 'behavior=1 docs=0 metadata=0 tests=0'], ['app/test_mode.py', 'behavior=1 docs=0 metadata=0 tests=0'], ['tests/test_mode.py', 'behavior=0 docs=0 metadata=0 tests=1']] as const) {