@feigi/fleet-ctl 3.51.0 → 3.53.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@feigi/fleet-ctl",
3
- "version": "3.51.0",
3
+ "version": "3.53.0",
4
4
  "description": "Agent fleet: run-team controller, merge bot, PR reviewer, and the ticket pipeline they share",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -0,0 +1,295 @@
1
+ #!/usr/bin/env node
2
+ // The finisher's worktree audit (duty 1) as one command, so the row lookup, the
3
+ // dirty check, the head-equality check and the reflog cause derivation cannot be
4
+ // run, or skipped, one at a time:
5
+ //
6
+ // finisher-audit.mjs --worktree <abs> --pin <sha> [--sample-seconds <n>] [--repo <dir>]
7
+ //
8
+ // `--worktree` is the absolute path the finisher was dispatched with, spelled
9
+ // however it was reached: it is matched by its realpath. `--pin` is the full
10
+ // 40-hex head the finisher was dispatched against. `--repo` is the directory
11
+ // `worktree-audit.sh` runs in (it audits the worktrees of whichever repository
12
+ // it stands in); the cwd when omitted. `--sample-seconds` is the gap between the
13
+ // two `git diff --stat` samples of a dirty tree, 60 when omitted. Reached
14
+ // through the Resolver: `~/.fleet/bin/fleet-run finisher-audit.mjs ...`.
15
+ //
16
+ // Stdout is always one JSON line, the verdict:
17
+ //
18
+ // {worktree, realpath, pin, head, cause, evidence}
19
+ //
20
+ // worktree the path as given
21
+ // realpath its physical path, the form the audit's row names it by
22
+ // pin the pin, lowercased
23
+ // head `git -C <worktree> rev-parse HEAD`, null when it was never read
24
+ // cause null, or the word the ledger's `halted:<cause>` takes: live-editor,
25
+ // rebase, past-pin, unreadable, missing, absent or other
26
+ // evidence one entry per step that ran, each holding what that step read
27
+ //
28
+ // Exit vocabulary:
29
+ //
30
+ // 0 the worktree is clean at the pin: `cause` is null and nothing else is
31
+ // 1 a halt cause: `cause` names it and `evidence` holds what it was derived from
32
+ // 2 it could not look - the invocation or a read failed, `evidence.error`
33
+ // says which and the same line is on stderr. `cause` is null in that
34
+ // verdict and means nothing: only exit 0 is clean.
35
+ //
36
+ // Derivation, in this order, each step's output in `evidence`. A step runs only
37
+ // if every earlier one answered "no cause".
38
+ //
39
+ // 1 The row. `worktree-audit.sh` takes no argument and audits every worktree,
40
+ // so the row is found by `realpath(--worktree)` against the row's `worktree`,
41
+ // which is the physical path `git worktree list` reports - never by the path
42
+ // as written, so a spelling reached through a symlink (macOS's `/tmp` and
43
+ // `/var/folders` are symlinks too) still finds a healthy worktree's row.
44
+ // - no row at all: `absent`.
45
+ // - `readable:false` with null counts: `unreadable`, the script's own
46
+ // `UNREADABLE: <wt> (<cause>)` stderr line quoted in `evidence.audit`.
47
+ // - `readable:false` with zero counts: `missing`, its `MISSING on disk:
48
+ // <wt>` line quoted the same way.
49
+ // `git status` is no substitute for the row on the first two: in a worktree
50
+ // whose `.git` linkage is missing it answers for the enclosing repository, at
51
+ // rc 0.
52
+ //
53
+ // 2 Dirty. The row's `dirty` count, cross-checked with `git -C <wt> status
54
+ // --porcelain -unormal` - the explicit mode, never bare `--porcelain`, or
55
+ // `status.showUntrackedFiles = no` reads a dirty tree as clean. Either one
56
+ // reporting dirt is dirt. Then `git diff --stat` is sampled twice,
57
+ // `--sample-seconds` apart, and the cause is `live-editor` with both samples
58
+ // in the evidence: a diffstat that grew between them is someone still writing.
59
+ // Every dirty tree halts, grown or not - a finisher that verifies the dirt is
60
+ // harmless and labels anyway has replaced the rule with its purpose.
61
+ //
62
+ // 3 Head-equality. `git -C <wt> rev-parse HEAD` equal to the pin on a clean tree
63
+ // settles it: `cause` null, exit 0. It is against the dispatch pin, never
64
+ // against the PR's `headRefOid`: a member that kept working and pushed after
65
+ // the pin matches the branch tip on a clean tree, so a `headRefOid` comparison
66
+ // would report "settled" over commits no reviewer read. And no reflog entry
67
+ // is read at all on this path - a rebase sitting at or behind the pin is that
68
+ // head's provenance (the implementer's own pre-push replay), not divergence
69
+ // from it.
70
+ //
71
+ // 4 Only when the head differs from the pin: `git -C <wt> reflog -n 20`, and the
72
+ // newest entry is the move that put HEAD where it is.
73
+ // - a `reset` or `rebase` entry: `rebase`. The branch replayed onto a new
74
+ // base - its own commits on a new parent, content-identical only on a
75
+ // conflict-free replay. Evidence: the reflog line and the output of
76
+ // `git cherry <pin> HEAD origin/main`, run in the worktree.
77
+ // - a plain `commit` entry: `past-pin`. A member kept working after the
78
+ // dispatch. Evidence: `git log -1 --format='%h %s'` and whether that
79
+ // commit is pushed, unpushed or unknown, read from `git ls-remote origin
80
+ // refs/heads/<branch>` - the branch being the row's, and the full ref
81
+ // name so a branch named like the tail of another ref matches only
82
+ // itself. Only a successful read settles pushed against unpushed: the
83
+ // remote's value equal to HEAD is `pushed`, anything else from a read
84
+ // that succeeded is `unpushed`, the commit existing only in that
85
+ // worktree where no reviewer can reach it. A failed read - a non-zero
86
+ // exit, a timeout, a detached HEAD with no branch to ask about - is
87
+ // `unknown`, never `unpushed`, the same rule `release-ticket.sh`'s own
88
+ // `ls-remote` states. The remote is asked rather than the PR object,
89
+ // whose head lags a ref move.
90
+ // - anything else, an empty reflog included: `other`. Evidence: both status
91
+ // reads (the step-2 read and one after the reflog), the reflog line at
92
+ // the move, and both SHAs. A cause nobody has named yet is still a cause
93
+ // observed, and the report is what gets it named.
94
+ //
95
+ // Every cause halts, always - named or not. A rebase is not a fast-forward the
96
+ // finisher gets to accept, a commit past the pin is not one either, and a cause
97
+ // that could not be named is the least settled of the lot.
98
+ //
99
+ // A usage refusal (a missing, unknown or malformed flag) is a one-line refusal
100
+ // on stderr with no verdict, exit 2, as in every other script's `die()`.
101
+
102
+ import { spawnSync } from "node:child_process";
103
+ import { realpathSync, statSync } from "node:fs";
104
+ import { basename, dirname, join, resolve } from "node:path";
105
+ import { fileURLToPath } from "node:url";
106
+ import { makeDie, defineFlags, writeAll } from "./arg.mjs";
107
+ import { gitEnv } from "./git-env.mjs";
108
+
109
+ const NAME = "finisher-audit";
110
+ const die = makeDie(NAME);
111
+ const { arg, numArg, sweep, stray } = defineFlags(die, {
112
+ flags: { worktree: "value", pin: "value", "sample-seconds": "value", repo: "value" },
113
+ });
114
+ const USAGE = "usage: finisher-audit.mjs --worktree <abs> --pin <sha> [--sample-seconds <n>] [--repo <dir>]";
115
+ // The sweep runs before the required-flag check so a misspelled flag is named
116
+ // as that, not buried under a missing-flag usage line.
117
+ sweep();
118
+ stray();
119
+
120
+ const AUDIT = join(dirname(fileURLToPath(import.meta.url)), "worktree-audit.sh");
121
+ const DEFAULT_SAMPLE_SECONDS = 60;
122
+ // A read of the remote that has not answered by now is an unknown answer, not a
123
+ // reason to hold the finisher's halt report.
124
+ const LS_REMOTE_TIMEOUT_MS = 30_000;
125
+ // One audit row per worktree, each carrying its dirty files: far past
126
+ // spawnSync's 1 MiB default on a repository with many dirty worktrees.
127
+ const AUDIT_BUFFER = 256 * 1024 * 1024;
128
+ const REFLOG_LIMIT = "20";
129
+ // Atomics.wait never blocks on a value nothing writes, so it is a plain sleep.
130
+ const IDLE = new Int32Array(new SharedArrayBuffer(4));
131
+
132
+ const worktree = arg("worktree");
133
+ const pinArg = arg("pin");
134
+ const sampleSeconds = numArg("sample-seconds");
135
+ const repoArg = arg("repo");
136
+ if (worktree === null || pinArg === null) die(USAGE);
137
+ if (!worktree.startsWith("/")) die(`--worktree needs an absolute path, got ${worktree}`);
138
+ // Full SHAs only, lowercased: a shorter pin could not be compared to HEAD, and
139
+ // case is folded rather than refused, as finisher-label.mjs does.
140
+ const pin = pinArg.toLowerCase();
141
+ if (!/^[0-9a-f]{40}$/.test(pin)) die(`--pin needs a full 40-character commit SHA, got ${pinArg}`);
142
+ // A missing directory makes spawn report ENOENT for the binary itself, which
143
+ // would blame git or sh for a bad --repo. A stat that throws (EACCES on an
144
+ // ancestor) is the same refusal, not a crash with no verdict.
145
+ if (repoArg !== null) {
146
+ let isDir = false;
147
+ try {
148
+ isDir = statSync(repoArg, { throwIfNoEntry: false })?.isDirectory() === true;
149
+ } catch (e) {
150
+ die(`--repo cannot be read: ${repoArg} (${e.code ?? e.message})`);
151
+ }
152
+ if (!isDir) die(`--repo is not a directory: ${repoArg}`);
153
+ }
154
+ const repo = repoArg === null ? process.cwd() : resolve(repoArg);
155
+
156
+ // The physical form of a path, for a path that may no longer exist: the deepest
157
+ // ancestor that resolves is made physical and the rest is appended as written,
158
+ // which is how `git worktree list` names a worktree whose directory is gone
159
+ // under a symlinked ancestor.
160
+ function physical(path) {
161
+ const tail = [];
162
+ let here = resolve(path);
163
+ for (;;) {
164
+ try {
165
+ return join(realpathSync(here), ...tail.reverse());
166
+ } catch {
167
+ const up = dirname(here);
168
+ if (up === here) return resolve(path);
169
+ tail.push(basename(here));
170
+ here = up;
171
+ }
172
+ }
173
+ }
174
+
175
+ const realpath = physical(worktree);
176
+ const GIT_ENV = gitEnv({ GIT_TERMINAL_PROMPT: "0" });
177
+ const verdict = { worktree, realpath, pin, head: null, cause: null, evidence: {} };
178
+ const evidence = verdict.evidence;
179
+
180
+ function finish(exit, cause = null) {
181
+ verdict.cause = cause;
182
+ writeAll(1, `${JSON.stringify(verdict)}\n`);
183
+ process.exit(exit);
184
+ }
185
+
186
+ // The finisher could not look: the verdict carries what failed and the exit is
187
+ // 2, so a read that failed is never taken for a read that found nothing.
188
+ function fail(error) {
189
+ evidence.error = error;
190
+ writeAll(2, `\n${NAME}: ${error}\n`);
191
+ finish(2);
192
+ }
193
+
194
+ const halt = (cause) => finish(1, cause);
195
+
196
+ function run(cmd, args, options = {}) {
197
+ return spawnSync(cmd, args, { encoding: "utf8", env: GIT_ENV, maxBuffer: AUDIT_BUFFER, ...options });
198
+ }
199
+
200
+ // A git call inside the worktree. A call that could not run, was killed or
201
+ // exited non-zero stops the audit at exit 2 unless the caller asked to read the
202
+ // failure itself (`soft`).
203
+ function git(step, args, { soft = false, timeout } = {}) {
204
+ const r = run("git", ["-C", realpath, ...args], timeout === undefined ? {} : { timeout });
205
+ if (r.error || r.signal || r.status !== 0) {
206
+ if (soft) return { ok: false, out: "", error: (r.error?.message ?? r.stderr ?? "").trim() || `exit ${r.status ?? r.signal}` };
207
+ const why = r.error?.message ?? (r.signal ? `killed by ${r.signal}` : (r.stderr ?? "").trim() || `exit ${r.status}`);
208
+ fail(`${step}: git ${args.join(" ")} failed: ${why}`);
209
+ }
210
+ return { ok: true, out: r.stdout, error: null };
211
+ }
212
+
213
+ // --- 1: the row --------------------------------------------------------------
214
+ const audit = run("sh", [AUDIT], { cwd: repo });
215
+ if (audit.error || audit.signal || audit.status !== 0) {
216
+ fail(`worktree-audit.sh failed: ${audit.error?.message ?? (audit.signal ? `killed by ${audit.signal}` : (audit.stderr ?? "").trim() || `exit ${audit.status}`)}`);
217
+ }
218
+ let rows;
219
+ try {
220
+ rows = JSON.parse(audit.stdout);
221
+ } catch {
222
+ fail(`worktree-audit.sh printed no JSON: ${audit.stdout.slice(0, 200)}`);
223
+ }
224
+ if (!Array.isArray(rows)) fail(`worktree-audit.sh printed an unexpected shape: ${audit.stdout.slice(0, 200)}`);
225
+
226
+ const row = rows.find((r) => r !== null && typeof r === "object" && typeof r.worktree === "string" && physical(r.worktree) === realpath);
227
+ // The audit's own stderr line for a row, quoted where it printed one.
228
+ const quote = (prefix) => audit.stderr.split("\n").find((l) => l.trimStart().startsWith(prefix)) ?? null;
229
+ if (!row) {
230
+ evidence.audit = { row: null, rows: rows.map((r) => r?.worktree ?? null) };
231
+ halt("absent");
232
+ }
233
+ if (row.readable !== true) {
234
+ const unreadable = row.ahead === null || row.dirty === null;
235
+ evidence.audit = { row, stderr: quote(unreadable ? `UNREADABLE: ${row.worktree} (` : `MISSING on disk: ${row.worktree}`)?.trim() ?? null };
236
+ halt(unreadable ? "unreadable" : "missing");
237
+ }
238
+ evidence.audit = { row };
239
+
240
+ // --- 2: dirty ----------------------------------------------------------------
241
+ const status = () => git("status", ["status", "--porcelain", "-unormal"]).out;
242
+ const statusFirst = status();
243
+ evidence.status = [statusFirst];
244
+ if (row.dirty > 0 || statusFirst.trim() !== "") {
245
+ const stat = () => git("sample", ["diff", "--stat"]).out;
246
+ const first = stat();
247
+ Atomics.wait(IDLE, 0, 0, (sampleSeconds ?? DEFAULT_SAMPLE_SECONDS) * 1000);
248
+ const second = stat();
249
+ evidence.samples = [first, second];
250
+ halt("live-editor");
251
+ }
252
+
253
+ // --- 3: head-equality ----------------------------------------------------------
254
+ const head = git("head", ["rev-parse", "HEAD"]).out.trim();
255
+ verdict.head = head;
256
+ if (head === pin) finish(0);
257
+
258
+ // --- 4: the reflog -------------------------------------------------------------
259
+ // `--no-decorate --no-color`: a user's `log.decorate` or `color.ui` config would
260
+ // otherwise put `(HEAD -> branch)` or an escape ahead of the subject, and the
261
+ // subject match below would read every move as `other`.
262
+ const reflog = git("reflog", ["reflog", "--no-decorate", "--no-color", "-n", REFLOG_LIMIT]).out;
263
+ const move = reflog.split("\n").find((l) => l.trim() !== "") ?? null;
264
+ // `<abbrev> HEAD@{0}: <subject>`: the subject is what names the operation.
265
+ const subject = move === null ? "" : (/^\S+ [^\s:]*@\{\d+\}: (.*)$/.exec(move)?.[1] ?? "");
266
+ evidence.reflog = move;
267
+
268
+ if (/^(reset|rebase)\b/.test(subject)) {
269
+ const cherry = git("cherry", ["cherry", pin, "HEAD", "origin/main"], { soft: true });
270
+ evidence.cherry = cherry.ok ? cherry.out : { error: cherry.error };
271
+ halt("rebase");
272
+ }
273
+
274
+ if (/^commit\b/.test(subject)) {
275
+ evidence.commit = git("log", ["log", "-1", "--format=%h %s"]).out.trim();
276
+ const branch = row.branch === "DETACHED" ? null : row.branch;
277
+ if (typeof branch !== "string" || branch === "") {
278
+ evidence.remote = { state: "unknown", error: "detached HEAD: no branch to ask the remote about" };
279
+ } else {
280
+ const ref = `refs/heads/${branch}`;
281
+ const r = git("ls-remote", ["ls-remote", "origin", ref], { soft: true, timeout: LS_REMOTE_TIMEOUT_MS });
282
+ if (!r.ok) {
283
+ evidence.remote = { state: "unknown", ref, error: r.error };
284
+ } else {
285
+ const line = r.out.split("\n").find((l) => l.split("\t")[1] === ref);
286
+ const sha = line === undefined ? null : line.split("\t")[0];
287
+ evidence.remote = { state: sha === head ? "pushed" : "unpushed", ref, sha };
288
+ }
289
+ }
290
+ halt("past-pin");
291
+ }
292
+
293
+ evidence.status.push(status());
294
+ evidence.shas = { pin, head };
295
+ halt("other");
@@ -21,6 +21,15 @@
21
21
 
22
22
  import { createHash } from "node:crypto";
23
23
 
24
+ // How an archive beside the ledger is named. `ledger.mjs rotate` files the
25
+ // ledger as `ledger.<stamp>.md` and the phase-0 receipt as `phase0.<stamp>.json`
26
+ // under one stamp, and `phase0.mjs` files a receipt the rotation left behind
27
+ // the same way, so the format lives here once.
28
+ const RECEIPT_STEM = "phase0";
29
+ export const RECEIPT = `${RECEIPT_STEM}.json`;
30
+ export const archiveStamp = () => new Date().toISOString().replace(/\.\d{3}Z$/, "Z").replaceAll(":", "");
31
+ export const receiptArchiveName = (stamp) => `${RECEIPT_STEM}.${stamp}.json`;
32
+
24
33
  // The outcome vocabulary, verbatim from the spec. A word is matched exactly,
25
34
  // except the three that carry a value, which match OUTCOME_PATTERNS below.
26
35
  const FAMILIES = {
@@ -47,7 +47,7 @@ import { fileURLToPath } from "node:url";
47
47
  import { spawnSync, execFileSync } from "node:child_process";
48
48
  import { makeDie, isFlagLike, hasEqualsForm, isDigits } from "./arg.mjs";
49
49
  import { fleetFile, FleetDirUnresolvable } from "./fleet-dir.mjs";
50
- import { parseMember, parseToken, memberTokens, nextMergeBot, nextRetry, liveOnLedger, retiredOnLedger, isRetirable, agentDefinition, CELL, tierValues, rowPr, rowWriteRefusal, isReviewToken, addedReviewToken, newSplitRow, splitRowClause, added, premisesOf, MEMBER_FAMILIES, ROWS, DISPATCHED, FILED, RULED, DRAIN, RETIRED, headerRe, escapeText, unescapeText } from "./ledger-grammar.mjs";
50
+ import { parseMember, parseToken, memberTokens, nextMergeBot, nextRetry, liveOnLedger, retiredOnLedger, isRetirable, agentDefinition, CELL, tierValues, rowPr, rowWriteRefusal, isReviewToken, addedReviewToken, newSplitRow, splitRowClause, added, premisesOf, MEMBER_FAMILIES, ROWS, DISPATCHED, FILED, RULED, DRAIN, RETIRED, RECEIPT, archiveStamp, receiptArchiveName, headerRe, escapeText, unescapeText } from "./ledger-grammar.mjs";
51
51
  import { deriveRun, LedgerError, labelOffMember, HELD, CONFLICT_HOLD } from "./fleet-tick.mjs";
52
52
  import { stateFileIn, readState, writeState, assessBeat, stallsAt } from "./fleet-state.mjs";
53
53
  import { processSource, ancestry, controllerOf, judgeController, ProcUnreadable } from "./proc.mjs";
@@ -1446,7 +1446,10 @@ function runCheck() {
1446
1446
  // hard-linked to its stamped name, then unlinked or, when a successor is
1447
1447
  // carried, replaced by it — so its bytes are untouched, and the link refuses
1448
1448
  // atomically when that name is already taken rather than overwriting an older
1449
- // archive.
1449
+ // archive. A `phase0.json` receipt beside the ledger belongs to the same run,
1450
+ // so it is archived as `phase0.<stamp>.json` under the ledger archive's own
1451
+ // stamp — a warning-only move after the ledger move, refused up front only
1452
+ // when that name is taken.
1450
1453
  //
1451
1454
  // What follows depends on the verdict below. After a `dead` or `none` one
1452
1455
  // nothing is carried: the next write subcommand finds no file and starts the
@@ -1564,9 +1567,16 @@ function runRotate() {
1564
1567
  carry = carryOf(text);
1565
1568
  }
1566
1569
  const carrying = carry.rows.length > 0 || carry.dispatched.length > 0 || carry.retired.length > 0;
1570
+ // The phase-0 receipt beside the ledger belongs to the run being rotated
1571
+ // away, so it takes the archive's own stamp: `phase0.<stamp>.json` next to
1572
+ // `ledger.<stamp>.md`. A name already taken refuses before anything moves,
1573
+ // as the ledger's own does.
1574
+ const stamp = archiveStamp();
1575
+ const receipt = join(dirname(file), RECEIPT);
1576
+ const receiptArchive = existsSync(receipt) ? join(dirname(file), receiptArchiveName(stamp)) : null;
1577
+ if (receiptArchive !== null && existsSync(receiptArchive)) die(`refusing to rotate ${file}: ${receiptArchive} already exists`);
1567
1578
  let archive = null;
1568
1579
  if (exists) {
1569
- const stamp = new Date().toISOString().replace(/\.\d{3}Z$/, "Z").replaceAll(":", "");
1570
1580
  archive = join(dirname(file), `${basename(file, ".md")}.${stamp}.md`);
1571
1581
  try {
1572
1582
  linkSync(file, archive);
@@ -1588,6 +1598,17 @@ function runRotate() {
1588
1598
  } else {
1589
1599
  console.error(` nothing to rotate: ${file} does not exist`);
1590
1600
  }
1601
+ // After the ledger has moved, and a warning rather than a refusal: the
1602
+ // ledger is already archived, and a receipt left where it is is read as a
1603
+ // previous run's by the next phase 0, which moves it aside itself.
1604
+ if (receiptArchive !== null) {
1605
+ try {
1606
+ renameSync(receipt, receiptArchive);
1607
+ console.error(` archived ${receipt} -> ${receiptArchive}`);
1608
+ } catch (e) {
1609
+ console.error(` could not archive ${receipt} -> ${receiptArchive}: ${e.message}`);
1610
+ }
1611
+ }
1591
1612
  // Nothing to carry writes nothing, so the next write starts the skeleton
1592
1613
  // exactly as after any other verdict.
1593
1614
  if (carrying) {
@@ -0,0 +1,562 @@
1
+ #!/usr/bin/env node
2
+ // Phase 0 as one command: the run's start sequence, in order, with a receipt.
3
+ //
4
+ // phase0.mjs --session <dir> [--implementer-cap n] [--reviewer-cap n]
5
+ // [--plugin-checkout <dir>] [--spend-dir <dir>]
6
+ // [--workflow <name> | --declare-no-ci]
7
+ //
8
+ // Reached through the Resolver and run from the MAIN checkout (a linked
9
+ // worktree refuses: the checks below judge the checkout the controller reads
10
+ // its rules from). The steps, each a named entry in the receipt, run in
11
+ // this order because the order is the point — the pin certifies the tree the
12
+ // fast-forward left, the rotation comes before the fold-in, the scratch
13
+ // reclaim straight after the rotation, the metrics refresh before the first
14
+ // Pull is routed:
15
+ //
16
+ // branch `git symbolic-ref -q HEAD` is refs/heads/main. A checkout left
17
+ // on a branch whose PR has merged would fast-forward that branch
18
+ // and the baseline would record it as the run's ref.
19
+ // fast-forward `git fetch origin`, `rev-list --count main..origin/main`,
20
+ // `merge --ff-only origin/main`. HEAD moving means the rules this
21
+ // script came from are superseded: prints `SUPERSEDED <n>
22
+ // commits; re-run phase0.mjs` and fails, so the re-run executes
23
+ // from the new tree.
24
+ // pin `instruments.sh --pin`, with `--audit <plugin-checkout>` when
25
+ // given (a workspace that tracks no `plugin/…` of its own).
26
+ // baseline `main-checkout.mjs --record`; its refusals fail the step.
27
+ // preflight `preflight.mjs`. A non-zero exit fails the step; the FAIL, WARN
28
+ // and PREFLIGHT lines of an exit 1 are printed.
29
+ // ruleset `.github/scripts/apply-ruleset.sh --check`, when the workspace
30
+ // checks a ruleset spec in. Exit 3 is `drift` (the diff is the
31
+ // output), exit 2 or anything else `unanswered`; neither stops
32
+ // the run — reconciling is a write to the gate and the
33
+ // maintainer's.
34
+ // tier-roles `tier-roles.mjs --check`.
35
+ // metrics `metrics-refresh.mjs`. A non-zero exit fails the step.
36
+ // cockpit `board.mjs serve --open` launched detached, `--spend-dir`
37
+ // passed through. Recorded; never fails the run.
38
+ // rotate `ledger.mjs rotate`. Exit 2 is a refusal and fails the step.
39
+ // reclaim `reclaim-scratch.mjs --root <scratch> --after-rotate --apply`.
40
+ // Recorded; never fails the run.
41
+ // recipe `derive-testcmd.sh . install` and `. test --at origin/main`.
42
+ // Either exiting 1 is a cache with nothing valid in it: pending,
43
+ // `NEED derive-recipe`. Exit 3 (a tool the reader could not run)
44
+ // fails the step — deriving would not help.
45
+ // fold-in every open PR no carried ledger row names: one that closes an
46
+ // issue gets a `#<pr>` row from `ledger.mjs row` (the tick queues
47
+ // its review off it); one that closes none is listed as `NEED
48
+ // review PR#<pr> (closes no issue)`.
49
+ // stranded `stranded.mjs`. A `resume` entry whose ticket has no ledger row
50
+ // yet is pending: `NEED resume #<n> <worktree> <branch>`. A
51
+ // `report` entry is printed. Resuming a claim writes its row, so
52
+ // a re-run after the dispatch finds the need met.
53
+ // shortlist `shortlist.mjs`. A non-zero exit fails the step.
54
+ //
55
+ // THE RECEIPT is `.fleet/phase0.json` (resolved through fleet-dir.mjs, so a
56
+ // worktree and the main checkout name one file):
57
+ //
58
+ // { run, session, scratch, caps: {impl, review},
59
+ // steps: { <name>: { status, at, output } } }
60
+ //
61
+ // `status` is ok, pending, failed, drift or unanswered; `at` an ISO time;
62
+ // `output` the step's own words — the refusal for a failure, the NEED lines for
63
+ // a pending step. Every step name is always present: one not yet run is
64
+ // `pending`. `run` is the `at` that `ledger.mjs rotate` wrote into the
65
+ // controller record in `.fleet/heartbeat.json`, null until the rotation has
66
+ // run. `session` is `--session`, the one place the controller states its
67
+ // session directory. `scratch` is what `scratch-root.mjs` prints. `caps` are
68
+ // the flags as given, null for one not given: the tick's own defaults apply to
69
+ // a cap nobody set, and a number here would pretend somebody had.
70
+ //
71
+ // RESUMABLE. A re-run reads the receipt. It continues it — skipping every `ok`
72
+ // step and re-running the rest — only when its `run` equals the `at` the
73
+ // controller record holds now AND its `session` equals `--session`. That
74
+ // comparison alone does not separate two runs before the new run's rotation:
75
+ // the record still carries the previous run's `at` until `ledger.mjs rotate`
76
+ // writes the next, so the previous run's receipt still matches it, and a
77
+ // re-run that trusted `run` alone would skip `rotate`. The session rule closes
78
+ // a new session. A receipt of any other run (a `run` that is set and does not
79
+ // match, or a different session) is held as `phase0.previous.json` and the
80
+ // script starts at `branch`; this run's own receipt is written at
81
+ // `phase0.json` after every step. A receipt whose rotation has not run is
82
+ // simply overwritten: every step before `rotate` is idempotent and is re-run
83
+ // on every invocation until the rotation has run.
84
+ //
85
+ // THE ROTATION FILES THE PREVIOUS RUN'S RECEIPT. The `rotate` step takes this
86
+ // run's partial receipt off disk, puts the held one back at `phase0.json` and
87
+ // runs `ledger.mjs rotate`, which archives it as `phase0.<UTC stamp>.json`
88
+ // beside `ledger.<UTC stamp>.md`, one stamp for both. A rotation that refused
89
+ // leaves it held for the next attempt; one that archived the ledger and not
90
+ // the receipt files it under a stamp of this script's own. With no omp process
91
+ // above the run the rotation writes no controller record and `run` stays
92
+ // null; a receipt whose `rotate` step is `ok` is then resumed on the session
93
+ // alone.
94
+ //
95
+ // A step that fails stops the script; so does a pending one — nothing after
96
+ // the recipe may run before it is proven, and the shortlist waits for the
97
+ // stranded claims. The steps after it stay `pending` in the receipt.
98
+ //
99
+ // `--workflow` and `--declare-no-ci` name how a repository without a workflow
100
+ // called CI runs. `preflight.mjs` takes no arguments, so they are not passed
101
+ // to it: they are checked against each other here and recorded in the
102
+ // `preflight` step's output.
103
+ //
104
+ // One `phase0: <step>: <status> …` line per step on stdout, a step's further
105
+ // output indented under it when there is any, and the `NEED` lines last.
106
+ // Exit 0 every step ok, or `drift`/`unanswered` — advice the run goes on past;
107
+ // 2 a usage error; 3 a step failed, or the run could not start or record itself
108
+ // (the scratch root, the controller record, the receipt); 4 a step needs the
109
+ // controller — dispatch what the NEED line names, then run this again. A NEED
110
+ // the fold-in prints is advice too and changes no exit status: a PR with no
111
+ // issue behind it is the controller's to queue or leave, and nothing a re-run
112
+ // could meet.
113
+ //
114
+ // Zero deps: node builtins and sibling scripts only.
115
+
116
+ import { spawn, spawnSync } from "node:child_process";
117
+ import { existsSync, mkdirSync, readFileSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
118
+ import { dirname, join, resolve } from "node:path";
119
+ import { fileURLToPath } from "node:url";
120
+ import { makeDie, defineFlags, isDigits } from "./arg.mjs";
121
+ import { FleetDirUnresolvable, fleetFile } from "./fleet-dir.mjs";
122
+ import { readState, stateFileIn } from "./fleet-state.mjs";
123
+ import { gitEnv } from "./git-env.mjs";
124
+ import { isCLI } from "./is-cli.mjs";
125
+ import { RECEIPT, archiveStamp, receiptArchiveName, rowNums } from "./ledger-grammar.mjs";
126
+
127
+ const NAME = "phase0";
128
+ const SCRIPTS = dirname(fileURLToPath(import.meta.url));
129
+ const MAX_BUFFER = 64 * 1024 * 1024;
130
+ const NETWORK_TIMEOUT_MS = 120_000;
131
+ const PR_LIMIT = 1000;
132
+ // The tail of a child's output is the part that says why it stopped.
133
+ const OUTPUT_MAX = 16_000;
134
+ // The previous run's receipt, set aside at startup until the rotation files it.
135
+ const HELD = "phase0.previous.json";
136
+ const RULESET_SPEC = join(".github", "rulesets", "main.json");
137
+ const RULESET_CHECK = join(".github", "scripts", "apply-ruleset.sh");
138
+
139
+ const script = (name) => join(SCRIPTS, name);
140
+
141
+ function how(r) {
142
+ if (r.error) return r.error.code ?? r.error.message;
143
+ if (r.signal) return `killed by ${r.signal}`;
144
+ return `exit ${r.status}`;
145
+ }
146
+
147
+ const trimmed = (s) => String(s ?? "").trim();
148
+ const lines = (s) => trimmed(s).split("\n").filter((l) => l.trim() !== "");
149
+
150
+ /**
151
+ * Runs a child to completion from `cwd`. `status` is the exit status, null
152
+ * when the child never ran or was killed (`how` says which); `text` is its
153
+ * stdout then stderr, trimmed.
154
+ */
155
+ function run(cmd, args, { cwd, env, timeoutMs } = {}) {
156
+ const r = spawnSync(cmd, args, {
157
+ cwd, encoding: "utf8", maxBuffer: MAX_BUFFER, env: gitEnv(env), timeout: timeoutMs,
158
+ });
159
+ const stdout = trimmed(r.stdout);
160
+ const stderr = trimmed(r.stderr);
161
+ return { status: r.error ? null : r.status, stdout, stderr, text: [stdout, stderr].filter(Boolean).join("\n"), how: how(r) };
162
+ }
163
+
164
+ const node = (name, args, opts) => run(process.execPath, [script(name), ...args], opts);
165
+ const sh = (name, args, opts) => run("sh", [script(name), ...args], opts);
166
+
167
+ const ok = (output) => ({ status: "ok", output });
168
+ const failed = (output) => ({ status: "failed", output });
169
+ const withText = (head, r) => (r.text ? `${head}\n${r.text}` : head);
170
+ const refusal = (what, r) => failed(withText(`${what} ${r.how}`, r));
171
+
172
+ // ── the steps ────────────────────────────────────────────────────────────────
173
+
174
+ function branch({ cwd }) {
175
+ const r = run("git", ["symbolic-ref", "-q", "HEAD"], { cwd });
176
+ if (r.status === 0 && r.stdout === "refs/heads/main") return ok("HEAD is refs/heads/main");
177
+ const now = r.status === 0 ? r.stdout : r.status === 1 ? "detached" : `unreadable (${r.how})`;
178
+ return failed(`HEAD is ${now}, not refs/heads/main — switch the checkout to main before the run starts`);
179
+ }
180
+
181
+ function fastForward({ cwd }) {
182
+ const fetch = run("git", ["fetch", "origin"], { cwd, timeoutMs: NETWORK_TIMEOUT_MS });
183
+ if (fetch.status !== 0) return refusal("git fetch origin failed:", fetch);
184
+ const count = run("git", ["rev-list", "--count", "main..origin/main"], { cwd });
185
+ if (count.status !== 0 || !isDigits(count.stdout)) return refusal("git rev-list --count main..origin/main failed:", count);
186
+ const behind = Number(count.stdout);
187
+ if (behind === 0) return ok("main is level with origin/main");
188
+ const merge = run("git", ["merge", "--ff-only", "origin/main"], { cwd });
189
+ if (merge.status !== 0) return refusal("git merge --ff-only origin/main failed:", merge);
190
+ return failed(`SUPERSEDED ${behind} commits; re-run phase0.mjs`);
191
+ }
192
+
193
+ function pin({ cwd, pluginCheckout }) {
194
+ const r = sh("instruments.sh", ["--pin", ...(pluginCheckout ? ["--audit", pluginCheckout] : [])], { cwd });
195
+ if (r.status !== 0) return refusal("instruments.sh --pin failed:", r);
196
+ return ok(pluginCheckout ? `instruments pinned, auditing ${pluginCheckout}` : "instruments pinned");
197
+ }
198
+
199
+ function baseline({ cwd }) {
200
+ const r = node("main-checkout.mjs", ["--record"], { cwd });
201
+ if (r.status !== 0) return refusal("main-checkout.mjs --record refused:", r);
202
+ return ok("main-checkout baseline recorded");
203
+ }
204
+
205
+ function preflight({ cwd, ci }) {
206
+ const r = node("preflight.mjs", [], { cwd });
207
+ if (r.status !== 0) {
208
+ // Exit 1 is a row that failed, and its FAIL, WARN and PREFLIGHT lines are
209
+ // the report; exit 2 is a script that could not run, whose own words are
210
+ // all there is, as are an exit 1 that printed none of those lines.
211
+ const fails = r.status === 1 ? lines(r.text).filter((l) => /^(FAIL|WARN|PREFLIGHT)/.test(l)) : [];
212
+ const keep = fails.length > 0 ? fails : lines(r.text);
213
+ return failed([`preflight.mjs ${r.how}`, ...keep].join("\n"));
214
+ }
215
+ return ok([`preflight.mjs passed (${lines(r.stdout).at(-1) ?? "no output"})`, ...(ci === null ? [] : [ci])].join("\n"));
216
+ }
217
+
218
+ function ruleset({ cwd }) {
219
+ if (!existsSync(join(cwd, RULESET_SPEC))) return ok(`no ruleset spec at ${RULESET_SPEC} — nothing to check`);
220
+ const r = run("bash", [join(cwd, RULESET_CHECK), "--check"], { cwd, timeoutMs: NETWORK_TIMEOUT_MS });
221
+ if (r.status === 0) return ok("the live gate matches the ruleset spec");
222
+ if (r.status === 3) return { status: "drift", output: withText("the live gate differs from the ruleset spec", r) };
223
+ return { status: "unanswered", output: withText(`apply-ruleset.sh --check could not answer (${r.how})`, r) };
224
+ }
225
+
226
+ function tierRoles({ cwd }) {
227
+ const r = node("tier-roles.mjs", ["--check"], { cwd });
228
+ if (r.status !== 0) return refusal("tier-roles.mjs --check failed:", r);
229
+ return ok("every tier route resolves");
230
+ }
231
+
232
+ function metrics({ cwd }) {
233
+ const r = node("metrics-refresh.mjs", [], { cwd });
234
+ if (r.status !== 0) return refusal("metrics-refresh.mjs failed:", r);
235
+ return ok(withText("metrics-refresh.mjs ran", r));
236
+ }
237
+
238
+ function cockpit({ cwd, spendDir }) {
239
+ const args = [script("board.mjs"), "serve", "--open", ...(spendDir ? ["--spend-dir", spendDir] : [])];
240
+ let child;
241
+ try {
242
+ child = spawn(process.execPath, args, { cwd, detached: true, stdio: "ignore", env: gitEnv() });
243
+ } catch (e) {
244
+ return ok(`not launched: ${e.message}`);
245
+ }
246
+ // A launch that fails does so after this returns; nobody reads the event.
247
+ child.on("error", () => {});
248
+ child.unref();
249
+ return ok(child.pid === undefined ? "not launched" : `launched board.mjs serve, pid ${child.pid}`);
250
+ }
251
+
252
+ function rotate(ctx) {
253
+ // This run's own partial receipt is off disk while the rotation runs, so the
254
+ // archive cannot file it under the previous run's stamp. What the rotation
255
+ // finds beside the ledger is the previous run's receipt, held since startup.
256
+ rmSync(ctx.receiptPath, { force: true });
257
+ const restored = existsSync(ctx.held);
258
+ if (restored) renameSync(ctx.held, ctx.receiptPath);
259
+ const r = node("ledger.mjs", ["rotate"], { cwd: ctx.cwd });
260
+ if (restored && existsSync(ctx.receiptPath)) {
261
+ // Not archived. After a refusal it waits, held, for the next attempt; after
262
+ // a rotation that moved the ledger and not the receipt it is filed here,
263
+ // unless that name is taken.
264
+ const filed = join(ctx.fleetDir, receiptArchiveName(archiveStamp()));
265
+ renameSync(ctx.receiptPath, r.status === 0 && !existsSync(filed) ? filed : ctx.held);
266
+ }
267
+ if (r.status !== 0) return refusal("ledger.mjs rotate refused:", r);
268
+ const { controller } = readState(stateFileIn(ctx.fleetDir), NAME);
269
+ ctx.receipt.run = controller?.at ?? null;
270
+ const head = ctx.receipt.run === null ? "ledger rotated; no omp process above this run, so no controller record — a re-run is keyed on the session alone" : `ledger rotated, run ${ctx.receipt.run}`;
271
+ // What rotate says on stderr is the only account of rows it did not carry
272
+ // and a receipt it could not archive.
273
+ return ok([head, ...lines(r.stderr).map((l) => l.trim())].join("\n"));
274
+ }
275
+
276
+ function reclaim({ cwd, scratch }) {
277
+ const r = node("reclaim-scratch.mjs", ["--root", scratch, "--after-rotate", "--apply"], { cwd });
278
+ return ok(r.status === 0 ? "scratch reclaimed" : withText(`reclaim-scratch.mjs ${r.how}, not enforced`, r));
279
+ }
280
+
281
+ function recipe({ cwd }) {
282
+ const reads = [["install"], ["test", "--at", "origin/main"]].map((a) => ({ a, r: sh("derive-testcmd.sh", [".", ...a], { cwd }) }));
283
+ const broken = reads.filter(({ r }) => r.status === 3 || (r.status !== 0 && r.status !== 1));
284
+ if (broken.length > 0) {
285
+ return failed(broken.map(({ a, r }) => withText(`derive-testcmd.sh . ${a.join(" ")} ${r.how} — the cache's state is unknown, and deriving would not help`, r)).join("\n"));
286
+ }
287
+ const refused = reads.filter(({ r }) => r.status === 1);
288
+ if (refused.length > 0) {
289
+ return { status: "pending", output: [...refused.map(({ a, r }) => withText(`derive-testcmd.sh . ${a.join(" ")} refused:`, r)), "NEED derive-recipe"].join("\n") };
290
+ }
291
+ return ok(`Recipe cache valid: ${reads.map(({ r }) => lines(r.stdout).at(-1) ?? "").join(" ; ")}`);
292
+ }
293
+
294
+ // The ledger's rows, read through `ledger.mjs read` so the ledger keeps one
295
+ // parser. `{ error }` when the read did not answer, `{ rows }` otherwise.
296
+ function ledgerRows(cwd) {
297
+ const r = node("ledger.mjs", ["read"], { cwd });
298
+ if (r.status !== 0) return { error: withText(`ledger.mjs read ${r.how}`, r) };
299
+ try {
300
+ const { rows } = JSON.parse(r.stdout);
301
+ if (Array.isArray(rows) && rows.every((x) => typeof x === "string")) return { rows };
302
+ } catch {
303
+ // Falls through to the refusal below.
304
+ }
305
+ return { error: "ledger.mjs read printed no {rows}" };
306
+ }
307
+
308
+ const rowKey = (row) => row.split(/\s/)[0];
309
+
310
+ function foldIn({ cwd }) {
311
+ const list = run("gh", ["pr", "list", "--state", "open", "--json", "number,closingIssuesReferences", "--limit", String(PR_LIMIT)], {
312
+ cwd, env: { GH_REPO: "" }, timeoutMs: NETWORK_TIMEOUT_MS,
313
+ });
314
+ if (list.status !== 0) return refusal("gh pr list failed:", list);
315
+ let prs;
316
+ try {
317
+ prs = JSON.parse(list.stdout);
318
+ } catch (e) {
319
+ return failed(`could not parse gh pr list: ${e.message}`);
320
+ }
321
+ if (!Array.isArray(prs)) return failed("gh pr list did not print a JSON array");
322
+ if (prs.length >= PR_LIMIT) return failed(`gh pr list came back at its cap of ${PR_LIMIT} — it may hold more PRs than it showed, so none is folded in`);
323
+ const ledger = ledgerRows(cwd);
324
+ if (ledger.error) return failed(`${ledger.error} — which PRs a carried row names is unknown`);
325
+
326
+ // A PR a carried row names is queued by that row already, and a `row` write
327
+ // replaces the whole line, wiping the live tokens carried on it.
328
+ const named = new Set();
329
+ for (const row of ledger.rows) {
330
+ const { keyNum, pr } = rowNums(row);
331
+ if (keyNum !== null) named.add(keyNum);
332
+ if (pr !== null) named.add(pr);
333
+ }
334
+ const queued = [];
335
+ const advice = [];
336
+ let carried = 0;
337
+ for (const pr of [...prs].sort((a, b) => a.number - b.number)) {
338
+ if (named.has(pr.number)) {
339
+ carried += 1;
340
+ continue;
341
+ }
342
+ const issues = (pr.closingIssuesReferences ?? []).map((i) => i.number).filter(Number.isInteger);
343
+ if (issues.length === 0) {
344
+ advice.push(`NEED review PR#${pr.number} (closes no issue)`);
345
+ continue;
346
+ }
347
+ const closes = `closes ${issues.map((n) => `#${n}`).join(", ")}`;
348
+ const w = node("ledger.mjs", ["row", String(pr.number), `PR#${pr.number} · inherited (${closes})`], { cwd });
349
+ if (w.status !== 0) return refusal(`ledger.mjs row ${pr.number} failed:`, w);
350
+ queued.push(`queued PR#${pr.number} for review (${closes})`);
351
+ }
352
+ const head = `${queued.length} PR(s) queued, ${carried} already on a carried row, ${advice.length} closing no issue`;
353
+ return ok([head, ...queued, ...advice].join("\n"));
354
+ }
355
+
356
+ function stranded({ cwd }) {
357
+ const r = node("stranded.mjs", [], { cwd });
358
+ if (r.status !== 0) return refusal("stranded.mjs could not answer:", r);
359
+ let verdict;
360
+ try {
361
+ verdict = JSON.parse(r.stdout);
362
+ } catch (e) {
363
+ return failed(`could not parse stranded.mjs output: ${e.message}`);
364
+ }
365
+ if (!Array.isArray(verdict?.claims) || !Array.isArray(verdict?.carried)) return failed("stranded.mjs printed no {claims, carried}");
366
+ const ledger = ledgerRows(cwd);
367
+ if (ledger.error) return failed(`${ledger.error} — which claims are already resumed is unknown`);
368
+ const rowed = new Set(ledger.rows.map(rowKey));
369
+
370
+ const body = [];
371
+ const needs = [];
372
+ for (const c of verdict.claims) {
373
+ if (c.action !== "resume") body.push(`report #${c.n} — ${c.why}`);
374
+ else if (rowed.has(`#${c.n}`)) body.push(`#${c.n} resumed: its ledger row is there`);
375
+ else needs.push(`NEED resume #${c.n} ${c.worktree} ${c.branch}`);
376
+ }
377
+ for (const t of verdict.carried) body.push(`carried ${t.name} ${t.token} (row ${t.row ?? "none"})`);
378
+ const head = `prior ${verdict.prior}: ${verdict.claims.length} claim(s), ${verdict.carried.length} live token(s) carried`;
379
+ return { status: needs.length > 0 ? "pending" : "ok", output: [head, ...body, ...needs].join("\n") };
380
+ }
381
+
382
+ function shortlist({ cwd }) {
383
+ const r = node("shortlist.mjs", [], { cwd });
384
+ if (r.status !== 0) return refusal("shortlist.mjs refused:", r);
385
+ return ok("shortlist built");
386
+ }
387
+
388
+ const STEPS = {
389
+ "branch": branch, "fast-forward": fastForward, "pin": pin, "baseline": baseline, "preflight": preflight,
390
+ "ruleset": ruleset, "tier-roles": tierRoles, "metrics": metrics, "cockpit": cockpit, "rotate": rotate,
391
+ "reclaim": reclaim, "recipe": recipe, "fold-in": foldIn, "stranded": stranded, "shortlist": shortlist,
392
+ };
393
+
394
+ const STEP_NAMES = Object.keys(STEPS);
395
+
396
+ // ── the receipt ──────────────────────────────────────────────────────────────
397
+
398
+ // Null when there is no receipt; a receipt that is there and cannot be read or
399
+ // is not one throws, naming the file and why.
400
+ function readReceipt(path) {
401
+ let text;
402
+ try {
403
+ text = readFileSync(path, "utf8");
404
+ } catch (e) {
405
+ if (e.code === "ENOENT") return null;
406
+ throw new Error(`cannot read the receipt ${path} (${e.code ?? e.message}) — move it aside and re-run`);
407
+ }
408
+ let r;
409
+ try {
410
+ r = JSON.parse(text);
411
+ } catch (e) {
412
+ throw new Error(`the receipt ${path} is not JSON (${e.message}) — move it aside and re-run`);
413
+ }
414
+ const record = (x) => x !== null && typeof x === "object" && !Array.isArray(x);
415
+ if (!(record(r) && record(r.steps) && Object.hasOwn(r, "run") && typeof r.session === "string")) {
416
+ throw new Error(`the receipt ${path} has no steps, run and session — move it aside and re-run`);
417
+ }
418
+ return r;
419
+ }
420
+
421
+ function writeReceipt(path, receipt) {
422
+ const tmp = `${path}.${process.pid}.tmp`;
423
+ mkdirSync(dirname(path), { recursive: true });
424
+ writeFileSync(tmp, `${JSON.stringify(receipt, null, 2)}\n`);
425
+ renameSync(tmp, path);
426
+ }
427
+
428
+ const capped = (s) => (s.length > OUTPUT_MAX ? `…${s.slice(-(OUTPUT_MAX - 1))}` : s);
429
+
430
+ function main() {
431
+ const die = makeDie(NAME);
432
+ const F = defineFlags(die, {
433
+ flags: {
434
+ session: "value", "implementer-cap": "value", "reviewer-cap": "value", "plugin-checkout": "value",
435
+ "spend-dir": "value", workflow: "value", "declare-no-ci": "bool",
436
+ },
437
+ });
438
+ F.sweep();
439
+ F.stray();
440
+ const absent = (name) => F.arg(name) === null;
441
+ if (absent("session")) die("--session is required: the controller's session directory, `~/.omp/agent/sessions/<encoded-cwd>/<ISO>_<uuid>`");
442
+ const session = resolve(F.arg("session"));
443
+ try {
444
+ if (!statSync(session).isDirectory()) die(`--session ${session} is not a directory`);
445
+ } catch (e) {
446
+ if (e.code === undefined) throw e;
447
+ die(`--session ${session} is not readable (${e.code})`);
448
+ }
449
+ const positive = (name) => {
450
+ const n = F.numArg(name);
451
+ if (n !== null && n < 1) die(`--${name} needs a positive number, got ${n}`);
452
+ return n;
453
+ };
454
+ const caps = { impl: positive("implementer-cap"), review: positive("reviewer-cap") };
455
+ if (F.has("declare-no-ci") && !absent("workflow")) die("--workflow and --declare-no-ci are alternatives, not a pair");
456
+ const ci = F.has("declare-no-ci") ? "CI: declared absent (--declare-no-ci)" : absent("workflow") ? null : `CI: workflow ${F.arg("workflow")} (--workflow)`;
457
+ const pathOf = (name) => (absent(name) ? null : resolve(F.arg(name)));
458
+ const pluginCheckout = pathOf("plugin-checkout");
459
+ const spendDir = pathOf("spend-dir");
460
+
461
+ let fleetDir;
462
+ try {
463
+ fleetDir = fleetFile(null);
464
+ } catch (e) {
465
+ if (!(e instanceof FleetDirUnresolvable)) throw e;
466
+ die(e.message);
467
+ }
468
+ const cwd = dirname(fleetDir);
469
+ const top = run("git", ["rev-parse", "--show-toplevel"], { cwd: process.cwd() });
470
+ if (top.status !== 0 || realpathSync(top.stdout) !== realpathSync(cwd)) {
471
+ die(`run this from the main checkout ${cwd}${top.status === 0 ? `, not ${top.stdout}` : ""}`);
472
+ }
473
+ const root = node("scratch-root.mjs", [], { cwd });
474
+ if (root.status !== 0) {
475
+ process.stderr.write(`${NAME}: scratch-root.mjs ${root.how}\n${root.text}\n`);
476
+ process.exitCode = 3;
477
+ return;
478
+ }
479
+ const scratch = root.stdout;
480
+
481
+ const receiptPath = join(fleetDir, RECEIPT);
482
+ const held = join(fleetDir, HELD);
483
+ const state = readState(stateFileIn(fleetDir), NAME);
484
+ if (state.degraded) {
485
+ // The record decides whether a receipt is the previous run's, and a record
486
+ // that could not be read says nothing about that.
487
+ process.stderr.write(`${NAME}: ${stateFileIn(fleetDir)} ${state.degraded} — repair it so the controller record is intact; a receipt is not set aside on a record that could not be read\n`);
488
+ process.exitCode = 3;
489
+ return;
490
+ }
491
+ const record = state.controller;
492
+ const now = new Date().toISOString();
493
+ let previous;
494
+ try {
495
+ previous = readReceipt(receiptPath);
496
+ } catch (e) {
497
+ // A receipt that is there and cannot be used may record a rotation already
498
+ // done; starting over would run it a second time.
499
+ process.stderr.write(`${NAME}: ${e.message}\n`);
500
+ process.exitCode = 3;
501
+ return;
502
+ }
503
+ // A receipt belongs to a rotated run when the rotation wrote a controller
504
+ // record it can be keyed on, or, with no omp process above the run to write
505
+ // one, when its rotation is recorded `ok`. Either way it is this run's only
506
+ // if the record now holds the `at` it names and the session is the same.
507
+ const rotated = previous !== null && (previous.run !== null || previous.steps.rotate?.status === "ok");
508
+ const resumed = rotated && previous.run === (record?.at ?? null) && previous.session === session;
509
+ if (rotated && !resumed) {
510
+ if (existsSync(held)) {
511
+ process.stderr.write(`${NAME}: cannot hold the previous run's receipt for the rotation: ${held} already holds another\n`);
512
+ process.exitCode = 3;
513
+ return;
514
+ }
515
+ renameSync(receiptPath, held);
516
+ }
517
+
518
+ const receipt = { run: resumed ? previous.run : null, session, scratch, caps, steps: {} };
519
+ for (const name of STEP_NAMES) {
520
+ const was = resumed ? previous.steps[name] : undefined;
521
+ receipt.steps[name] = was?.status === "ok" ? was : { status: "pending", at: now, output: "not run" };
522
+ }
523
+
524
+ const ctx = { cwd, fleetDir, held, receipt, receiptPath, scratch, pluginCheckout, spendDir, ci };
525
+ const say = (line) => process.stdout.write(`${line}\n`);
526
+ let stop = null;
527
+ for (const name of STEP_NAMES) {
528
+ if (receipt.steps[name].status === "ok") {
529
+ say(`phase0: ${name}: ok (done earlier in this run)`);
530
+ continue;
531
+ }
532
+ let result;
533
+ try {
534
+ result = STEPS[name](ctx);
535
+ } catch (e) {
536
+ result = failed(`${name} threw: ${e.message}`);
537
+ }
538
+ receipt.steps[name] = { status: result.status, at: new Date().toISOString(), output: capped(result.output) };
539
+ try {
540
+ writeReceipt(receiptPath, receipt);
541
+ } catch (e) {
542
+ say(`phase0: ${name}: ${result.status}`);
543
+ process.stderr.write(`${NAME}: cannot write ${receiptPath}: ${e.message}\n`);
544
+ process.exitCode = 3;
545
+ return;
546
+ }
547
+ const [head, ...rest] = lines(result.output).filter((l) => !l.startsWith("NEED "));
548
+ say(`phase0: ${name}: ${result.status}${head ? ` — ${head}` : ""}`);
549
+ for (const l of rest) say(` ${l}`);
550
+ if (result.status === "failed" || result.status === "pending") {
551
+ stop = result.status;
552
+ break;
553
+ }
554
+ }
555
+
556
+ for (const name of STEP_NAMES) {
557
+ for (const l of lines(receipt.steps[name].output)) if (l.startsWith("NEED ")) say(l);
558
+ }
559
+ process.exitCode = stop === "failed" ? 3 : stop === "pending" ? 4 : 0;
560
+ }
561
+
562
+ if (isCLI(import.meta.url)) main();
@@ -3209,40 +3209,34 @@ correctly halted. Note what that costs to detect: two reads of the same worktree
3209
3209
  a minute apart showed *different* mutants, so a member's report and any single
3210
3210
  `git status` are each valid only at their instant. Its duties, in this order:
3211
3211
 
3212
- 1. **Audit the worktree** — run `worktree-audit.sh` (it takes no argument; it
3213
- audits every worktree in one pass, so find this worktree's row in its
3214
- output). Match the row by the resolved form of the worktree path you were
3215
- dispatched with — `realpath <abs-path>`, or `cd <abs-path> && pwd -P` —
3216
- never by that path as written: the row's `worktree` field is the physical
3217
- path `git worktree list` reports, so a spelling reached through a symlink
3218
- (macOS's `/tmp` and `/var/folders` are symlinks too) matches no row on a
3219
- healthy worktree. Two checks, each with the instrument that can answer it.
3220
- **Dirty:** the row's `dirty` field, or `git status --porcelain -unormal`
3221
- inside the worktree itself — the explicit mode, never bare `--porcelain`, or
3222
- `status.showUntrackedFiles = no` reads a dirty worktree as clean. The
3223
- row is the better read: in a worktree whose `.git` linkage is missing,
3224
- `git status` answers for the enclosing repo at rc 0, where the audit reports
3225
- the worktree unreadable. **Diverged:** the worktree's `HEAD` against your
3226
- dispatch pin — the cause block's head-equality check below. Neither
3227
- instrument above answers it: `git status --porcelain` reports no commits,
3228
- and the row's `ahead` is counted against `origin/main`, which a healthy
3229
- worktree on an open, unmerged PR is ahead of too, so it cannot answer this.
3230
- Three row shapes halt too, each named in the report with the script's
3231
- stderr line quoted where it prints one: `readable:false` with `null` counts
3232
- (`UNREADABLE: <wt> (<cause>)`) is *worktree unreadable*, `readable:false`
3233
- with zero counts (`MISSING on disk: <wt>`) is *worktree missing*, and no
3234
- row for this worktree at all is *worktree absent*. `git status` is no
3235
- substitute for the audit here — it answers the dirty check only, and a
3236
- finisher that cannot see the tree it labels cannot vouch for it. Dirty,
3237
- diverged, unreadable, missing or absent halts the finisher *here*, before
3238
- the label: it reports what it found and labels nothing. A finisher that
3212
+ 1. **Audit the worktree** by running one script, `finisher-audit.mjs` — the row
3213
+ lookup, the dirty check, the head-equality check and the cause derivation
3214
+ are one command, because each of them alone reads like the whole duty. Its
3215
+ exit code is the verdict of this duty:
3216
+ `~/.fleet/bin/fleet-run finisher-audit.mjs --worktree <abs-path> --pin <your dispatch pin>`,
3217
+ the path the one you were dispatched with, however it was spelled, and the
3218
+ pin the full SHA. It runs `worktree-audit.sh` itself and finds this
3219
+ worktree's row by its `realpath`, so a spelling reached through a symlink
3220
+ still finds a healthy worktree's row; it reads dirty from the row and from
3221
+ `git status --porcelain -unormal`; it compares the worktree's `HEAD` to your
3222
+ dispatch pin; and when the head differs from the pin it derives the cause
3223
+ from the reflog. It prints one JSON verdict,
3224
+ `{worktree, realpath, pin, head, cause, evidence}`. Exit 0, `cause` null, is
3225
+ the only result that means the worktree is clean at your pin. Exit 1 means
3226
+ `cause` names why not — `live-editor`, `rebase`, `past-pin`, `unreadable`,
3227
+ `missing`, `absent` or `other` — and exit 2 means the script could not
3228
+ look. Every non-zero exit halts the finisher *here*, before the label: it
3229
+ reports the verdict as printed and labels nothing, and an exit 2 is cause
3230
+ `other` with the line the script printed on stderr as its evidence. A
3231
+ finisher that cannot see the tree it labels cannot vouch for it, so none of
3232
+ the script's steps is run by hand to get past a halt. A finisher that
3239
3233
  verifies the dirt is harmless and labels anyway has substituted the rule's
3240
- purpose for the rule, and you find out at merge time. **Give it the cause block below,
3241
- verbatim** — a bare SHA mismatch names no cause, and the halt report needs
3242
- one. **Give it `<testCmd>` too** — the same string you passed the workflow
3243
- and the fix-applier — because duty 2's mutation gate runs it and nothing
3244
- else hands the finisher one; substituted with nothing it leaves that gate
3245
- no command at all.
3234
+ purpose for the rule, and you find out at merge time. **Give it the cause
3235
+ block below, verbatim** — it holds the script call and what each exit
3236
+ means, and a bare SHA mismatch names no cause. **Give it `<testCmd>` too** —
3237
+ the same string you passed the workflow and the fix-applier — because duty
3238
+ 2's mutation gate runs it and nothing else hands the finisher one;
3239
+ substituted with nothing it leaves that gate no command at all.
3246
3240
  2. **Confirm every deferral — and every claimed APPLY — has a home that outlives
3247
3241
  the merge.** The test is a durable home, not a tracker number: a tracker
3248
3242
  issue and a committed in-tree comment both qualify, and for a finding whose
@@ -3353,18 +3347,19 @@ a minute apart showed *different* mutants, so a member's report and any single
3353
3347
  `filed` failed twice — and anything
3354
3348
  it halted on — cause and evidence, below, never a bare "head moved". The
3355
3349
  cause is one word of the ledger's `halted:<cause>` vocabulary:
3356
- `live-editor`, `rebase` or `past-pin` from the cause block below,
3357
- `unreadable`, `missing` or `absent` from duty 1's row shapes, and `other`
3358
- for every other halt — the block's *anything else*, and a halt at duty 2,
3359
- duty 3, the instrument re-check or the CI gate. A `rebase` halt's report
3360
- carries the output of `git cherry <pin> HEAD origin/main`, run in the
3361
- worktree.
3350
+ `live-editor`, `rebase`, `past-pin`, `unreadable`, `missing` or `absent` as
3351
+ duty 1's verdict names it, and `other` for every other halt — that
3352
+ verdict's own `other`, and a halt at duty 2, duty 3, the instrument
3353
+ re-check or the CI gate. A duty 1 halt's report carries the verdict as
3354
+ printed, the JSON line, so a `rebase` halt's report carries the output of
3355
+ `git cherry <pin> HEAD origin/main` that its `evidence` holds.
3362
3356
 
3363
3357
  **Give the finisher the instrument re-check verbatim too.** Duty 1 and duty 2
3364
- each run a script the digest covers — `worktree-audit.sh` and `ledger.mjs`,
3365
- both under `plugin/scripts/` — and the label at duty 3 rests on what they
3366
- returned. The rule is stated once, at the top of this file, which no finisher
3367
- is dispatched to read, so it reaches one through this block or not at all:
3358
+ each run a script the digest covers — `finisher-audit.mjs` (which runs
3359
+ `worktree-audit.sh`) and `ledger.mjs`, both under `plugin/scripts/` — and the
3360
+ label at duty 3 rests on what they returned. The rule is stated once, at the
3361
+ top of this file, which no finisher is dispatched to read, so it reaches one
3362
+ through this block or not at all:
3368
3363
 
3369
3364
  > **Re-check the instrument set before you act on what duty 1 or duty 2 read,
3370
3365
  > and again before you add the label.**
@@ -3495,61 +3490,29 @@ guard — but its refusal costs a pass and leaves the label lying, which is your
3495
3490
  to clear either way, the same way: `label-off=` first, then the removal.
3496
3491
 
3497
3492
  A halt at step 1 reads identical from a bare SHA mismatch whatever caused it,
3498
- and the causes below are the ones seen so far, not a closed list. Give the
3499
- finisher this verbatim, so it derives the cause itself instead of asking anyone:
3500
-
3501
- > Worktree differs from your pin, or from what you last read. **Check
3502
- > head-equality first: `worktree HEAD == the SHA you were dispatched against` on
3503
- > a clean tree settles it.** Against your dispatch pin, never against
3504
- > `PR headRefOid`: a member that kept working and pushed after the pin matches
3505
- > the branch tip on a clean tree, so a headRefOid comparison reports "settled"
3506
- > over commits no reviewer read — the exact divergence this halt exists to
3507
- > catch. `headRefOid` is a second, separate read (pushed vs unpushed), never the
3508
- > equality the halt turns on. A rebase entry sitting at or behind the pin is
3509
- > that head's provenance — the implementer's own pre-push replay — not
3510
- > divergence from it, and needs no adjudication at all. Three finishers in one
3511
- > run adjudicated a reflog this one check had already answered. Only when the
3512
- > head differs from your pin, work out what happened. Each cause below is cheap
3513
- > and self-checkable, and `anything else` is a cause too, not a gap:
3493
+ and the causes `finisher-audit.mjs` names are the ones seen so far, not a
3494
+ closed list. Give the finisher this verbatim, so it gets the cause from one
3495
+ script instead of asking anyone:
3496
+
3497
+ > **Duty 1 is one script, and its exit code is your verdict.**
3498
+ > `~/.fleet/bin/fleet-run finisher-audit.mjs --worktree <abs-path> --pin <your dispatch pin>`
3499
+ > (the path you were dispatched with, and the full SHA). It finds your
3500
+ > worktree's row, reads whether the tree is dirty, compares the worktree's
3501
+ > `HEAD` to your pin, and when the head differs derives the cause from the
3502
+ > reflog. Exit 0, with `cause` null, is the only code that means the worktree is
3503
+ > clean at your pin. Exit 1 means `cause` is non-null: you are halted, and
3504
+ > `cause` is the word you name — `live-editor`, `rebase`, `past-pin`,
3505
+ > `unreadable`, `missing`, `absent` or `other`, and `other` is a cause too, not
3506
+ > a gap. Exit 2 means the script could not look: you are halted with cause
3507
+ > `other`, with the line it printed on stderr as the evidence.
3514
3508
  >
3515
- > - **Live editor.** `git status --porcelain -unormal` is dirty. Sample
3516
- > `git diff --stat` twice, a minute apart — diffstat growing means someone
3517
- > is still writing. Halt, name `live-editor`, report both samples.
3518
- > - **Rebase.** `git status --porcelain -unormal` is clean, head still differs
3519
- > from your pin. `git reflog` in the worktree: a `reset`/rebase entry near
3520
- > the move, not a plain `commit`, means the branch replayed onto a new
3521
- > base — its own commits on a new parent, content-identical only on a
3522
- > conflict-free replay.
3523
- > Halt, name `rebase`, report the reflog line and the output of
3524
- > `git cherry <pin> HEAD origin/main`, run in the worktree.
3525
- > - **Work past the pin.** `git status --porcelain -unormal` is clean, head
3526
- > still differs from your pin, and `git reflog` in the worktree reads a plain
3527
- > `commit` at the move — no `reset`/rebase entry there, any of those sitting
3528
- > at or behind the pin as provenance. A member kept working and committed
3529
- > after you were dispatched. Measured 2026-08-28 on one PR, where the finisher
3530
- > matched neither cause above and halted on its own judgement.
3531
- > Halt, name `past-pin`, and report **the commit, and whether it
3532
- > is pushed, unpushed, or unknown**: `git log -1 --format='%h %s'` names it,
3533
- > and `git ls-remote origin <branch>` answers the rest — a non-zero exit or
3534
- > any other failed read is **unknown**, never folded into "unpushed": the
3535
- > same rule `release-ticket.sh`'s own `ls-remote` names ("a failure here is
3536
- > an unknown answer, never a 'no'") and `reaping.md`'s remote check shares
3537
- > ("its failure is an unknown answer, never a 'not pushed'"). Only a
3538
- > successful read settles pushed vs not: equal to that commit means pushed,
3539
- > and a fresh finisher can audit it; a successful read that comes back
3540
- > without it means the commit exists only in that worktree, where no
3541
- > reviewer can reach it. Ask the remote, not the PR object, whose head lags
3542
- > a ref move — the same field `run-merge-bot.md` refuses to poll, for that
3543
- > reason. The controller's next move differs between pushed, unpushed, and
3544
- > unknown, so a report naming only two of the three is not a report of this
3545
- > cause.
3546
- > - **Anything else.** Matching none of the above is not a licence to report
3547
- > the mismatch as unexplained — that report is the one this block exists to
3548
- > make unnecessary, and it is where labelling over a moved head starts
3549
- > looking reasonable. Halt, name `other`, and name what you did find: both
3550
- > `git status --porcelain -unormal` samples, the `git reflog` line at the
3551
- > move, and both SHAs. A cause nobody has named yet is still a cause you
3552
- > observed, and your report is what gets it named.
3509
+ > The pin is the SHA you were dispatched against, never `PR headRefOid`: a
3510
+ > member that kept working and pushed after the pin matches the branch tip on a
3511
+ > clean tree, so a headRefOid comparison reports "settled" over commits no
3512
+ > reviewer read — the exact divergence this halt exists to catch. You do not
3513
+ > run any of the script's steps by hand to get past a halt or to second-guess
3514
+ > it. Put the verdict, the JSON line it printed, in your report as printed: its
3515
+ > `evidence` is what the controller resolves the halt from.
3553
3516
  >
3554
3517
  > Every cause halts, always — named or not, you never verify the dirt is
3555
3518
  > harmless and label over it, a rebase is not a fast-forward you get to accept,