@feigi/fleet-ctl 0.0.0 → 3.16.3

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.
Files changed (153) hide show
  1. package/agents/{fleet-implementer.agent.md → fleet-implementer-slow-high.agent.md} +23 -2
  2. package/agents/fleet-implementer-slow-medium.agent.md +231 -0
  3. package/agents/fleet-implementer-smol-high.agent.md +231 -0
  4. package/agents/{fleet-implementer-alt.agent.md → fleet-implementer-task-high.agent.md} +23 -2
  5. package/agents/fleet-implementer-task-max.agent.md +231 -0
  6. package/agents/fleet-review-comments.agent.md +4 -2
  7. package/agents/fleet-review-correctness.agent.md +2 -1
  8. package/agents/fleet-review-runner.agent.md +14 -10
  9. package/agents/fleet-review-silent-failure.agent.md +4 -3
  10. package/agents/fleet-review-simplify.agent.md +2 -1
  11. package/agents/fleet-review-snapshot.agent.md +2 -1
  12. package/agents/fleet-review-test-run.agent.md +29 -0
  13. package/agents/fleet-review-tests.agent.md +10 -5
  14. package/agents/fleet-review-types.agent.md +4 -2
  15. package/agents/fleet-review-verifier.agent.md +4 -3
  16. package/commands/review-and-fix.md +7 -6
  17. package/commands/run-merge-bot.md +14 -4
  18. package/package.json +4 -2
  19. package/scripts/agent-test.test.mjs +36 -32
  20. package/scripts/ambient-git-vars-mjs-prose.test.mjs +23 -13
  21. package/scripts/apply-ruleset.test.mjs +4 -3
  22. package/scripts/arg-header-probes-prose.test.mjs +1 -0
  23. package/scripts/arg.test.mjs +18 -18
  24. package/scripts/board-cli.test.mjs +18 -21
  25. package/scripts/board-identity.test.mjs +9 -9
  26. package/scripts/board-liveness-banner.test.mjs +6 -6
  27. package/scripts/board-prev-shape.test.mjs +12 -13
  28. package/scripts/board-tryparse-null.test.mjs +7 -7
  29. package/scripts/board.mjs +4 -7
  30. package/scripts/board.test.mjs +57 -61
  31. package/scripts/candidates.test.mjs +228 -17
  32. package/scripts/ci-completes-premise-prose.test.mjs +1 -1
  33. package/scripts/ci-state-prose.test.mjs +2 -2
  34. package/scripts/ci-state.mjs +389 -187
  35. package/scripts/ci-state.test.mjs +458 -165
  36. package/scripts/citation-sweep-prose.test.mjs +59 -1
  37. package/scripts/claim-lifecycle.test.mjs +2 -1
  38. package/scripts/claim-ticket.test.mjs +35 -34
  39. package/scripts/closing-keyword-prose.test.mjs +1 -1
  40. package/scripts/cockpit-tick-nonblocking.test.mjs +8 -8
  41. package/scripts/compute-board.mjs +13 -3
  42. package/scripts/compute-board.test.mjs +64 -1
  43. package/scripts/compute-spend.mjs +46 -8
  44. package/scripts/compute-spend.test.mjs +64 -10
  45. package/scripts/cross-repo-citation-prose.test.mjs +18 -19
  46. package/scripts/delete-merged-branch.sh +218 -0
  47. package/scripts/delete-merged-branch.test.mjs +576 -0
  48. package/scripts/derive-testcmd.sh +18 -7
  49. package/scripts/derive-testcmd.test.mjs +9 -8
  50. package/scripts/diff-stats.mjs +2 -2
  51. package/scripts/diff-stats.test.mjs +7 -11
  52. package/scripts/dispatch-block-golden-prose.test.mjs +111 -6
  53. package/scripts/dispatch-block-pins-prose.test.mjs +5 -5
  54. package/scripts/dispositions-check.mjs +507 -0
  55. package/scripts/dispositions-check.test.mjs +843 -0
  56. package/scripts/dispositions-gate-prose.test.mjs +114 -0
  57. package/scripts/drop-merged-label.test.mjs +3 -4
  58. package/scripts/exec-stub.mjs +93 -0
  59. package/scripts/exec-stub.test.mjs +69 -0
  60. package/scripts/filing-bar-seat-prose.test.mjs +1 -1
  61. package/scripts/finisher-test-verdict-prose.test.mjs +102 -0
  62. package/scripts/fix-applier-correction-rules-prose.test.mjs +11 -10
  63. package/scripts/fleet-bootstrap +5 -20
  64. package/scripts/fleet-bootstrap.test.mjs +75 -0
  65. package/scripts/fleet-heartbeat.mjs +2 -2
  66. package/scripts/fleet-provenance +15 -24
  67. package/scripts/fleet-provenance.test.mjs +86 -12
  68. package/scripts/fleet-run.test.mjs +5 -5
  69. package/scripts/fleet-state.mjs +33 -11
  70. package/scripts/fleet-state.test.mjs +90 -3
  71. package/scripts/fleet-tick.mjs +346 -70
  72. package/scripts/fleet-tick.test.mjs +566 -16
  73. package/scripts/force-with-lease-reason-prose.test.mjs +1 -1
  74. package/scripts/frontmatter-check.mjs +3 -2
  75. package/scripts/frontmatter-check.test.mjs +6 -6
  76. package/scripts/immutable-body-claim-prose.test.mjs +53 -262
  77. package/scripts/implementer-model-tier.test.mjs +98 -506
  78. package/scripts/inflight.test.mjs +18 -127
  79. package/scripts/is-cli.mjs +26 -0
  80. package/scripts/is-cli.test.mjs +99 -0
  81. package/scripts/json.test.mjs +3 -3
  82. package/scripts/ledger-dispatch.test.mjs +368 -7
  83. package/scripts/ledger-grammar.mjs +85 -1
  84. package/scripts/ledger-grammar.test.mjs +86 -1
  85. package/scripts/ledger-read-require-file.test.mjs +7 -7
  86. package/scripts/ledger-rotate.test.mjs +142 -0
  87. package/scripts/ledger.mjs +181 -17
  88. package/scripts/ledger.test.mjs +12 -130
  89. package/scripts/main-checkout.mjs +312 -0
  90. package/scripts/main-checkout.test.mjs +332 -0
  91. package/scripts/member-outcomes-header.test.mjs +3 -3
  92. package/scripts/member-outcomes.mjs +4 -5
  93. package/scripts/member-outcomes.test.mjs +92 -18
  94. package/scripts/member-prompt-prose.test.mjs +17 -13
  95. package/scripts/member-record.mjs +8 -3
  96. package/scripts/member-record.test.mjs +5 -5
  97. package/scripts/member-write-guard.mjs +5 -5
  98. package/scripts/member-write-guard.test.mjs +6 -3
  99. package/scripts/no-undo-audit.sh +24 -21
  100. package/scripts/no-undo-audit.test.mjs +9 -13
  101. package/scripts/pointer-target-prose.test.mjs +1 -1
  102. package/scripts/pr-overlap.test.mjs +6 -9
  103. package/scripts/prompt-renderer.mjs +10 -9
  104. package/scripts/prose-pin.mjs +10 -11
  105. package/scripts/prove-merge.test.mjs +3 -3
  106. package/scripts/quiet-payload-prose.test.mjs +1 -1
  107. package/scripts/reap.test.mjs +3 -4
  108. package/scripts/release-label-split-prose.test.mjs +17 -2
  109. package/scripts/release-ticket.test.mjs +35 -44
  110. package/scripts/review-core-cwd-isolation.test.mjs +7 -6
  111. package/scripts/review-core-reads.test.mjs +1 -1
  112. package/scripts/review-core-scratch-refusal.test.mjs +64 -0
  113. package/scripts/review-core-shared-test-run.test.mjs +238 -0
  114. package/scripts/review-core-snapshot-path.test.mjs +59 -12
  115. package/scripts/review-core-specialist-scratch.test.mjs +12 -10
  116. package/scripts/review-core-testcmd.test.mjs +76 -45
  117. package/scripts/review-core-unrun.test.mjs +154 -168
  118. package/scripts/review-core.mjs +250 -56
  119. package/scripts/review-eval.mjs +11 -4
  120. package/scripts/review-host-fixture.mjs +12 -3
  121. package/scripts/review-in-run-retry.test.mjs +27 -3
  122. package/scripts/review-runner-spawns.test.mjs +5 -3
  123. package/scripts/review-runner.test.mjs +14 -3
  124. package/scripts/review-tier-audit.test.mjs +1 -1
  125. package/scripts/run-merge-bot-prose.test.mjs +29 -6
  126. package/scripts/scratch-partition-invariant-prose.test.mjs +1 -1
  127. package/scripts/section-between-guard-prose.test.mjs +4 -3
  128. package/scripts/select-dimensions.test.mjs +1 -1
  129. package/scripts/shell-traps-prose.test.mjs +6 -9
  130. package/scripts/shortlist.mjs +4 -1
  131. package/scripts/shortlist.test.mjs +30 -16
  132. package/scripts/snapshot-repo.test.mjs +177 -4
  133. package/scripts/stash-prohibition-prose.test.mjs +1 -1
  134. package/scripts/temp-dir.mjs +47 -0
  135. package/scripts/tier-check.mjs +95 -28
  136. package/scripts/tier-check.test.mjs +131 -29
  137. package/scripts/tier-outcomes-header.test.mjs +11 -54
  138. package/scripts/tier-outcomes.mjs +34 -12
  139. package/scripts/tier-outcomes.test.mjs +157 -4
  140. package/scripts/tier-roles.mjs +118 -29
  141. package/scripts/tier-roles.test.mjs +226 -61
  142. package/scripts/tracker-block-copy-prose.test.mjs +3 -3
  143. package/scripts/verify-sha.test.mjs +4 -5
  144. package/scripts/watcher-degraded-block.test.mjs +5 -8
  145. package/scripts/within-run-pair-prose.test.mjs +43 -75
  146. package/scripts/worktree-audit.test.mjs +2 -1
  147. package/skills/next-ticket/SKILL.md +2 -2
  148. package/skills/run-team/SKILL.md +433 -303
  149. package/skills/run-team/references/ci-and-staleness.md +7 -6
  150. package/skills/run-team/references/correction-tickets.md +3 -3
  151. package/skills/run-team/references/isolation.md +1 -1
  152. package/skills/sizing-a-ticket/SKILL.md +8 -8
  153. package/scripts/tier-guard-gate-prose.test.mjs +0 -216
@@ -6,7 +6,9 @@
6
6
 
7
7
  import { test } from "node:test";
8
8
  import assert from "node:assert/strict";
9
- import { parseToken, memberTokens, nextMergeBot } from "./ledger-grammar.mjs";
9
+ import { existsSync } from "node:fs";
10
+ import { join } from "node:path";
11
+ import { parseMember, parseToken, memberTokens, nextMergeBot, expectedDefinition, agentDefinition, MEMBER_FAMILIES, CELL, CELL_DEF, drawCell } from "./ledger-grammar.mjs";
10
12
 
11
13
  // Every outcome word the spec names, per family, verbatim — the must-ACCEPT
12
14
  // half. A parser that refused everything would pass every refusal below.
@@ -140,3 +142,86 @@ test("nextMergeBot counts every merge-bot entry, live or settled, and nothing el
140
142
  // ## Dispatched's real entries justify (measured: merge-bot-3, not -2).
141
143
  assert.equal(nextMergeBot(["merge-bot-1=done", "merge-bot-2x-garbage"]), "merge-bot-2");
142
144
  });
145
+
146
+ test("expectedDefinition refuses a tier= it cannot name one definition file by", () => {
147
+ assert.throws(() => expectedDefinition("impl-7 · tier=alt · tier=slow-high"), /conflicting tier= tokens \(tier=alt, tier=slow-high\)/);
148
+ assert.throws(() => expectedDefinition("impl-7 · tier=../../etc"), /is not a definition suffix/);
149
+ // Lowercase only: on a case-insensitive filesystem `tier=Task-High` would
150
+ // find fleet-implementer-task-high.agent.md, so the existence check
151
+ // `ledger.mjs dispatch` adds cannot refuse a name no definition carries.
152
+ assert.throws(() => expectedDefinition("impl-7 · tier=Task-High"), /tier=Task-High is not a definition suffix/);
153
+ assert.equal(expectedDefinition("impl-7 · tier=task-high · tier=task-high"), "fleet-implementer-task-high");
154
+ });
155
+
156
+ // #2330: null is a review fix-applier's deliberate "generic `task`", so a
157
+ // family agentDefinition has no case for must throw, never read as one. This
158
+ // walks every family parseMember can yield (MEMBER is built from
159
+ // MEMBER_FAMILIES) — a family added to FAMILIES without a case here fails
160
+ // this test, not a dispatch.
161
+ test("agentDefinition names a definition for every member family, and throws on one it has no case for", () => {
162
+ const agents = join(import.meta.dirname, "..", "agents");
163
+ for (const family of MEMBER_FAMILIES) {
164
+ const member = parseMember(`${family}-7`);
165
+ const definition = agentDefinition(member, "", true);
166
+ assert.match(definition, /^fleet-/, `${family}: ${definition}`);
167
+ // #2129 deleted the bare `fleet-implementer`: a name with no file behind
168
+ // it is what `ledger.mjs dispatch` refuses, so an untiered impl row or a
169
+ // conflict-hold fix-applier pointing at it would stop every such dispatch.
170
+ assert.ok(existsSync(join(agents, `${definition}.agent.md`)), `${family}: ${definition} has no agents/${definition}.agent.md`);
171
+ }
172
+ // The must-ACCEPT half: the deliberate null is still null, not a throw.
173
+ assert.equal(agentDefinition(parseMember("fix-pr-7"), "", false), null);
174
+ assert.throws(
175
+ () => agentDefinition({ name: "review-pr-7", family: "review-pr", number: 7 }, "", false),
176
+ /no case for member family 'review-pr' \(review-pr-7\)/,
177
+ );
178
+ });
179
+
180
+ test("CELL is <role>-<level> over omp's three roles and six levels; CELL_DEF is its definition name", () => {
181
+ for (const cell of ["slow-high", "task-max", "smol-minimal", "slow-xhigh"]) {
182
+ assert.ok(CELL.test(cell), cell);
183
+ assert.ok(CELL_DEF.test(`fleet-implementer-${cell}`), cell);
184
+ }
185
+ for (const cell of ["alt", "default", "fast-high", "slow-ultra", "slow-high-x", "Slow-High", "high-slow"]) {
186
+ assert.ok(!CELL.test(cell), cell);
187
+ assert.ok(!CELL_DEF.test(`fleet-implementer-${cell}`), cell);
188
+ }
189
+ // The family has no bare member: nothing is named `fleet-implementer` alone.
190
+ assert.ok(!CELL_DEF.test("fleet-implementer"));
191
+ assert.ok(!CELL_DEF.test("xfleet-implementer-slow-high"));
192
+ });
193
+
194
+ const GRID = ["slow-high", "slow-medium", "task-high", "task-max", "smol-high"];
195
+ const SESSION = "01a0815e-e141-716c-b2d8-2adf310fbe55";
196
+
197
+ test("drawCell with every non-default cell withdrawn runs the policy cell at k = K = 0", () => {
198
+ assert.deepEqual(drawCell({ session: SESSION, ticket: 2129, policyCell: "slow-high", cells: ["slow-high"] }), { cell: "slow-high", k: 0, K: 0 });
199
+ assert.deepEqual(drawCell({ session: SESSION, ticket: 2129, policyCell: "slow-high", cells: [] }), { cell: "slow-high", k: 0, K: 0 });
200
+ });
201
+
202
+ test("drawCell is sha256(session\\tticket)[0:8] mod K over the sorted non-policy cells", () => {
203
+ // Golden: sha256("<SESSION>\t2129") starts 6b9befca; 0x6b9befca % 4 = 2, so
204
+ // k = 3 over [slow-medium, smol-high, task-high, task-max].
205
+ assert.deepEqual(drawCell({ session: SESSION, ticket: 2129, policyCell: "slow-high", cells: GRID }), { cell: "task-high", k: 3, K: 4 });
206
+ // The input order of `cells` is not an input: the draw sorts by token.
207
+ assert.deepEqual(drawCell({ session: SESSION, ticket: 2129, policyCell: "slow-high", cells: [...GRID].reverse() }), { cell: "task-high", k: 3, K: 4 });
208
+ });
209
+
210
+ test("drawCell never draws the policy cell, reaches every other one, and with no policy cell draws over all", () => {
211
+ const drawn = new Set();
212
+ for (let ticket = 1; ticket <= 200; ticket++) {
213
+ const { cell, k, K } = drawCell({ session: "s", ticket, policyCell: "slow-high", cells: GRID });
214
+ assert.equal(K, 4);
215
+ assert.ok(k >= 1 && k <= K, `k=${k}`);
216
+ drawn.add(cell);
217
+ }
218
+ assert.deepEqual([...drawn].sort(), ["slow-medium", "smol-high", "task-high", "task-max"]);
219
+ // Burn-in (spec § 4 R4) calls it with `policyCell: null`: nothing withheld.
220
+ const burnIn = new Set();
221
+ for (let ticket = 1; ticket <= 200; ticket++) {
222
+ const { cell, K } = drawCell({ session: "s", ticket, policyCell: null, cells: GRID });
223
+ assert.equal(K, 5);
224
+ burnIn.add(cell);
225
+ }
226
+ assert.deepEqual([...burnIn].sort(), [...GRID].sort());
227
+ });
@@ -18,10 +18,11 @@
18
18
  import { test } from "node:test";
19
19
  import assert from "node:assert/strict";
20
20
  import { spawnSync } from "node:child_process";
21
- import { mkdtempSync, writeFileSync, chmodSync, readFileSync, existsSync } from "node:fs";
22
- import { tmpdir } from "node:os";
21
+ import { writeFileSync, readFileSync, existsSync } from "node:fs";
22
+ import { tempDir } from "./temp-dir.mjs";
23
23
  import { join } from "node:path";
24
24
  import { fileURLToPath } from "node:url";
25
+ import { writeExecStub } from "./exec-stub.mjs";
25
26
 
26
27
  const BOARD = fileURLToPath(new URL("./board.mjs", import.meta.url));
27
28
  const REAL_SCRIPTS = fileURLToPath(new URL("./", import.meta.url));
@@ -40,10 +41,9 @@ const EMPTY_LEDGER = "# Fleet run ledger\n\n## Rows\n\n\n## Filed\n\n\n## Ruled\
40
41
  // script ignores — which is the whole defect — so the two arms that decide
41
42
  // whether the fix works must not use one.
42
43
  function gatherLedger({ ledgerBody = null, scriptDir = REAL_SCRIPTS } = {}) {
43
- const cwd = mkdtempSync(join(tmpdir(), "board-ledger-"));
44
- const bin = mkdtempSync(join(tmpdir(), "board-ledger-bin-"));
45
- writeFileSync(join(bin, "gh"), "#!/bin/sh\nexit 1\n");
46
- chmodSync(join(bin, "gh"), 0o755);
44
+ const cwd = tempDir("board-ledger-");
45
+ const bin = tempDir("board-ledger-bin-");
46
+ writeExecStub(join(bin, "gh"), "#!/bin/sh\nexit 1\n");
47
47
  const ledgerFile = join(cwd, "ledger.md");
48
48
  if (ledgerBody !== null) writeFileSync(ledgerFile, ledgerBody);
49
49
 
@@ -61,7 +61,7 @@ function gatherLedger({ ledgerBody = null, scriptDir = REAL_SCRIPTS } = {}) {
61
61
  // A stub ledger.mjs whose body is supplied per test, plus an argv sentinel so a
62
62
  // test can assert what board.mjs actually spawned rather than inferring it.
63
63
  function stubScripts(body) {
64
- const dir = mkdtempSync(join(tmpdir(), "board-ledger-stub-"));
64
+ const dir = tempDir("board-ledger-stub-");
65
65
  const argvFile = join(dir, "argv.txt");
66
66
  writeFileSync(join(dir, "ledger.mjs"),
67
67
  `import { writeFileSync } from "node:fs";\n` +
@@ -0,0 +1,142 @@
1
+ // `ledger.mjs rotate`: one ledger per run. The current file is archived
2
+ // byte-for-byte beside itself and nothing is carried forward, so the next
3
+ // write starts the empty skeleton. Every call is its own process against a
4
+ // scratch `--file` ledger; the heartbeat mark the liveness guard reads is the
5
+ // `heartbeat.json` in the same directory, which is where fleet-state.mjs keeps
6
+ // it beside the real `.fleet/ledger.md`.
7
+
8
+ import { test } from "node:test";
9
+ import assert from "node:assert/strict";
10
+ import { spawnSync } from "node:child_process";
11
+ import { mkdtempSync, mkdirSync, rmSync, writeFileSync, readFileSync, readdirSync, existsSync } from "node:fs";
12
+ import { tmpdir } from "node:os";
13
+ import { join } from "node:path";
14
+ import { fileURLToPath } from "node:url";
15
+ import { stallsAt } from "./fleet-state.mjs";
16
+
17
+ const SCRIPT = fileURLToPath(new URL("./ledger.mjs", import.meta.url));
18
+
19
+ const LEDGER = [
20
+ "# Fleet run ledger", "", "## Rows", "", "- #7 impl-7=killed", "- #8 excluded · behind-pr:#9", "",
21
+ "## Dispatched", "", "- impl-7=killed", "", "## Filed", "", "- #11 a filed subject", "",
22
+ "## Ruled", "", "- #9 merge as is", "", "## Drain", "", "- budget", "",
23
+ ].join("\n");
24
+
25
+ const STAMPED = /^ledger\.\d{4}-\d{2}-\d{2}T\d{6}Z\.md$/;
26
+ const stamp = (ms) => new Date(ms).toISOString().replace(/\.\d{3}Z$/, "Z").replaceAll(":", "");
27
+
28
+ function fixture(t, { ledger = LEDGER, mark = null } = {}) {
29
+ const dir = mkdtempSync(join(tmpdir(), "ledger-rotate-"));
30
+ t.after(() => rmSync(dir, { recursive: true, force: true }));
31
+ const file = join(dir, "ledger.md");
32
+ if (ledger !== null) writeFileSync(file, ledger);
33
+ if (mark !== null) writeFileSync(join(dir, "heartbeat.json"), JSON.stringify({ quiet: 0, elapsed: 0, digest: "", ...mark }));
34
+ const bin = join(dir, "bin");
35
+ mkdirSync(bin);
36
+ const env = { ...process.env, PATH: bin };
37
+ delete env.GIT_DIR;
38
+ delete env.GIT_WORK_TREE;
39
+ const cli = (args, extraEnv = {}) =>
40
+ spawnSync(process.execPath, [SCRIPT, "--file", file, ...args], { encoding: "utf8", env: { ...env, ...extraEnv }, cwd: dir });
41
+ const archives = () => readdirSync(dir).filter((n) => STAMPED.test(n)).sort();
42
+ return { dir, file, cli, archives };
43
+ }
44
+
45
+ const beat = (agoMs, interval = 300, stopped = "") => ({ beat: { at: Date.now() - agoMs, interval, stopped } });
46
+
47
+ test("rotate with no heartbeat mark moves the ledger byte-identical to ledger.<UTC stamp>.md, and the next write starts the empty skeleton", (t) => {
48
+ const f = fixture(t);
49
+ const before = Date.now();
50
+ const r = f.cli(["rotate"]);
51
+ assert.equal(r.status, 0, r.stderr);
52
+ const [archive] = f.archives();
53
+ assert.ok(archive, `no stamped archive in ${readdirSync(f.dir)}`);
54
+ const at = Date.parse(archive.slice("ledger.".length, -".md".length).replace(/T(\d\d)(\d\d)(\d\d)Z$/, "T$1:$2:$3Z"));
55
+ assert.ok(at >= Math.floor(before / 1000) * 1000 && at <= Date.now(), `${archive} is not a UTC stamp of this call`);
56
+ assert.deepEqual(JSON.parse(r.stdout), { rotated: true, archive: join(f.dir, archive) });
57
+ assert.equal(readFileSync(join(f.dir, archive), "utf8"), LEDGER, "the archive must be the ledger's own bytes");
58
+ assert.equal(existsSync(f.file), false, "rotate must leave no ledger behind");
59
+
60
+ const w = f.cli(["row", "12", "impl-12"]);
61
+ assert.equal(w.status, 0, w.stderr);
62
+ assert.deepEqual(JSON.parse(f.cli(["read"]).stdout), { rows: ["#12 impl-12"], filed: [], ruled: [], dispatched: [], drain: null });
63
+ assert.equal(readFileSync(join(f.dir, archive), "utf8"), LEDGER, "a later write must not land in the archive");
64
+ });
65
+
66
+ test("rotate archives a ledger the readers refuse, as-is", (t) => {
67
+ const bad = `${LEDGER}- a second marker\n`;
68
+ const f = fixture(t, { ledger: bad });
69
+ assert.equal(f.cli(["read"]).status, 2, "the fixture must be a ledger load() refuses");
70
+ const r = f.cli(["rotate"]);
71
+ assert.equal(r.status, 0, r.stderr);
72
+ assert.equal(readFileSync(join(f.dir, f.archives()[0]), "utf8"), bad);
73
+ });
74
+
75
+ test("rotate proceeds under a stalled mark and under a recorded stop", (t) => {
76
+ for (const mark of [beat(11 * 60_000), beat(10_000, 300, "budget exhausted"), { ...beat(11 * 60_000), ticked: { at: Date.now() - 60 * 60_000 } }]) {
77
+ const f = fixture(t, { mark });
78
+ const r = f.cli(["rotate"]);
79
+ assert.equal(r.status, 0, `${JSON.stringify(mark)}: ${r.stderr}`);
80
+ assert.equal(f.archives().length, 1);
81
+ assert.equal(existsSync(f.file), false);
82
+ }
83
+ });
84
+
85
+ test("rotate refuses while the previous controller is beating, naming the last beat and when it would count as stalled", (t) => {
86
+ // A fresh beat, and a stale beat covered by a fresh tick — both read as
87
+ // beating to fleet-state.mjs's assessBeat.
88
+ for (const mark of [beat(10_000), { ...beat(11 * 60_000), ticked: { at: Date.now() - 5_000 } }]) {
89
+ const f = fixture(t, { mark });
90
+ const r = f.cli(["rotate"]);
91
+ assert.notEqual(r.status, 0, `${JSON.stringify(mark)}: rotated under a live controller`);
92
+ assert.equal(r.stdout, "");
93
+ assert.match(r.stderr, new RegExp(`last beat ${new Date(mark.beat.at).toISOString()}`));
94
+ const stalls = new Date(stallsAt({ beat: mark.beat, ticked: mark.ticked ?? null })).toISOString();
95
+ assert.match(r.stderr, new RegExp(`stalled after ${stalls.replaceAll(".", "\\.")}`));
96
+ assert.equal(readFileSync(f.file, "utf8"), LEDGER, "a refusal must not touch the ledger");
97
+ assert.deepEqual(f.archives(), []);
98
+ }
99
+ });
100
+
101
+ test("rotate refuses when the archive name already exists, moving nothing", (t) => {
102
+ const f = fixture(t);
103
+ // Every second this call can plausibly land on is taken.
104
+ const now = Date.now();
105
+ for (let s = 0; s < 30; s++) writeFileSync(join(f.dir, `ledger.${stamp(now + s * 1000)}.md`), "older archive\n");
106
+ const r = f.cli(["rotate"]);
107
+ assert.notEqual(r.status, 0, r.stderr);
108
+ assert.match(r.stderr, /refusing to rotate .* already exists/);
109
+ assert.equal(readFileSync(f.file, "utf8"), LEDGER);
110
+ for (const a of f.archives()) assert.equal(readFileSync(join(f.dir, a), "utf8"), "older archive\n");
111
+ });
112
+
113
+ test("rotate with no ledger file says there is nothing to rotate and exits 0", (t) => {
114
+ const f = fixture(t, { ledger: null });
115
+ const r = f.cli(["rotate"]);
116
+ assert.equal(r.status, 0, r.stderr);
117
+ assert.match(r.stderr, /nothing to rotate/);
118
+ assert.deepEqual(JSON.parse(r.stdout), { rotated: false, archive: null });
119
+ assert.deepEqual(f.archives(), []);
120
+ assert.equal(existsSync(f.file), false);
121
+ });
122
+
123
+ test("rotate refuses a stray argument — an imagined --dry-run — moving nothing", (t) => {
124
+ const f = fixture(t);
125
+ for (const extra of ["--dry-run", "now"]) {
126
+ const r = f.cli(["rotate", extra]);
127
+ assert.equal(r.status, 2, `${extra}: ${r.stderr}`);
128
+ assert.match(r.stderr, /usage: ledger\.mjs rotate/);
129
+ assert.equal(readFileSync(f.file, "utf8"), LEDGER);
130
+ assert.deepEqual(f.archives(), []);
131
+ }
132
+ });
133
+
134
+ test("rotate takes the write lock: a live holder keeps it from moving the file", (t) => {
135
+ const f = fixture(t);
136
+ writeFileSync(`${f.file}.lock`, String(process.pid));
137
+ const r = f.cli(["rotate"], { LEDGER_LOCK_TIMEOUT_MS: "200" });
138
+ assert.equal(r.status, 2, r.stderr);
139
+ assert.match(r.stderr, /cannot lock/);
140
+ assert.equal(readFileSync(f.file, "utf8"), LEDGER);
141
+ assert.deepEqual(f.archives(), []);
142
+ });
@@ -20,21 +20,29 @@
20
20
  // lets `merge-bot-<n>` be counted from it.
21
21
  //
22
22
  // Writer policy (#531, reversing #151's item #7): the controller owns run
23
- // state (`row`/`settle`/`dispatch`/`drain`/`ruled`); filers append filings
24
- // with `filed`; all writes are serialized by `<file>.lock`. Every write
25
- // subcommand rewrites the WHOLE file from what it loaded, so two unlocked
26
- // writers are last-writer-wins — measured, 8 concurrent `filed` kept 2-5 of 8
27
- // rows — and the lock is what lets a second kind of writer exist at all. The
28
- // reasoning for each part of the lock lives at acquireLock() below.
23
+ // state (`row`/`settle`/`dispatch`/`drain`/`ruled`/`rotate`); filers append
24
+ // filings with `filed`; all writes are serialized by `<file>.lock`. Every
25
+ // write subcommand except `rotate` — which moves the file whole and never
26
+ // loads it, see runRotate() — rewrites the WHOLE file from what it loaded,
27
+ // so two unlocked writers are last-writer-wins — measured, 8 concurrent
28
+ // `filed` kept 2-5 of 8 rows — and the lock is what lets a second kind of
29
+ // writer exist at all. The reasoning for each part of the lock lives at
30
+ // acquireLock() below.
29
31
 
30
- import { readFileSync, writeFileSync, mkdirSync, existsSync, renameSync, openSync, writeSync, closeSync, unlinkSync } from "node:fs";
31
- import { dirname, resolve, join } from "node:path";
32
+ import { readFileSync, writeFileSync, mkdirSync, existsSync, renameSync, openSync, writeSync, closeSync, unlinkSync, linkSync } from "node:fs";
33
+ import { dirname, resolve, join, basename } from "node:path";
34
+ import { fileURLToPath } from "node:url";
32
35
  import { spawnSync, execFileSync } from "node:child_process";
33
36
  import { makeDie, isFlagLike, hasEqualsForm, isDigits } from "./arg.mjs";
34
37
  import { gitEnv, workspaceDirFromGitCommonDir } from "./git-env.mjs";
35
- import { parseMember, parseToken, memberTokens, nextMergeBot } from "./ledger-grammar.mjs";
38
+ import { parseMember, parseToken, memberTokens, nextMergeBot, agentDefinition } from "./ledger-grammar.mjs";
39
+ import { deriveRun, LedgerError, labelOffMember } from "./fleet-tick.mjs";
40
+ import { stateFileIn, readState, assessBeat, stallsAt } from "./fleet-state.mjs";
36
41
 
37
42
  const NAME = "ledger";
43
+ // The plugin's own agent definitions — the directory tier-check.mjs reads
44
+ // with its default `--repo`, so the two agree on which definitions exist.
45
+ const AGENTS_DIR = join(dirname(fileURLToPath(import.meta.url)), "..", "agents");
38
46
 
39
47
  // die() shared with the other fleet scripts (writeSync-based, pipe-safe —
40
48
  // see arg.mjs for the #176/#328/#363 rationale). arg()/has() themselves are
@@ -233,7 +241,7 @@ const requireFile = requireFileIdx !== -1;
233
241
  if (requireFileIdx !== -1) argv.splice(requireFileIdx, 1);
234
242
 
235
243
  const [cmd, ...rest] = argv;
236
- if (!cmd) die("usage: ledger.mjs [--file <path>] [--require-file] row|filed|ruled|check|read|dispatch|settle|drain [args]");
244
+ if (!cmd) die("usage: ledger.mjs [--file <path>] [--require-file] row|filed|ruled|check|read|dispatch|settle|drain|rotate [args]");
237
245
 
238
246
  const ROWS = "## Rows";
239
247
  const DISPATCHED = "## Dispatched";
@@ -783,9 +791,12 @@ async function acquireLock() {
783
791
  // bundles both under one undifferentiated exit 2, with no ordering between them.
784
792
  if (requireFile && !existsSync(file)) die(`--require-file given but ledger file does not exist: ${file}`);
785
793
 
786
- const WRITE_COMMANDS = new Set(["row", "filed", "ruled", "dispatch", "settle", "drain"]);
794
+ const WRITE_COMMANDS = new Set(["row", "filed", "ruled", "dispatch", "settle", "drain", "rotate"]);
787
795
  if (WRITE_COMMANDS.has(cmd)) await acquireLock();
788
- const data = load();
796
+ // `rotate` moves the file whole and never parses it: a ledger load() would
797
+ // refuse is still the previous run's record, and archiving it as-is is the
798
+ // whole job.
799
+ const data = cmd === "rotate" ? null : load();
789
800
 
790
801
  // The payload subcommands end by falling out of this chain, never by calling
791
802
  // process.exit(). On a pipe, process.stdout.write is async and process.exit()
@@ -833,6 +844,22 @@ if (cmd === "read") {
833
844
  // rewrite alike; a well-formed token, live or settled, still goes through.
834
845
  const malformed = memberTokens(line).find((t) => t.error !== null);
835
846
  if (malformed) die(`row ${key}: malformed member token '${malformed.name}=${malformed.outcome}' — ${malformed.error}`);
847
+ // #2331: `label-off=<attempt>` tells the tick a missing `ready-to-merge` is
848
+ // the controller's own removal, not a finisher's miss — so one naming no
849
+ // finisher-pr member this run has would mask a real miss behind a record of
850
+ // nothing. Known means in `## Dispatched` or among a row's member tokens as
851
+ // they stand before this write, the two places dispatch's live-sibling check
852
+ // reads: a token `row` wrote never enters `## Dispatched`, and this line's
853
+ // own copy of a name vouches for nothing. Local only — never `gh` (#152).
854
+ const known = new Set([...data.dispatched.map(parseToken), ...data.rows.flatMap(memberTokens)]
855
+ .filter((t) => t && t.family === "finisher-pr").map((t) => t.name));
856
+ const badOff = line.split(/\s+/).find((tok) => {
857
+ const m = labelOffMember(tok);
858
+ return m === null || (m !== undefined && !known.has(m.name));
859
+ });
860
+ if (badOff !== undefined) {
861
+ die(`row ${key}: '${badOff}' names no finisher-pr member this run has dispatched or recorded — label-off=<finisher-pr-M[-x]>, the latest finisher attempt, before taking ready-to-merge off PR M`);
862
+ }
836
863
  const i = data.rows.findIndex((r) => r.split(/\s/)[0] === key);
837
864
  const created = i === -1;
838
865
  if (created) {
@@ -912,8 +939,13 @@ if (cmd === "read") {
912
939
  console.error(` already draining: ${data.drain}`);
913
940
  }
914
941
  console.log(JSON.stringify({ drain: data.drain, created }));
942
+ } else if (cmd === "rotate") {
943
+ // It moves the file, so a stray word — an imagined `--dry-run` — is
944
+ // refused rather than read as permission to move it.
945
+ if (rest.length) die("usage: ledger.mjs rotate");
946
+ runRotate();
915
947
  } else {
916
- die(`unknown subcommand '${cmd}' — expected row, filed, ruled, check, read, dispatch, settle or drain`);
948
+ die(`unknown subcommand '${cmd}' — expected row, filed, ruled, check, read, dispatch, settle, drain or rotate`);
917
949
  }
918
950
 
919
951
  // `check` alone of the subcommands leaves its arm early: the already-filed
@@ -1509,6 +1541,54 @@ function runCheck() {
1509
1541
  process.exitCode = verdict === "tracker-hit" ? 3 : 0;
1510
1542
  }
1511
1543
 
1544
+ // ── rotate ───────────────────────────────────────────────────────────────────
1545
+ //
1546
+ // One ledger per run. Phase 0 of every run moves the previous run's file aside
1547
+ // before anything reads it, so no row, exclusion, filing, ruling or drain
1548
+ // marker outlives the run that wrote it: the next write subcommand finds no
1549
+ // file and starts the empty skeleton, exactly as on a first run. The archive
1550
+ // is the file itself — hard-linked to its stamped name, then unlinked — so its
1551
+ // bytes are untouched, and the link refuses atomically when that name is
1552
+ // already taken rather than overwriting an older archive.
1553
+ //
1554
+ // Under the write lock like every other write subcommand, so a concurrent
1555
+ // writer either lands before the move (in the archive, whole) or after it (in
1556
+ // the fresh skeleton) — never half in each.
1557
+ //
1558
+ // The liveness guard reads the heartbeat mark beside the ledger, through
1559
+ // fleet-state.mjs's own reader and verdict: a controller whose mark is still
1560
+ // beating owns this file, and rotating under it would split its run across
1561
+ // two ledgers. A stalled mark, a recorded stop, or no mark at all allows the
1562
+ // rotation. The guard proves "not beating", never "dead": a controller alive
1563
+ // but busy outside its heartbeat hold for longer than its recorded interval
1564
+ // reads as stalled, and is rotated under.
1565
+ function runRotate() {
1566
+ if (!existsSync(file)) {
1567
+ console.error(` nothing to rotate: ${file} does not exist`);
1568
+ console.log(JSON.stringify({ rotated: false, archive: null }));
1569
+ return;
1570
+ }
1571
+ const beatFile = stateFileIn(dirname(file));
1572
+ const { beat, ticked } = readState(beatFile, NAME);
1573
+ if (assessBeat({ beat, ticked, now: Date.now() }).kind === "beating") {
1574
+ die(`refusing to rotate ${file}: the controller that owns it is still beating — last beat ${new Date(beat.at).toISOString()} in ${beatFile}; it counts as stalled after ${new Date(stallsAt({ beat, ticked })).toISOString()}`);
1575
+ }
1576
+ const stamp = new Date().toISOString().replace(/\.\d{3}Z$/, "Z").replaceAll(":", "");
1577
+ const archive = join(dirname(file), `${basename(file, ".md")}.${stamp}.md`);
1578
+ try {
1579
+ linkSync(file, archive);
1580
+ } catch (e) {
1581
+ die(e.code === "EEXIST" ? `refusing to rotate ${file}: ${archive} already exists` : `cannot rotate ${file} to ${archive}: ${e.message}`);
1582
+ }
1583
+ try {
1584
+ unlinkSync(file);
1585
+ } catch (e) {
1586
+ die(`archived ${file} as ${archive} but could not remove it: ${e.message} — remove it by hand before the next write`);
1587
+ }
1588
+ console.error(` rotated ${file} -> ${archive}`);
1589
+ console.log(JSON.stringify({ rotated: true, archive }));
1590
+ }
1591
+
1512
1592
  // ── dispatch / settle (#1799) ────────────────────────────────────────────────
1513
1593
  //
1514
1594
  // Hoisted beside runCheck() for the same reason: each has several refusals
@@ -1568,6 +1648,34 @@ function refuseMalformedDispatched() {
1568
1648
  }
1569
1649
  }
1570
1650
 
1651
+ // Why a finisher on PR `pr` may not be recorded yet, or null when it may.
1652
+ // `review` is the tick fold's `reviewed` entry for the PR, undefined when the
1653
+ // PR has no returned review.
1654
+ function dispositionsRefusal(pr, review) {
1655
+ if (review === undefined) return null;
1656
+ if (review.fixLive.length > 0) {
1657
+ return `${review.fixLive.join(", ")} still live on PR #${pr} — a fix-applier answering review ${review.head} has not settled, `
1658
+ + "so no dispositions verdict answers its work yet; settle it, run dispositions-check.mjs for it, then dispatch the finisher again";
1659
+ }
1660
+ if (review.survived === 0 && review.unverified === 0) return null;
1661
+ const v = review.dispositions;
1662
+ if (v === null) {
1663
+ return `dispositions unchecked — no dispositions-ok=/dispositions-mismatch=/dispositions-escalate= token answers PR #${pr}'s latest review, `
1664
+ + `reviewed=${review.head}; run dispositions-check.mjs --member fix-pr-${pr}[-<x>] --scratch <scratch> for the fix-applier `
1665
+ + "that answered that review, then dispatch the finisher again";
1666
+ }
1667
+ if (v.verdict === "mismatch") {
1668
+ return `dispositions mismatch — ${v.member}'s disposition record fails the check against review ${review.head}; `
1669
+ + `dispositions-check.mjs --member ${v.member} --scratch <scratch> names each violating entry by bucket, index and rule`;
1670
+ }
1671
+ if (v.verdict === "escalate") {
1672
+ return `dispositions escalate — ${v.member} deferred a finding above suggestion severity because its remedy lies outside the PR's diff, `
1673
+ + `which needs a human's ruling: review ${review.head} gets no finisher and no retry; dispositions-check.mjs --member ${v.member} `
1674
+ + "--scratch <scratch> names each escalated finding by bucket and index, for the PR comment that hands it to a human";
1675
+ }
1676
+ return null;
1677
+ }
1678
+
1571
1679
  function runDispatch() {
1572
1680
  const usage = "usage: ledger.mjs dispatch <ticket|pr> <member>, or dispatch merge-bot";
1573
1681
  if (rest.length === 0 || rest.length > 2) die(usage);
@@ -1640,6 +1748,61 @@ function runDispatch() {
1640
1748
  }
1641
1749
  }
1642
1750
 
1751
+ // The definition the `task` call names, printed so the controller reads it
1752
+ // off this output rather than recalling it from prose a compaction drops
1753
+ // (#2208). An implementer's comes off its row's `tier=`, the same function
1754
+ // tier-check.mjs judges it by — so a row that names no single definition,
1755
+ // or names one with no file under `agents/` (a well-formed `tier=` whose
1756
+ // definition has not shipped: a `task` call naming it cannot resolve), is
1757
+ // refused here, before the member is live, not discovered by the check
1758
+ // after the call.
1759
+ //
1760
+ // A fix-applier's turns on whether its PR sits on an unresolved conflict
1761
+ // hold (#2299), and that is the tick's own verdict, not a second reading
1762
+ // of row `i`: a PR's tokens can be split across its ticket row and its own
1763
+ // `#<pr>` row (#2283), and a settle can live in `## Dispatched` alone, so
1764
+ // one row's text can read held where the tick reads cleared, and the
1765
+ // reverse. A ledger the tick refuses is refused here too, before the member
1766
+ // is live, rather than named a definition off a reading the tick rejects.
1767
+ // `tickFold` reads that fold for whichever of the two families needs it,
1768
+ // `what` naming what could not be read off a refused ledger.
1769
+ const tickFold = (what) => {
1770
+ try {
1771
+ return deriveRun({ rows: data.rows, dispatched: data.dispatched, drain: data.drain }, []);
1772
+ } catch (e) {
1773
+ if (!(e instanceof LedgerError)) throw e;
1774
+ die(`${e.message} — fleet-tick.mjs refuses this ledger, so ${member.name}'s ${what} cannot be read off it; fix it with \`ledger.mjs row\` before dispatching`);
1775
+ }
1776
+ };
1777
+ const held = member.family === "fix-pr" && tickFold("definition").conflictHeld.includes(member.number);
1778
+
1779
+ // A finisher labels its PR `ready-to-merge`, so it is recorded only once
1780
+ // the PR's current dispositions verdict is ok — read off the tick's own
1781
+ // per-PR fold, the same latest `reviewed=` head the tick reads — and no
1782
+ // fix-applier on the PR is still live. A PR whose latest review counts no
1783
+ // survived and no unverified finding had nothing for a fix-applier to rule
1784
+ // on, and one never reviewed has no review file: neither is gated on a
1785
+ // verdict. Refused here, before anything is written, so the check cannot
1786
+ // be skipped by forgetting to run it.
1787
+ if (member.family === "finisher-pr") {
1788
+ const review = tickFold("dispositions verdict").reviewed.find((r) => r.pr === member.number);
1789
+ const refusal = dispositionsRefusal(member.number, review);
1790
+ if (refusal !== null) die(`${member.name}: ${refusal} — not dispatching ${member.name}`);
1791
+ }
1792
+ // Every error caught here carries its own cause and remedy — a row's `tier=`
1793
+ // (fix it with `ledger.mjs row`) for an implementer, a family
1794
+ // ledger-grammar.mjs has no definition case for otherwise (#2330) — so this
1795
+ // refusal's tail names neither.
1796
+ let agent;
1797
+ try {
1798
+ agent = agentDefinition(member, i === -1 ? "" : data.rows[i], held);
1799
+ if (member.family === "impl" && !existsSync(join(AGENTS_DIR, `${agent}.agent.md`))) {
1800
+ throw new Error(`row #${member.number}'s tier= names ${agent}, which has no agents/${agent}.agent.md — fix the row with \`ledger.mjs row\``);
1801
+ }
1802
+ } catch (e) {
1803
+ die(`${member.name}: ${e.message} — not dispatching ${member.name}`);
1804
+ }
1805
+
1643
1806
  let line = null;
1644
1807
  const created = member.bound !== null && i === -1;
1645
1808
  if (created) {
@@ -1656,7 +1819,7 @@ function runDispatch() {
1656
1819
  save(data);
1657
1820
  console.error(` dispatched ${member.name}`);
1658
1821
  console.log(JSON.stringify({
1659
- member: member.name, ticket: line === null ? null : rowKey(line), line, created, total: data.dispatched.length,
1822
+ member: member.name, agent, ticket: line === null ? null : rowKey(line), line, created, total: data.dispatched.length,
1660
1823
  }));
1661
1824
  }
1662
1825
 
@@ -1718,9 +1881,10 @@ function runSettle() {
1718
1881
  // live, so a PR-bound member can be dispatched before this settle names the
1719
1882
  // PR here — and memberRowIndex() then finds no row naming it, so
1720
1883
  // runDispatch() keys a row of its own to the PR. Once this row names the PR
1721
- // too, two rows would: the cockpit draws two cards and the tick's
1722
- // first-row-wins `byPr` reads one. Fold that row's tokens onto this one, in
1723
- // order, so later PR-bound writes find the one row through rowPr(). Only
1884
+ // too, two rows would: the cockpit draws two cards and the tick merges the
1885
+ // two rows' tokens in row order (#2283), not in the order they were written.
1886
+ // Fold that row's tokens onto this one, in order, so later PR-bound writes
1887
+ // find the one row through rowPr(). Only
1724
1888
  // an implementer settles to `PR#M` (ledger-grammar.mjs), and only when the
1725
1889
  // settling row named NO PR before this write: `rowPr()` and the tick's
1726
1890
  // `PR_MENTION` both read the FIRST `PR#` mention on a row, so a row that