Run each driven /ship phase as one command, count its calls, and stop it at 100 minutes (GST-2984) (#4451)

A driven /ship now runs each ship/DRIVER.md phase as one command, shows
how many calls the run made, and stops itself with a printed line at 100
minutes.

Why: measured /ship runs made 121 to 308 calls where the driver plans 9
to 12, and 10 of 12 ran past the 100-minute stop while those limits were
only prose.

Nothing to do: older ship records without `calls=` still validate and
print.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
Review-Finding: p1/outside-voice#1 reader=outside-voice
This commit is contained in:
Garry Tanandcapy-ai[bot] authored and GitHub committed 2026-11-17 16:44:06 +00:00
1 parent 9c6e0a0f85
commit 0ee5914628
19 files changed
+807 -49

No files matched your search

+60
View File
@@ -0,0 +1,60 @@
#!/usr/bin/env -S bun --no-env-file --config=/dev/null
/**
* gstack-ship-phase — one ship/DRIVER.md phase as one call (G2).
*
* gstack-ship-phase run --dir <run dir> --phase <n> [--record <rec>] [--wait-s <s>] -- '<command>' ['<command>' ...]
* Runs the phase's commands in order, each in the background (output in <run dir>/phases/<n>/<k>.log), and prints
* only result lines: RAN: <k>/<N> exit=<c> with each command's CODE: lines, then PHASE: <n> done. A command still
* running after --wait-s (default 200) keeps running and the run prints WAITING: and NEXT: rerun; rerun the same
* command to resume. A failed command prints STOP: (exit 3); fix it and rerun the same command: finished commands
* stay done (the journal keys each by the sha256 of its text). With --record, a stopped run or one past 100
* minutes prints STOP: and runs nothing (exit 3); past 100 minutes it also writes <ledger dir>/stop.json.
* gstack-ship-phase program
* Prints the checked-in Capy phase program (lib/capy-ship-phase.js): PROGRAM: v<n> sha256=<h> bytes=<n>, then its
* text as one JSON string. Load it the way capy/skill/gstack/SKILL.md loads the review pass program.
*
* Exit: 0 done or waiting · 3 stop · 2 usage. Logic: lib/ship-phase.ts, lib/ship-clock.ts.
*/
import { createHash } from 'node:crypto';
import * as fs from 'node:fs';
import * as path from 'node:path';
import { runPhase } from '../lib/ship-phase';
import { logShipCall } from '../lib/ship-call-log';
logShipCall('gstack-ship-phase');
const PROGRAM_VERSION = 1;
const [command, ...rest] = process.argv.slice(2);
const usage = (why: string) => { process.stderr.write(`gstack-ship-phase: ${why} (usage; see gstack-ship-phase --help)\n`); process.exit(2); };
if (!command || command === '--help' || command === '-h') {
const lines = (await Bun.file(import.meta.path).text()).split('\n');
(command ? console.log : console.error)(lines.slice(2, lines.indexOf(' */')).map(l => l.replace(/^ \* ?/, '')).join('\n'));
process.exit(command ? 0 : 2);
}
if (command === 'program') {
const text = fs.readFileSync(path.join(import.meta.dir, '..', 'lib', 'capy-ship-phase.js'), 'utf8');
const sha = createHash('sha256').update(text).digest('hex');
process.stdout.write(`PROGRAM: v${PROGRAM_VERSION} sha256=${sha} bytes=${Buffer.byteLength(text)}\n${JSON.stringify(text)}\n`);
process.exit(0);
}
if (command !== 'run') usage(`unknown command '${command}'`);
const sep = rest.indexOf('--');
const opts = sep < 0 ? rest : rest.slice(0, sep);
const commands = sep < 0 ? [] : rest.slice(sep + 1);
const flag = (name: string) => { const i = opts.indexOf(`--${name}`); return i >= 0 ? opts[i + 1] : undefined; };
const known = new Set(['--dir', '--phase', '--record', '--wait-s']);
for (let i = 0; i < opts.length; i += 2) if (!known.has(opts[i]!) || opts[i + 1] === undefined) usage(`run: unexpected '${opts[i]}'`);
const dir = flag('dir'), phase = flag('phase'), waitRaw = flag('wait-s');
if (!dir) usage('run needs --dir <run dir>');
if (!phase || !/^[A-Za-z0-9._-]+$/.test(phase)) usage('run needs --phase <n> (letters, digits, dot, underscore or dash)');
if (!commands.length || commands.some(c => !c.trim())) usage("run needs the phase's commands after --, one argument each");
if (waitRaw !== undefined && !/^\d+$/.test(waitRaw)) usage(`--wait-s '${waitRaw}' is not a whole number of seconds`);
try {
const out = await runPhase({ dir: dir!, phase: phase!, commands, record: flag('record'), waitS: waitRaw === undefined ? undefined : Number(waitRaw), cwd: process.cwd(), env: process.env });
if (out.stdout.length) process.stdout.write(out.stdout.join('\n') + '\n');
process.exit(out.exit);
} catch (e: any) {
process.stderr.write(`gstack-ship-phase: ${e?.message ?? e}\n`);
process.exit(e?.exit === 3 ? 3 : 2);
}
+13 -1
View File
@@ -3,7 +3,7 @@
* gstack-ship-receipt — the handoff record, identifiers first (plan C5).
*
* gstack-ship-receipt write [--pr <n>] [--head <sha>] [--base <ref>] [--version <X>] [--gated-tree <sha>]
* [--predecessor <sha>] [--gate <json|@file>] [--ci <json|@file>] [--spend-usd <n>]
* [--predecessor <sha>] [--gate <json|@file>] [--ci <json|@file>] [--spend-usd <n>] [--calls <n> | --budget-record <rec>]
* [--session-kind <k>] [--artifacts-consumed <n>/<m>] [--run <id>] [--thread <id>]
* [--receipt <tree-receipt.json>] [--policy <label>] [--preregistration <text>] [--history <text>]
* [--pregate <pregate.json>] [--issues <json|@file>] [--approval <line>]... [--approval-run <dir>]...
@@ -66,6 +66,7 @@ import { historyLine, placeRunEntry, prReviewHistory, reviewRoute, runStub } fro
import { grantAt, readReviewRoundGrants } from '../lib/review-round-grant';
import { readMechanicalLines } from '../lib/ship-mechanical';
import { isRegistryUnavailable, loadRegistryFromBase } from '../lib/regen';
import { runCalls } from '../lib/ship-clock';
const HELP = `gstack-ship-receipt — the \`\`\`gstack-ship-receipt\`\`\` block (docs/ship-policy.md#ship-receipt)
@@ -108,6 +109,7 @@ const HELP = `gstack-ship-receipt — the \`\`\`gstack-ship-receipt\`\`\` block
instead); any over (or absent) file exits 1 (DOCS_AUDIT_BLOCKED)
write flags: --pr --head --base --version --gated-tree --predecessor --gate <json|@file> --ci <json|@file> --spend-usd
--calls <n> | --budget-record <rec> (calls=: the run's calls from the call log since gstack-ship-budget start; lib/ship-clock.ts)
--session-kind --artifacts-consumed <n>/<m> --run --thread --receipt <tree-receipt.json> --policy --preregistration
--history --queue-mode --pregate <pregate.json> (C8: refused unless current, green and every requires-remote obligation
carries a receipt: PREGATE_STALE / PREGATE_LANE_FAILED / PREGATE_INCOMPLETE / PREGATE_REMOTE_UNCLEARED) --issues <json|@file>
@@ -232,6 +234,15 @@ function ciCarried(base: string): ShipReceipt['ci_carried'] {
try { const list = JSON.parse(r.stdout); return Array.isArray(list) && list.length ? list : undefined; } catch { return undefined; }
}
/** calls= (G2): --calls <n>, or the run's count from the call log through its budget record; absent when neither is given or the log holds no row. */
function callsArg(rest: string[]): number | undefined {
const raw = flag(rest, '--calls');
if (raw !== undefined) { if (!/^\d+$/.test(raw)) throw new Error(`--calls '${raw}' is not a whole number`); return Number(raw); }
const record = flag(rest, '--budget-record');
if (record === undefined) return undefined;
try { return runCalls(record, process.env) ?? undefined; } catch (e: any) { throw new Error(`--budget-record ${record}: ${e.message}`); }
}
function cmdWrite(rest: string[], json: boolean): number {
const repoRoot = git(['rev-parse', '--show-toplevel']) ?? process.cwd();
const checkedOut = git(['rev-parse', 'HEAD'], repoRoot);
@@ -350,6 +361,7 @@ function cmdWrite(rest: string[], json: boolean): number {
tree: tree?.tree, gate_reuse: tree ? `${tree.gate_reuse} (${tree.gate_reuse_reason})` : undefined,
gate: jsonArg(flag(rest, '--gate')), ci: jsonArg(flag(rest, '--ci')), ci_carried: carried,
spend_usd: flag(rest, '--spend-usd') !== undefined ? (Number.isFinite(Number(flag(rest, '--spend-usd'))) ? Number(flag(rest, '--spend-usd')) : flag(rest, '--spend-usd')) : undefined,
calls: callsArg(rest),
session_kind: sessionKind, artifacts_consumed: flag(rest, '--artifacts-consumed'), run: flag(rest, '--run'), thread: flag(rest, '--thread'),
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,
+1 -1
View File
@@ -46,7 +46,7 @@ Capy checklist for `/autoplan`: drive `gstack-autoplan`, never a hand adaptation
Token caps on /ship: pass a brief's cap as `--token-cap <n>`. /ship reads `cost.tokens` and `cost.credits` from `tools.thread.get({ thread_id: "<your own jam id>" })` (its own jam; a subagent reading root `"this"` starts `--subagent --reading-from this --meter-scope tree`) inside the same execute program as the `gstack-ship-budget` command that takes them as `--reading <n> --credits <c>`, never alone. `ship/DRIVER.md` starts `--mode observe`: each program ends with `note`, and only a note past the cap stops (`docs/ship-budget.md`).
/ship on Capy is about a dozen calls, each an execute program (`ship/DRIVER.md`). Each review pass and Step 11 is one call to the checked-in pass program (fill only `input`): `const t0 = await now(); const p = (await tools.capy.bash({ command: ". '<launch file>' && gstack-review-dispatch program", description: "Pass" })).output.split("\n"); return p[0] + "\n" + (await new (Object.getPrototypeOf(async () => {}).constructor)("tools", "sleep", "now", "input", JSON.parse(p[1]))(tools, sleep, now, { startedAt: t0, launch: "<launch file>", cwd: "<repo>", base: "<base>", out: "<run dir>/p<n>", pass: "<run>-p<n>", laneModel: "<your model id>", planFlags: [], logStart: ["review"], jam: "<jam id>", record: "<rec>", step: "9.2" }));` It plans, logs `logStart` (`reservation` mode from `RESERVATION_ID:`), sends each brief on `machine: "shared"`, then polls: one `tools.subagent.list` per ~20 s tick, returning 200 s after the program's first line, where a reader is settled only at status `done` or `failed` or with a `summary` (a just-created `idle` reader has not run); it starts readers under `rejected` with `tools.subagent.start` as slots free and stops on one stuck 20 minutes. It ends on `NEXT:` (`poll`: rerun) or `STOP:`. `models` maps roles to models (`outside-voice`: another family, pinned in `voice-models.json`); Step 11 swaps `logStart` for `stage: "voices"`; a full repeat pass, `diffBase: "<RANGE_BASE>"`. Steps 7, 8 and 14.5 (`step: "14.5"`) use `extras`, JSON `{name, prompt_file, first, model}` (prompts verbatim from their sections, Step 7 `first`); they cannot block, so omit `model`: the pass prints `AUDIT_MODEL:`. Waits: never let 5 minutes pass between calls. While readers run, never end the turn on `wait`; rerun the loader. Else re-issue `wait` with `duration_seconds: 200` and operation ids. At Step 22 report the `CALLS:` line of `gstack-ship-budget calls --record <rec>`. A small waiting child saves nothing.
/ship on Capy is about a dozen calls, each an execute program (`ship/DRIVER.md`). Each review pass and Step 11 is one call to the checked-in pass program (fill only `input`): `const t0 = await now(); const p = (await tools.capy.bash({ command: ". '<launch file>' && gstack-review-dispatch program", description: "Pass" })).output.split("\n"); return p[0] + "\n" + (await new (Object.getPrototypeOf(async () => {}).constructor)("tools", "sleep", "now", "input", JSON.parse(p[1]))(tools, sleep, now, { startedAt: t0, launch: "<launch file>", cwd: "<repo>", base: "<base>", out: "<run dir>/p<n>", pass: "<run>-p<n>", laneModel: "<your model id>", planFlags: [], logStart: ["review"], jam: "<jam id>", record: "<rec>", step: "9.2" }));` It plans, logs `logStart` (`reservation` mode from `RESERVATION_ID:`), sends each brief on `machine: "shared"`, then polls: one `tools.subagent.list` per ~20 s tick, returning 200 s after the program's first line, where a reader is settled only at status `done` or `failed` or with a `summary` (a just-created `idle` reader has not run); it starts readers under `rejected` with `tools.subagent.start` as slots free and stops on one stuck 20 minutes. It ends on `NEXT:` (`poll`: rerun) or `STOP:`. `models` maps roles to models (`outside-voice`: another family, pinned in `voice-models.json`); Step 11 swaps `logStart` for `stage: "voices"`; a full repeat pass, `diffBase: "<RANGE_BASE>"`. Steps 7, 8 and 14.5 (`step: "14.5"`) use `extras`, JSON `{name, prompt_file, first, model}` (prompts verbatim from their sections, Step 7 `first`); they cannot block, so omit `model`: the pass prints `AUDIT_MODEL:`. Every other phase is one call to `gstack-ship-phase program`, loaded the same way, with `input` `{ startedAt, launch, cwd, dir: "<run dir>", phase: <n>, commands: ["<bin> …"], record, jam, step: "<last step>" }` (Phase 2's `gstack-ship-budget start` takes `--reading "$GSTACK_SHIP_READING" --credits "$GSTACK_SHIP_CREDITS"`; `pass: { … }` runs that pass after the commands); on `NEXT: rerun`, call it again unchanged. Waits under about 80 minutes: never let 5 minutes pass between calls. While readers run, never end the turn on `wait`; rerun the loader. Else re-issue `wait` with `duration_seconds: 200` and operation ids. A wait expected past 80 minutes (full CI) ends the turn on one `wait` on its operations; never poll every 10-15 minutes. `STOP: past 100 minutes`: report its `stop.json` and end. At Step 22 report the `CALLS:` line of `gstack-ship-budget calls --record <rec>`. A small waiting child saves nothing.
## Plan, approve, ship
+1
View File
@@ -0,0 +1 @@
- **A driven /ship now runs each phase as one command, counts its calls, and stops itself at 100 minutes.** `gstack-ship-phase run` runs a ship/DRIVER.md phase's commands in order, prints only their result lines, returns after 200 s while slow work keeps running, and on a rerun skips what already finished; on Capy, `gstack-ship-phase program` serves a checked-in program that also runs the review pass or the closing budget note in the same call. `gstack-ship-budget note` records the calls since the previous note, and `gstack-ship-receipt write --budget-record <rec>` puts the run's total in the receipt, so `SHIP_RECEIPT:` shows `calls=` (older receipts without it still validate and carry). Past 100 minutes, the note or the phase runner prints `STOP: past 100 minutes` and writes the head, review passes and next act to `stop.json`; `gstack-ship-budget resume` restarts the clock. The driver also prices waits by length. It keeps a 200 s keep-alive under about 80 minutes, uses one wait for anything longer, and never polls every 10-15 minutes. Measured conductors made 121 to 308 calls against the driver's 9 to 12 and 10 of 12 ran past the 100-minute line while these limits were prose.
+47 -4
View File
@@ -31,9 +31,10 @@ delegated, so a run spends no call on the meter: each program the driver runs en
gstack-ship-budget note --run <id> --step <last step> [--label <what ran>] --reading <tokens> --credits <credits> \
[--dispatched-at <tokens before the readers> --dispatched-credits <credits before> --readers <n>]
which prints `NOTE: <step>[:<label>] used=<n> credits=<c> [readers=<n> readers_tokens=<n> readers_credits=<c>]`
and the `BUDGET:` line. The cap is one hard stop: a note (or a check) whose `used + unknown` is past
`--token-cap` prints the stop block and exits 3, and nothing else stops the run. No review-log marker
which prints `NOTE: <step>[:<label>] used=<n> credits=<c> [readers=<n> readers_tokens=<n> readers_credits=<c>] [calls=<n>]`
and the `BUDGET:` line. `calls=` is the calls since the previous note, counted from the call log
(below), so `BUDGET_TIMELINE:` shows where a run's calls went. The cap is the one stop on spend: a note (or a check) whose `used + unknown` is past
`--token-cap` prints the stop block and exits 3. The other stop is the clock ([The 100-minute stop](#the-100-minute-stop)). No review-log marker
is written, so `gstack-review-log --start` takes no `--reservation`, and `close` audits no
unreserved dispatch. `close` prints `BUDGET_TIMELINE:`, one entry per note. The admission mode
below is what `ship/SKILL.md` runs; it is unchanged.
@@ -67,7 +68,8 @@ that did not note, then a loader 200 s or more later) and never below 0
are not in it.
**Credits.** Every command that takes `--reading` also takes `--credits <cost.credits>` from the
same `thread.get`. Tokens count a cached read the same as a fresh one; credits are what the run
same `thread.get`; when Capy reports only `cost.dollars`, the checked-in phase and pass programs pass
`cost.dollars` x 1,000 instead. Tokens count a cached read the same as a fresh one; credits are what the run
costs, including the full-context re-bill after a gap over five minutes (about 40x a cached call,
handoffs/GSTA-167/cache-probe.md). The first credits reading is the baseline; the `BUDGET:`,
`BUDGET_FINAL:` and record-block lines print `credits=<used>` once one exists, and a reading below
@@ -75,6 +77,47 @@ the last is refused like a token reading ([BUDGET_READING_REJECTED](troubleshoot
A successor thread's readings open a new epoch for credits as well as tokens
([Successor handoff](#successor-handoff)).
### The 100-minute stop
ship/DRIVER.md stops a run past 100 minutes. Measured conductors ran past it in 10 of 12 runs while it was a
line of prose (handoffs/ship-conductor-cost-2026-11-16), so it is now code (`lib/ship-clock.ts`). In observe mode
the first `note`, or `gstack-ship-phase run --record`, past 100 minutes from the ledger's start prints
STOP: past 100 minutes (<m> min since <start>) head=<sha12> rounds=<n> calls=<n> next=<next act> state=<ledger dir>/stop.json
RECOVER: hand <stop.json> to the next session; it runs gstack-ship-budget resume --record <rec> (the clock restarts), then reruns the phase that stopped
GSTACK_RESULT: skill=ship status=incomplete run=<ledger dir>
and exits 3. `stop.json` holds the head, the review passes noted so far (`rounds`: Step 9 notes that dispatched
readers), the next act (the last line under the record's Next steps heading) and the run's calls, so the stop is a
clean handoff. Until `resume` the ledger stays stopped: every `note` and every `gstack-ship-phase run --record`
prints the stop again and runs nothing. `resume` prints `CLOCK: restarted at <iso>` and the next 100 minutes count
from there. Admission mode (`ship/SKILL.md`) has no clock.
### The phase runner
`gstack-ship-phase run --dir <run dir> --phase <n> [--record <rec>] [--wait-s 200] -- '<command>'...` runs one
driver phase's commands in order, each in the background with its output in `<run dir>/phases/<n>/<k>.log`, and
prints only result lines (`CODE: …` lines and `gstack-<bin>: …` refusals): `RAN: <k>/<N> exit=<c>` per command,
then `PHASE: <n> done`. A command still running after `--wait-s` keeps running; the run prints `WAITING:` and
`NEXT: rerun`, and the same command resumes the wait. A failed command prints `STOP:` (exit 3); after the fix, the
same command starts at it, because the journal (`phases/<n>/journal.json`) keeps each finished command by the
sha256 of its text. A command a restart killed runs again; a changed list stops a replaced command that still runs, then reruns from its first changed command.
On Capy one call runs a whole phase: `gstack-ship-phase program` prints the checked-in program
`lib/capy-ship-phase.js`, loaded like the review pass program. It reads this jam's counter into
`$GSTACK_SHIP_READING` and `$GSTACK_SHIP_CREDITS` for the commands, runs `gstack-ship-phase run`, then either the
review pass program (`input.pass`) or the closing `note` with a fresh reading, then the next phase's section parts.
**Waits priced by length.** A warm keep-alive at a conductor's average 231k-token context costs about $0.05 and a
cold re-cache about $1.16, so they break even at about 80 minutes of waiting (estimated). Keep the 200 s keep-alive
for expected waits under about 80 minutes; end the turn on one wait for longer ones (full CI, a long preflight);
never poll every 10 to 15 minutes, which pays a full re-cache each time.
**calls= in the receipt.** `gstack-ship-receipt write --budget-record <rec>` (or `--calls <n>`) puts the run's
calls, start to write, in the receipt; `SHIP_RECEIPT:` prints `calls=<n>`. The count is the call log's
(`total_est` over the run): calls that ran a gstack command plus the keep-alive estimate, so quick calls that run
no gstack command are not in it. Receipts written before it have no `calls` and still validate, print and carry.
## Quickstart
**Capy.** Read your own jam's counter inside the execute program that runs the command, never as a
+1 -1
View File
@@ -88,7 +88,7 @@ const mark = async (reader, state, extra) => {
const reading = async () => {
if (!input.record || !input.jam) return null;
const t = await tools.thread.get({ thread_id: input.jam });
return { tokens: t.cost.tokens, credits: t.cost.credits };
return { tokens: t.cost.tokens, credits: t.cost.credits ?? Math.round(Number(String(t.cost.dollars).replace(/[^0-9.]/g, '')) * 100000) / 100 };
};
const briefText = async (r) => {
let text = '';
+69
View File
@@ -0,0 +1,69 @@
// gstack /ship phase program for Capy (lib/capy-ship-phase.js, G2). The body of an async function (tools, sleep, now, input),
// served verbatim by `gstack-ship-phase program` and loaded the way capy/skill/gstack/SKILL.md loads the review pass program;
// never retyped. One call runs one ship/DRIVER.md phase end to end:
// 1. `gstack-ship-phase run` with input.commands, in order and resumable (lib/ship-phase.ts). With input.jam, this jam's
// cost.tokens and cost.credits (cost.dollars x 1,000 when the host reports only dollars) go to the commands as
// $GSTACK_SHIP_READING and $GSTACK_SHIP_CREDITS (gstack-ship-budget start).
// A command still running at 200 s returns NEXT: rerun: call the same program again with the same input.
// 2. With input.pass, the review pass program (gstack-review-dispatch program) on that pass's input: its dispatches, polls
// and closing note. Otherwise, with input.record and input.step, the closing `gstack-ship-budget note` with a fresh reading.
// 3. The next phase's section parts (`gstack-ship-parts next`) once Phase 2 started <dir>/parts.
// It returns result lines only, at most 32 KB; any STOP: line ends the phase (STOP: past 100 minutes included).
const T0 = input.startedAt ?? (await now());
const RETURN_BYTES = 32000;
const q = (s) => "'" + String(s).replace(/'/g, "'\\''") + "'";
const lines = [];
const sh = async (cmd, env) => {
const pre = (input.launch ? '. ' + q(input.launch) + ' && ' : '') + (input.cwd ? 'cd ' + q(input.cwd) + ' && ' : '') + (env || '');
const r = await tools.capy.bash({ command: pre + cmd, description: 'Ship phase ' + input.phase, timeout: 300 });
return { code: r.exit_code, out: (r.output || '').trimEnd() };
};
const finish = () => {
const text = lines.join('\n');
if (text.length <= RETURN_BYTES) return text;
const last = '\n(return capped at 32 KB; each command\'s log is under <dir>/phases)\n' + lines[lines.length - 1];
return lines.slice(0, -1).join('\n').slice(0, Math.max(0, RETURN_BYTES - last.length)) + last;
};
const push = (out) => { for (const l of out.split('\n')) if (l.trim()) lines.push(l); };
const stopped = () => lines.some((l) => l.startsWith('STOP:'));
const reading = async () => {
const t = await tools.thread.get({ thread_id: input.jam });
return { tokens: t.cost.tokens, credits: t.cost.credits ?? Math.round(Number(String(t.cost.dollars).replace(/[^0-9.]/g, '')) * 100000) / 100 };
};
if (!input.dir || input.phase === undefined || input.phase === null) return 'STOP: input.dir and input.phase are required; nothing ran';
const commands = input.commands || [];
if (!Array.isArray(commands) || !commands.every((c) => typeof c === 'string' && c.trim())) return 'STOP: input.commands must be a list of shell command strings; nothing ran';
if (commands.length) {
const r0 = input.jam ? await reading() : null;
const env = r0 ? 'GSTACK_SHIP_READING=' + r0.tokens + ' GSTACK_SHIP_CREDITS=' + r0.credits + ' ' : '';
const run = await sh('gstack-ship-phase run --dir ' + q(input.dir) + ' --phase ' + q(input.phase) + (input.record ? ' --record ' + q(input.record) : '')
+ ' --wait-s ' + Math.max(1, Math.round((T0 + (input.budgetMs || 200000) - (await now())) / 1000)) + ' -- ' + commands.map(q).join(' '), env);
push(run.out);
if (run.code !== 0 && !stopped()) lines.push('STOP: gstack-ship-phase run exited ' + run.code + '; nothing after it ran');
if (run.code !== 0 || (lines.length && lines[lines.length - 1].startsWith('NEXT: rerun'))) return finish();
}
if (input.pass) {
const p = await sh('gstack-review-dispatch program');
const nl = p.out.indexOf('\n');
if (p.code !== 0 || !p.out.startsWith('PROGRAM: ') || nl < 0) { lines.push('STOP: gstack-review-dispatch program exited ' + p.code + ': ' + p.out.slice(0, 300)); return finish(); }
lines.push(p.out.slice(0, nl));
const AsyncFunction = Object.getPrototypeOf(async () => {}).constructor;
const passInput = Object.assign({ startedAt: T0, launch: input.launch, cwd: input.cwd, record: input.record, jam: input.jam }, input.pass);
push(String(await new AsyncFunction('tools', 'sleep', 'now', 'input', JSON.parse(p.out.slice(nl + 1).split('\n')[0]))(tools, sleep, now, passInput)));
return finish();
}
if (input.record && input.step) {
if (!input.jam) { lines.push('STOP: the closing note needs input.jam (this jam\'s id) for its reading; the phase\'s commands ran'); return finish(); }
const r1 = await reading();
const n = await sh('gstack-ship-budget note --record ' + q(input.record) + ' --step ' + q(input.step) + (input.label ? ' --label ' + q(input.label) : '')
+ ' --reading ' + r1.tokens + ' --credits ' + r1.credits);
push(n.out);
if (n.code !== 0) { if (!stopped()) lines.push('STOP: gstack-ship-budget note exited ' + n.code + ' (its lines above say why)'); return finish(); }
}
const s = await sh('test -f ' + q(String(input.dir).replace(/\/+$/, '') + '/parts/state.json') + ' && echo started || true');
if (s.out.startsWith('started') && /^\d+$/.test(String(input.phase))) {
const room = RETURN_BYTES - lines.join('\n').length - 200;
const p = await sh('gstack-ship-parts next --run ' + q(input.dir) + ' --phase ' + (Number(input.phase) + 1) + ' --room ' + Math.max(0, room));
push(p.out);
}
return finish();
+3 -1
View File
@@ -102,6 +102,8 @@ export interface PregateFile {
export interface ShipReceipt {
schema_version: 1; head: string; base: string; pr?: number; version?: string; gated_tree?: string;
gate?: Record<string, unknown>; ci?: Record<string, unknown>; spend_usd?: number | string; predecessor?: string;
/** The run's calls from the call log (lib/ship-clock.ts callsSince: gstack-command calls plus keep-alives), so a 200-call run shows at the receipt; absent on older receipts. */
calls?: number;
/** GSTA-258: the lanes CI carried at this head's tree, one entry per run (gstack-evidence carried). */
ci_carried?: Array<{ lane: string; run: number; attempt: number; tree: string; exception?: BoundLaneException }>;
session_kind?: string; artifacts_consumed?: string; run?: string;
@@ -263,7 +265,7 @@ export const ARTIFACT_SCHEMAS = {
type: 'object', required: ['schema_version', 'head', 'base'],
properties: {
schema_version: { const: 1 }, pr: { type: 'integer' }, head: str, version: str, base: str, gated_tree: str,
gate: { type: 'object' }, ci: { type: 'object' }, spend_usd: { type: ['number', 'string'] }, predecessor: str,
gate: { type: 'object' }, ci: { type: 'object' }, spend_usd: { type: ['number', 'string'] }, calls: { type: 'integer', minimum: 0 }, predecessor: str,
ci_carried: { type: 'array', items: { type: 'object', required: ['lane', 'run', 'attempt', 'tree'], properties: { lane: str, run: { type: 'integer', minimum: 1 }, attempt: { type: 'integer', minimum: 1 }, tree: str,
exception: { type: 'object', required: ['head', 'files', 'by', 'reason', 'at', 'approval', 'preflight'], properties: { head: str, files: strList, by: str, reason: str, at: str, approval: str,
preflight: { type: 'object', required: ['label', 'tests_ran'], properties: { label: str, tests_ran: { type: 'integer', minimum: 1 } } } } } } } },
+13 -5
View File
@@ -21,6 +21,7 @@ import {
} from './ship-budget';
import { callLogFile, countLoggedCalls, loggedCallsLine, readCallLog } from './ship-call-log';
import { callsLine, countCalls } from './ship-calls';
import { callsSince, timeStop } from './ship-clock';
import { claudeConfigDir, loadMeterState, newMeterState, nonceSessions, readClaudeUsage, saveMeterState, sessionJournals } from './claude-usage';
export type Opts = Record<string, string | true>;
@@ -380,14 +381,15 @@ export function cmdClose(argv: string[], ctx: Ctx): Outcome {
});
}
const noteText = (n: Note) => `${n.step}${n.label ? `:${n.label}` : ''} used=${n.used}${n.credits === undefined ? '' : ` credits=${n.credits}`}`
const noteText = (n: Note) => `${n.step}${n.label ? `:${n.label}` : ''} used=${n.used}${n.credits === undefined ? '' : ` credits=${n.credits}`}${n.calls === undefined ? '' : ` calls=${n.calls}`}`
+ (n.readers ? ` readers=${n.readers.n} readers_tokens=${n.readers.tokens}${n.readers.credits === undefined ? '' : ` readers_credits=${n.readers.credits}`}` : '');
/**
* note: record one program's readings (tokens and credits) and, when --dispatched-at
* brackets them, the readers it dispatched; stop only once used + unknown pass the cap.
* It reserves, admits and delegates nothing: ship/DRIVER.md's observe runs end every
* program with it instead of a check at each boundary.
* program with it instead of a check at each boundary. It records the calls since the previous
* note (lib/ship-clock.ts), and in observe mode past 100 minutes it prints STOP: past 100 minutes.
*/
export function cmdNote(argv: string[], ctx: Ctx): Outcome {
const o = parseArgs(argv, ['run', 'record', 'step', 'label', 'reading', 'credits', 'dispatched-at', 'dispatched-credits', 'readers']);
@@ -406,9 +408,14 @@ export function cmdNote(argv: string[], ctx: Ctx): Outcome {
const credits = creditsUsed(l);
const readers = dispatched && l.meter.last !== null ? { n: dispatched.readers ?? 1, tokens: l.meter.last - dispatched.at,
...(before !== undefined && l.credits ? { credits: Math.round((l.credits.last - before) * 100) / 100 } : {}) } : undefined;
const n: Note = { step, ...(label ? { label } : {}), at: new Date().toISOString(), used: tally(l).used, ...(credits === null ? {} : { credits }), ...(readers ? { readers } : {}) };
const at = new Date().toISOString();
const prev = l.notes?.at(-1)?.at;
const calls = callsSince(ctx.env, prev ?? l.created_at, at, prev === undefined);
const n: Note = { step, ...(label ? { label } : {}), at, used: tally(l).used, ...(credits === null ? {} : { credits }), ...(readers ? { readers } : {}), ...(calls === null ? {} : { calls }) };
(l.notes ??= []).push(n);
return observed(l, step, label ?? step, null, `NOTE: ${noteText(n)}`);
const out = observed(l, step, label ?? step, null, `NOTE: ${noteText(n)}`);
const stop = out.exit === 0 ? timeStop(l, ctx.cwd, step, ctx.env) : null;
return stop ? { stdout: [out.stdout[0]!, ...stop], exit: 3 } : out;
});
}
@@ -480,8 +487,9 @@ export function cmdResume(argv: string[], ctx: Ctx): Outcome {
}
const was = l.stopped;
delete l.stopped;
if (was?.reason === 'past_100_minutes') l.clock_from = new Date().toISOString();
pointMarker(l.marker, l);
return [`BUDGET_RUN: id=${l.run} ledger=${l.file}`, `RESUMED: from=${was ? `Step ${was.step} (${was.reason})` : 'running'}`, budgetLine(l, { call: null, next: was?.next ?? '-', projected: 0, verdict: 'continue' })];
return [`BUDGET_RUN: id=${l.run} ledger=${l.file}`, `RESUMED: from=${was ? `Step ${was.step} (${was.reason})` : 'running'}`, ...(was?.reason === 'past_100_minutes' ? [`CLOCK: restarted at ${l.clock_from} (the 100-minute limit counts from here)`] : []), budgetLine(l, { call: null, next: was?.next ?? '-', projected: 0, verdict: 'continue' })];
});
return { stdout: [...lines, ...out], exit: 0 };
}
+3 -1
View File
@@ -70,7 +70,7 @@ export interface Reservation {
starts?: Array<{ token: string; at: string }>;
}
/** One observation: the run's totals at a program's end, and the readers it dispatched when it measured them. */
export interface Note { step: string; label?: string; at: string; used: number; credits?: number; readers?: { n: number; tokens: number; credits?: number } }
export interface Note { step: string; label?: string; at: string; used: number; credits?: number; readers?: { n: number; tokens: number; credits?: number }; calls?: number }
export interface Sample { id: string; kind: 'step' | 'dispatch'; epoch: number; prior: number; projected: number; actual: number }
export interface Handoff {
n: number; sha: string; file: string; from: string; to: string; sub_cap: number; reservation: string; reading_at: number | null;
@@ -102,6 +102,8 @@ export interface Ledger {
/** tree: the reading is the root thread's counter (a subagent cannot read its own jam id), so every cost line carries TREE_METER. */
meter_scope?: 'tree';
stopped?: { at: string; reason: string; step: string; next: string }; closed_at?: string;
/** Where the 100-minute clock starts (lib/ship-clock.ts): created_at, or the resume after a time stop. */
clock_from?: string;
}
/** A refusal: exit 2 for usage and validation (stderr), exit 3 for a stop. */
+7
View File
@@ -25,6 +25,12 @@ export interface LoggedCalls {
}
const NESTED = 'GSTACK_SHIP_CALL_NESTED';
let pending: { bin: string; sub: string; started: number } | null = null;
/** This process's own row as it will be written at exit (null when it writes none), for a count taken before it exits (lib/ship-clock.ts). */
export function pendingRow(): CallRow | null {
return pending && { v: 1, bin: pending.bin, sub: pending.sub, start: new Date(pending.started).toISOString(), ms: Date.now() - pending.started, exit: 0 };
}
const ROTATE_BYTES = 8 * 1024 * 1024;
const JOIN_MS = 5_000;
const POLL_S = 200;
@@ -41,6 +47,7 @@ export function logShipCall(bin: string, argv: string[] = process.argv.slice(2))
const started = Date.now();
const flag = (name: string) => { const i = argv.indexOf(`--${name}`); return i >= 0 ? argv[i + 1] : undefined; };
const num = (name: string) => { const v = Number(flag(name)); return flag(name) !== undefined && Number.isFinite(v) ? v : undefined; };
pending = { bin, sub: argv[0] && !argv[0].startsWith('-') ? argv[0] : '', started };
process.on('exit', code => {
try {
const row: CallRow = { v: 1, bin, sub: argv[0] && !argv[0].startsWith('-') ? argv[0] : '', start: new Date(started).toISOString(), ms: Date.now() - started, exit: code };
+86
View File
@@ -0,0 +1,86 @@
/**
* ship-clock — a driven /ship's 100-minute stop and its call count, in code instead of prose (ship/DRIVER.md).
* Measured conductors made 121-308 calls against the driver's 9 to 12, and 10 of 12 ran past its 100-minute stop
* (handoffs/ship-conductor-cost-2026-11-16), so the limits now print. An observe-mode run measures its time from
* the ledger's start, or from the resume that followed a time stop; the first `gstack-ship-budget note` or
* `gstack-ship-phase run` past 100 minutes stops the run and writes its state (head, review passes, next act) to
* <ledger dir>/stop.json, so the next session starts from that file and the record, not from memory.
* Calls come from the call log (lib/ship-call-log.ts): the calls that ran a gstack command plus its keep-alive
* estimate; quick calls that run no gstack command are not in it.
*/
import { spawnSync } from 'node:child_process';
import * as fs from 'node:fs';
import * as path from 'node:path';
import { ledgerFileFor, readLedger, type Ledger } from './ship-budget';
import { callLogFile, countLoggedCalls, pendingRow, readCallLog } from './ship-call-log';
export const TIME_LIMIT_MIN = 100;
export const STOP_FILE = 'stop.json';
export const clockFrom = (l: Pick<Ledger, 'created_at' | 'clock_from'>) => l.clock_from ?? l.created_at;
export const elapsedMin = (l: Pick<Ledger, 'created_at' | 'clock_from'>, now = Date.now()) => (now - Date.parse(clockFrom(l))) / 60_000;
/**
* Calls whose rows start after `since` (and at or before `until`): the log's calls plus its keep-alive estimate.
* Counting rows by start keeps two back-to-back windows from sharing a row. At the run's start (`fromRunStart`) a row
* still running at `since` counts too: the call that ran `gstack-ship-budget start` began before the ledger existed.
* This process's own row, written only at its exit, counts as if written. Null when the window holds none.
*/
export function callsSince(env: NodeJS.ProcessEnv, since: string, until?: string, fromRunStart = false): number | null {
const from = Date.parse(since), to = until ? Date.parse(until) : Infinity;
const self = pendingRow();
const rows = [...readCallLog(callLogFile(env)), ...(self ? [self] : [])].filter(r => { const s = Date.parse(r.start); return s <= to && (s > from || (fromRunStart && s + Math.max(0, r.ms) >= from)); });
if (!rows.length) return null;
const c = countLoggedCalls(rows);
return c.calls + c.keepaliveEst;
}
/** A run's calls from its budget record, start to now (gstack-ship-receipt write --budget-record); null when the log holds none. */
export function runCalls(record: string, env: NodeJS.ProcessEnv): number | null {
return callsSince(env, readLedger(ledgerFileFor({ record }, env)).created_at, undefined, true);
}
const HEADING = /^\s*(?:[-*]\s*)?(?:#+\s*)?(?:\*\*)?(Release|Decisions|Reviews|Checks|Documentation|Next steps)(?:\*\*)?:?(?:\*\*)?(?:\s|$)/;
/** The record's next act: the last line under its Next steps heading (one of the six lib/ship-handoff.ts names), else null. */
export function nextAct(record: string | undefined): string | null {
if (!record) return null;
let text: string;
try { text = fs.readFileSync(record, 'utf8'); } catch { return null; }
const lines = text.split('\n');
const at = lines.findIndex(l => HEADING.exec(l)?.[1] === 'Next steps');
if (at < 0) return null;
const end = lines.findIndex((l, i) => i > at && (HEADING.test(l) || l.startsWith('```')));
const body = lines.slice(at + 1, end < 0 ? lines.length : end).map(l => l.replace(/^\s*[-*]\s*/, '').trim())
.filter(l => l && !l.startsWith('<!--'));
return body.at(-1) ?? null;
}
const oneLine = (s: string) => s.replace(/[\x00-\x1f\x7f]+/g, ' ').slice(0, 300);
/**
* The time stop: null while an observe-mode run is within 100 minutes (or already stopped or closed); past them it
* marks the ledger stopped, writes stop.json and returns the STOP block. The caller persists the ledger (mutateLedger).
*/
export function timeStop(l: Ledger, cwd: string, step: string, env: NodeJS.ProcessEnv, now = Date.now(), fallbackNext = `resume, then continue after Step ${step}`): string[] | null {
if (l.mode !== 'observe' || l.stopped || l.closed_at) return null;
const min = elapsedMin(l, now);
if (!(min > TIME_LIMIT_MIN)) return null;
const at = new Date(now).toISOString();
const g = spawnSync('git', ['rev-parse', 'HEAD'], { cwd, encoding: 'utf8', timeout: 15_000 });
const head = g.status === 0 ? g.stdout.trim() : 'unknown';
const rounds = (l.notes ?? []).filter(n => n.step === '9' && n.readers).length;
const next = nextAct(l.record) ?? fallbackNext;
const calls = callsSince(env, l.created_at, at, true);
const file = path.join(l.dir, STOP_FILE);
const state = { schema_version: 1, kind: 'gstack-ship-stop', reason: 'past_100_minutes', run: l.run, record: l.record ?? null, at,
clock_from: clockFrom(l), elapsed_min: Math.floor(min), step, head, rounds, next, calls };
fs.mkdirSync(l.dir, { recursive: true, mode: 0o700 });
fs.writeFileSync(file, JSON.stringify(state, null, 2) + '\n', { mode: 0o600 });
l.stopped = { at, reason: 'past_100_minutes', step, next };
return [
`STOP: past 100 minutes (${Math.floor(min)} min since ${clockFrom(l)}) head=${head.slice(0, 12)} rounds=${rounds} calls=${calls ?? 'unknown'} next=${oneLine(next)} state=${file}`,
`RECOVER: hand ${file} to the next session; it runs gstack-ship-budget resume --record ${l.record ?? '<record>'} (the clock restarts), then reruns the phase that stopped`,
`GSTACK_RESULT: skill=ship status=incomplete run=${l.dir}`,
];
}
+123
View File
@@ -0,0 +1,123 @@
/**
* ship-phase — one ship/DRIVER.md phase as one command (G2, handoffs/ship-conductor-cost-2026-11-16): measured
* conductors made 121-308 calls where the driver plans 9 to 12, so a phase's bins now run from one command.
* `run` executes the phase's commands in order, each in the background with its output in <dir>/phases/<phase>/,
* and prints only their result lines. A command still running when --wait-s ends (200 s) keeps running and the run
* prints `NEXT: rerun`: the same command resumes the wait. The journal keeps each finished command by the sha256 of
* its text, so a rerun after a failure or a restart starts at the first command that has not passed, and a command
* a restart killed runs again. With --record, a stopped run, or one past 100 minutes (lib/ship-clock.ts), refuses to
* start the phase and prints the STOP block.
*/
import { spawn } from 'node:child_process';
import { createHash } from 'node:crypto';
import * as fs from 'node:fs';
import * as path from 'node:path';
import { ledgerFileFor, mutateLedger, parseRecordBlock } from './ship-budget';
import { bashCommandInvocation } from './script-invocation';
import { timeStop } from './ship-clock';
export interface PhaseEntry { sha: string; cmd: string; state: 'running' | 'done' | 'failed'; pid?: number; started: string; ended?: string; exit?: number; log: string; lines?: string[] }
export interface Journal { schema_version: 1; phase: string; entries: PhaseEntry[] }
export interface PhaseOut { stdout: string[]; exit: number }
export const WAIT_S_DEFAULT = 200;
const MAX_LINES = 60;
const RESULT_RE = /^(?:[A-Z][A-Z0-9_]*(?:\([^)]*\))?|gstack-[a-z0-9-]+(?: [a-z0-9-]+)?): /;
const sha256 = (s: string) => createHash('sha256').update(s).digest('hex');
/** The lines of a command's output that a parent acts on: `CODE: …` result lines and `gstack-<bin>: …` refusals. */
export function resultLines(text: string): string[] {
const hits = text.split('\n').map(l => l.trimEnd()).filter(l => RESULT_RE.test(l)).map(l => (l.length > 2000 ? l.slice(0, 2000) + ' …' : l));
return hits.length > MAX_LINES ? [...hits.slice(0, MAX_LINES - 1), `(${hits.length - MAX_LINES + 1} more result lines in the log)`, hits[hits.length - 1]!] : hits;
}
const alive = (pid: number | undefined) => { if (!pid) return false; try { process.kill(pid, 0); return true; } catch { return false; } };
function readJournal(file: string, phase: string): Journal {
try { const j = JSON.parse(fs.readFileSync(file, 'utf8')); if (j?.schema_version === 1 && Array.isArray(j.entries)) return j; } catch { /* a new or unreadable journal starts over */ }
return { schema_version: 1, phase, entries: [] };
}
function writeJournal(file: string, j: Journal): void {
fs.writeFileSync(`${file}.tmp`, JSON.stringify(j, null, 2) + '\n', { mode: 0o600 });
fs.renameSync(`${file}.tmp`, file);
}
/** Start one command detached: its output goes to the log and its exit status to <log>.exit when it ends, even after this process returns. */
function start(cmd: string, log: string, cwd: string, env: NodeJS.ProcessEnv): number | undefined {
try { fs.rmSync(`${log}.exit`, { force: true }); } catch { /* absent */ }
const inv = bashCommandInvocation('( eval "$GSTACK_SHIP_PHASE_CMD" ) >"$GSTACK_SHIP_PHASE_LOG" 2>&1 </dev/null; echo $? >"$GSTACK_SHIP_PHASE_LOG.exit.tmp"; mv "$GSTACK_SHIP_PHASE_LOG.exit.tmp" "$GSTACK_SHIP_PHASE_LOG.exit"');
if (!inv.ok) { fs.writeFileSync(log, `gstack-ship-phase: ${inv.error}\n`); fs.writeFileSync(`${log}.exit`, '127\n'); return undefined; }
const child = spawn(inv.cmd, inv.argv, { cwd, env: { ...env, GSTACK_SHIP_PHASE_CMD: cmd, GSTACK_SHIP_PHASE_LOG: log }, detached: true, stdio: 'ignore' });
child.unref();
return child.pid;
}
/** The run's stop check before a phase starts: a stopped run, or one past 100 minutes; null to go on (no record, or no ledger yet). */
function preflight(record: string | undefined, phase: string, cwd: string, env: NodeJS.ProcessEnv): string[] | null {
if (!record || !parseRecordBlock(record)?.ledger) return null;
return mutateLedger(ledgerFileFor({ record }, env), env, l => {
if (l.stopped) return [`STOP: run ${l.run} stopped (${l.stopped.reason}) at Step ${l.stopped.step}; nothing ran; resume first: gstack-ship-budget resume --record ${l.record}`, `GSTACK_RESULT: skill=ship status=incomplete run=${l.dir}`];
return timeStop(l, cwd, `Phase ${phase}`, env, Date.now(), `resume, then rerun Phase ${phase}`);
});
}
export interface RunOpts { dir: string; phase: string; commands: string[]; record?: string; waitS?: number; cwd: string; env: NodeJS.ProcessEnv; pollMs?: number }
/** run: the phase's commands in order, resumable from the journal; see the header. */
export async function runPhase(o: RunOpts): Promise<PhaseOut> {
const t0 = Date.now();
const deadline = t0 + (o.waitS ?? WAIT_S_DEFAULT) * 1000;
const stopped = preflight(o.record, o.phase, o.cwd, o.env);
if (stopped) return { stdout: stopped, exit: 3 };
const dir = path.join(path.resolve(o.dir), 'phases', o.phase);
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
const file = path.join(dir, 'journal.json');
const j = readJournal(file, o.phase);
const out: string[] = [];
const n = o.commands.length;
const firstChanged = j.entries.findIndex((e, i) => i >= n || e.sha !== sha256(o.commands[i]!));
if (firstChanged >= 0) {
const live = j.entries.slice(firstChanged).filter(e => e.state === 'running' && alive(e.pid));
for (const e of live) {
out.push(`REPLACED: ${j.entries.indexOf(e) + 1}/${n} pid=${e.pid} ran a command this list no longer names; stopping it (log=${e.log})`);
try { process.kill(-e.pid!, 'SIGTERM'); } catch { /* already gone */ }
}
for (let t = 0; t < 50 && live.some(e => alive(e.pid)); t++) await Bun.sleep(100);
const stuck = live.filter(e => alive(e.pid));
if (stuck.length) return { stdout: [...out, `STOP: phase ${o.phase}: replaced command pid ${stuck.map(e => e.pid).join(',')} is still running and shares its log and exit file with the new list; stop it (kill -- -<pid>), then rerun the same command`], exit: 3 };
j.entries.length = firstChanged;
}
for (let i = 0; i < n; i++) {
const cmd = o.commands[i]!;
const k = `${i + 1}/${n}`;
let e = j.entries[i];
if (e?.state === 'done') { out.push(`RAN: ${k} exit=0 (done earlier)`, ...(e.lines ?? [])); continue; }
if (!e || e.state === 'failed' || (e.state === 'running' && !alive(e.pid) && !fs.existsSync(`${e.log}.exit`))) {
const log = path.join(dir, `${i + 1}.log`);
e = j.entries[i] = { sha: sha256(cmd), cmd, state: 'running', started: new Date().toISOString(), log };
e.pid = start(cmd, log, o.cwd, o.env);
writeJournal(file, j);
}
while (!fs.existsSync(`${e.log}.exit`)) {
if (Date.now() >= deadline) {
const ran = Math.round((Date.now() - Date.parse(e.started)) / 1000);
out.push(`WAITING: ${k} pid=${e.pid ?? 'unknown'} running=${ran}s log=${e.log}`, `NEXT: rerun (the same gstack-ship-phase command resumes the wait; commands before ${i + 1} stay done)`);
return { stdout: out, exit: 0 };
}
if (!alive(e.pid) && !fs.existsSync(`${e.log}.exit`)) { await Bun.sleep(200); if (!fs.existsSync(`${e.log}.exit`)) break; }
await Bun.sleep(o.pollMs ?? 500);
}
const raw = fs.existsSync(`${e.log}.exit`) ? fs.readFileSync(`${e.log}.exit`, 'utf8').trim() : '';
const code = /^\d+$/.test(raw) ? Number(raw) : -1;
const text = fs.existsSync(e.log) ? fs.readFileSync(e.log, 'utf8') : '';
e.exit = code; e.ended = new Date().toISOString(); e.lines = resultLines(text); e.state = code === 0 ? 'done' : 'failed';
writeJournal(file, j);
out.push(`RAN: ${k} exit=${code < 0 ? 'lost' : code}${code === 0 ? '' : ` log=${e.log}`}`, ...e.lines);
if (code === 0) continue;
if (!e.lines.length) out.push(...text.trimEnd().split('\n').slice(-5).map(l => ` | ${l.slice(0, 500)}`));
out.push(`STOP: phase ${o.phase} command ${k} exited ${code < 0 ? 'without a status (killed?)' : code}; fix the cause, then rerun the same command (commands before ${i + 1} stay done)`);
return { stdout: out, exit: 3 };
}
out.push(`PHASE: ${o.phase} done commands=${n} elapsed_s=${Math.round((Date.now() - t0) / 1000)} journal=${file}`);
return { stdout: out, exit: 0 };
}
+2 -1
View File
@@ -21,7 +21,7 @@ import { stampOnlyLine, type BranchSide } from './stamp-only';
export const RECEIPT_FENCE = 'gstack-ship-receipt';
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',
'schema_version', 'pr', 'head', 'version', 'base', 'gated_tree', 'predecessor', 'tree', 'gate_reuse', 'gate', 'ci', 'ci_carried', 'spend_usd', 'calls',
'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', 'review_round_grants', 'ruled_notes', 'gate_dispositions', 'mechanical', 'review_targeted', 'design', 'review_exclude', 'carry', 'base_red', 'flaky_exception', 'no_stop',
@@ -200,6 +200,7 @@ export function receiptSummaryLine(r: ShipReceipt): string {
if (r.predecessor) parts.push(`predecessor=${r.predecessor.slice(0, 12)}`);
if (r.session_kind) parts.push(`session_kind=${r.session_kind}`);
if (r.artifacts_consumed) parts.push(`artifacts_consumed=${r.artifacts_consumed}`);
if (typeof r.calls === 'number') parts.push(`calls=${r.calls}`);
if (r.review_depth && typeof r.review_depth.depth === 'string') parts.push(`depth=${r.review_depth.depth}`);
if (r.approval) parts.push(`approval=${approvalSummary(r.approval)}`);
const loop = parseReviewLoop(r.review_loop);
+17 -17
View File
@@ -7,16 +7,16 @@ Read this, not `ship/SKILL.md`, when a parent agent runs /ship
the `GSTACK_LAUNCH` assignments your installer printed (`. <its GSTACK_LAUNCH_FILE>`), never
`export $(...)`, `env`, `printenv` or a bare `set` in a tool fence.
**Rules.** Each phase below is one call: one program (Capy: execute; else a script)
that runs the bins, reads, dispatches and waits, returning only result lines and reader
outputs verbatim. The model keeps only lead judgment, fixes, CHANGELOG, PR prose,
**Rules.** Each phase below is one call: `gstack-ship-phase run --dir <run dir> --phase <n> --record <rec> -- <cmds>`
runs its bins, reads, dispatches and waits, returning only result lines and reader
outputs verbatim. The model keeps only judgment, fixes, CHANGELOG, PR prose,
gates, the report. `STOP:` (exit 3) means nothing after it ran; `NEXT:` names
the next act. Read a section only when a phase or the list below sends you, never
up front. A STOP or decision this file does not cover: read `ship/SKILL.md` at that step, finish there,
come back. Unattended, take a question's recommended option (log it); gate
dispositions and approvals stay pending and end the run, except `gstack-no-stop`. Keep a record (`--record`): write its six headings at Phase 1, fill each per phase: **Checks**
(Phases 2-4: lanes, pregate, evals, `Coverage:`, the plan checks, `Exploratory QA:`, `Scope Check:`), **Decisions** (any
phase: each answered or auto-taken question, verbatim), **Reviews** (Phases 3-5: the plan line,
phase: questions and answers, verbatim), **Reviews** (Phases 3-5: the plan line,
start tokens, `Pre-Landing Review:`, `Gate edits:`, the reviewed tree), **Release** (Phases 5-7:
version, CHANGELOG, commits), **Documentation** (Step 14.5) and **Next steps** (every phase: the next act).
@@ -27,18 +27,18 @@ file, unchanged; its findings reach `merged.jsonl` only via `collect`; `judge` r
14.5 once; findings go to the PR body.
**Calls.** One pass with no fixes is 9 calls: Phases 1-8 and the report; at most 12 with a STOP's
section read or fix-check, plus a keep-alive per 200 s waited.
section read or fix-check, plus a keep-alive per 200 s waited under ~80 min (longer: end the turn on one wait; no 10-15 min polls).
**Budget: observe.** `gstack-ship-budget start --mode observe` records, never admits: each program ends
with `gstack-ship-budget note --step <last step> --reading R --credits C --record <rec>`, R and C read in that program
**Budget: observe.** `gstack-ship-budget start --mode observe` only records: each program ends
with `gstack-ship-budget note --step <last step> --reading R --credits C --record <rec>`, R and C read in it
(Capy: `cost.tokens`, `cost.credits`). No check per step, no reservation, no meter-only
call, no handoff; under `--token-cap` a note past the cap prints `verdict=stop`, the one stop check.
A dispatching program takes `BEFORE` (R and C) as readers start and passes
`--dispatched-at <R> --dispatched-credits <C> --readers <n>` with the reading after the last settles.
call, no handoff; under `--token-cap` a note past the cap prints `verdict=stop`, the one stop check on spend.
A dispatching program passes `--dispatched-at <R> --dispatched-credits <C> --readers <n>` (`BEFORE`).
**Waits.** No call waits past 200 s: a program returns what still runs 200 s after its first line; the next
call resumes the poll. Lanes, pregate, `finish` run in background; after a restart, rerun the same command. Never end the turn while
readers run (each wakes it). A small waiting child saves nothing. Past 100 minutes, stop. Returns:
readers run. A small waiting child saves nothing. Past 100 minutes the run stops:
`STOP: past 100 minutes`, state in `stop.json`. Returns:
≤32 KB per program; split longer reads at headings, each byte once, before first use: phase programs
end with `gstack-ship-parts next --run <run dir> --phase <n+1> --room <32000 - its output>`; on
`NEXT: parts` run it alone.
@@ -63,8 +63,8 @@ Install check, this file.
`gstack-ship-preflight --base <base> --run <run dir name> --lane <label>=<test command>...`. `CARRY: carried` ends the run on its `GSTACK_RESULT:`
line. `ship_lanes_from`: push early (`sections/tests.md#ci-carry`). A lane passes on `tests_ran: N` with exit 0; `0` is ZERO-RUN (failed); `unknown`
is `count unavailable`. In-branch failures stop; after a repair rerun `--tests-only`.
`requires-remote` needs `gstack-pregate clear` before Step 18. When prompts, templates, judges or eval
harness changed, start the eval selector and pre-merge command (detached past 30 min); else
`requires-remote` needs `gstack-pregate clear` before Step 18. Changed prompts, templates, judges or eval
harness: start the eval selector and pre-merge command (detached past 30 min); else
record `evals: none affected`. Step 6.5 runs only if `gstack-greptile-early detect` finds
Greptile. Then `gstack-ship-preflight --audit --base <base> --out <run dir>` writes the diff once
(`CONTEXT:`) and the TODOS.md items on touched paths (`TODOS:`); prints the coverage map,
@@ -92,7 +92,7 @@ pass with `fixCheck: {fix_list, hunks, tests, callers}`; `done` or `voices`: tha
Judge the voices; missing outside coverage is `unavailable`, never clean; queued fixes rerun Phases
3-4. Then `gstack-review-dispatch verify` (`VERIFY: clean`) and `gstack-review-read`: the final Step 9 and Step 11 native rows (or `CURRENT` freshness
after a planned skip) agree on `wtree`, `start_wtree`, `end_wtree`; save that tree and base `<b>`. Then
after a planned skip) agree on their trees; save that tree and base `<b>`. Then
`gstack-ship-release version --base <base> [--bump micro|patch] --why '<line>'`; MINOR, MAJOR, `BUMP_ANSWER_REQUIRED`:
approvals; `VERSION: skipped|kept`: no write.
@@ -106,7 +106,7 @@ One re-audit at most.
## 7. Release: Steps 15, 16, 17
Commit in bisectable chunks; `gstack-ship-release finish --base <base> --reviewed-tree <t> --reviewed-base <b>
Commit bisectably; `gstack-ship-release finish --base <base> --reviewed-tree <t> --reviewed-base <b>
--docs-post <post> --lane ... [--build <cmd>] --trailer '<t>' [--plan <line>]`: `PLAN:`, `ROUTE:`, `DOCS:`, `EVIDENCE:` (FRESH;
STALE or MISSING reruns once), `PREGATE:`; print them, the last `Gate edits:` and each `tests_ran`. Then
`gstack-ship-release push --branch <branch> [--gate-open <n>]`: `REDACT_PREPUSH:`, `SEALED:`, `GUARDS:`, `PUSH:`
@@ -116,9 +116,9 @@ repo gates run beside CI. Unattended, push defers the pre-push offer; else its S
## 8. Publish: Steps 18, 19, 19-C, 20, 21, 22
- Step 18: the open-PR lookup; a plain `v<NEW_VERSION> ` title (`gstack-plain-title check`). `UNATTENDED_SHIP:` with no open PR at HEAD takes Step 18-H.
- Step 19 body: plain opening sentences, then sections `sections/pr-body.md` lists, led under `CAPY_PR: on` (Step 19-C) by What changed, Why and Blast radius; Agent notes last (receipt, `gstack-approvals render --plan`, `REVIEW_LOOP:`). `gstack-prose-lint <top> --sections 'Why,Summary,Blast radius' --gate`; `gstack-issue-links`; `gstack-review-scope summary --since "$REVIEW_SINCE" --run <dir> && gstack-ship-receipt write --pr <n> --base <base> --gate @<f> --pregate <f> --issues @<f> --review-loop @<f> --docs @<f> [--review-exclude <d>] [--review-targeted @<f>] --body <body>`; `gstack-post pr-body` and `pr-title` (new PR: host PR tool; draft while a gate finding is `open`). `SHIP_RECEIPT:` opens your report.
- Step 19 body: plain opening sentences, then sections `sections/pr-body.md` lists, led under `CAPY_PR: on` (Step 19-C) by What changed, Why and Blast radius; Agent notes last (receipt, `gstack-approvals render --plan`, `REVIEW_LOOP:`). `gstack-prose-lint <top> --sections 'Why,Summary,Blast radius' --gate`; `gstack-issue-links`; `gstack-review-scope summary --since "$REVIEW_SINCE" --run <dir> && gstack-ship-receipt write --pr <n> --base <base> --gate @<f> --pregate <f> --issues @<f> --review-loop @<f> --docs @<f> --budget-record <rec> [--review-exclude <d>] [--review-targeted @<f>] --body <body>`; `gstack-post pr-body` and `pr-title` (new PR: host PR tool; draft while a gate finding is `open`). `SHIP_RECEIPT:` opens your report.
- Step 20: a metrics row via `gstack-review-log`.
- Step 22: `gstack-ship-budget close --reading R --credits C` (report `BUDGET_FINAL:`, `BUDGET_TIMELINE:` (tokens, credits), any `METER:` line), then `gstack-ship-receipt result --pr <n>`: `GSTACK_RESULT: skill=ship status=complete head=<sha> run=<dir>`. Under a merge queue, `gstack-ship-queue ready --pr <n> [--screen|--no-screen]` at the pushed head; paste its output.
- Step 22: `gstack-ship-budget close --reading R --credits C` (report `BUDGET_FINAL:`, `BUDGET_TIMELINE:`, any `METER:` line), then `gstack-ship-receipt result --pr <n>`: `GSTACK_RESULT: skill=ship status=complete head=<sha> run=<dir>`. Under a merge queue, `gstack-ship-queue ready --pr <n> [--screen|--no-screen]` at the pushed head; paste its output.
## Where each STOP sends you (paths under `<root>/ship/`)
+17 -17
View File
@@ -5,16 +5,16 @@ Read this, not `ship/SKILL.md`, when a parent agent runs /ship
the `GSTACK_LAUNCH` assignments your installer printed (`. <its GSTACK_LAUNCH_FILE>`), never
`export $(...)`, `env`, `printenv` or a bare `set` in a tool fence.
**Rules.** Each phase below is one call: one program (Capy: execute; else a script)
that runs the bins, reads, dispatches and waits, returning only result lines and reader
outputs verbatim. The model keeps only lead judgment, fixes, CHANGELOG, PR prose,
**Rules.** Each phase below is one call: `gstack-ship-phase run --dir <run dir> --phase <n> --record <rec> -- <cmds>`
runs its bins, reads, dispatches and waits, returning only result lines and reader
outputs verbatim. The model keeps only judgment, fixes, CHANGELOG, PR prose,
gates, the report. `STOP:` (exit 3) means nothing after it ran; `NEXT:` names
the next act. Read a section only when a phase or the list below sends you, never
up front. A STOP or decision this file does not cover: read `ship/SKILL.md` at that step, finish there,
come back. Unattended, take a question's recommended option (log it); gate
dispositions and approvals stay pending and end the run, except `gstack-no-stop`. Keep a record (`--record`): write its six headings at Phase 1, fill each per phase: **Checks**
(Phases 2-4: lanes, pregate, evals, `Coverage:`, the plan checks, `Exploratory QA:`, `Scope Check:`), **Decisions** (any
phase: each answered or auto-taken question, verbatim), **Reviews** (Phases 3-5: the plan line,
phase: questions and answers, verbatim), **Reviews** (Phases 3-5: the plan line,
start tokens, `Pre-Landing Review:`, `Gate edits:`, the reviewed tree), **Release** (Phases 5-7:
version, CHANGELOG, commits), **Documentation** (Step 14.5) and **Next steps** (every phase: the next act).
@@ -25,18 +25,18 @@ file, unchanged; its findings reach `merged.jsonl` only via `collect`; `judge` r
14.5 once; findings go to the PR body.
**Calls.** One pass with no fixes is 9 calls: Phases 1-8 and the report; at most 12 with a STOP's
section read or fix-check, plus a keep-alive per 200 s waited.
section read or fix-check, plus a keep-alive per 200 s waited under ~80 min (longer: end the turn on one wait; no 10-15 min polls).
**Budget: observe.** `gstack-ship-budget start --mode observe` records, never admits: each program ends
with `gstack-ship-budget note --step <last step> --reading R --credits C --record <rec>`, R and C read in that program
**Budget: observe.** `gstack-ship-budget start --mode observe` only records: each program ends
with `gstack-ship-budget note --step <last step> --reading R --credits C --record <rec>`, R and C read in it
(Capy: `cost.tokens`, `cost.credits`). No check per step, no reservation, no meter-only
call, no handoff; under `--token-cap` a note past the cap prints `verdict=stop`, the one stop check.
A dispatching program takes `BEFORE` (R and C) as readers start and passes
`--dispatched-at <R> --dispatched-credits <C> --readers <n>` with the reading after the last settles.
call, no handoff; under `--token-cap` a note past the cap prints `verdict=stop`, the one stop check on spend.
A dispatching program passes `--dispatched-at <R> --dispatched-credits <C> --readers <n>` (`BEFORE`).
**Waits.** No call waits past 200 s: a program returns what still runs 200 s after its first line; the next
call resumes the poll. Lanes, pregate, `finish` run in background; after a restart, rerun the same command. Never end the turn while
readers run (each wakes it). A small waiting child saves nothing. Past 100 minutes, stop. Returns:
readers run. A small waiting child saves nothing. Past 100 minutes the run stops:
`STOP: past 100 minutes`, state in `stop.json`. Returns:
≤32 KB per program; split longer reads at headings, each byte once, before first use: phase programs
end with `gstack-ship-parts next --run <run dir> --phase <n+1> --room <32000 - its output>`; on
`NEXT: parts` run it alone.
@@ -61,8 +61,8 @@ Install check, this file.
`gstack-ship-preflight --base <base> --run <run dir name> --lane <label>=<test command>...`. `CARRY: carried` ends the run on its `GSTACK_RESULT:`
line. `ship_lanes_from`: push early (`sections/tests.md#ci-carry`). A lane passes on `tests_ran: N` with exit 0; `0` is ZERO-RUN (failed); `unknown`
is `count unavailable`. In-branch failures stop; after a repair rerun `--tests-only`.
`requires-remote` needs `gstack-pregate clear` before Step 18. When prompts, templates, judges or eval
harness changed, start the eval selector and pre-merge command (detached past 30 min); else
`requires-remote` needs `gstack-pregate clear` before Step 18. Changed prompts, templates, judges or eval
harness: start the eval selector and pre-merge command (detached past 30 min); else
record `evals: none affected`. Step 6.5 runs only if `gstack-greptile-early detect` finds
Greptile. Then `gstack-ship-preflight --audit --base <base> --out <run dir>` writes the diff once
(`CONTEXT:`) and the TODOS.md items on touched paths (`TODOS:`); prints the coverage map,
@@ -90,7 +90,7 @@ pass with `fixCheck: {fix_list, hunks, tests, callers}`; `done` or `voices`: tha
Judge the voices; missing outside coverage is `unavailable`, never clean; queued fixes rerun Phases
3-4. Then `gstack-review-dispatch verify` (`VERIFY: clean`) and `gstack-review-read`: the final Step 9 and Step 11 native rows (or `CURRENT` freshness
after a planned skip) agree on `wtree`, `start_wtree`, `end_wtree`; save that tree and base `<b>`. Then
after a planned skip) agree on their trees; save that tree and base `<b>`. Then
`gstack-ship-release version --base <base> [--bump micro|patch] --why '<line>'`; MINOR, MAJOR, `BUMP_ANSWER_REQUIRED`:
approvals; `VERSION: skipped|kept`: no write.
@@ -104,7 +104,7 @@ One re-audit at most.
## 7. Release: Steps 15, 16, 17
Commit in bisectable chunks; `gstack-ship-release finish --base <base> --reviewed-tree <t> --reviewed-base <b>
Commit bisectably; `gstack-ship-release finish --base <base> --reviewed-tree <t> --reviewed-base <b>
--docs-post <post> --lane ... [--build <cmd>] --trailer '<t>' [--plan <line>]`: `PLAN:`, `ROUTE:`, `DOCS:`, `EVIDENCE:` (FRESH;
STALE or MISSING reruns once), `PREGATE:`; print them, the last `Gate edits:` and each `tests_ran`. Then
`gstack-ship-release push --branch <branch> [--gate-open <n>]`: `REDACT_PREPUSH:`, `SEALED:`, `GUARDS:`, `PUSH:`
@@ -114,9 +114,9 @@ repo gates run beside CI. Unattended, push defers the pre-push offer; else its S
## 8. Publish: Steps 18, 19, 19-C, 20, 21, 22
- Step 18: the open-PR lookup; a plain `v<NEW_VERSION> ` title (`gstack-plain-title check`). `UNATTENDED_SHIP:` with no open PR at HEAD takes Step 18-H.
- Step 19 body: plain opening sentences, then sections `sections/pr-body.md` lists, led under `CAPY_PR: on` (Step 19-C) by What changed, Why and Blast radius; Agent notes last (receipt, `gstack-approvals render --plan`, `REVIEW_LOOP:`). `gstack-prose-lint <top> --sections 'Why,Summary,Blast radius' --gate`; `gstack-issue-links`; `gstack-review-scope summary --since "$REVIEW_SINCE" --run <dir> && gstack-ship-receipt write --pr <n> --base <base> --gate @<f> --pregate <f> --issues @<f> --review-loop @<f> --docs @<f> [--review-exclude <d>] [--review-targeted @<f>] --body <body>`; `gstack-post pr-body` and `pr-title` (new PR: host PR tool; draft while a gate finding is `open`). `SHIP_RECEIPT:` opens your report.
- Step 19 body: plain opening sentences, then sections `sections/pr-body.md` lists, led under `CAPY_PR: on` (Step 19-C) by What changed, Why and Blast radius; Agent notes last (receipt, `gstack-approvals render --plan`, `REVIEW_LOOP:`). `gstack-prose-lint <top> --sections 'Why,Summary,Blast radius' --gate`; `gstack-issue-links`; `gstack-review-scope summary --since "$REVIEW_SINCE" --run <dir> && gstack-ship-receipt write --pr <n> --base <base> --gate @<f> --pregate <f> --issues @<f> --review-loop @<f> --docs @<f> --budget-record <rec> [--review-exclude <d>] [--review-targeted @<f>] --body <body>`; `gstack-post pr-body` and `pr-title` (new PR: host PR tool; draft while a gate finding is `open`). `SHIP_RECEIPT:` opens your report.
- Step 20: a metrics row via `gstack-review-log`.
- Step 22: `gstack-ship-budget close --reading R --credits C` (report `BUDGET_FINAL:`, `BUDGET_TIMELINE:` (tokens, credits), any `METER:` line), then `gstack-ship-receipt result --pr <n>`: `GSTACK_RESULT: skill=ship status=complete head=<sha> run=<dir>`. Under a merge queue, `gstack-ship-queue ready --pr <n> [--screen|--no-screen]` at the pushed head; paste its output.
- Step 22: `gstack-ship-budget close --reading R --credits C` (report `BUDGET_FINAL:`, `BUDGET_TIMELINE:`, any `METER:` line), then `gstack-ship-receipt result --pr <n>`: `GSTACK_RESULT: skill=ship status=complete head=<sha> run=<dir>`. Under a merge queue, `gstack-ship-queue ready --pr <n> [--screen|--no-screen]` at the pushed head; paste its output.
## Where each STOP sends you (paths under `<root>/ship/`)
+1
View File
@@ -330,6 +330,7 @@ describe('parity with the measured prototype', () => {
'lib/eval-plan-checks.ts': 'lib/eval-plan.ts and bin/gstack-eval-plan import it (the result checks), so it reaches every consumer of the eval planner',
'lib/ship-receipt-docs.ts': 'bin/gstack-ship-receipt imports it (the docs audit record and doc caps), so it reaches every consumer of the receipt binary',
'lib/ship-receipt-prose.ts': 'bin/gstack-ship-receipt imports it (read --check-prose), so it reaches every consumer of the receipt binary',
'lib/ship-clock.ts': 'G2: bin/gstack-ship-receipt (write --budget-record), lib/ship-budget-cli.ts (note, resume) and lib/ship-phase.ts import it, so it reaches every consumer of the receipt and budget binaries',
'lib/default-base.ts': 'GST-511/GST-774: lib/ship-policy.ts (resolveBaseBranch), lib/gate-diff/git.ts, lib/pregate/context.ts, lib/ship-receipt-depth.ts and the review-plan, gate-diff, pregate, docs-candidate and diff-scope bins import or run it, so it reaches every consumer of those readers',
};
+13
View File
@@ -841,6 +841,19 @@ describe('Capy pass program (fake host, real bins)', () => {
expect(res).not.toContain('NEXT: judge');
}, 240_000);
// Value: protects=a host whose thread.get reports cost.dollars and no cost.credits still notes the pass with a credits reading (1,000 credits a dollar); fails_when=the pass passes --credits undefined and its note refuses it;
// why_new=Capy's thread.get returned only cost.dollars on 2026-11-17; seam=tools.thread.get stub; no_claim=Capy's own pricing
test('a host that reports only cost.dollars still notes the pass in credits', async () => {
const { dir, env } = repo();
const rec = path.join(dir, '.state/rec.md');
fs.mkdirSync(path.dirname(rec), { recursive: true });
expect(spawnSync('bash', ['-c', 'gstack-ship-budget start --record "$1" --mode observe --reading 1000 --credits 1', '_', rec], { cwd: dir, env, encoding: 'utf8', timeout: 60_000 }).status).toBe(0);
const h = host(dir, env);
h.tools.thread.get = async () => ({ cost: { tokens: 2000, dollars: '$0.05' } }) as never;
const res = await runPass(h, { base: 'main', out: path.join(dir, '.state/run/p1'), pass: 'x15d', planFlags: ['--depth-floor', 'full'], record: rec, jam: 'jam_test', step: '9' });
expect(res).toMatch(/NOTE: \S+ used=\d+ credits=49 /);
}, 240_000);
test('Step 14.5 runs as an audit-only pass: its docs reader alone, verbatim, with no reviewer plan', async () => {
const { dir, env } = repo();
const out = path.join(dir, '.state/run/docs');
+330
View File
@@ -0,0 +1,330 @@
/**
* G2 (handoffs/fold-subagents-2026-11-17, handoffs/ship-conductor-cost-2026-11-16): ship/DRIVER.md's limits in tools.
* Measured conductors made 121-308 calls against the driver's 9 to 12 and 10 of 12 ran past its 100-minute stop, so
* a phase now runs as one gstack-ship-phase command (resumable from its journal), every note records its calls, the
* receipt carries calls=, and the first note or phase past 100 minutes prints STOP: past 100 minutes with the run's
* state on disk. All checks here are free: real bins on fixture repositories, and the Capy phase program on a fake host
* whose shell is real.
*/
import { afterAll, describe, expect, test } from 'bun:test';
import { spawnSync } from 'node:child_process';
import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
import { extractReceipt, orderReceipt, placeReceipt, receiptSummaryLine, validateReceipt } from '../lib/ship-receipt';
import { resultLines } from '../lib/ship-phase';
import { cleanup, makeFixtureRepo, runBin, type FixtureRepo } from './helpers/restamp-fixture';
const ROOT = path.resolve(import.meta.dir, '..');
const BIN_DIR = path.join(ROOT, 'bin');
const tmp = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'ship-phase-')));
const repos: FixtureRepo[] = [];
afterAll(() => { fs.rmSync(tmp, { recursive: true, force: true }); while (repos.length) cleanup(repos.pop()!); });
interface Box { root: string; repo: string; state: string; record: string; env: NodeJS.ProcessEnv }
let n = 0;
/** A git fixture with a feature branch, a state root and an invocation record whose Next steps names the next act. */
function box(): Box {
const root = path.join(tmp, `box-${++n}`);
const repo = path.join(root, 'repo');
fs.mkdirSync(path.join(repo, 'src'), { recursive: true });
const env = { ...process.env, GSTACK_STATE_ROOT: path.join(root, 'state'), GSTACK_CAPY: '1', GSTACK_SHIP_CALL_NESTED: '', GIT_AUTHOR_NAME: 't', GIT_AUTHOR_EMAIL: 't@example.com', GIT_COMMITTER_NAME: 't', GIT_COMMITTER_EMAIL: 't@example.com' };
const git = (...a: string[]) => { const r = spawnSync('git', a, { cwd: repo, env, encoding: 'utf8', timeout: 30_000 }); if (r.status !== 0) throw new Error(r.stderr); return r.stdout.trim(); };
git('init', '-q', '-b', 'main');
fs.writeFileSync(path.join(repo, 'src', 'a.ts'), 'export const a = 1;\n');
fs.writeFileSync(path.join(repo, 'package.json'), '{"name":"fixture","scripts":{"test":"true"}}\n');
git('add', '-A'); git('commit', '-qm', 'init');
git('checkout', '-qb', 'feat');
fs.writeFileSync(path.join(repo, 'src', 'b.ts'), 'export const b = 2;\n');
git('add', '-A'); git('commit', '-qm', 'feat: b');
git('update-ref', 'refs/remotes/origin/main', 'main');
const record = path.join(root, 'record.md');
fs.writeFileSync(record, '# /ship record\n\n## Checks\n## Decisions\n## Reviews\n## Release\n## Documentation\n## Next steps\n- Phase 3: audits and review\n');
return { root, repo, state: path.join(root, 'state'), record, env };
}
const bin = (b: Box, name: string, args: string[], extra: NodeJS.ProcessEnv = {}) =>
spawnSync(path.join(BIN_DIR, name), args, { cwd: b.repo, env: { ...b.env, ...extra }, encoding: 'utf8', timeout: 60_000 });
const phase = (b: Box, args: string[], cmds: string[], extra: NodeJS.ProcessEnv = {}) =>
bin(b, 'gstack-ship-phase', ['run', '--dir', path.join(b.root, 'run'), ...args, '--', ...cmds], extra);
const ledgerOf = (b: Box) => /ledger=(\S+)/.exec(fs.readFileSync(b.record, 'utf8'))![1]!;
const backdate = (b: Box, minutes: number) => {
const l = JSON.parse(fs.readFileSync(ledgerOf(b), 'utf8'));
l.created_at = new Date(Date.now() - minutes * 60_000).toISOString();
fs.writeFileSync(ledgerOf(b), JSON.stringify(l, null, 2));
};
const start = (b: Box, mode: 'observe' | 'admit' = 'observe') => {
const r = bin(b, 'gstack-ship-budget', ['start', '--record', b.record, ...(mode === 'observe' ? ['--mode', 'observe'] : []), '--reading', '1000', '--credits', '1']);
expect(r.status, r.stdout + r.stderr).toBe(0);
};
describe('gstack-ship-phase run', () => {
// Value: protects=a phase is one command that prints only result lines and resumes from its journal: a rerun after a failure starts at the failed command, finished ones stay done, and a changed list reruns from the first change; fails_when=the runner reruns finished commands (a second budget start, a second preflight), prints whole logs into the parent, or keeps a stale result after the command text changed;
// why_new=G2: the one-call-per-phase rule was prose and conductors made 121-308 calls; seam=none; no_claim=how many calls a model makes
test('result lines only, a failed command stops the phase, and the same command resumes at it', () => {
const b = box();
const count = path.join(b.root, 'count');
const first = `echo noise; echo x >> ${count}; echo 'FIRST: ran'`;
const second = `test -f ${b.root}/fixed || { echo 'BAD: not fixed yet'; echo detail; exit 1; }; echo 'SECOND: ok'`;
const failed = phase(b, ['--phase', '7'], [first, second]);
expect(failed.status).toBe(3);
const out = failed.stdout.trim().split('\n');
expect(out[0]).toBe('RAN: 1/2 exit=0');
expect(out).toContain('FIRST: ran');
expect(out).toContain('BAD: not fixed yet');
expect(failed.stdout).not.toContain('noise');
expect(failed.stdout).not.toContain('detail');
expect(out.at(-1)).toBe('STOP: phase 7 command 2/2 exited 1; fix the cause, then rerun the same command (commands before 2 stay done)');
fs.writeFileSync(path.join(b.root, 'fixed'), '');
const again = phase(b, ['--phase', '7'], [first, second]);
expect(again.status, again.stdout + again.stderr).toBe(0);
expect(again.stdout).toContain('RAN: 1/2 exit=0 (done earlier)\nFIRST: ran\nRAN: 2/2 exit=0\nSECOND: ok\nPHASE: 7 done commands=2');
expect(fs.readFileSync(count, 'utf8')).toBe('x\n');
const changed = phase(b, ['--phase', '7'], [first + ' # v2', second]);
expect(changed.status).toBe(0);
expect(changed.stdout).toStartWith('RAN: 1/2 exit=0\nFIRST: ran\nRAN: 2/2 exit=0\n');
expect(fs.readFileSync(count, 'utf8')).toBe('x\nx\n');
}, 60_000);
// Value: protects=no phase call waits past its 200 s budget: a long command keeps running after the call returns NEXT: rerun, and the rerun attaches to the same process instead of starting it again; fails_when=the runner blocks until slow work ends (a cold cache re-bill per long wait), kills the command when it returns, or starts it a second time on the rerun;
// why_new=G2 waits; seam=none; no_claim=the host's own timeout
test('a command past --wait-s keeps running, the call returns NEXT: rerun, and the rerun waits on the same process', async () => {
const b = box();
const count = path.join(b.root, 'starts');
const slow = `echo s >> ${count}; sleep 3; echo 'SLOW: done'`;
const first = phase(b, ['--phase', '2', '--wait-s', '1'], [slow]);
expect(first.status).toBe(0);
expect(first.stdout).toMatch(/^WAITING: 1\/1 pid=\d+ running=\d+s log=\S+\/phases\/2\/1\.log\nNEXT: rerun /);
const done = phase(b, ['--phase', '2', '--wait-s', '30'], [slow]);
expect(done.status, done.stdout + done.stderr).toBe(0);
expect(done.stdout).toStartWith('RAN: 1/1 exit=0\nSLOW: done\nPHASE: 2 done');
expect(fs.readFileSync(count, 'utf8')).toBe('s\n');
}, 60_000);
// Value: protects=a changed command list never credits the replaced command's exit status to its replacement: the replaced process is stopped before the new command starts on the same log; fails_when=the old process keeps running and writes exit 0 into the file the new command is judged by (a false pass);
// why_new=/ship outside-voice review of #4451 reproduced the false pass; seam=none; no_claim=a process that ignores SIGTERM (it stops the phase instead)
test.skipIf(process.platform === 'win32')('a replaced command still running is stopped, so its exit never settles the new command', () => {
const b = box();
const first = phase(b, ['--phase', '5', '--wait-s', '1'], [`sleep 2; echo 'OLD: ok'`]);
expect(first.stdout).toContain('NEXT: rerun');
const changed = phase(b, ['--phase', '5', '--wait-s', '30'], [`sleep 4; echo 'NEW: failed'; exit 1`]);
expect(changed.stdout).toMatch(/^REPLACED: 1\/1 pid=\d+ ran a command this list no longer names; stopping it/);
expect(changed.status, changed.stdout + changed.stderr).toBe(3);
expect(changed.stdout).toContain('RAN: 1/1 exit=1');
expect(changed.stdout).toContain('NEW: failed');
expect(changed.stdout).not.toContain('OLD: ok');
}, 60_000);
test('result lines keep CODE: lines and gstack refusals, and drop everything else', () => {
expect(resultLines('noise\nBUDGET: used=1\n INDENTED: no\ngstack-ship-receipt write: refused (X)\nGSTACK_RESULT: skill=ship\nlower: no\n'))
.toEqual(['BUDGET: used=1', 'gstack-ship-receipt write: refused (X)', 'GSTACK_RESULT: skill=ship']);
});
test('usage errors exit 2 and run nothing', () => {
const b = box();
expect(bin(b, 'gstack-ship-phase', ['run', '--phase', '2', '--', 'true']).status).toBe(2);
expect(bin(b, 'gstack-ship-phase', ['run', '--dir', b.root, '--phase', '2']).status).toBe(2);
expect(bin(b, 'gstack-ship-phase', ['run', '--dir', b.root, '--phase', '../x', '--', 'true']).status).toBe(2);
expect(bin(b, 'gstack-ship-phase', ['nope']).status).toBe(2);
expect(fs.existsSync(path.join(b.root, 'phases'))).toBe(false);
});
});
const PROGRAM = fs.readFileSync(path.join(ROOT, 'lib/capy-ship-phase.js'), 'utf8');
const AsyncFunction = Object.getPrototypeOf(async () => {}).constructor as new (...a: string[]) => (...v: unknown[]) => Promise<string>;
/** A fake Capy host whose shell is real: bash runs in the fixture with bin/ on PATH; the jam's counter grows 1,000 tokens a read. */
function host(b: Box, intercept: (cmd: string) => { exit_code: number; output: string } | null = () => null) {
let tokens = 1000;
const bashes: string[] = [];
const tools = {
capy: { bash: async ({ command, timeout }: { command: string; timeout?: number }) => {
bashes.push(command);
const hit = intercept(command);
if (hit) return hit;
const r = spawnSync('bash', ['-c', command], { cwd: b.repo, env: { ...b.env, PATH: `${BIN_DIR}${path.delimiter}${process.env.PATH}` }, encoding: 'utf8', timeout: (timeout ?? 120) * 1000 });
return { exit_code: r.status ?? 1, output: r.stdout + r.stderr };
} },
thread: { get: async () => { tokens += 1000; return { cost: { tokens, credits: tokens / 1000 } }; } },
};
return { tools, bashes, run: (input: Record<string, unknown>) => new AsyncFunction('tools', 'sleep', 'now', 'input', PROGRAM)(tools, async () => {}, async () => Date.now(), input) };
}
describe('the Capy phase program', () => {
// Value: protects=the checked-in phase program drives a real DRIVER phase on a fixture in one call: the budget start takes this jam's reading through $GSTACK_SHIP_READING, preflight --audit runs, only result lines return, and the closing note records the phase's calls; the same call again reruns nothing; fails_when=the program loses the reading, returns whole logs, skips the note, or a rerun repeats the budget start or the preflight;
// why_new=G2 item 1 (a no-cost check that the runner drives a real phase); seam=tools.capy.bash and tools.thread.get (real shell, counter stub); no_claim=Capy's own execute limits
test('Phase 2 on a fixture: budget start and preflight --audit through gstack-ship-phase, then the note, in one program', async () => {
const b = box();
const h = host(b);
const run = path.join(b.root, 'run');
const input = { dir: run, phase: 2, record: b.record, jam: 'jam_test', step: '6', label: 'preflight', cwd: b.repo, commands: [
`gstack-ship-budget start --record ${b.record} --mode observe --reading "$GSTACK_SHIP_READING" --credits "$GSTACK_SHIP_CREDITS"`,
`gstack-ship-preflight --audit --base main --out ${run}`] };
const first = (await h.run(input)).split('\n');
expect(first[0]).toBe('RAN: 1/2 exit=0');
expect(first).toContain('RAN: 2/2 exit=0');
expect(first.some(l => l.startsWith('CONTEXT: diff='))).toBe(true);
expect(first.some(l => l.startsWith('READER: coverage='))).toBe(true);
expect(first.some(l => l.startsWith('PHASE: 2 done commands=2'))).toBe(true);
expect(first.find(l => l.startsWith('NOTE: 6:preflight '))).toMatch(/^NOTE: 6:preflight used=1000 credits=1 calls=\d+$/);
expect(first.every(l => !l.startsWith(' ') && !l.includes('diff --git'))).toBe(true);
const ledger = JSON.parse(fs.readFileSync(ledgerOf(b), 'utf8'));
expect(ledger.meter.baseline).toBe(2000);
const again = await h.run(input);
expect(again).toContain('RAN: 1/2 exit=0 (done earlier)');
expect(again).toContain('RAN: 2/2 exit=0 (done earlier)');
});
// Value: protects=a host whose thread.get reports cost.dollars and no cost.credits still gives the budget a credits reading (1,000 credits a dollar); fails_when=the program passes --credits undefined and the start or closing note refuses it;
// why_new=Capy's thread.get returned only cost.dollars on 2026-11-17, so every phase note failed parseCredits; seam=tools.thread.get stub; no_claim=Capy's own pricing
test('a host that reports only cost.dollars still gets a credits reading', async () => {
const b = box();
const h = host(b);
let tokens = 1000;
h.tools.thread.get = async () => { tokens += 1000; return { cost: { tokens, dollars: `$${(tokens / 1000).toFixed(2)}` } } as never; };
const run = path.join(b.root, 'run');
const out = await h.run({ dir: run, phase: 2, record: b.record, jam: 'jam_test', step: '6', cwd: b.repo, commands: [
`gstack-ship-budget start --record ${b.record} --mode observe --reading "$GSTACK_SHIP_READING" --credits "$GSTACK_SHIP_CREDITS"`] });
expect(out).not.toContain('STOP:');
expect(out.split('\n').find(l => l.startsWith('NOTE: 6 '))).toMatch(/^NOTE: 6 used=1000 credits=1000 calls=\d+$/);
});
// Value: protects=a review phase is the same one call: after its commands, the program hands the review pass program its pass input with the launch, checkout, record and jam, and returns that program's lines; a phase whose commands stop never dispatches; fails_when=the phase program dispatches after a failed command, or drops the record or jam the pass notes with;
// why_new=G2 (dispatches inside the phase call); seam=gstack-review-dispatch program, replaced by a stub that echoes its input; no_claim=the pass program's own behavior (test/review-pass.test.ts)
test('with input.pass it runs the review pass program on that input, and never after a failed command', async () => {
const b = box();
const stub = 'return "PASS_INPUT: " + JSON.stringify({ pass: input.pass, out: input.out, record: input.record, jam: input.jam, cwd: input.cwd });';
const h = host(b, cmd => (cmd.endsWith('gstack-review-dispatch program') ? { exit_code: 0, output: `PROGRAM: v9 sha256=x bytes=1\n${JSON.stringify(stub)}\n` } : null));
const out = await h.run({ dir: path.join(b.root, 'run'), phase: 3, record: b.record, jam: 'jam_test', cwd: b.repo, commands: ['echo "AUDIT: ok"'], pass: { pass: 'r-p1', out: path.join(b.root, 'run', 'p1') } });
expect(out).toContain('AUDIT: ok');
expect(out).toContain('PROGRAM: v9 sha256=x bytes=1');
expect(out).toContain(`PASS_INPUT: {"pass":"r-p1","out":"${path.join(b.root, 'run', 'p1')}","record":"${b.record}","jam":"jam_test","cwd":"${b.repo}"}`);
const failed = await h.run({ dir: path.join(b.root, 'run2'), phase: 3, cwd: b.repo, commands: ['echo "BAD: no"; exit 1'], pass: { pass: 'r-p2' } });
expect(failed).toContain('STOP: phase 3 command 1/1 exited 1');
expect(failed).not.toContain('PASS_INPUT');
});
});
describe('the 100-minute stop', () => {
// Value: protects=the 100-minute stop is a printed STOP with the run's state on disk (head, review passes, next act), the run refuses to start another phase until a resume restarts the clock, and an admit-mode run (ship/SKILL.md) never stops on time; fails_when=a note past 100 minutes continues (10 of 12 measured runs ran past the prose stop), stop.json lacks the head or the next act, a stopped run still starts a phase, or resume leaves the clock where every later note stops again;
// why_new=G2 item 3; seam=the ledger's created_at, backdated instead of waiting 100 minutes; no_claim=what the next session does with the state
test('a note past 100 minutes prints STOP: past 100 minutes, writes stop.json, blocks the next phase until resume restarts the clock', () => {
const b = box();
start(b);
const early = bin(b, 'gstack-ship-budget', ['note', '--record', b.record, '--step', '2', '--reading', '2000', '--credits', '2']);
expect(early.status, early.stdout + early.stderr).toBe(0);
backdate(b, 101);
const late = bin(b, 'gstack-ship-budget', ['note', '--record', b.record, '--step', '6', '--reading', '3000', '--credits', '3']);
expect(late.status).toBe(3);
const lines = late.stdout.trim().split('\n');
expect(lines[0]).toMatch(/^NOTE: 6 used=2000 credits=2/);
const head = spawnSync('git', ['rev-parse', 'HEAD'], { cwd: b.repo, encoding: 'utf8', timeout: 30_000 }).stdout.trim();
const dir = path.dirname(ledgerOf(b));
expect(lines[1]).toMatch(new RegExp(`^STOP: past 100 minutes \\(10[01] min since \\S+\\) head=${head.slice(0, 12)} rounds=0 calls=\\d+ next=Phase 3: audits and review state=${dir}/stop\\.json$`));
expect(lines.at(-1)).toBe(`GSTACK_RESULT: skill=ship status=incomplete run=${dir}`);
const state = JSON.parse(fs.readFileSync(path.join(dir, 'stop.json'), 'utf8'));
expect(state).toMatchObject({ kind: 'gstack-ship-stop', reason: 'past_100_minutes', head, rounds: 0, next: 'Phase 3: audits and review', step: '6', record: b.record });
const marker = path.join(b.root, 'phase-ran');
const blocked = phase(b, ['--phase', '3', '--record', b.record], [`touch ${marker}`]);
expect(blocked.status).toBe(3);
expect(blocked.stdout).toContain('STOP: run ');
expect(blocked.stdout).toContain('stopped (past_100_minutes) at Step 6; nothing ran; resume first: gstack-ship-budget resume --record');
expect(fs.existsSync(marker)).toBe(false);
const resumed = bin(b, 'gstack-ship-budget', ['resume', '--record', b.record, '--reading', '3000', '--credits', '3']);
expect(resumed.status, resumed.stdout + resumed.stderr).toBe(0);
expect(resumed.stdout).toContain('RESUMED: from=Step 6 (past_100_minutes)');
expect(resumed.stdout).toMatch(/^CLOCK: restarted at \S+ \(the 100-minute limit counts from here\)$/m);
const ran = phase(b, ['--phase', '3', '--record', b.record], [`touch ${marker}`]);
expect(ran.status, ran.stdout).toBe(0);
expect(bin(b, 'gstack-ship-budget', ['note', '--record', b.record, '--step', '9', '--reading', '4000', '--credits', '4']).status).toBe(0);
});
test('a phase that starts past 100 minutes stops before its first command; an admit-mode run never stops on time', () => {
const b = box();
start(b);
backdate(b, 120);
const marker = path.join(b.root, 'phase-ran');
const late = phase(b, ['--phase', '5', '--record', b.record], [`touch ${marker}`]);
expect(late.status).toBe(3);
expect(late.stdout).toMatch(/^STOP: past 100 minutes \(1[12]\d min since /);
expect(late.stdout).toContain('next=Phase 3: audits and review');
expect(fs.existsSync(marker)).toBe(false);
const admit = box();
start(admit, 'admit');
backdate(admit, 300);
const note = bin(admit, 'gstack-ship-budget', ['note', '--record', admit.record, '--step', '6', '--reading', '2000', '--credits', '2']);
expect(note.stdout).not.toContain('past 100 minutes');
});
});
describe('calls per phase and calls= in the receipt', () => {
// Value: protects=every note records the calls since the previous one and the receipt carries the run's total, so a 200-call run shows at the receipt; receipts written before calls= still validate, print and carry; fails_when=note drops calls, two notes count the same call, the summary line omits calls=, the schema refuses an older receipt or accepts a negative count, or carry loses calls;
// why_new=G2 item 2; seam=none; no_claim=calls that run no gstack command (the call log cannot see them)
test('notes record calls per phase and close prints them in the timeline', () => {
const b = box();
phase(b, ['--phase', '2', '--record', b.record], [`${BIN_DIR}/gstack-ship-budget start --record ${b.record} --mode observe --reading 1000 --credits 1`]);
const n1 = bin(b, 'gstack-ship-budget', ['note', '--record', b.record, '--step', '2', '--reading', '2000', '--credits', '2']);
expect(n1.stdout).toMatch(/^NOTE: 2 used=1000 credits=1 calls=1$/m);
const n2 = bin(b, 'gstack-ship-budget', ['note', '--record', b.record, '--step', '6', '--reading', '3000', '--credits', '3']);
expect(n2.stdout).toMatch(/^NOTE: 6 used=2000 credits=2 calls=1$/m);
const close = bin(b, 'gstack-ship-budget', ['close', '--record', b.record, '--reading', '3500', '--credits', '3.5']);
expect(close.stdout).toMatch(/^BUDGET_TIMELINE: 2 used=1000 credits=1 calls=1; 6 used=2000 credits=2 calls=1$/m);
});
test('receipt write takes --calls or the run total from --budget-record', () => {
const repo = makeFixtureRepo({ prefix: 'ship-phase-write-' });
repos.push(repo);
const env = { GSTACK_STATE_ROOT: path.join(repo.root, 'state'), GSTACK_CAPY: '1', GSTACK_SHIP_CALL_NESTED: '' };
const record = path.join(repo.root, 'record.md');
fs.writeFileSync(record, '# record\n');
expect(runBin(repo, 'gstack-ship-budget', ['start', '--record', record, '--mode', 'observe', '--reading', '1000', '--credits', '1'], env).status).toBe(0);
expect(runBin(repo, 'gstack-ship-budget', ['note', '--record', record, '--step', '2', '--reading', '2000', '--credits', '2'], env).status).toBe(0);
const write = (extra: string[]) => runBin(repo, 'gstack-ship-receipt', ['write', '--pr', '9', '--base', 'main', '--session-kind', 'unattended', ...extra], env);
const counted = write(['--budget-record', record]);
expect(counted.status, counted.err).toBe(0);
expect(counted.err).toMatch(/^SHIP_RECEIPT: pr=9 .* calls=[1-9]\d*( |$)/m);
expect(extractReceipt(counted.out).receipt!.calls).toBeGreaterThanOrEqual(1);
const given = write(['--calls', '214']);
expect(given.err).toMatch(/ calls=214( |$)/m);
expect(write(['--calls', 'many']).status).toBe(2);
expect(write([]).err).not.toContain('calls=');
}, 60_000);
test('the receipt field: optional, a whole number, printed as calls=, kept by placement and carry', () => {
const old = { schema_version: 1, pr: 5, head: 'a'.repeat(40), base: 'main' };
expect(validateReceipt(old)).toEqual([]);
expect(receiptSummaryLine(old as any)).not.toContain('calls=');
const withCalls = orderReceipt({ ...old, spend_usd: 1.5, session_kind: 'unattended', calls: 214 } as any);
expect(Object.keys(withCalls)).toEqual(['schema_version', 'pr', 'head', 'base', 'spend_usd', 'calls', 'session_kind']);
expect(validateReceipt(withCalls)).toEqual([]);
expect(receiptSummaryLine(withCalls)).toBe(`SHIP_RECEIPT: pr=5 head=${'a'.repeat(12)} version=- base=main session_kind=unattended calls=214`);
for (const bad of [-1, 1.5, '12']) expect(validateReceipt({ ...old, calls: bad }).length).toBeGreaterThan(0);
expect(extractReceipt(placeReceipt('## Summary\n\nProse.\n', withCalls)).receipt!.calls).toBe(214);
});
test('carry moves a receipt with calls= and one without it to a test-only head', () => {
for (const calls of [undefined, 37]) {
const repo = makeFixtureRepo({ prefix: 'ship-phase-carry-' });
repos.push(repo);
fs.mkdirSync(path.join(repo.work, 'src'), { recursive: true });
fs.mkdirSync(path.join(repo.work, 'test'), { recursive: true });
fs.writeFileSync(path.join(repo.work, 'src', 'app.ts'), 'export const a = 1;\n');
fs.writeFileSync(path.join(repo.work, 'test', 'app.test.ts'), 'test a\n');
repo.git('add', '.'); repo.git('commit', '-qm', 'seed'); repo.git('push', '-q', 'origin', 'main');
repo.git('checkout', '-qb', 'feat');
fs.writeFileSync(path.join(repo.work, 'src', 'app.ts'), 'export const a = 2;\n');
repo.git('commit', '-qam', 'feat: a=2');
const reviewed = repo.git('rev-parse', 'HEAD');
fs.writeFileSync(path.join(repo.work, 'test', 'app.test.ts'), 'test a=2\n');
repo.git('commit', '-qam', 'test: fix expectation');
const head = repo.git('rev-parse', 'HEAD');
const body = path.join(repo.root, 'body.md');
fs.writeFileSync(body, placeReceipt('## Summary\n\nProse.\n', { schema_version: 1, pr: 5, head: reviewed, base: 'main', ...(calls === undefined ? {} : { calls }) } as any));
const carried = runBin(repo, 'gstack-ship-receipt', ['carry', '--body', body], { GSTACK_STATE_ROOT: path.join(repo.root, 'state'), GSTACK_SESSION_KIND: 'unattended' });
expect(carried.status, carried.out + carried.err).toBe(0);
const after = extractReceipt(fs.readFileSync(body, 'utf8'));
expect(after.errors).toEqual([]);
expect(after.receipt!.head).toBe(head);
expect(after.receipt!.calls).toBe(calls);
expect(carried.err.includes(`calls=${calls}`)).toBe(calls !== undefined);
}
}, 60_000);
});