A used review grant can no longer be claimed again, plus two /ship finish fixes (GST-3560) (#4722)

A grant for one follow-up review of a fix can no longer be claimed again
once that review ran, so one grant still buys one round.

/ship finish no longer calls the docs audit stale for a file a clean
follow-up review read, and the CI-record timeout no longer counts local
test runs.

Nothing to do: the merge checks only get stricter, and the timeout
setting keeps its name and default.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
Review-Finding: pass1/outside-voice#1 reader=outside-voice
Review-Finding: pass1/outside-voice#2 reader=outside-voice
Review-Finding: pass1/outside-voice#3 reader=outside-voice
Review-Finding: pass2/outside-voice#2 reader=outside-voice
This commit is contained in:
Garry Tanandcapy-ai[bot] authored and GitHub committed 2026-11-23 01:08:54 +00:00
1 parent 79f3052f35
commit ccd80de8eb
15 files changed
+198 -36

No files matched your search

+6 -1
View File
@@ -76,7 +76,10 @@
* whose inventory command refuses HEAD's tree (inventory_failed) is recorded
* as source "remote_gate" when the cleared pregate.json/remote_gate verifies
* for that exact tree (lib/remote-gate-stand-in.ts, GST-1688); `carried`
* never lists it, since no CI run carried it.
* never lists it, since no CI run carried it. Before it runs any file here (a
* per_file remainder of CI-skipped files, or a test-lane exception's preflight),
* it prints CI_RECORD_PHASE: local, which ends the ci_record_timeout_s bound
* gstack-ship-release and gstack-ship-preflight hold it to (GST-3560).
*
* MACHINE-LOCAL by design: neither the ledger nor the logs are brain-synced.
* A synced record citing an unsynced log would grade FRESH on a machine where
@@ -821,6 +824,8 @@ async function cmdRecordCi(argv: string[]): Promise<number> {
}
let exception: BoundLaneException | undefined;
const grant = atHead.find((g) => g.approval === v.exceptedBy);
const local = (v.excepted?.length && grant ? v.excepted.length : 0) + (v.remainder?.length ?? 0);
if (local) console.error(`CI_RECORD_PHASE: local files=${local} (the CI run is found and verified; ci_record_timeout_s does not bound these runs)`);
if (v.excepted?.length && grant) {
const preLabel = `${label}.excepted`;
console.error(`gstack-evidence record-ci: test-lane exception ${grant.approval}: preflighting ${v.excepted.length} uncovered file(s) here at ${head.slice(0, 12)}, one at a time (label=${preLabel})`);
+9 -2
View File
@@ -1062,17 +1062,24 @@ function cmdStop(rest: string[]): number {
}
/** Before a granted round's first dispatch: this run spends the grant, so no other run can buy the same round with it. */
function cmdClaim(rest: string[]): number {
async function cmdClaim(rest: string[]): Promise<number> {
const run = flag(rest, '--run'), id = flag(rest, '--grant');
if (!run || !/^[\w.:-]{1,120}$/.test(run) || !id) { process.stderr.write('gstack-ship-receipt claim: --run <the /ship run id> and --grant <approval id> are required\n'); return EXIT.usage; }
const repoRoot = git(['rev-parse', '--show-toplevel']);
if (!repoRoot) { process.stderr.write('gstack-ship-receipt claim: run it inside the git checkout\n'); return EXIT.usage; }
const read = readBody(rest);
if (!read.ok) { process.stderr.write(`gstack-ship-receipt claim: ${read.why}; fix: ${read.fix}\n`); return EXIT.fail; }
const g = readReviewRoundGrants(repoRoot).find(x => x.approval === id);
const grants = readReviewRoundGrants(repoRoot), g = grants.find(x => x.approval === id);
if (!g) { process.stderr.write(`${resultLine('gstack-ship-receipt claim', 'GRANT_UNKNOWN', `no approved fix-check or round grant ${id} (a gstack-approvals round-grant row, or an owner's review_loop_grant <head> row) in this branch's approval record`)}\n`); return EXIT.refused; }
const other = receiptRuns(read.body).find(r => r.mark === 'grant' && r.grant === id && r.run !== run);
if (other) { process.stderr.write(`${resultLine('gstack-ship-receipt claim', 'GRANT_SPENT', `grant ${id} was claimed by run ${other.run}: a grant buys one round; the lane or its Captain records a new one`)}\n`); return EXIT.refused; }
const held = receiptRuns(read.body).some(r => r.mark === 'grant' && r.grant === id && r.run === run);
if (!held && g.kind === 'fix-check') {
const rows = reviewRows(repoRoot);
if (!rows) { process.stderr.write(`gstack-ship-receipt claim: gstack-review-read failed, so whether a fix-check already spent grant ${id} is unknown; not claimed, so do not dispatch\n`); return EXIT.fail; }
const { bindFixCheckRow, grantSpent } = await import('../lib/fix-check-clearing');
if (grantSpent(rows, g, row => bindFixCheckRow(repoRoot, row, grants, { open: true }).ok)) { process.stderr.write(`${resultLine('gstack-ship-receipt claim', 'GRANT_SPENT', `a counted fix-check already read under grant ${id} (it carries the grant, or started after the grant was recorded): a grant buys one round; the lane or its Captain records a new one (docs/troubleshooting.md#pr-round-cap)`)}\n`); return EXIT.refused; }
}
const err = postBody(rest, read.pr, placeRunEntry(read.body, grantMarker({ head: g.head, run, grant: id })));
if (err) { process.stderr.write(`gstack-ship-receipt claim: ${err}; not claimed, so do not dispatch\n`); return EXIT.fail; }
const handedOff = !flag(rest, '--body') && hostPublishes();
@@ -0,0 +1,4 @@
---
important: blocker
---
**A fix-check grant that a fix-check already used can no longer be claimed for a second read.** `gstack-ship-receipt claim` now also checks the review log: when a counted fix-check already read under the grant (one that carries it, or one that carries no grant and was logged after the grant was recorded, such as a read planned through `gstack-review-plan --grant` with no claim), claim refuses with `GRANT_SPENT`. /ship finish no longer reports the docs audit stale for a path a clean fix-check read and nothing changed since; `DOCS: fresh` lists it as `fix_checked=<n>`. `ci_record_timeout_s` now bounds only finding and verifying the CI run: the local runs of CI-skipped files that `gstack-evidence record-ci` does afterwards get up to an hour more, so a long remainder no longer runs into the bound, and a slow CI lookup is still stopped at the bound, as `ci_record_timeout`. (GST-3560)
+4 -2
View File
@@ -1474,8 +1474,10 @@ them (`ci_carried=<lane>:<run>/<attempt>`). A run whose `tree.json` lists
from its job log adds `tree_source: "job-log"` to its entries and
`tree_source=job-log` after them ([tree_log_step](#tree-log-step)). Each `record-ci` gets the base
policy's [`ci_record_timeout_s`](ship-policy.md#ci-record-timeout) (600 s by
default, 3600 s at most), in preflight's Step 5 and finish as well as in accept, and accept and
preflight print it as `CI_RECORD_TIMEOUT:`.
default, 3600 s at most) to find and verify the CI run, in preflight's Step 5 and finish as well as in accept, and accept and
preflight print it as `CI_RECORD_TIMEOUT:`. The local runs that follow
`CI_RECORD_PHASE: local` (a `per_file` remainder or an exception preflight)
don't count against it and get up to an hour more.
<a id="record-ci-reuse"></a>**record-ci reuses its own row at the same tree (GST-1795).** Step 5's
carry and accept both call `record-ci`, so at an unchanged pushed tree the
+7 -2
View File
@@ -230,7 +230,9 @@ caught on another crew's PRs.
An extra-round grant never answers a stop.
A run whose flags name a grant runs `gstack-ship-receipt claim` before its
first dispatch, which writes a grant record into the runs block; a grant
another run claimed is refused (`GRANT_SPENT`), a voided run's claim still
another run claimed, or a fix-check grant a counted fix-check already read
under (one carrying no grant and logged after it included), is refused (`GRANT_SPENT`), a
voided run's claim still
spends it, and stop and grant records are never trimmed from the block. When
the run record cannot save the claim, claim fails and the run starts no
reviewers; rerun claim with the same `--run` once the record is writable, since
@@ -1005,7 +1007,10 @@ fix-check read after a base merge also edited it (GST-1195), routes as
`fix_checked=` in `ROUTE:` and is listed on a
`FIX_CHECK: reviewed` line, a gate-edited test included. The line names the
grant whose stop head is newest in that range, the fix-check's own when several
grants fall inside it (GST-1610). Authored docs keep the
grants fall inside it (GST-1610). A `fix_checked` path the Step 14.5 audit
hashed also doesn't stale that audit at stage 3: `DOCS: fresh` counts it as
`fix_checked=<n>` in its carried list, since a clean fix-check read its current
bytes and the path is unchanged since that read (GST-3560). Authored docs keep the
stage 2.2 recheck, and a path the branch edited after the fix-check still routes by the
rules above. Any other row prints
`FIX_CHECK: not counted (<reason>)` and changes nothing. `gstack-review-log`
+1 -1
View File
@@ -89,7 +89,7 @@ branch that changes the policy.
| `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`. |
| `test_code` | glob list | `[]` | Root-anchored globs of test code the built-in test names miss, never under `.gstack/` or `.github/`, and never matching a file there (`["tests/**/*.gd"]` for GDScript checks). A matching file changed after review routes as test code, one scoped reader of its test hunks, instead of behavior, beside the built-in globs; shared `helpers/` and `fixtures/` files stay behavior. See [test code and Godot UID sidecars](#test-code). Read from the base revision only. Needs `min_gstack_version`. |
| `plan_record` | `off` \| `warn` \| `require` | `off` | <a id="plan-record"></a>Whether `gstack-ship-queue ready` and `land` (direct, stamp and train land) and `/ship`'s `gstack-ship-release finish --plan "<line>"` check the PR body's `Plan:` line (GST-1751). The line is the brief's (`Plan: approved: <run id or row id>`, `Plan: exempt: <reason>` or `Plan: required`), written under `## Approvals` by `gstack-approvals render --plan`. `ready` resolves it with lib/plan-record.ts against every branch's approval rows on the lane machine: a run id needs the newest gate revision's plan approval answered `approved`, in the owner's words, with no decision of that revision left unanswered; a row id needs an approved row that is not a ruling or grant, and a row from an autoplan run stands for that run's gate the same way; a broken or unreadable store refuses (`PLAN_STORE_UNAVAILABLE`) and never throws, and under `off` changes nothing; an exemption must be one crew/docs/captain.md lists or `crew:<rule>`; a diff of changelog fragments only needs no line. `finish` resolves the brief's line the same way before its first stage. `ready` (train ready included) prints `PLAN:` and writes the resolved record into the READY note; `land` checks that the note carries the PR body's current line and never reads the store. `warn` prints and continues; `require` refuses (`PLAN_RECORD_MISSING`, `PLAN_UNRESOLVED`, `PLAN_NOT_APPROVED`, `PLAN_EXEMPT_UNKNOWN`, `PLAN_STORE_UNAVAILABLE`, `QUEUE_PLAN_MISMATCH`). When this key is `off` or absent, the mode comes from `GSTACK_PLAN_RECORD` (a crew's opt-in), then `plan_record` in `<state root>/config.yaml` (`gstack-config set plan_record off|warn|require`: the untracked source for a repo that commits no `.gstack/`; a typo is rejected, and the `PLAN:` line names the file), then `warn` in a Capy session (`GSTACK_CAPY=1`), then `off`; a machine's key never loosens a tracked `warn` or `require`. A repo with no tracked policy gets the check at `ready` and `finish` only: ready writes no READY note there and `land` refuses before its plan step. Capy's state root does not survive a fresh machine, so a Capy crew that wants more than `warn` sets `GSTACK_PLAN_RECORD` in its project env. On a public or unknown-visibility repository `render --plan` writes `Plan: approved (record r-<12 hex>)`, an opaque id of the approval row (opaque, not secret), so no run id, row id or path reaches the PR body or the READY note pushed to origin; `ready` resolves it by hashing every row id it reads and then applies the row-id rules, and render refuses with no output when an approved line does not resolve. gstack never infers a feature from the diff, title or changelog. Read from the base revision only. Needs `min_gstack_version`. |
| `ci_record_timeout_s` | integer seconds, at least 60 | `600` | <a id="ci-record-timeout"></a>How long one `gstack-evidence record-ci` may run before it stops that lane, in `gstack-ship-release accept` and finish and in `gstack-ship-preflight`'s Step 5. A value over 3600 is clamped to 3600. accept and preflight print the bound they used as `CI_RECORD_TIMEOUT: <n>s (default)`, `(origin/<base> ci_record_timeout_s)` or `(… <value> is over the 3600s ceiling)`. Raise it when record-ci runs long, for example when it reruns a per_file remainder of CI-skipped files here (harness-evals #271 needed about 745 s). Read from the base revision only, so a branch can't raise its own bound. Needs `min_gstack_version`. |
| `ci_record_timeout_s` | integer seconds, at least 60 | `600` | <a id="ci-record-timeout"></a>How long one `gstack-evidence record-ci` may spend finding and verifying the CI run before it stops that lane as `ci_record_timeout`, in `gstack-ship-release accept` and finish and in `gstack-ship-preflight`'s Step 5. A value over 3600 is clamped to 3600. accept and preflight print the bound they used as `CI_RECORD_TIMEOUT: <n>s (default)`, `(origin/<base> ci_record_timeout_s)` or `(… <value> is over the 3600s ceiling)`. The local runs that follow, a per_file remainder of CI-skipped files or an exception preflight, start once record-ci prints `CI_RECORD_PHASE: local`; they don't count against it and get up to an hour more, so a long remainder no longer needs a higher bound (harness-evals #538 ran 445 remainder tests in about 880 s against 900). Read from the base revision only, so a branch can't raise its own bound. 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`. |
+7 -2
View File
@@ -8015,8 +8015,13 @@ The digest binds the abandon to the bytes you inspected.
### `GRANT_SPENT`
**Meaning.** `gstack-ship-receipt claim` found another `/ship` run's grant
record for this round grant in the PR body's runs block. A grant buys one round,
and a voided run's claim still spends it. Within the run that claimed it, a
record for this round grant in the PR body's runs block, or, for a fix-check
grant, a counted fix-check in the review log that already read under it: a row
carrying the grant, or one carrying no grant logged after the grant was recorded
(a row stamped with another grant was that grant's read). The second case
catches a fix-check that ran with no claim (an owner's `review_loop_grant` row or
a round grant planned through `gstack-review-plan --grant`). A grant buys one
round, and a voided run's claim still spends it. Within the run that claimed it, a
fix-check row that doesn't count (`converged:false`, partial hunks) spends
nothing: log a correct row in the same run instead of asking for a new grant
([review-policy.md](review-policy.md#one-grant-path)).
+6 -2
View File
@@ -46,9 +46,13 @@ const nameOf = (b: OpenBlocker) => (typeof b === 'string' ? b : b.id);
export const countedFixCheck = (r: Row, bind?: (row: Row) => boolean) => r?.skill === 'review-fix-check'
&& (r.fix_check_base !== undefined && bind ? bind(r) : r.completed === true && r.converged === true);
/** A fix-check grant buys one counted fix-check: it is spent once a counted row carries it, or once a counted fix-check started after it was recorded. */
/**
* A fix-check grant buys one counted fix-check: it is spent once a counted row carries it, or once a counted fix-check that
* carries no grant (an unclaimed read, such as one planned through gstack-review-plan --grant) started after it was recorded.
* A row a claim stamped with another grant was that grant's read, so it never spends this one (GST-3560).
*/
export const grantSpent = (rows: readonly Row[], g: Pick<ReviewRoundGrant, 'approval' | 'at'>, bind?: (row: Row) => boolean) =>
rows.some(r => countedFixCheck(r, bind) && (r.grant === g.approval || rowTime(r) > Date.parse(g.at)));
rows.some(r => countedFixCheck(r, bind) && (r.grant === g.approval || (!r.grant && rowTime(r) > Date.parse(g.at))));
/**
* The grant-and-row binding finish and write share (amendments A, B and H): a review-fix-check row gstack-review-log stamped from a
+25 -5
View File
@@ -197,15 +197,34 @@ export function mappedLanes(cwd: string, base: string, list: { label: string; co
* and records the CI-sourced ledger row; or, when the lane's inventory refuses this tree, the cleared remote gate for this exact
* tree stands in (`remoteGate`, lib/remote-gate-stand-in.ts, GST-1688); or why neither held (`carryNone`), so the caller runs it.
*/
export function carryLane(cwd: string, base: string, l: { label: string; command: string }, timeoutS = recordCiTimeout(shipPolicy(cwd, base), base).seconds): LaneResult {
const rec = bin(cwd, 'gstack-evidence', ['record-ci', '--label', l.label, '--base', base, '--remote-gate-stands-in', '--', l.command], timeoutS * 1000);
export async function carryLane(cwd: string, base: string, l: { label: string; command: string }, timeoutS = recordCiTimeout(shipPolicy(cwd, base), base).seconds): Promise<LaneResult> {
const inv = scriptInvocation(path.join(BIN_DIR, 'gstack-evidence'), ['record-ci', '--label', l.label, '--base', base, '--remote-gate-stands-in', '--', l.command]);
if (!inv.ok) return { label: l.label, exit: null, testsRan: 'unknown', log: '-', carryNone: `record_failed: ${inv.error}` };
const rec = await new Promise<{ status: number | null; stderr: string; bound: boolean }>(resolve => {
const child = spawn(inv.cmd, inv.argv, { cwd, stdio: ['ignore', 'ignore', 'pipe'] });
let stderr = '', local = false, bound = false;
let timer = setTimeout(() => { bound = true; child.kill('SIGKILL'); }, timeoutS * 1000);
child.stderr.on('data', d => {
stderr = (stderr + d).slice(-200_000);
if (local || !/^CI_RECORD_PHASE: local /m.test(stderr)) return;
local = true;
clearTimeout(timer);
timer = setTimeout(() => child.kill('SIGKILL'), LOCAL_RUNS_ALLOWANCE_S * 1000);
});
child.on('error', e => { clearTimeout(timer); resolve({ status: null, stderr: [e.message, stderr].filter(Boolean).join('\n'), bound: false }); });
child.on('close', status => { clearTimeout(timer); resolve({ status, stderr, bound }); });
});
if (rec.bound) return { label: l.label, exit: null, testsRan: 'unknown', log: '-', carryNone: `ci_record_timeout: finding and verifying the CI run took over the ${timeoutS} s bound (ci_record_timeout_s); nothing was recorded` };
const got = recordCiResult(rec.stderr);
if (rec.status === 0 && got.remoteGate) return { label: l.label, exit: 0, testsRan: got.tests!, log: '-', remoteGate: got.remoteGate, standIn: got.standIn ?? 'not carried' };
if (rec.status === 0 && got.runs) return { label: l.label, exit: 0, testsRan: got.files ? `${got.tests} (files)` : got.tests!, log: '-', carried: got.runs, ...(got.treeSource ? { treeSource: got.treeSource } : {}), ...(got.notOwed ? { notOwed: got.notOwed } : {}), ...(got.here ? { here: got.here } : {}), ...(got.exception ? { exception: got.exception } : {}), ...(got.reused ? { reused: got.reused } : {}), ...(got.from ? { from: got.from } : {}) };
return { label: l.label, exit: null, testsRan: 'unknown', log: '-', carryNone: got.none ?? `record_failed: ${firstLine(rec.stderr)}`, ...(got.diagnosis ? { diagnosis: got.diagnosis } : {}) };
}
/** The bound on one record-ci, in accept, finish and preflight alike (GST-1606, GST-3360): the base policy's `ci_record_timeout_s`, 600 s by default, clamped to 3600 s. */
/** How long a record-ci may run once it prints CI_RECORD_PHASE: local, for the local runs of its per_file remainder or exception preflight, which the bound does not count (GST-3560). */
const LOCAL_RUNS_ALLOWANCE_S = 3600;
/** The bound on one record-ci's finding and verifying of the CI run, in accept, finish and preflight alike (GST-1606, GST-3360, GST-3560): the base policy's `ci_record_timeout_s`, 600 s by default, clamped to 3600 s. */
export function recordCiTimeout(policy: Record<string, any> | null, base: string): { seconds: number; line: string } {
const set = policy?.ci_record_timeout_s;
if (typeof set !== 'number' || set === DEFAULT_POLICY.ci_record_timeout_s) return { seconds: DEFAULT_POLICY.ci_record_timeout_s, line: `CI_RECORD_TIMEOUT: ${DEFAULT_POLICY.ci_record_timeout_s}s (default)` };
@@ -227,11 +246,12 @@ export async function runLanes(cwd: string, list: { label: string; command: stri
const mapped = opts.base ? mappedLanes(cwd, opts.base, list) : new Map<string, ShipLaneMapping>();
const bound = mapped.size ? opts.recordCiTimeoutS ?? recordCiTimeout(shipPolicy(cwd, opts.base!), opts.base!).seconds : 0;
const refused = list.map(l => !!opts.hold && mapped.has(l.label) && bin(cwd, 'gstack-ci-carry', ['find', '--base', opts.base!, '--command', l.command, '--allow-repo-commands']).status !== 0);
const carries = list.map((l, i) => (refused[i] ? carryLane(cwd, opts.base!, l, bound) : null));
const carries: (LaneResult | null)[] = [];
for (const [i, l] of list.entries()) carries.push(refused[i] ? await carryLane(cwd, opts.base!, l, bound) : null);
const done = (c: LaneResult | null) => !!(c?.carried || c?.remoteGate);
const held = () => list.map((l, i) => { const c = carries[i]; return c && done(c) ? c : { ...(c ?? { label: l.label, exit: null, testsRan: 'unknown', log: '-' }), held: true as const }; });
if (opts.hold && carries.some(c => c && !done(c))) return held();
for (const [i, l] of list.entries()) if (!carries[i] && mapped.has(l.label)) carries[i] = carryLane(cwd, opts.base!, l, bound);
for (const [i, l] of list.entries()) if (!carries[i] && mapped.has(l.label)) carries[i] = await carryLane(cwd, opts.base!, l, bound);
if (opts.hold && carries.some(c => c && !done(c))) return held();
let next = 0;
const worker = async () => {
+2 -2
View File
@@ -104,7 +104,7 @@ export interface ShipPolicy {
/** Globs of test code the built-in test names miss (GDScript checks), which /ship finish routes as test code (docs/ship-policy.md#test-code); read from the base only. */ test_code: string[];
/** `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;
/** Seconds accept gives each `gstack-evidence record-ci` (docs/ship-policy.md#ci-record-timeout), clamped to 3600; read from the base only. */ ci_record_timeout_s: number;
/** Seconds accept gives each `gstack-evidence record-ci` to find and verify the CI run (docs/ship-policy.md#ci-record-timeout), clamped to 3600; read from the base only. */ ci_record_timeout_s: number;
/** Whether ready and land check the PR body's Plan line (lib/plan-record.ts, docs/ship-policy.md#plan-record); read from the base only. */ plan_record: 'off' | 'warn' | 'require';
/** Human-docs globs beyond README.md, docs/ and changelog.d/ for the docs-only class (lib/docs-only.ts, docs/pregate.md#repo-docs-paths); read from the base only. */ docs_only: DocsOnlyPolicy | null;
}
@@ -241,7 +241,7 @@ export const POLICY_EXPLANATIONS: Record<PolicyKey, string> = {
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,
test_code: 'Root-anchored globs of test code the built-in test names miss, never under .gstack/ or .github/, for example ["tests/**/*.gd"] for GDScript checks. /ship finish routes a matching file changed after review as test code (one scoped reader of its test hunks) instead of behavior, beside the built-in globs; shared helpers and fixtures stay behavior. Read from the base branch only. Empty (default) declares none.',
ci_record_timeout_s: 'Seconds one `gstack-evidence record-ci` may run before it stops that lane (gstack-ship-release accept and finish, gstack-ship-preflight Step 5), an integer of at least 60 (default 600). A value over 3600 is clamped to 3600, and accept prints the bound it used (`CI_RECORD_TIMEOUT:`). Raise it when record-ci runs long, for example a per_file remainder of CI-skipped files. Read from the base branch only.',
ci_record_timeout_s: 'Seconds one `gstack-evidence record-ci` may spend finding and verifying the CI run before it stops that lane (gstack-ship-release accept and finish, gstack-ship-preflight Step 5), an integer of at least 60 (default 600). A value over 3600 is clamped to 3600, and accept prints the bound it used (`CI_RECORD_TIMEOUT:`). The local runs of a per_file remainder of CI-skipped files, or of an exception preflight, come after and do not count against it; they get up to an hour more. Read from the base branch only.',
plan_record: 'off (default) | warn | require. Whether `gstack-ship-queue ready` and `land` check the PR body\'s `Plan:` line (approved: <run id or row id> | exempt: <reason>) against the approval store (docs/ship-policy.md#plan-record). warn prints the PLAN: line and continues; require refuses a missing, unresolved or agent-approved plan. This key is read from the base branch only; with it off, GSTACK_PLAN_RECORD, then plan_record in <state root>/config.yaml (gstack-config set plan_record warn, for a repo that commits no .gstack/), then warn in a Capy session decide. On a public repo render --plan writes Plan: approved (record r-<id>) instead of the run id.',
docs_only: '{ allow, deny?, tests? } or null, read from the base revision only (docs/pregate.md#repo-docs-paths). allow (1 to 16) adds human-docs globs to the docs-only allowlist (README.md, docs/**.md, changelog.d/*.md): each ends in .md, starts with a literal directory or file name and passes through no hidden, code, test or agent directory ("wiki/board/**.md"). deny (up to 64 globs) removes paths, built-in ones included. tests (up to 16 test file paths) are the repository\'s checks for those directories: the docs lane runs them, and a non-docs file that names an allowed directory ("wiki/", \'wiki\') refuses the change unless it is one of them, names one, or one names it. The built-in deny list (agent instructions, templates, prompts, preferences, tool configuration, pinned results, preregistrations, generated outputs) always wins, a path a script or test names stays pinned, and a pull request that edits this file is never docs-only. An unknown key under docs_only is a warning, and the classifier then ignores allow. Needs min_gstack_version.',
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).',
+19 -17
View File
@@ -219,7 +219,7 @@ function harnessRepin(cwd: string, from: string, to: string, p: string): boolean
* 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' | 'mechanical' | 'accepted' | 'fix_checked' | 'sidecar', string[]>;
type Routed = Record<'behavior' | 'docs' | 'metadata' | 'tests' | 'base' | 'context' | 'bounded' | 'mechanical' | 'accepted' | 'fix_checked' | 'fix_checked_exact' | 'sidecar', string[]>;
type ReviewedBase = { commit: string; parent: boolean };
type RouteOpts = { docsRechecked: boolean; contextReviewed?: string; loop?: FixCheckException; audited: Record<string, string | null> | null; bookkeeping: readonly string[]; mechanical: readonly MechanicalConstant[]; testCode: readonly string[]; excluded: readonly string[]; baseRelease?: string[] };
@@ -293,7 +293,7 @@ function docsBridge(cwd: string, from: string, o: BridgeOpts): { reviewedAt: str
* findings name counts only through a clean link after it, and a finding no later clean link's range touched refuses the chain. A path counts as fix_checked when a clean link's range touched it and it is unchanged since that link,
* or its patch against the base is still the one the link read.
*/
function fixChecked(cwd: string, o: BridgeOpts & { now: string; parent?: string; currentBase?: string; candidates: string[] }, r: Report): { counted: boolean; paths: string[] } | null {
function fixChecked(cwd: string, o: BridgeOpts & { now: string; parent?: string; currentBase?: string; candidates: string[] }, r: Report): { counted: boolean; paths: string[]; exact: string[] } | null {
const reviewRows: Record<string, any>[] = bin(cwd, 'gstack-review-read', [], 60_000).stdout.split('\n---CONFIG---')[0].split('\n')
.flatMap(l => { try { const v = JSON.parse(l); return v?.skill === 'review' || v?.skill === 'review-fix-check' ? [v] : []; } catch { return []; } });
const rows = reviewRows.filter(v => v.skill === 'review-fix-check');
@@ -362,22 +362,22 @@ function fixChecked(cwd: string, o: BridgeOpts & { now: string; parent?: string;
if (notCounted) r.add(`FIX_CHECK: not counted (${notCounted})`);
const rulable = (l: FixLink) => (Array.isArray(l.row.findings) ? l.row.findings : []).filter((f: any) => !!f && !f.gate && RULABLE.has(f.action) && holdsOpen(f) && typeof f.fingerprint === 'string' && !ruledOn(l).has(f.fingerprint)).map((f: any) => f.fingerprint as string);
for (const l of notCounted ? chain : []) if (rulable(l).length) r.add(`FIX_CHECK_OPEN: ${rulable(l).join(',')} on the fix-check at ${l.commit.slice(0, 12)}: the owner rules each one a disclosed note with gstack-approvals rule --finding <fingerprint> --head ${l.commit.slice(0, 12)} --reason '<why>' --words '<owner\'s exact words>' --by '<owner>'; a review-loop exception accepts edits after a fix-check, never its findings (docs/troubleshooting.md#fix-check-open)`);
if (!chain.length || notCounted) return { counted: false, paths: [] };
if (!chain.length || notCounted) return { counted: false, paths: [], exact: [] };
if (bridged) r.add(bridged);
const read: ((p: string) => boolean)[] = [];
const read: { any: (p: string) => boolean; exact: (p: string) => boolean }[] = [];
for (const [k, l] of chain.entries()) {
if (!clean.has(l)) continue;
const later = new Set(chain.slice(k + 1).flatMap(d => handedOn.get(d) ?? []));
const range = ranges.get(l), after = touchedPaths(cwd, l.commit, o.now);
if (!range || !after) { r.stop(`git could not diff the fix-check range ${l.from.slice(0, 12)}..${l.commit.slice(0, 12)} against the reviewed and current trees: stage 2 is blocked`); return null; }
const sides = { reviewedBase: patchBase(cwd, o.baseRef, l.commit, o.parent), reviewed: l.commit, currentBase: o.currentBase ?? git(cwd, ['merge-base', o.baseRef, 'HEAD']).stdout.trim(), current: o.now };
read.push(p => !later.has(p) && range.has(p) && (!after.has(p) || (!!sides.reviewedBase && !!sides.currentBase && comparePath(cwd, sides, p) === 'same')));
read.push({ any: p => !later.has(p) && range.has(p) && (!after.has(p) || (!!sides.reviewedBase && !!sides.currentBase && comparePath(cwd, sides, p) === 'same')), exact: p => !later.has(p) && range.has(p) && !after.has(p) });
}
const paths = o.candidates.filter(p => read.some(f => f(p))).sort();
const paths = o.candidates.filter(p => read.some(f => f.any(p))).sort();
const list = paths.length ? short(paths) : 'none';
r.add(chain.length === 1 ? `FIX_CHECK: reviewed ${list} (fix-check at ${chain[0]!.commit.slice(0, 12)}, range from ${chain[0]!.from.slice(0, 12)}, grant ${granted[0]!.id})`
: `FIX_CHECK: reviewed ${list} (fix-check chain of ${chain.length} from ${chain[0]!.from.slice(0, 12)}: ${chain.map((l, k) => `at ${l.commit.slice(0, 12)} grant ${granted[k]!.id}${clean.has(l) ? '' : ' (found issues)'}`).join('; ')})`);
return { counted: true, paths };
return { counted: true, paths, exact: paths.filter(p => read.some(f => f.exact(p))) };
}
function route(cwd: string, base: string, reviewed: string, reviewedBase: ReviewedBase | undefined, release: string[], opts: RouteOpts, r: Report): Routed | null {
@@ -399,7 +399,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: [], mechanical: [], accepted: [], fix_checked: [], sidecar: [] };
const by: Routed = { behavior: [], docs: [], metadata: [], tests: [], base: [], context: [], bounded: [], mechanical: [], accepted: [], fix_checked: [], fix_checked_exact: [], sidecar: [] };
const isMetadata = (p: string) => parent && shipped.has(p) ? opts.baseRelease!.includes(p) || harnessRepin(cwd, sides!.currentBase, now, p) : release.includes(p) || harnessRepin(cwd, reviewed, now, p);
const onlyShipped = new Set(parent ? [...shipped].filter(p => !changedSet.has(p)) : []);
const baseSide = new Set<string>();
@@ -430,6 +430,7 @@ function route(cwd: string, base: string, reviewed: string, reviewedBase: Review
if (!fix) return null;
const counted = fix.counted;
by.fix_checked = fix.paths;
by.fix_checked_exact = fix.exact;
for (const k of ['behavior', 'tests', 'context', 'bounded'] as const) by[k] = by[k].filter(p => !by.fix_checked.includes(p));
const ancestor = (a: string, d: string) => git(cwd, ['merge-base', '--is-ancestor', a, d]).status === 0;
const loop = opts.loop;
@@ -488,12 +489,12 @@ function route(cwd: string, base: string, reviewed: string, reviewedBase: Review
}
/**
* Step 16 stage 3. Test code, paths only the base or a stamp moved, a slot restamp after the audit (the CHANGELOG's heading
* Step 16 stage 3. Test code, paths a counted fix-check read at their current bytes (stage 2's fix_checked, unchanged since that read, never by patch equivalence across a base merge; GST-3560), paths only the base or a stamp moved, a slot restamp after the audit (the CHANGELOG's heading
* move or re-heading after the restamp writer's own merge of the base's CHANGELOG into the audited one, the version file's
* version, each against the audited bytes; GST-906), and --docs-requested fixes the audit's own result asked for do not
* stale the audit (GST-391).
*/
function docsFresh(cwd: string, base: string, postFile: string, moved: readonly string[], requested: string[], resultFile: string | undefined, loopAccepted: readonly string[] | undefined, parent: string | undefined, testCode: readonly string[], r: Report): boolean {
function docsFresh(cwd: string, base: string, postFile: string, moved: readonly string[], requested: string[], resultFile: string | undefined, loopAccepted: readonly string[] | undefined, fixChecked: readonly string[], parent: string | undefined, testCode: readonly string[], r: Report): boolean {
const cmp = bin(cwd, 'gstack-docs-candidate', ['compare', postFile], 120_000);
let stale: string[] | null = null;
try { stale = JSON.parse(cmp.stdout).content_changed; } catch { stale = null; }
@@ -547,11 +548,12 @@ function docsFresh(cwd: string, base: string, postFile: string, moved: readonly
return kept !== null && merged !== null && normalizeChangelog(kept) === normalizeChangelog(audited.stdout) && normalizeChangelog(merged) === normalizeChangelog(now);
});
const carried = { tests: stale.filter(p => isTestCode(p, testCode)), base: stale.filter(p => !isTestCode(p, testCode) && (moved.includes(p) || restamped.includes(p) || (!!auditBase && !!nowBase && !branchAtAudit.has(p) && !branchNow.has(p))
|| (!!auditBase && !!nowBase && /^[0-9a-f]{40,64}$/.test(nowTree) && ![...record.staged, ...record.unstaged, ...record.untracked].includes(p) && comparePath(cwd, { reviewedBase: auditBase, reviewed: record.head, currentBase: nowBase, current: nowTree }, p) === 'same'))), requested: [] as string[], accepted: [] as string[] };
|| (!!auditBase && !!nowBase && /^[0-9a-f]{40,64}$/.test(nowTree) && ![...record.staged, ...record.unstaged, ...record.untracked].includes(p) && comparePath(cwd, { reviewedBase: auditBase, reviewed: record.head, currentBase: nowBase, current: nowTree }, p) === 'same'))), requested: [] as string[], accepted: [] as string[], fix_checked: [] as string[] };
carried.accepted = stale.filter(p => loopAccepted?.includes(p) && !carried.tests.includes(p) && !carried.base.includes(p));
carried.fix_checked = stale.filter(p => fixChecked.includes(p) && !carried.tests.includes(p) && !carried.base.includes(p) && !carried.accepted.includes(p));
let audit: any = null;
try { audit = resultFile ? JSON.parse(fs.readFileSync(resultFile, 'utf8')) : null; } catch { audit = null; }
for (const p of requested.filter(q => stale!.includes(q) && !carried.tests.includes(q) && !carried.base.includes(q) && !carried.accepted.includes(q))) {
for (const p of requested.filter(q => stale!.includes(q) && !carried.tests.includes(q) && !carried.base.includes(q) && !carried.accepted.includes(q) && !carried.fix_checked.includes(q))) {
const asked = [...(Array.isArray(audit?.blockers) ? audit.blockers : []), ...(Array.isArray(audit?.decisions) ? audit.decisions : [])].filter((s: unknown) => typeof s === 'string');
const token = new RegExp(`(^|[\\s\`'"(\\[])${p.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(?::\\d+(?::\\d+)?)?(?=$|[\\s\`'")\\]]|[,.:;](?:$|\\s))`);
const stat = git(cwd, ['diff', '--numstat', '--no-renames', record.head, '--', `:(literal)${p}`]).stdout.trim().split(/\s+/);
@@ -566,8 +568,8 @@ function docsFresh(cwd: string, base: string, postFile: string, moved: readonly
carried.requested.push(p);
}
if (carried.requested.length && bin(cwd, 'gstack-ship-receipt', ['docs-caps', '--base', base], 60_000).status !== 0) { r.stop('a --docs-requested fix breaks a doc cap (gstack-ship-receipt docs-caps): trim the file, then rerun finish'); return false; }
const left = stale.filter(p => !carried.tests.includes(p) && !carried.base.includes(p) && !carried.requested.includes(p) && !carried.accepted.includes(p));
const note = left.length || stale.length === 0 ? '' : ` (carried: tests=${carried.tests.length} base=${carried.base.length} requested=${carried.requested.length}${loopAccepted ? ` accepted=${carried.accepted.length}` : ''})`;
const left = stale.filter(p => !carried.tests.includes(p) && !carried.base.includes(p) && !carried.requested.includes(p) && !carried.accepted.includes(p) && !carried.fix_checked.includes(p));
const note = left.length || stale.length === 0 ? '' : ` (carried: tests=${carried.tests.length} base=${carried.base.length} requested=${carried.requested.length}${loopAccepted ? ` accepted=${carried.accepted.length}` : ''}${fixChecked.length ? ` fix_checked=${carried.fix_checked.length}` : ''})`;
const exception = record.exception ? ` (blocked; documentation exception accepted by ${record.exception.accepted_by} ${record.exception.date} via ${record.exception.via})` : '';
r.add(`DOCS: ${left.length ? `stale (${short(left)})` : `fresh against the Step 14.5 post-audit snapshot${note}${exception}`}`);
if (left.length) { r.stop('documentation inputs changed since the accepted audit: use stage 3 recovery (the remaining re-audit, a fix the audit\'s result asked for via --docs-requested <path> --docs-result <audit-id>-result.json, or a named risk); never refresh hashes'); return false; }
@@ -637,7 +639,7 @@ async function finishStages(argv: readonly string[], cwd: string): Promise<Repor
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, mechanical, testCode: globs('test_code'), excluded: [...globs('review_exclude_paths'), ...forbidden], baseRelease }, r);
if (!routed) 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, globs('test_code'), 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, routed.fix_checked_exact, reviewedBase?.parent ? reviewedBase.commit : undefined, globs('test_code'), 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;
@@ -647,7 +649,7 @@ async function finishStages(argv: readonly string[], cwd: string): Promise<Repor
let e = check(l);
if (!/EVIDENCE: FRESH/.test(e)) {
const m = mapped.get(l.label);
const res = m ? carryLane(cwd, base, l) : (await runLanes(cwd, [l], Infinity, { base }))[0]!;
const res = m ? await carryLane(cwd, base, l) : (await runLanes(cwd, [l], Infinity, { base }))[0]!;
if (m && !res.carried && !res.remoteGate) {
r.add(`EVIDENCE: DEFERRED label=${l.label} (${short([res.carryNone ?? 'not carried'], 1).slice(0, 160)}): CI at the pushed head carries it in accept`);
deferred.push(l.label);
@@ -720,7 +722,7 @@ export async function accept(argv: readonly string[], cwd: string): Promise<Repo
const exceptions: string[] = [];
for (const l of list) {
const m = mapped.get(l.label);
const res = m ? carryLane(cwd, base, l, recordCi.seconds) : (await runLanes(cwd, [l], Infinity, { base }))[0]!;
const res = m ? await carryLane(cwd, base, l, recordCi.seconds) : (await runLanes(cwd, [l], Infinity, { base }))[0]!;
for (const line of carryNoneLines(res)) r.add(line);
if (m && !res.carried && !res.remoteGate) return r.stop(`lane ${l.label} was not carried from the green run (${short([res.carryNone ?? ''], 1).slice(0, 120)}): fix the cause, or run it here with gstack-ship-preflight --tests-only`);
const ran = laneLine(res);
+9
View File
@@ -209,6 +209,15 @@ describe('harness-evals#504: a fix-check grant answering a stop after a gate-cla
expect(grantSpent([{ ...read('2026-11-21T00:00:00.000Z'), grant: 'a-2' }], g)).toBe(true);
});
// Value: protects=two recorded grants each buy one read: a counted fix-check a claim stamped with grant a-3 was a-3's read, so
// it leaves a-2 unspent however late it ran; fails_when=claim refuses a-2 with GRANT_SPENT after a-3's read; seam=grantSpent
test('a later read stamped with another grant leaves this grant unspent', () => {
const g = { approval: 'a-2', at: '2026-11-21T01:00:00.000Z' };
const read = { skill: 'review-fix-check', completed: true, converged: true, status: 'clean', review_binding: { state: 'verified', started_at: '2026-11-21T01:01:00.000Z' } };
expect(grantSpent([{ ...read, grant: 'a-3' }], g)).toBe(false);
expect(grantSpent([{ ...read, grant: 'a-3' }, read], g)).toBe(true);
});
// Value: protects=the same through the CLI: --round-grant and --stop after --last fix-check with a gate-class fix plan next=fix-check
// with the fix-check reader only; fails_when=the plan prints next=stop; seam=gstack-review-plan
test('gstack-review-plan plans the granted fix-check after a fix-check that edited a gate-class path', () => {
+36
View File
@@ -68,6 +68,13 @@ function fixCheck(c: Cap, o: { grant: string; run: string; fixList: string; row?
return prompt;
}
/** A fix-check read logged with no claim (the gstack-review-plan --grant path): no claim stamps it, so it names no grant. */
function unclaimedFixCheck(c: Cap, row: Record<string, unknown> = {}) {
c.f.write({ 'src/x.ts': 'export const x = 3;\n' }); c.f.commit('fix');
const start = ok(c.run('gstack-review-log', ['--start', 'review-fix-check'])).trim();
ok(c.run('gstack-review-log', [JSON.stringify({ skill: 'review-fix-check', timestamp: new Date().toISOString(), via: 'ship', review_scope: 'frozen', ...CLEAN, ...row }), '--finish', start]));
}
function write(c: Cap, run: string) {
const loop = path.join(c.f.root, 'loop.json');
ok(c.run('gstack-review-scope', ['summary', '--since', c.since, '--no-ledger', '--out', loop]));
@@ -219,6 +226,35 @@ describe('a grant spends only on a counted fix-check (gskills#24, gskills#25)',
expect(p.stderr).toContain(`FIX_CHECK_HUNKS: built from git diff ${c.S.slice(0, 12)} HEAD`);
expect(p.stdout).toContain('src/y.ts');
});
// Value: protects=a grant buys one round: a fix-check grant an unclaimed fix-check already spent (an owner's review_loop_grant
// or a round-grant planned through gstack-review-plan --grant, neither of which leaves a claim in the PR body) cannot be
// claimed for a second read; fails_when=claim prints GRANT_CLAIMED; seam=gstack-ship-receipt claim
test('claim refuses GRANT_SPENT for a grant an unclaimed counted fix-check already spent', () => {
for (const legacy of [true, false]) {
const c = atCap([open(ID, FP)]);
const id = legacy
? JSON.parse(ok(c.run('gstack-approvals', ['add', '--ask', `Owner grant: one scoped fix-check after round 2 (review_loop_grant ${c.S})`, '--words', 'do it', '--by', CAPTAIN, '--scope', 'this /ship invocation', '--owner-ref', 'GSTA-36:2026-11-22T12:00:00Z', '--json']))).added[0] as string
: grantId(ok(c.run('gstack-approvals', ['round-grant', '--pr', '7', '--head', c.S, '--kind', 'fix-check', '--reason', 'fix it', '--by', CAPTAIN, '--owner-ref', 'GSTA-36:2026-11-22T12:00:00Z', '--words', 'fix it'])));
unclaimedFixCheck(c);
expect(rows(c).filter(x => x.skill === 'review-fix-check').at(-1)?.grant).toBeUndefined();
const r = c.run('gstack-ship-receipt', ['claim', '--body', c.body, '--pr', '7', '--run', 'r2', '--grant', id]);
expect([legacy, r.status, r.stdout]).toEqual([legacy, 3, '']);
expect(r.stderr).toContain('GRANT_SPENT');
expect(fs.readFileSync(c.body, 'utf8')).not.toContain(id);
}
});
// Value: protects=the negative controls: an unspent grant still claims, a malformed row spends nothing, and the run that holds
// the claim may claim again after its own read; fails_when=claim refuses any of them; seam=gstack-ship-receipt claim
test('claim still takes an unspent grant, one only a malformed row read, and this run\'s own claim again', () => {
const c = atCap([open(ID, FP)]);
const id = grantId(ok(c.run('gstack-approvals', ['round-grant', '--pr', '7', '--head', c.S, '--kind', 'fix-check', '--reason', 'fix it', '--by', CAPTAIN, '--owner-ref', 'GSTA-36:2026-11-22T12:00:00Z', '--words', 'fix it'])));
unclaimedFixCheck(c, { converged: false });
ok(c.run('gstack-ship-receipt', ['claim', '--body', c.body, '--pr', '7', '--run', 'r2', '--grant', id]));
fixCheck(c, { grant: id, run: 'r2', fixList: 'fix ' + ID + '\n', claim: false });
expect(ok(c.run('gstack-ship-receipt', ['claim', '--body', c.body, '--pr', '7', '--run', 'r2', '--grant', id]))).toContain(`GRANT_CLAIMED: grant=${id}`);
});
});
describe('a post-review edit with no stop gets a grant (GST-3546, gbrain#10068)', () => {
+19
View File
@@ -394,3 +394,22 @@ describe('the docs bridge line prints only when the fix-check counts (GST-2294 a
expect([r.status, lineOf(r.stdout, 'FIX_CHECK_DOCS_BRIDGE'), lineOf(r.stdout, 'FIX_CHECK')], r.stdout).toEqual([3, '', 'FIX_CHECK: not counted (no approved review_loop_grant names a stop head inside its range_base..commit)']);
});
});
describe('a path a counted fix-check read does not stale the docs audit (GST-3560)', () => {
// Value: protects=HARN-64: the docs audit ran at the reviewed head, the fix after it changed a path the audit hashed, and a clean
// granted fix-check read that fix at the current head; fails_when=finish stops on DOCS: stale (src/x.ts), though stage 2 routes
// the path as fix_checked; seam=finish's docsFresh carry
test('a fix-checked path carries as fix_checked, and a change no fix-check read still refuses', () => {
const { f, t, reviewed, reviewedBase } = reviewedShape();
const post = path.join(f.root, 'post.json');
expect(run(f, 'gstack-docs-candidate', ['snapshot', '--out', post, '--audit-id', 'a1', '--mode', 'edit', '--base', 'main', '--docs', 'README.md']).status).toBe(0);
edit(f, { 'src/x.ts': 'export const x = 3;\n' }, 'fix the round-2 blocker');
link(f, t, CLEAN);
const args = ['finish', '--base', 'main', '--reviewed-tree', reviewed, '--docs-post', post, '--reviewed-base', reviewedBase, '--lane', LANE];
const r = f.run(RELEASE, args);
expect([r.status, lineOf(r.stdout, 'ROUTE'), lineOf(r.stdout, 'DOCS')], r.stdout).toEqual([0, expect.stringMatching(/ behavior=0 .* fix_checked=1$/), expect.stringMatching(/^DOCS: fresh .*carried: tests=0 base=0 requested=0 fix_checked=1\)/)]);
edit(f, { 'src/y.ts': 'export const y = 2;\n' }, 'an unread change');
const s = f.run(RELEASE, args);
expect([s.status, stopLine(s.stdout)]).toEqual([3, `${STOP}src/y.ts)`]);
});
});
+44
View File
@@ -6,7 +6,9 @@
*/
import { afterEach, describe, expect, setDefaultTimeout, test } from 'bun:test';
import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
import { bunIsolationArgs } from '../lib/bun-isolation';
import { fakeGhScript, type FakeWorld } from './helpers/fake-gh-runs';
import { findFilesBySuffix } from './helpers/scratch-repo';
import { lineOf, PREFLIGHT, RELEASE, shipFixture, type ShipFx } from './helpers/ship-bin-fixture';
@@ -140,3 +142,45 @@ describe('record-ci reuses its own CI row at the same tree (GST-1795)', () => {
expect([again.status, perFileRuns(f), lineOf(again.stderr, 'CI_RECORD_REUSED')], again.stderr).toEqual([0, 2, '']);
});
});
describe('the record-ci bound covers finding the CI run, not the local remainder (GST-3560)', () => {
const slow = (key: 'inventory' | 'per_file') => {
const cfg = JSON.parse(BASE['.gstack/pregate.json']);
cfg.ship_lanes_from[FREE][key] = 'sleep 8; ' + cfg.ship_lanes_from[FREE][key];
const f = shipFixture({ ...BASE, '.gstack/pregate.json': JSON.stringify(cfg, null, 2) + '\n' });
fixtures.push(f);
world(f);
return f;
};
const carry = (f: ShipFx, bound: number) => {
const code = `const { carryLane } = await import(${JSON.stringify(path.join(import.meta.dir, '..', 'lib', 'ship-bin-common.ts'))}); console.log(JSON.stringify(await carryLane(process.cwd(), 'main', { label: 'free', command: process.env.LANE_CMD }, ${bound})));`;
const r = f.run(process.execPath, [...bunIsolationArgs(), '-e', code], { LANE_CMD: FREE });
expect(r.status, r.stderr).toBe(0);
return JSON.parse(r.stdout.trim().split('\n').at(-1)!);
};
// Value: protects=HARN-64: record-ci's local per_file remainder ran 879.7 s against ci_record_timeout_s=900, so the bound meant
// for finding and verifying the CI run also had to fit local test runs; fails_when=carryLane kills record-ci while the
// remainder runs (carryNone record_failed) though the CI phase finished well inside the bound; seam=carryLane, CI_RECORD_PHASE
test('a remainder that runs past the bound still carries', () => {
const f = slow('per_file');
expect([carry(f, 6), perFileRuns(f)]).toEqual([expect.objectContaining({ exit: 0, carried: '7/1', here: expect.any(String) }), 1]);
});
// Value: protects=the bound still holds while the CI run is found and verified: a lookup past it is stopped then, not after it
// returns, and runs nothing here; fails_when=the bound is dropped or checked only after the lookup; seam=carryLane
test('a CI phase past the bound stops as ci_record_timeout and runs nothing here', () => {
const f = slow('inventory');
const t0 = Date.now();
const got = carry(f, 3);
expect([got.carryNone, perFileRuns(f)]).toEqual([expect.stringMatching(/^ci_record_timeout: finding and verifying the CI run took over the 3 s bound/), 0]);
expect(Date.now() - t0).toBeLessThan(8_000);
});
// Value: protects=a record-ci that cannot start returns record_failed for its lane, as the synchronous spawn did, so accept,
// finish and preflight report it; fails_when=the spawn error is unhandled and the tool crashes; seam=carryLane
test('a record-ci that cannot start returns record_failed instead of crashing', async () => {
const { carryLane } = await import('../lib/ship-bin-common');
const got = await carryLane(path.join(fs.realpathSync(os.tmpdir()), 'gstack-no-such-checkout-' + process.pid), 'main', { label: 'free', command: FREE }, 5);
expect([got.exit, got.carryNone]).toEqual([null, expect.stringMatching(/^record_failed: /)]);
});
});