@feigi/fleet-ctl 3.56.0 → 3.58.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.
@@ -5,7 +5,7 @@ model: "@slow:high"
5
5
  spawns: task
6
6
  ---
7
7
 
8
- You are a fleet fix-applier. Your brief — for a red-check fix, the prompt the controller writes by hand — names this dispatch's worktree, PR branch and test command, and the kind of work it is: a review's findings to apply or defer, a dispositions retry, a conflict hold to clear, or a red CI check to fix. The brief of a review and of a dispositions retry also names the scratch directory; a conflict hold's names none, so every rule below that cites `<scratch>` is for the kinds whose brief names one. The rules about findings — scope and refuters, the apply/defer split, the dispositions record and the report of the split and the deferral issues — are for a review and a dispositions retry: a conflict hold and a red-check fix have no review file, and what each says to report is in its brief. Every other rule below holds for every kind. The review file and review path that those rules cite are the ones your brief names. Where the rules write `<abs-path>`, `<branch>`, `<testCmd>`, `<scratch>`, `<pr>` or `<run>`, they name the value your brief gives you; a prompt you write for a refuter carries the value itself, never the placeholder.
8
+ You are a fleet fix-applier. Your brief names this dispatch's worktree, PR branch and test command, and the kind of work it is: a review's findings to apply or defer, a dispositions retry, a conflict hold to clear, or a red CI check to fix. The brief of a review and of a dispositions retry also names the scratch directory; a conflict hold's and a red-check fix's name none, so every rule below that cites `<scratch>` is for the kinds whose brief names one. The rules about findings — scope and refuters, the apply/defer split, the dispositions record and the report of the split and the deferral issues — are for a review and a dispositions retry: a conflict hold and a red-check fix have no review file, and what each says to report is in its brief. Every other rule below holds for every kind. The review file and review path that those rules cite are the ones your brief names. Where the rules write `<abs-path>`, `<branch>`, `<testCmd>`, `<scratch>`, `<pr>` or `<run>`, they name the value your brief gives you; a prompt you write for a refuter carries the value itself, never the placeholder.
9
9
 
10
10
  **`edit` and `read` resolve a bare relative path against the SESSION ROOT —
11
11
  the controller's own main checkout — not against that worktree and not
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@feigi/fleet-ctl",
3
- "version": "3.56.0",
3
+ "version": "3.58.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": {
@@ -6,7 +6,7 @@
6
6
  //
7
7
  // Roles: implementer, fix-applier, finisher, merge-bot, review-runner,
8
8
  // recipe-deriver. A role with kinds (fix-applier: review, conflict,
9
- // dispositions-retry; finisher: fresh, repair) requires --kind; a role
9
+ // dispositions-retry, red-check; finisher: fresh, repair) requires --kind; a role
10
10
  // without them refuses it as an unknown flag.
11
11
  //
12
12
  // OUTPUT. The brief on stdout and nothing else. With --json the payload
@@ -47,6 +47,16 @@
47
47
  // never when. Pruned to the live set on every tick, so a settled
48
48
  // member's stamp does not outlive it. Carried, never written, by
49
49
  // the heartbeat and by ledger.mjs.
50
+ // applied fleet-tick only, and only under --apply. {run, reapAfter}: the
51
+ // merge-bot numbers whose `merge-bot-<n>=done` the tick has already
52
+ // run reap.sh and reclaim-scratch.mjs after, and the controller
53
+ // record's `at` they belong to. Written only under a record: with
54
+ // none, nothing tells one run from the next. Merge-bot numbering
55
+ // restarts at 1 in a run that carries no bot forward, and this
56
+ // file outlives the rotation, so a list whose `run` is not the
57
+ // current record's `at` is the previous run's and names nothing in
58
+ // this one. Carried, never written, by the heartbeat and by
59
+ // ledger.mjs.
50
60
  //
51
61
  // One writer per key. A key two scripts wrote would need locking to be
52
62
  // correct, and none of them is in a position to hold one. That holds per key,
@@ -119,7 +129,7 @@ export function readState(path, name) {
119
129
  // to judge and nothing to report. A zeroed mark would date the beat to the
120
130
  // epoch and read as decades overdue on a run that has simply not started
121
131
  // one — the cry-wolf direction this key must never fail in.
122
- const fresh = { quiet: 0, elapsed: 0, digest: "", beat: null, ticked: null, acted: null, controller: null, seen: {}, rest: {} };
132
+ const fresh = { quiet: 0, elapsed: 0, digest: "", beat: null, ticked: null, acted: null, controller: null, seen: {}, applied: null, rest: {} };
123
133
  // The same state, flagged: the file EXISTS and could not be used. A caller
124
134
  // that acts on the absence of a record — ledger.mjs rotate — must tell this
125
135
  // from `fresh`, which is a run that has simply not written one yet. The
@@ -227,7 +237,18 @@ export function readState(path, name) {
227
237
  for (const [member, at] of Object.entries(v)) if (Number.isInteger(at) && at > 0) out[member] = at;
228
238
  return out;
229
239
  };
230
- const { quiet, elapsed, digest, beat, ticked, acted, controller, seen, ...rest } = parsed;
240
+ // `applied` is validated as a unit for the controller record's reason: a
241
+ // list is only read against the run it names, so one whose `run` is not a
242
+ // positive integer belongs to no run and reads as absent. Absent is the
243
+ // safe direction: the duties it records are idempotent, and the next
244
+ // --apply tick runs them again. A junk entry in the list costs that entry
245
+ // alone.
246
+ const done = (v) => {
247
+ if (!isRecord(v) || !Array.isArray(v.reapAfter)) return null;
248
+ if (!(Number.isInteger(v.run) && v.run > 0)) return null;
249
+ return { run: v.run, reapAfter: v.reapAfter.filter((n) => Number.isInteger(n) && n > 0) };
250
+ };
251
+ const { quiet, elapsed, digest, beat, ticked, acted, controller, seen, applied, ...rest } = parsed;
231
252
  // A controller key that ctl() rejects is a record someone wrote and nobody
232
253
  // can judge, not the absence of one — announced like the other degraded
233
254
  // causes, and flagged.
@@ -245,6 +266,7 @@ export function readState(path, name) {
245
266
  acted: tick(acted),
246
267
  controller: record,
247
268
  seen: stamps(seen),
269
+ applied: done(applied),
248
270
  rest,
249
271
  };
250
272
  }
@@ -301,6 +323,9 @@ export function writeState(path, name, prev, patch) {
301
323
  // `seen` is fleet-tick's, and the heartbeat and ledger.mjs write this file
302
324
  // too: carried the same way, so neither erases the ages the tick keeps.
303
325
  ...(prev.seen && Object.keys(prev.seen).length > 0 ? { seen: prev.seen } : {}),
326
+ // `applied` too: a heartbeat write that dropped it would have the next
327
+ // --apply tick reap again after every merge pass it already reaped after.
328
+ ...(prev.applied ? { applied: prev.applied } : {}),
304
329
  ...patch,
305
330
  };
306
331
  const tmp = `${path}.${process.pid}.tmp`;
@@ -207,9 +207,10 @@ function implementers(s, left) {
207
207
  }
208
208
  // Held until tier-check.mjs has run on the newest implementer and written
209
209
  // its verdict to the ledger — a Pull on top of an unchecked
210
- // dispatch repeats whatever it got wrong. Running the check is the
211
- // controller's own step, so it is asked to act, with the command in the
212
- // detail.
210
+ // dispatch repeats whatever it got wrong. `--apply` runs the check itself
211
+ // before this row is read; the row is the controller's to act on when the
212
+ // tick ran without `--apply`, or the check wrote no verdict, so it asks to
213
+ // act, with the command in the detail.
213
214
  if (s.tierUnchecked.length) {
214
215
  return row(`HOLD (tier unchecked ${s.tierUnchecked.join(" ")})`, { acts: true, extra: tierCheckStep(s.tierUnchecked, s.phase0?.session) });
215
216
  }
@@ -886,6 +887,9 @@ export function deriveRun({ rows, dispatched, drain }, prs, closed = new Set(),
886
887
  implLive: live("impl"),
887
888
  fixLive: live("fix-pr"),
888
889
  mergeBotLive,
890
+ // The number of every merge bot settled `done`: each is a merge pass
891
+ // `--apply` reaps and reclaims after, once (reapDue).
892
+ mergeBotDone: all.filter((m) => m.family === "merge-bot" && m.outcome === "done").map((m) => m.number).sort(asc),
889
893
  reviewsLive: liveReviews.length,
890
894
  // The in-flight reviews of PRs the open list does not carry: the ones
891
895
  // `finished` could retire, so the caller asks gh about these and no others.
@@ -1073,20 +1077,77 @@ export function livenessLines({ live, seen, thresholds, now }) {
1073
1077
  return out;
1074
1078
  }
1075
1079
 
1080
+ // --apply's pure half. The merge-bot numbers `applied.reapAfter` names for
1081
+ // THIS run: none when its `run` is not the controller record's `at`, since
1082
+ // merge-bot numbering restarts with a run and the state file outlives it
1083
+ // (fleet-state.mjs's `applied`). `controllerAt` is null with no record, and
1084
+ // with no record nothing tells this run from the one before it: a list then
1085
+ // names nothing, and the sweeps run again on the next tick.
1086
+ export function reapedAfter(applied, controllerAt) {
1087
+ return applied !== null && controllerAt != null && applied.run === controllerAt ? applied.reapAfter : [];
1088
+ }
1089
+
1090
+ // The merge passes owed their reap and reclaim: every merge bot settled
1091
+ // `done` that reapedAfter() does not name.
1092
+ export function reapDue(done, applied, controllerAt) {
1093
+ const ran = new Set(reapedAfter(applied, controllerAt));
1094
+ return done.filter((n) => !ran.has(n));
1095
+ }
1096
+
1097
+ // The implementers the tick would print `HOLD (tier unchecked …)` for: read
1098
+ // off the rows reconcile() computed, so whatever outranks that hold — the
1099
+ // drain, a mismatch, phase 0, the main checkout — outranks the check too.
1100
+ export function tierCheckDue(rows, unchecked) {
1101
+ return rows.some((r) => r.role === "implementers" && r.action.startsWith("HOLD (tier unchecked ")) ? unchecked : [];
1102
+ }
1103
+
1104
+ // The one JSON line a receipt-printing script ends on, or null.
1105
+ function receiptOf(stdout) {
1106
+ try {
1107
+ const r = JSON.parse(String(stdout).trim().split("\n").at(-1));
1108
+ return r !== null && typeof r === "object" ? r : null;
1109
+ } catch {
1110
+ return null;
1111
+ }
1112
+ }
1113
+
1114
+ // reap.sh's receipt as `reaped <k>, kept <m>, worktreesRemoved <w>`, or null
1115
+ // for a stdout that carries none. A receipt with warnings adds `warnings
1116
+ // <n>: <first note>`: reap.sh exits 0 with them, and this line is the only
1117
+ // place an unattended tick can say so.
1118
+ export function reapSummary(stdout) {
1119
+ const r = receiptOf(stdout);
1120
+ if (r === null || ![r.reaped, r.kept, r.worktreesRemoved].every(Array.isArray)) return null;
1121
+ const warned = Array.isArray(r.warnings) ? r.warnings : [];
1122
+ const first = warned[0]?.note;
1123
+ return `reaped ${r.reaped.length}, kept ${r.kept.length}, worktreesRemoved ${r.worktreesRemoved.length}`
1124
+ + (warned.length ? `, warnings ${warned.length}${typeof first === "string" ? `: ${first}` : ""}` : "");
1125
+ }
1126
+
1127
+ // reclaim-scratch.mjs's receipt as `removed <k>, kept <m>, failed <f>`, or
1128
+ // null. A removal that failed is in the receipt and exits 0: it is reported
1129
+ // here, and the pass still counts as reclaimed after.
1130
+ export function reclaimSummary(stdout) {
1131
+ const r = receiptOf(stdout);
1132
+ if (r === null || ![r.removed, r.kept, r.failed].every(Array.isArray)) return null;
1133
+ return `removed ${r.removed.length}, kept ${r.kept.length}, failed ${r.failed.length}`;
1134
+ }
1135
+
1076
1136
  // --------------------------------------------------------------------------
1077
1137
  // I/O. Everything below runs only as a CLI — importing this file must never
1078
1138
  // parse argv or touch the network, or the pure half stops being unit-testable.
1079
1139
 
1080
1140
  import { execFileSync, spawnSync } from "node:child_process";
1081
1141
  import { createHash } from "node:crypto";
1082
- import { readFileSync } from "node:fs";
1142
+ import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
1143
+ import { tmpdir } from "node:os";
1083
1144
  import { dirname, join } from "node:path";
1084
1145
  import { fileURLToPath } from "node:url";
1085
1146
  import { isCLI } from "./is-cli.mjs";
1086
1147
  import { parseArgs } from "node:util";
1087
1148
  import { makeDie, isDigits } from "./arg.mjs";
1088
1149
  import { gitEnv } from "./git-env.mjs";
1089
- import { fleetFile, FleetDirUnresolvable } from "./fleet-dir.mjs";
1150
+ import { fleetFile, FleetDirUnresolvable, scratchRoot } from "./fleet-dir.mjs";
1090
1151
  import { statePath, readState, writeState, assessBeat, isStalled, isReported, stallReport, stallOwner } from "./fleet-state.mjs";
1091
1152
  import { checkMainCheckout, describe } from "./main-checkout.mjs";
1092
1153
  import { readRunReceipt, phase0Gate } from "./phase0-receipt.mjs";
@@ -1149,6 +1210,13 @@ const OPTIONS = {
1149
1210
  // unattended night affordable. Opt-in because folding is wrong on an edge:
1150
1211
  // a controller that just acted needs the full rows.
1151
1212
  "fold-unchanged": { type: "boolean", default: false },
1213
+ // `--apply` runs the idempotent follow-ups whose trigger the ledger and the
1214
+ // state file show, before the rows: reap.sh and reclaim-scratch.mjs after
1215
+ // every merge pass settled `done`, and tier-check.mjs on every implementer
1216
+ // the tick would hold as unchecked. It never dispatches, never settles a
1217
+ // member and writes no ledger row but through those scripts. Without it the
1218
+ // tick is read-only.
1219
+ apply: { type: "boolean", default: false },
1152
1220
  // Path override, for tests. An empty value cannot be told from an absent one
1153
1221
  // under parseArgs, and no path is legitimately empty, so empty resolves to
1154
1222
  // the default.
@@ -1184,7 +1252,7 @@ function options() {
1184
1252
  return {
1185
1253
  implCap: positive("implementer-cap"), reviewerCap,
1186
1254
  maxReviews: values["max-reviews"] === undefined ? reviewerCap : positive("max-reviews"),
1187
- fold: values["fold-unchanged"], state: values.state || statePath(NAME),
1255
+ fold: values["fold-unchanged"], apply: values.apply, state: values.state || statePath(NAME),
1188
1256
  liveness: Object.fromEntries(Object.entries(LIVENESS_FLAGS).map(([family, flag]) => [family, positive(flag)])),
1189
1257
  };
1190
1258
  }
@@ -1411,6 +1479,94 @@ function refresh() {
1411
1479
  return { ok: true, ...p };
1412
1480
  }
1413
1481
 
1482
+ // A sibling script --apply runs, the way refresh() runs shortlist.mjs: stdout
1483
+ // kept for its receipt, stderr captured so only a failure's last line rides
1484
+ // along. A `.mjs` runs under this node, reap.sh by its own shebang.
1485
+ function runSibling(file, args) {
1486
+ const opts = { encoding: "utf8", maxBuffer: MAX_BUFFER, stdio: ["ignore", "pipe", "pipe"] };
1487
+ return file.endsWith(".mjs")
1488
+ ? spawnSync(process.execPath, [join(SCRIPT_DIR, file), ...args], opts)
1489
+ : spawnSync(join(SCRIPT_DIR, file), args, opts);
1490
+ }
1491
+
1492
+ // One duty's line: `APPLIED <label>: <receipt summary>`, or `APPLY FAILED
1493
+ // <duty>: <why>` for a script that did not exit 0 or printed no receipt.
1494
+ // True when it applied.
1495
+ function reportDuty(r, { label, duty, what, summarise }) {
1496
+ const ran = !r.error && r.status === 0;
1497
+ const summary = ran ? summarise(r.stdout) : null;
1498
+ console.log(summary !== null ? `APPLIED ${label}: ${summary}`
1499
+ : `APPLY FAILED ${duty}: ${ran ? `${what} printed no receipt` : failure(r, what)}`);
1500
+ return summary !== null;
1501
+ }
1502
+
1503
+ // Reap, then reclaim, after the merge passes in `due` — once however many
1504
+ // there are, since both sweep the whole repository and scratch root rather
1505
+ // than one pass's share. Reclaim runs whether or not reap did: neither reads
1506
+ // the other's result. True only when both applied, the one case `due` is
1507
+ // recorded as reaped after; otherwise the next --apply tick runs both again.
1508
+ function applyReap(due) {
1509
+ const label = `reap after ${due.map((n) => `merge-bot-${n}`).join(" ")}`;
1510
+ const reaped = reportDuty(runSibling("reap.sh", ["--apply"]), { label, duty: "reap", what: "reap.sh", summarise: reapSummary });
1511
+ let root;
1512
+ try {
1513
+ root = scratchRoot();
1514
+ } catch (e) {
1515
+ if (!(e instanceof FleetDirUnresolvable)) throw e;
1516
+ console.log(`APPLY FAILED reclaim: ${e.message}`);
1517
+ return false;
1518
+ }
1519
+ const reclaimed = reportDuty(runSibling("reclaim-scratch.mjs", ["--root", root, "--apply"]),
1520
+ { label: "reclaim", duty: "reclaim", what: "reclaim-scratch.mjs", summarise: reclaimSummary });
1521
+ return reaped && reclaimed;
1522
+ }
1523
+
1524
+ // tier-check.mjs's verdict by its exit status, each one a token the check
1525
+ // writes on the ledger itself. Exit 2 writes nothing. Exit 1 is the check's
1526
+ // mismatch and also what node exits with on a throw, so it stands as a
1527
+ // verdict only once the ledger carries it.
1528
+ const TIER_VERDICTS = new Map([[0, "tier-ok"], [1, "tier-mismatch"], [3, "tier-unverifiable"]]);
1529
+
1530
+ // Whether the ledger holds tier-check.mjs's mismatch for `member`: the token
1531
+ // on a row, or the member itself settled `tier-mismatch`.
1532
+ function mismatchOnLedger(member) {
1533
+ const { rows, dispatched } = readLedger();
1534
+ return [...rows, ...dispatched].some((text) => text.split(/\s+/)
1535
+ .some((tok) => tok === `${member}=tier-mismatch` || tok.startsWith(`tier-mismatch=${member}:`)));
1536
+ }
1537
+
1538
+ // tier-check.mjs on each member, a batch of one apiece in a temporary file,
1539
+ // `session` the phase-0 receipt's — left out when the receipt records none,
1540
+ // which the check refuses by name. True when any check wrote a verdict, so
1541
+ // the caller reads the ledger it changed again.
1542
+ function applyTierChecks(members, session) {
1543
+ let wrote = false;
1544
+ for (const member of members) {
1545
+ const dir = mkdtempSync(join(tmpdir(), "fleet-tick-tier-"));
1546
+ let r;
1547
+ try {
1548
+ const batch = join(dir, "batch.json");
1549
+ writeFileSync(batch, JSON.stringify([session === null ? { member } : { member, session }]));
1550
+ r = runSibling("tier-check.mjs", ["--batch", batch]);
1551
+ } finally {
1552
+ rmSync(dir, { recursive: true, force: true });
1553
+ }
1554
+ const verdict = r.error ? undefined : TIER_VERDICTS.get(r.status);
1555
+ if (verdict !== undefined && (r.status !== 1 || mismatchOnLedger(member))) {
1556
+ wrote = true;
1557
+ console.log(`APPLIED tier-check ${member}: ${verdict}`);
1558
+ } else if (!r.error && r.status === 2) {
1559
+ // No verdict — most often a live member with no transcript yet — so
1560
+ // the hold stands, and the check's own line says why.
1561
+ const last = String(r.stderr ?? "").trim().split("\n").at(-1);
1562
+ console.log(`APPLIED tier-check ${member}: no verdict${last ? ` — ${last}` : ""}`);
1563
+ } else {
1564
+ console.log(`APPLY FAILED tier-check ${member}: ${failure(r, "tier-check.mjs")}`);
1565
+ }
1566
+ }
1567
+ return wrote;
1568
+ }
1569
+
1414
1570
  // How many tickets a dead run stranded. `in-progress` is the claim label
1415
1571
  // claim-ticket.sh adds and candidates.mjs's query EXCLUDES — which is why a
1416
1572
  // stranded ticket is invisible to the next run's scans, and why this count is
@@ -1450,8 +1606,23 @@ function controllerState(controller) {
1450
1606
  }
1451
1607
  }
1452
1608
 
1609
+ // The run off the ledger, with the closed tickets and finished reviews gh
1610
+ // says the ledger cannot. A ledger it cannot read refuses the tick.
1611
+ function readRun(prs) {
1612
+ try {
1613
+ const ledger = readLedger();
1614
+ const run = deriveRun(ledger, prs);
1615
+ const closed = closedTickets(run.tierMismatch);
1616
+ const finished = finishedReviewPrs(run.reviewsOffList);
1617
+ return closed.size || finished.size ? deriveRun(ledger, prs, closed, finished) : run;
1618
+ } catch (e) {
1619
+ if (e instanceof LedgerError) die(e.message);
1620
+ throw e;
1621
+ }
1622
+ }
1623
+
1453
1624
  function main() {
1454
- const { fold, state: path, liveness, ...caps } = options();
1625
+ const { fold, apply, state: path, liveness, ...caps } = options();
1455
1626
  const listPath = shortlistPath();
1456
1627
  const current = readShortlist(listPath);
1457
1628
  // Beside the shortlist, off the same git probe rather than a second one.
@@ -1485,18 +1656,49 @@ function main() {
1485
1656
  }
1486
1657
 
1487
1658
  // Every read happens before anything prints: a partial tick is worse than no
1488
- // tick, because half a reconcile still reads like a reconcile.
1659
+ // tick, because half a reconcile still reads like a reconcile. The APPLIED
1660
+ // lines are the exception, printed as each duty runs: they say what was
1661
+ // done, which is true whether or not the reconcile after them lands.
1489
1662
  const prs = openPrs();
1490
- let run;
1491
- try {
1492
- const ledger = readLedger();
1493
- run = deriveRun(ledger, prs);
1494
- const closed = closedTickets(run.tierMismatch);
1495
- const finished = finishedReviewPrs(run.reviewsOffList);
1496
- if (closed.size || finished.size) run = deriveRun(ledger, prs, closed, finished);
1497
- } catch (e) {
1498
- if (e instanceof LedgerError) die(e.message);
1499
- throw e;
1663
+ let run = readRun(prs);
1664
+
1665
+ // The main checkout against the run's baseline, on every tick — the
1666
+ // backstop for what member-write-guard cannot see. Never a refusal of the tick:
1667
+ // every answer but `clean` is a hold on the dispatching rows plus one line
1668
+ // saying why, so the rest of the run keeps reporting.
1669
+ const mainCheckout = checkMainCheckout();
1670
+ // This run's phase 0, off its receipt: unfinished holds the same rows the
1671
+ // main checkout does, and never refuses the tick either. Judged against
1672
+ // the controller record this tick started from, and against whether that
1673
+ // record's process is still there: a finished receipt of the run before
1674
+ // carries the same `at` until this run's rotation writes the next.
1675
+ const receipt = readRunReceipt();
1676
+ const phase0 = phase0Gate(receipt.read, {
1677
+ path: receipt.path, controllerAt: controller?.at, controller: controllerState(controller),
1678
+ });
1679
+
1680
+ if (apply) {
1681
+ // Reap and reclaim after every merge pass settled `done` since the last
1682
+ // time they ran. Recorded only once both applied, on a fresh read of the
1683
+ // state file so nothing the heartbeat wrote meanwhile is reverted, never
1684
+ // onto a file that could not be read, and never with no controller
1685
+ // record: nothing could tell a list recorded then from the next run's.
1686
+ const run0 = controller?.at ?? null;
1687
+ const due = reapDue(run.mergeBotDone, priorState.applied, run0);
1688
+ if (due.length && applyReap(due) && run0 !== null) {
1689
+ const now = readState(path, NAME);
1690
+ if (!now.degraded) {
1691
+ writeState(path, NAME, now, { applied: { run: run0, reapAfter: [...new Set([...reapedAfter(now.applied, run0), ...due])] } });
1692
+ }
1693
+ }
1694
+ // The tier check, on exactly the members the implementer row would hold
1695
+ // as unchecked — that row reads the same before the refresh as after it.
1696
+ // A verdict written changes the ledger, so the run is read again.
1697
+ const unchecked = tierCheckDue(reconcile({
1698
+ ...caps, ...run, heads: unclaimed(current.entries, run), supply: current.scanned, dropped: current.dropped,
1699
+ shortlistStatus: current.status, refresh: null, mainCheckout, phase0, router,
1700
+ }), run.tierUnchecked);
1701
+ if (unchecked.length && applyTierChecks(unchecked, phase0.session)) run = readRun(prs);
1500
1702
  }
1501
1703
 
1502
1704
  // Pull from the current file first; refresh when it is short, absent, an
@@ -1528,21 +1730,6 @@ function main() {
1528
1730
  }
1529
1731
  }
1530
1732
 
1531
- // The main checkout against the run's baseline, on every tick — the
1532
- // backstop for what member-write-guard cannot see. Never a refusal of the tick:
1533
- // every answer but `clean` is a hold on the dispatching rows plus one line
1534
- // saying why, so the rest of the run keeps reporting.
1535
- const mainCheckout = checkMainCheckout();
1536
- // This run's phase 0, off its receipt: unfinished holds the same rows the
1537
- // main checkout does, and never refuses the tick either. Judged against
1538
- // the controller record this tick started from, and against whether that
1539
- // record's process is still there: a finished receipt of the run before
1540
- // carries the same `at` until this run's rotation writes the next.
1541
- const receipt = readRunReceipt();
1542
- const phase0 = phase0Gate(receipt.read, {
1543
- path: receipt.path, controllerAt: controller?.at, controller: controllerState(controller),
1544
- });
1545
-
1546
1733
  const rows = reconcile({
1547
1734
  ...caps, ...run, heads, supply, dropped, shortlistStatus: current.status, refresh: fresh, mainCheckout, phase0, router,
1548
1735
  });
@@ -22,10 +22,11 @@
22
22
  import { createHash } from "node:crypto";
23
23
 
24
24
  // How an archive beside the ledger is named. `ledger.mjs rotate` files the
25
- // ledger as `ledger.<stamp>.md` and the two run receipts, the phase-0 one as
25
+ // ledger as `ledger.<stamp>.md`, the two run receipts, the phase-0 one as
26
26
  // `phase0.<stamp>.json` and the end-of-run one as `closeout.<stamp>.json`,
27
- // under one stamp. `phase0.mjs` files a phase-0 receipt the rotation left
28
- // behind the same way, so the format lives here once.
27
+ // and the briefs directory as `briefs.<stamp>`, all under one stamp.
28
+ // `phase0.mjs` files a phase-0 receipt the rotation left behind the same
29
+ // way, so the format lives here once.
29
30
  const RECEIPT_STEM = "phase0";
30
31
  export const RECEIPT = `${RECEIPT_STEM}.json`;
31
32
  export const archiveStamp = () => new Date().toISOString().replace(/\.\d{3}Z$/, "Z").replaceAll(":", "");
@@ -33,14 +34,20 @@ export const receiptArchiveName = (stamp) => `${RECEIPT_STEM}.${stamp}.json`;
33
34
  const CLOSEOUT_STEM = "closeout";
34
35
  export const CLOSEOUT_RECEIPT = `${CLOSEOUT_STEM}.json`;
35
36
  export const closeoutArchiveName = (stamp) => `${CLOSEOUT_STEM}.${stamp}.json`;
37
+ // The directory dispatch-prompt.mjs renders a member's brief into, beside the
38
+ // ledger, archived by the same rotate under the same stamp: `briefs.<stamp>`.
39
+ export const BRIEFS = "briefs";
40
+ export const briefsArchiveName = (stamp) => `${BRIEFS}.${stamp}`;
36
41
 
37
42
  // The outcome vocabulary, verbatim from the spec. A word is matched exactly,
38
43
  // except the three that carry a value, which match OUTCOME_PATTERNS below.
44
+ // `role` is the dispatch-prompt.mjs template a member of the family is
45
+ // rendered from, the one its brief's sidecar must name.
39
46
  const FAMILIES = {
40
- impl: { label: "impl-N", bound: "ticket", outcomes: ["PR#M", "bailed", "released", "killed", "tier-mismatch"] },
41
- "fix-pr": { label: "fix-pr-M", bound: "pr", outcomes: ["applied:<head>", "no-op", "failed", "killed"] },
42
- "finisher-pr": { label: "finisher-pr-M", bound: "pr", outcomes: ["labelled", "failed", "killed", "halted:<cause>"] },
43
- "merge-bot": { label: "merge-bot-n", bound: null, outcomes: ["done", "killed"] },
47
+ impl: { label: "impl-N", bound: "ticket", role: "implementer", outcomes: ["PR#M", "bailed", "released", "killed", "tier-mismatch"] },
48
+ "fix-pr": { label: "fix-pr-M", bound: "pr", role: "fix-applier", outcomes: ["applied:<head>", "no-op", "failed", "killed"] },
49
+ "finisher-pr": { label: "finisher-pr-M", bound: "pr", role: "finisher", outcomes: ["labelled", "failed", "killed", "halted:<cause>"] },
50
+ "merge-bot": { label: "merge-bot-n", bound: null, role: "merge-bot", outcomes: ["done", "killed"] },
44
51
  };
45
52
  // Every family parseMember can yield: MEMBER below is built from this list,
46
53
  // so every family it matches has an entry here by construction.
@@ -98,6 +105,36 @@ export function memberTokens(text) {
98
105
  return text.split(/\s+/).filter(Boolean).map(parseToken).filter(Boolean);
99
106
  }
100
107
 
108
+ /** The dispatch-prompt.mjs role a member of `family` is rendered as. */
109
+ export function memberRole(family) {
110
+ return FAMILIES[family].role;
111
+ }
112
+
113
+ // A `## Dispatched` entry is a member token, followed by `brief=<hash>` when
114
+ // `ledger.mjs dispatch` recorded the brief the member was dispatched with:
115
+ // the first 8 hex of the sha256 the brief's sidecar carries. `settle`
116
+ // rewrites the token and keeps the word beside it.
117
+ const BRIEF_WORD = /^brief=([0-9a-f]{8})$/;
118
+
119
+ /**
120
+ * `{token, brief}` for one `## Dispatched` entry: the member token and the
121
+ * brief's hash, or null for an entry without one. An entry that is not a
122
+ * member token plus one well-formed `brief=` word is returned whole as
123
+ * `token`, so a reader parsing it with parseToken() refuses it exactly as it
124
+ * refuses any other entry this grammar cannot parse.
125
+ */
126
+ export function parseDispatchedEntry(entry) {
127
+ const words = entry.split(" ");
128
+ const m = words.length === 2 ? BRIEF_WORD.exec(words[1]) : null;
129
+ if (m === null || parseToken(words[0]) === null) return { token: entry, brief: null };
130
+ return { token: words[0], brief: m[1] };
131
+ }
132
+
133
+ /** The `## Dispatched` entry for `token`, with `brief=<brief>` unless brief is null. */
134
+ export function dispatchedEntry(token, brief) {
135
+ return brief === null ? token : `${token} brief=${brief}`;
136
+ }
137
+
101
138
  // `PR#<n>` as a word of a row's text, `PR #<n>` too.
102
139
  const PR_MENTION = /\bPR\s*#(\d+)\b/;
103
140
 
@@ -12,7 +12,8 @@
12
12
  // `dispatch`, `settle`, `review` and `drain` exist so a reader can derive
13
13
  // every liveness count from this file alone, rather than from row text a
14
14
  // controller typed by hand: `dispatch` writes a member's live token onto its
15
- // row and appends it to `## Dispatched`, `settle` rewrites that token to
15
+ // row and appends it to `## Dispatched` with `brief=<hash>`, the brief it
16
+ // refuses to dispatch without, `settle` rewrites that token to
16
17
  // `<member>=<outcome>` in both places (an implementer's settle to `PR#M` also
17
18
  // folds the PR's own `#M` row into its ticket's), `review` appends a PR's
18
19
  // `review=`/`reviewed=` tokens to the PR's row, and `drain` writes the
@@ -42,12 +43,13 @@
42
43
  // the rule).
43
44
 
44
45
  import { readFileSync, writeFileSync, mkdirSync, existsSync, renameSync, unlinkSync, linkSync } from "node:fs";
46
+ import { createHash } from "node:crypto";
45
47
  import { dirname, resolve, join, basename } from "node:path";
46
48
  import { fileURLToPath } from "node:url";
47
49
  import { spawnSync, execFileSync } from "node:child_process";
48
50
  import { makeDie, isFlagLike, hasEqualsForm, isDigits } from "./arg.mjs";
49
51
  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, RECEIPT, archiveStamp, receiptArchiveName, CLOSEOUT_RECEIPT, closeoutArchiveName, headerRe, escapeText, unescapeText } from "./ledger-grammar.mjs";
52
+ 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, CLOSEOUT_RECEIPT, closeoutArchiveName, BRIEFS, briefsArchiveName, memberRole, parseDispatchedEntry, dispatchedEntry, headerRe, escapeText, unescapeText } from "./ledger-grammar.mjs";
51
53
  import { deriveRun, LedgerError, labelOffMember, HELD, CONFLICT_HOLD } from "./fleet-tick.mjs";
52
54
  import { stateFileIn, readState, writeState, assessBeat, stallsAt } from "./fleet-state.mjs";
53
55
  import { processSource, ancestry, controllerOf, judgeController, ProcUnreadable } from "./proc.mjs";
@@ -465,7 +467,7 @@ function sectionOf(text, name) {
465
467
  }
466
468
 
467
469
  function load() {
468
- if (!existsSync(file)) return { rows: [], filed: [], ruled: [], dispatched: [], drain: null, retired: [] };
470
+ if (!existsSync(file)) return { rows: [], filed: [], ruled: [], dispatched: [], briefs: {}, drain: null, retired: [] };
469
471
  let text;
470
472
  try {
471
473
  text = readFileSync(file, "utf8");
@@ -491,11 +493,23 @@ function load() {
491
493
  }
492
494
  return {
493
495
  rows: section(ROWS), filed: section(FILED), ruled: section(RULED),
494
- dispatched: section(DISPATCHED), drain: drainEntries[0] ?? null,
496
+ ...dispatchedOf(section(DISPATCHED)), drain: drainEntries[0] ?? null,
495
497
  retired: section(RETIRED),
496
498
  };
497
499
  }
498
500
 
501
+ // `## Dispatched` held as its tokens, which is what every reader of `read`
502
+ // parses, and `briefs`, each member's `brief=` hash by name: one token per
503
+ // member name for the session, so a settle that rewrites the token keeps the
504
+ // name its brief is filed under. save() joins them back.
505
+ function dispatchedOf(entries) {
506
+ const parsed = entries.map(parseDispatchedEntry);
507
+ return {
508
+ dispatched: parsed.map((p) => p.token),
509
+ briefs: Object.fromEntries(parsed.filter((p) => p.brief !== null).map((p) => [parseToken(p.token).name, p.brief])),
510
+ };
511
+ }
512
+
499
513
  // `## Drain` is written only once there is a marker to hold: an empty section
500
514
  // under that name would read, to anyone scanning the file by eye, as a run
501
515
  // that is draining. `## Retired` likewise: only an `ancestor` rotate writes
@@ -506,7 +520,7 @@ function save(d) {
506
520
  const list = (entries) => entries.map((r) => `- ${escapeText(r)}`).join("\n");
507
521
  const out =
508
522
  `# Fleet run ledger\n\n${ROWS}\n\n` + list(d.rows) +
509
- `\n\n${DISPATCHED}\n\n` + list(d.dispatched) +
523
+ `\n\n${DISPATCHED}\n\n` + list(d.dispatched.map((t) => dispatchedEntry(t, d.briefs[parseToken(t)?.name] ?? null))) +
510
524
  `\n\n${FILED}\n\n` + list(d.filed) +
511
525
  `\n\n${RULED}\n\n` + list(d.ruled) +
512
526
  (d.drain === null ? "" : `\n\n${DRAIN}\n\n` + list([d.drain])) +
@@ -1448,7 +1462,8 @@ function runCheck() {
1448
1462
  // atomically when that name is already taken rather than overwriting an older
1449
1463
  // archive. The two receipts beside the ledger, `phase0.json` and
1450
1464
  // `closeout.json`, belong to the same run, so each is archived as
1451
- // `<name>.<stamp>.json` under the ledger archive's own stamp — a warning-only
1465
+ // `<name>.<stamp>.json` under the ledger archive's own stamp, and the
1466
+ // `briefs` directory beside them as `briefs.<stamp>` — a warning-only
1452
1467
  // move after the ledger move, refused up front only when a name is taken.
1453
1468
  //
1454
1469
  // What follows depends on the verdict below. After a `dead` or `none` one
@@ -1556,7 +1571,7 @@ function runRotate() {
1556
1571
  }
1557
1572
  // Read before anything moves: a ledger whose live tokens cannot be read is
1558
1573
  // refused with nothing moved, never archived with those tokens dropped.
1559
- let carry = { rows: [], dispatched: [], retired: [], skipped: [] };
1574
+ let carry = { rows: [], dispatched: [], briefs: {}, retired: [], skipped: [] };
1560
1575
  if (prior === "ancestor" && exists) {
1561
1576
  let text;
1562
1577
  try {
@@ -1569,10 +1584,12 @@ function runRotate() {
1569
1584
  const carrying = carry.rows.length > 0 || carry.dispatched.length > 0 || carry.retired.length > 0;
1570
1585
  // The receipts beside the ledger belong to the run being rotated away, so
1571
1586
  // each takes the archive's own stamp: `phase0.<stamp>.json` and
1572
- // `closeout.<stamp>.json` next to `ledger.<stamp>.md`. A name already taken
1573
- // refuses before anything moves, as the ledger's own does.
1587
+ // `closeout.<stamp>.json` next to `ledger.<stamp>.md`, and the briefs
1588
+ // directory `briefs.<stamp>`, so no brief of that run is found under a
1589
+ // name the next run dispatches. A name already taken refuses before
1590
+ // anything moves, as the ledger's own does.
1574
1591
  const stamp = archiveStamp();
1575
- const receipts = [[RECEIPT, receiptArchiveName], [CLOSEOUT_RECEIPT, closeoutArchiveName]]
1592
+ const receipts = [[RECEIPT, receiptArchiveName], [CLOSEOUT_RECEIPT, closeoutArchiveName], [BRIEFS, briefsArchiveName]]
1576
1593
  .map(([name, archiveName]) => ({ from: join(dirname(file), name), to: join(dirname(file), archiveName(stamp)) }))
1577
1594
  .filter(({ from }) => existsSync(from));
1578
1595
  for (const { to } of receipts) {
@@ -1615,7 +1632,7 @@ function runRotate() {
1615
1632
  // Nothing to carry writes nothing, so the next write starts the skeleton
1616
1633
  // exactly as after any other verdict.
1617
1634
  if (carrying) {
1618
- save({ rows: carry.rows, dispatched: carry.dispatched, filed: [], ruled: [], drain: null, retired: carry.retired });
1635
+ save({ rows: carry.rows, dispatched: carry.dispatched, briefs: carry.briefs, filed: [], ruled: [], drain: null, retired: carry.retired });
1619
1636
  }
1620
1637
  if (archive !== null) console.error(` rotated ${file} -> ${archive}`);
1621
1638
  for (const { line, why } of carry.skipped) {
@@ -1676,7 +1693,10 @@ function carryOf(text) {
1676
1693
  return false;
1677
1694
  }
1678
1695
  });
1679
- const allDispatched = sectionOf(text, DISPATCHED);
1696
+ // An entry's `brief=` travels with it: save() writes a brief only beside
1697
+ // the token it writes, so a carried member's record still names the brief
1698
+ // it was dispatched with and a dropped member's does not.
1699
+ const { dispatched: allDispatched, briefs: allBriefs } = dispatchedOf(sectionOf(text, DISPATCHED));
1680
1700
  const dispatched = allDispatched.filter((e) => {
1681
1701
  const t = parseToken(e);
1682
1702
  if (t !== null && t.error === null) return true;
@@ -1691,7 +1711,7 @@ function carryOf(text) {
1691
1711
  const live = liveOnLedger(rows, dispatched);
1692
1712
  const carried = { rows: live.rows.map((i) => rows[i]), dispatched: live.dispatched };
1693
1713
  const retired = retiredOnLedger([...rows, ...skippedRows], allDispatched, archivedRetired, carried);
1694
- return { ...carried, retired, skipped };
1714
+ return { ...carried, briefs: allBriefs, retired, skipped };
1695
1715
  }
1696
1716
 
1697
1717
  // ── dispatch / settle ────────────────────────────────────────────────────────
@@ -1931,6 +1951,10 @@ function runDispatch() {
1931
1951
  die(`${member.name}: ${e.message} — not dispatching ${member.name}`);
1932
1952
  }
1933
1953
 
1954
+ // Last, so every refusal above still names its own cause first, and before
1955
+ // anything is written.
1956
+ const brief = renderedBrief(member.name, memberRole(member.family));
1957
+
1934
1958
  let line = null;
1935
1959
  const created = member.bound !== null && i === -1;
1936
1960
  if (created) {
@@ -1944,13 +1968,60 @@ function runDispatch() {
1944
1968
  data.rows[i] = line;
1945
1969
  }
1946
1970
  data.dispatched.push(member.name);
1971
+ data.briefs[member.name] = brief.sha256.slice(0, 8);
1947
1972
  save(data);
1948
1973
  console.error(` dispatched ${member.name}`);
1949
1974
  console.log(JSON.stringify({
1950
- member: member.name, agent, ticket: line === null ? null : rowKey(line), line, created, total: data.dispatched.length,
1975
+ member: member.name, agent, ticket: line === null ? null : rowKey(line), line, created, total: data.dispatched.length, brief,
1951
1976
  }));
1952
1977
  }
1953
1978
 
1979
+ // The brief `name` is dispatched with, as dispatch-prompt.mjs `render
1980
+ // --member <name>` left it in the briefs directory beside the ledger: the
1981
+ // sidecar `<name>.json` must exist, name `role` — the template of the
1982
+ // member's family — and carry the brief's sha256, and the brief file beside
1983
+ // it, `<name>.md`, must exist and hash to it. `{path, sha256}` comes back,
1984
+ // `path` that file, so the controller hands the `task` call its content from
1985
+ // the path printed. Refused, nothing is written.
1986
+ function renderedBrief(name, role) {
1987
+ const dir = resolve(dirname(file), BRIEFS);
1988
+ const sidecar = join(dir, `${name}.json`);
1989
+ const render = `run \`dispatch-prompt.mjs render ${role} --member ${name} …\` with the ${role} template's arguments, then dispatch again`;
1990
+ let text;
1991
+ try {
1992
+ text = readFileSync(sidecar, "utf8");
1993
+ } catch (e) {
1994
+ if (e.code === "ENOENT") die(`no rendered brief for ${name} — ${render} (${sidecar} does not exist)`);
1995
+ die(`cannot read ${sidecar}: ${e.message} — not dispatching ${name}`);
1996
+ }
1997
+ let s;
1998
+ try {
1999
+ s = JSON.parse(text);
2000
+ } catch (e) {
2001
+ die(`${sidecar} is not JSON (${e.message}) — ${render}`);
2002
+ }
2003
+ if (s === null || typeof s !== "object" || Array.isArray(s)) die(`${sidecar} is not a JSON object — ${render}`);
2004
+ if (s.role !== role) {
2005
+ die(`${sidecar} is a brief for role ${JSON.stringify(s.role ?? null)}, but ${name} is dispatched as ${role} — ${render}`);
2006
+ }
2007
+ if (typeof s.sha256 !== "string" || !/^[0-9a-f]{64}$/.test(s.sha256)) {
2008
+ die(`${sidecar} carries no sha256 of 64 lowercase hex (${JSON.stringify(s.sha256 ?? null)}) — ${render}`);
2009
+ }
2010
+ const path = join(dir, `${name}.md`);
2011
+ let brief;
2012
+ try {
2013
+ brief = readFileSync(path);
2014
+ } catch (e) {
2015
+ if (e.code === "ENOENT") die(`no rendered brief for ${name} — ${render} (${path} does not exist)`);
2016
+ die(`cannot read ${path}: ${e.message} — not dispatching ${name}`);
2017
+ }
2018
+ const actual = createHash("sha256").update(brief).digest("hex");
2019
+ if (actual !== s.sha256) {
2020
+ die(`${path} hashes to ${actual}, but ${sidecar} carries ${s.sha256} — ${render}`);
2021
+ }
2022
+ return { path, sha256: s.sha256 };
2023
+ }
2024
+
1954
2025
  function runSettle() {
1955
2026
  const usage = "usage: ledger.mjs settle <member> <outcome>";
1956
2027
  // `settle impl-<N> PR#<n>`, or the one token it writes — `settle
@@ -611,7 +611,8 @@ phase, or in any later one, asks the maintainer which tickets to take.
611
611
  --oneline origin/main..HEAD`, `git -C <worktree> status --short`, and the
612
612
  files under `<scratch>/impl-<N>/`). Record it the ordinary way —
613
613
  `ledger.mjs row <N>
614
- "impl-<N>-b"`, then `ledger.mjs dispatch <N> impl-<N>-b`, then the `task`
614
+ "impl-<N>-b"`, then `dispatch-prompt.mjs render implementer --member
615
+ impl-<N>-b …`, then `ledger.mjs dispatch <N> impl-<N>-b`, then the `task`
615
616
  call naming the `agent` it printed, then the tier check — and never
616
617
  `claim-ticket.sh`: the claim already stands. A `report` goes to the
617
618
  maintainer as `#<N> — <why>` and nothing else: no dispatch, no label change,
@@ -1157,12 +1158,16 @@ a worktree, a branch and an `in-progress` label with no member behind them,
1157
1158
  released by the end-of-run sweep rather than by a member that did the work.
1158
1159
 
1159
1160
  **Record the dispatch before you make it.** `ledger.mjs row` wrote the row at
1160
- the Pull's step 7; `~/.fleet/bin/fleet-run ledger.mjs dispatch <N> impl-<N>`
1161
- then marks `impl-<N>` live on it and in `## Dispatched`, and the call follows.
1162
- Its JSON carries `agent`, the definition that call names — read it off that
1163
- output, never recall it. Live implementers are the `impl-` tokens with no
1161
+ the Pull's step 7; `~/.fleet/bin/fleet-run dispatch-prompt.mjs render
1162
+ implementer --member impl-<N> …` then renders its brief, and
1163
+ `~/.fleet/bin/fleet-run ledger.mjs dispatch <N> impl-<N>`
1164
+ marks `impl-<N>` live on it and in `## Dispatched`, and the call follows.
1165
+ Its JSON carries `agent`, the definition that call names, and `brief.path`,
1166
+ the rendered brief whose content is that call's prompt — read both off that
1167
+ output, never recall them. Live implementers are the `impl-` tokens with no
1164
1168
  `=<outcome>` — the tick reads that count off the ledger, and nobody states
1165
- it. `dispatch` refuses once the
1169
+ it. `dispatch` refuses a member with no brief rendered for its role, naming
1170
+ the `render` command to run first, and refuses once the
1166
1171
  run is draining: drain stops supply. It also refuses a row whose `tier=`
1167
1172
  names no single definition — two different values, or one that is not a
1168
1173
  definition suffix — or names one with no `agents/<definition>.agent.md`,
@@ -1224,9 +1229,12 @@ that the tier it resolves to is now declared and pinned rather than inherited by
1224
1229
  accident. Keep `name: impl-<N>`: the name is what makes a member, and both the
1225
1230
  spend classifier and `member-outcomes.mjs` read it.
1226
1231
 
1227
- **After every Pull's dispatch, run the tier check — a scripted step, never a
1228
- prose reminder.** `~/.fleet/bin/fleet-run tier-check.mjs --batch <path-to-batch.json>`
1229
- judges the implementer just dispatched on the ledger's terms. The definition it
1232
+ **After every Pull's dispatch, the tier check runs — a scripted step, never a
1233
+ prose reminder.** `tick --apply` runs it itself, a batch of one apiece, on every
1234
+ implementer it would print `HOLD (tier unchecked impl-<N>)` for, `session` off
1235
+ the phase-0 receipt, and prints `APPLIED tier-check impl-<N>: <verdict>`. By
1236
+ hand it is `~/.fleet/bin/fleet-run tier-check.mjs --batch <path-to-batch.json>`,
1237
+ which judges the implementer just dispatched on the ledger's terms. The definition it
1230
1238
  should have run under comes off its ticket row's `tier=` token: none means the
1231
1239
  policy cell, `fleet-implementer-slow-high`; `tier=<cell>` means
1232
1240
  `fleet-implementer-<cell>` — the same mapping `ledger.mjs dispatch` prints its
@@ -1262,8 +1270,9 @@ verdicts, whether that member is still running or already settled `bailed`,
1262
1270
  one. Only the newest member counts, so a replacement (`impl-<N>-b`) is what
1263
1271
  clears a mismatch — and is then owed its own check. A mismatch on a ticket
1264
1272
  whose issue is already CLOSED holds nothing: the tick probes that issue and
1265
- drops it, since there is nothing left to replace. The tick never reads a
1266
- transcript: clear an unchecked hold by running the check on that member. A
1273
+ drops it, since there is nothing left to replace. The tick reads no transcript
1274
+ itself: `tick --apply` runs the check, and an unchecked hold it leaves is
1275
+ cleared by running the check on that member by hand. A
1267
1276
  settled member's check works only when its transcript exists;
1268
1277
  without one, the verdict is `tier-unverifiable` for a member settled `killed`
1269
1278
  or `released`, and exit 2 naming the wrong session for any other. Clear a
@@ -1724,7 +1733,7 @@ ticket's line — never a hand edit.
1724
1733
  | Finisher report (failed / killed) | `ledger.mjs settle finisher-pr-<M>=failed` for a finisher that crashed or gave up, `=killed` for one that was killed; no label, and the tick prints no dispatch for it. The cockpit flags the PR `finisher:failed` / `finisher:killed` at severity 4 and you resolve it by hand (**Resolving a finisher that died**, below) |
1725
1734
  | Label seen (persistent Monitor) | nothing to record |
1726
1735
  | CI run terminal | `ci=<run-id>:<attempt>:<conclusion>` on the row; then the finisher gate (below) |
1727
- | Merge-bot pass report | `held-behind:#<lower>` rows; `ledger.mjs settle merge-bot-<n>=done`; `reap.sh --apply`; `reclaim-scratch.mjs --root <scratch> --apply`. (The bot may also have written `conflict-hold:#<pr>` onto a held PR's own row earlier in this same pass, before reporting — a token the bot wrote in this pass, never one `reap.sh` writes.) |
1736
+ | Merge-bot pass report | `held-behind:#<lower>` rows; `ledger.mjs settle merge-bot-<n>=done`; `tick --apply` runs the reap and the reclaim. (The bot may also have written `conflict-hold:#<pr>` onto a held PR's own row earlier in this same pass, before reporting — a token the bot wrote in this pass, never one `reap.sh` writes.) |
1728
1737
  | Drain | `ledger.mjs drain "<reason>"`; release the claims (below); `settle impl-<N>=released`; then the rest of **End of run** (below), `--stop` last |
1729
1738
  | Heartbeat | nothing to record |
1730
1739
 
@@ -1782,10 +1791,13 @@ owes beyond its row:
1782
1791
  - **Merge-bot pass reports done** → write each `held-behind-#<lower>` it reports
1783
1792
  into that ticket's row as `held-behind:#<lower>` — the verdict moves no label
1784
1793
  and leaves nothing in the repo, so the row is the only place the tick can read
1785
- it from — settle `merge-bot-<n>=done`, reap merged branches and worktrees with
1786
- `reap.sh --apply` (below) — always, even when the pass merged nothing — then
1787
- reclaim their scratch with `reclaim-scratch.mjs --root <scratch> --apply`
1788
- (below), and then run the tick. A label that landed at the last moment reads `DISPATCH
1794
+ it from — settle `merge-bot-<n>=done`, and then run the tick: `tick --apply`
1795
+ reaps merged branches and worktrees with `reap.sh --apply` (below), then
1796
+ reclaims their scratch with `reclaim-scratch.mjs --root <scratch> --apply`
1797
+ (below), once for every merge bot settled `done` — always, even when the pass
1798
+ merged nothing — and runs both again on the next tick after an `APPLY FAILED`
1799
+ line, and on every tick while this run has no controller record to remember
1800
+ the pass by. A label that landed at the last moment reads `DISPATCH
1789
1801
  merge-bot` again: dispatch the next bot straight away. A `rebase-fallback-#<pr>`
1790
1802
  on a conflict needs no record from you — the bot already appended
1791
1803
  `conflict-hold:#<pr>` to that PR's row, and the tick turns it into `DISPATCH
@@ -1884,7 +1896,7 @@ owes beyond its row:
1884
1896
  **Every wake ends in the tick.** One invocation, and you act on what it prints:
1885
1897
 
1886
1898
  ```
1887
- ~/.fleet/bin/fleet-run fleet-tick.mjs [--implementer-cap <n>] [--reviewer-cap <n>] [--max-reviews <n>]
1899
+ ~/.fleet/bin/fleet-run fleet-tick.mjs --apply [--implementer-cap <n>] [--reviewer-cap <n>] [--max-reviews <n>]
1888
1900
  ```
1889
1901
 
1890
1902
  It reads the run itself, and nobody states a count. Live implementers, live
@@ -1928,8 +1940,10 @@ depth** guard table applied in code. Act on each line as it reads:
1928
1940
  list shows PR M without `ready-to-merge`, and no `label-off=` (**Run ledger**)
1929
1941
  accounts for the removal. Apply the finisher gate (**Reviewers**: the
1930
1942
  `check` job green on the current head), then dispatch the next-suffix
1931
- finisher at that head — `ledger.mjs dispatch <M> finisher-pr-<M>-<x>`, one
1932
- letter past the highest the PR has used. Never add the label yourself. A head
1943
+ finisher at that head, one letter past the highest the PR has used: render
1944
+ its brief with `dispatch-prompt.mjs render finisher --kind repair --member
1945
+ finisher-pr-<M>-<x> …`, then `ledger.mjs dispatch <M> finisher-pr-<M>-<x>`.
1946
+ Never add the label yourself. A head
1933
1947
  that moved is caught by the new finisher's duty 1 `past-pin` halt and the
1934
1948
  re-review path that follows it. Finishers take no reviewer slot, so this
1935
1949
  prints whatever the reviewer cap reads.
@@ -1960,16 +1974,18 @@ depth** guard table applied in code. Act on each line as it reads:
1960
1974
  - `HOLD (…)` — the row is held and says why: draining, a tier mismatch, an
1961
1975
  unchecked tier, a saturated review side, `--max-reviews` in flight, or every
1962
1976
  queued merge candidate held behind a lower PR or on a conflict hold no
1963
- fix-applier has cleared. The two tier holds are yours to clear — an
1964
- unchecked tier by running `tier-check.mjs --batch` on the member it names
1965
- (its `tier-ok=`, or `tier-unverifiable=` for a member settled `killed` or
1966
- `released` with no transcript, clears it), a mismatch by dispatching the
1967
- replacement at the right tier (phase 2). Each
1968
- prints its clearing step in the row's detail: the `tier-check.mjs` command
1977
+ fix-applier has cleared. An unchecked tier is `tick --apply`'s to check, and
1978
+ the hold stays while the check writes no verdict (its `tier-ok=`, or
1979
+ `tier-unverifiable=` for a member settled `killed` or `released` with no
1980
+ transcript, clears it); a mismatch is yours to clear, by dispatching the
1981
+ replacement at the right tier (phase 2). Each prints its clearing step in
1982
+ the row's detail. For a mismatch that is the replacement's name —
1983
+ `impl-<N>-b` on a first retry, else one letter past the highest the ticket
1984
+ has used, or that no retry letter is left. For an unchecked tier, which
1985
+ `tick --apply` has already tried, it is the `tier-check.mjs` command to run
1986
+ by hand when the tick ran without `--apply` or the check wrote no verdict,
1969
1987
  with a batch entry per member it names (fill in `<file>`; `<session>` too
1970
- when no receipt of this run records one),
1971
- or the replacement's name — `impl-<N>-b` on a first retry, else one letter
1972
- past the highest the ticket has used, or that no retry letter is left.
1988
+ when no receipt of this run records one).
1973
1989
  - `AT CAP`, `IDLE OK` — nothing to do on that row.
1974
1990
  - `MAIN-CHECKOUT-DIRTY <paths> …`, printed above the rows, with every
1975
1991
  dispatching row (implementers, reviewers, merge-bot) reading
@@ -2032,7 +2048,7 @@ depth** guard table applied in code. Act on each line as it reads:
2032
2048
  `--liveness-merge-bot` and `--liveness-review` set the thresholds, in minutes.
2033
2049
 
2034
2050
  **Tier guards under Pull.** The per-dispatch `tier-check.mjs --batch` is
2035
- phase 2's own step: a mismatch it finds is the
2051
+ phase 2's own step, run by `tick --apply`: a mismatch it finds is the
2036
2052
  `HOLD (tier mismatch impl-<N>)` above, and a member it has no verdict on is
2037
2053
  the `HOLD (tier unchecked impl-<N>)`. Nothing else in the loop owns it.
2038
2054
 
@@ -2592,8 +2608,9 @@ no review fix-applier
2592
2608
  has landed `applied:`/`no-op` on since, with no fix-applier live on it — one
2593
2609
  named member per PR, `fix-pr-<pr#>` (the next suffix when that name is already
2594
2610
  on record), never the PR's
2595
- implementer, recorded with `ledger.mjs dispatch <pr#> fix-pr-<pr#>` before the
2596
- call. Its prompt carries the PR number, the worktree abs path, the PR's branch,
2611
+ implementer, its brief rendered with `dispatch-prompt.mjs render fix-applier
2612
+ --kind review --member fix-pr-<pr#> …` and then recorded with `ledger.mjs
2613
+ dispatch <pr#> fix-pr-<pr#>` before the call. Its prompt carries the PR number, the worktree abs path, the PR's branch,
2597
2614
  the same `testCmd` you passed the review, and the **path** `<scratch>/pr<pr>/<run>/review.json`,
2598
2615
  `<run>` off the PR's latest `reviewed=` — never the findings. Every `<scratch>`
2599
2616
  in that prompt is the absolute path `scratch-root.mjs` printed, the
@@ -2610,7 +2627,9 @@ unresolved `conflict-hold:#<M>`, the merge bot's (`run-merge-bot.md` step 1's
2610
2627
  fallback) or one you recorded off the tick's `CONFLICT` line —
2611
2628
  is the same slot with a different job, and no review file to hand
2612
2629
  over. Name it `fix-pr-<M>`, or the next suffix (`-b`, `-c` …) when that name is
2613
- already on record — `dispatch` refuses a reused one — and dispatch it with the
2630
+ already on record — `dispatch` refuses a reused one — render its brief with
2631
+ `dispatch-prompt.mjs render fix-applier --kind conflict --member <name> …`,
2632
+ and dispatch it with the
2614
2633
  `agent` that `ledger.mjs dispatch` printed, in the PR's existing worktree.
2615
2634
  `dispatch` prints this member's definition, `fleet-fix-applier` whatever the
2616
2635
  row's `tier=` — read it off that output, never recall it. Its prompt takes the prompt below's
@@ -2652,7 +2671,8 @@ edges are the only route there, so do not wait for an event. Edit one of these
2652
2671
  bullets without the others and what strands is exactly the red-only PR.
2653
2672
 
2654
2673
  Name it `fix-pr-<M>`, or the next free suffix (`-b`, `-c` …) — `dispatch`
2655
- refuses a reused name — record it with `ledger.mjs dispatch <pr#> <name>`
2674
+ refuses a reused name — render its brief with `dispatch-prompt.mjs render
2675
+ fix-applier --kind red-check --member <name> …`, record it with `ledger.mjs dispatch <pr#> <name>`
2656
2676
  before the call, and dispatch it with the `agent` that command printed
2657
2677
  (`fleet-fix-applier`, as for a review fix-applier), in the PR's
2658
2678
  existing worktree. Its prompt takes the prompt below's worktree, branch and
@@ -2671,7 +2691,7 @@ reach green" covers.
2671
2691
  **A `DISPATCH fix-pr PR#<M>` on a dispositions mismatch** — the PR's row carries
2672
2692
  `dispositions-mismatch=<member>:<run>` for its latest review's run, and no later
2673
2693
  fix-applier has landed — is one automatic retry, a review fix-applier named the
2674
- next suffix (`fix-pr-<M>-b`) and dispatched like the first. Its prompt is the
2694
+ next suffix (`fix-pr-<M>-b`) and dispatched like the first, its brief rendered with `--kind dispositions-retry`. Its prompt is the
2675
2695
  first one's, with three paths and a list copied in: the review file
2676
2696
  `<scratch>/pr<M>/<run>/review.json`, the mismatched member's record `<scratch>/dispositions-<member>.json`
2677
2697
  it starts from, its own record `<scratch>/dispositions-<its own name>.json` it writes, and the check's violation list **verbatim** — the lines
@@ -3146,7 +3166,9 @@ infer, see the five-condition note in the fix-applier block above) — or
3146
3166
  `ci-state.mjs` reads `verdict: "no-ci"`, see below — **and once the PR's review
3147
3167
  has returned and its fix-applier, if one was dispatched, has sent its report,
3148
3168
  which the CI-completes edge above states in full** — dispatch a
3149
- **finisher** — a fresh small agent, not the fix-applier resumed. Record it with
3169
+ **finisher** — a fresh small agent, not the fix-applier resumed. Render its brief
3170
+ with `dispatch-prompt.mjs render finisher --kind fresh --member finisher-pr-<pr#> …`
3171
+ (`--kind repair` once an earlier finisher reported `labelled` without the label landing), record it with
3150
3172
  `ledger.mjs dispatch <pr#> finisher-pr-<pr#>` before the call, then **dispatch
3151
3173
  it with the `agent` that command printed and omit `model` on the call** — the
3152
3174
  tier lives in that definition's frontmatter, `agents/fleet-finisher.agent.md`,
@@ -3571,8 +3593,11 @@ REVIEW-column open PR without the label, whose latest finisher attempt settled
3571
3593
  so, `finisher:failed` or `finisher:killed` at severity 4 — one token per
3572
3594
  outcome, neither the implementer's bare `killed` flag nor `unlabelled`. You
3573
3595
  resolve it by hand: investigate why the finisher died, or dispatch the
3574
- next-suffix finisher after the finisher gate, `ledger.mjs dispatch <M>
3575
- finisher-pr-<M>-<x>`. The flag clears when a later attempt settles — `labelled`
3596
+ next-suffix finisher after the finisher gate: render its brief with
3597
+ `dispatch-prompt.mjs render finisher --kind fresh --member finisher-pr-<M>-<x>
3598
+ …` (`--kind repair` once an earlier finisher reported `labelled` without the
3599
+ label landing), then `ledger.mjs dispatch <M> finisher-pr-<M>-<x>`. The flag
3600
+ clears when a later attempt settles — `labelled`
3576
3601
  (then `unlabelled` takes over while the label is still off), `halted:<cause>`,
3577
3602
  or a live `-b` — or when the PR carries `ready-to-merge`, merges or closes.
3578
3603
  You never add the label yourself, and the tick does not retry.
@@ -3641,7 +3666,10 @@ merge-bot` names it before the dispatch call — `n` is 1 + the highest
3641
3666
  `merge-bot-<n>` the session holds, in the ledger's `## Dispatched` list, on a
3642
3667
  row or in `## Retired`, so it restarts at 1 only when none was carried or
3643
3668
  retired (a `dead` or `none` rotate, or a fresh start), a replacement for a
3644
- dead bot takes the next `n`, and nobody counts. Dispatch
3669
+ dead bot takes the next `n`, and nobody counts. With no brief rendered for
3670
+ that name it refuses, naming the bot and the `dispatch-prompt.mjs render
3671
+ merge-bot --member merge-bot-<n> …` to run — render it, then run `ledger.mjs
3672
+ dispatch merge-bot` again. Dispatch
3645
3673
  it on the tick's `DISPATCH merge-bot`: the first `ready-to-merge` label is
3646
3674
  enough, and it never waits for the finisher's report. Tell it to read
3647
3675
  `$(~/.fleet/bin/fleet-run --root)/commands/run-merge-bot.md` and run **one**
@@ -3709,8 +3737,9 @@ worktree — and its installed dependencies — still on disk. Reap after **each
3709
3737
  not once at the end: a stale worktree still answers `git worktree list`, so the
3710
3738
  in-flight probe (`inflight.sh`, run by the Shortlist and by every Pull) reads an
3711
3739
  already-merged ticket as taken and the queue quietly shrinks. The trigger is the
3712
- bot's one exit report, and it reaps every time — a pass that merged nothing
3713
- included (phase 3, **Merge-bot pass reports done**). See references/reaping.md.
3740
+ bot's `merge-bot-<n>=done`, and `tick --apply` reaps once for every one — a pass
3741
+ that merged nothing included (phase 3, **Merge-bot pass reports done**). See
3742
+ references/reaping.md.
3714
3743
 
3715
3744
  `~/.fleet/bin/fleet-run reap.sh --apply` recomputes every precondition
3716
3745
  inside the same invocation as the delete — `for-each-ref` for `[gone]`, `git
@@ -3738,7 +3767,7 @@ See references/reaping.md.
3738
3767
 
3739
3768
  ### Reclaim scratch after each merge pass
3740
3769
 
3741
- Right after `reap.sh --apply`, every pass:
3770
+ `tick --apply` runs it right after `reap.sh --apply`, every pass:
3742
3771
  `~/.fleet/bin/fleet-run reclaim-scratch.mjs --root <scratch> --apply`,
3743
3772
  `<scratch>` the path `scratch-root.mjs` prints. Reap authorizes on git's
3744
3773
  evidence and never removes scratch; Reclaim authorizes on GitHub state and
@@ -4326,13 +4355,16 @@ it settles** — the grammar is `ledger-grammar.mjs`'s, and the tick derives eve
4326
4355
  live count from it, so nobody states one. Write neither by hand:
4327
4356
 
4328
4357
  - **`ledger.mjs dispatch <ticket|pr> <member>`** — before the dispatch call,
4329
- marks the member live on its row and appends it to `## Dispatched`. `dispatch
4358
+ marks the member live on its row and appends it to `## Dispatched` with
4359
+ `brief=<first 8 hex of its brief's sha256>`. `dispatch
4330
4360
  merge-bot` names the next bot itself. It prints `{member, agent, ticket,
4331
- line, created, total}`; `agent` is the definition the `task` call names — an
4361
+ line, created, total, brief}`, `brief` the `{path, sha256}` of the rendered
4362
+ brief the `task` call is handed; `agent` is the definition the `task` call names — an
4332
4363
  implementer's comes off its row's `tier=` (phase 2's tier check states the
4333
4364
  mapping), a finisher's and a merge bot's are their own definitions, and a
4334
4365
  fix-applier's is `fleet-fix-applier` for every kind of work. It
4335
- refuses a name this session already used — on the ledger or in its
4366
+ refuses a member whose `briefs/<member>.json` beside the ledger is missing,
4367
+ names another role or carries no sha256, a brief file beside it that is missing or does not hash to that sha256, a name this session already used — on the ledger or in its
4336
4368
  `## Retired` — and names the replacement (`-b`, `-c` …), a
4337
4369
  second live member on one ticket or PR, any implementer once the run is
4338
4370
  draining, an implementer whose row's `tier=` names no single definition
@@ -25,6 +25,13 @@ it. Do NOT create another worktree. There is no review file: the PR sits on a
25
25
  conflict hold and you are here to clear it — do not review, do not dispatch
26
26
  specialists.
27
27
 
28
+ ## kind: red-check
29
+ You are ALREADY in worktree `<abs-path>`, whose PR branch is `<branch>` — the
30
+ push destination below, given to you because a detached worktree cannot supply
31
+ it. Do NOT create another worktree. There is no review file: the PR's `check`
32
+ job is red on its current head and you are here to fix it — do not review, do
33
+ not dispatch specialists.
34
+
28
35
  ## kind: review, dispositions-retry
29
36
  Read `$(~/.fleet/bin/fleet-run --root)/commands/review-and-fix.md` and run **steps 2, 3
30
37
  and 5 only**: split apply-now/defer, commit, push, file every deferral as its
@@ -60,6 +67,13 @@ Bring `<branch>` current with `origin/main`, resolving every conflict by the
60
67
  Run `<testCmd>` from the worktree before you push, then push with
61
68
  `git push origin HEAD:<branch>`. Report the new head, or that no conflict was
62
69
  left.
70
+ ## kind: red-check
71
+ Read the failing job's log and fix the cause. Run `<testCmd>` from the
72
+ worktree before you push, then push with `git push origin HEAD:<branch>`.
73
+ Report the new head and **stop**: do not watch, poll or wait for CI — the
74
+ controller owns the next run on the pushed head. A red that is not yours to
75
+ fix — a flake that passes on rerun, or staleness — gets nothing pushed: report
76
+ that instead.
63
77
  ## kind: dispositions-retry
64
78
 
65
79
  This is the one automatic retry of a dispositions mismatch. The mismatched