Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 60 additions & 0 deletions bin/gstack-ship-phase
Original file line number Diff line number Diff line change
@@ -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);
}
14 changes: 13 additions & 1 deletion bin/gstack-ship-receipt
Original file line number Diff line number Diff line change
Expand Up @@ -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>]...
Expand Down Expand Up @@ -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)

Expand Down Expand Up @@ -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>
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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,
Expand Down
2 changes: 1 addition & 1 deletion capy/skill/gstack/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
1 change: 1 addition & 0 deletions changelog.d/capy-run-each-driven-ship.md
Original file line number Diff line number Diff line change
@@ -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.
51 changes: 47 additions & 4 deletions docs/ship-budget.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -67,14 +68,56 @@ 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
the last is refused like a token reading ([BUDGET_READING_REJECTED](troubleshooting.md#budget-reading-rejected)).
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
Expand Down
Loading
Loading