@feigi/fleet-ctl 0.0.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.
Files changed (245) hide show
  1. package/.claude-plugin/plugin.json +9 -0
  2. package/LICENSE +202 -0
  3. package/NOTICE +18 -0
  4. package/agents/fleet-finisher.agent.md +7 -0
  5. package/agents/fleet-implementer-alt.agent.md +210 -0
  6. package/agents/fleet-implementer.agent.md +210 -0
  7. package/agents/fleet-merge-bot.agent.md +7 -0
  8. package/agents/fleet-review-comments.agent.md +40 -0
  9. package/agents/fleet-review-correctness.agent.md +43 -0
  10. package/agents/fleet-review-runner.agent.md +73 -0
  11. package/agents/fleet-review-silent-failure.agent.md +49 -0
  12. package/agents/fleet-review-simplify.agent.md +46 -0
  13. package/agents/fleet-review-snapshot.agent.md +24 -0
  14. package/agents/fleet-review-tests.agent.md +46 -0
  15. package/agents/fleet-review-types.agent.md +41 -0
  16. package/agents/fleet-review-verifier.agent.md +29 -0
  17. package/commands/review-and-fix.md +98 -0
  18. package/commands/run-merge-bot.md +357 -0
  19. package/commands/run-team-help.md +17 -0
  20. package/package.json +23 -0
  21. package/scripts/agent-test-dir-prose.test.mjs +59 -0
  22. package/scripts/agent-test.test.mjs +1636 -0
  23. package/scripts/ambient-git-vars-mjs-prose.test.mjs +354 -0
  24. package/scripts/ambient-git-vars-prose.test.mjs +192 -0
  25. package/scripts/ancestry-check-position-prose.test.mjs +175 -0
  26. package/scripts/apply-ruleset.test.mjs +420 -0
  27. package/scripts/arg-header-probes-prose.test.mjs +393 -0
  28. package/scripts/arg.mjs +600 -0
  29. package/scripts/arg.test.mjs +1354 -0
  30. package/scripts/board-cli.test.mjs +694 -0
  31. package/scripts/board-identity.test.mjs +429 -0
  32. package/scripts/board-liveness-banner.test.mjs +119 -0
  33. package/scripts/board-prev-shape.test.mjs +229 -0
  34. package/scripts/board-tryparse-null.test.mjs +119 -0
  35. package/scripts/board.html +471 -0
  36. package/scripts/board.mjs +2037 -0
  37. package/scripts/board.test.mjs +3086 -0
  38. package/scripts/brief-after-cut-prose.test.mjs +53 -0
  39. package/scripts/candidates-exit3-prose.test.mjs +302 -0
  40. package/scripts/candidates.mjs +674 -0
  41. package/scripts/candidates.test.mjs +2101 -0
  42. package/scripts/caveat-unification-prose.test.mjs +98 -0
  43. package/scripts/ci-comment-rot-prose.test.mjs +2025 -0
  44. package/scripts/ci-completes-premise-prose.test.mjs +257 -0
  45. package/scripts/ci-state-prose.test.mjs +113 -0
  46. package/scripts/ci-state.mjs +761 -0
  47. package/scripts/ci-state.test.mjs +1640 -0
  48. package/scripts/ci-vacuous-green.test.mjs +368 -0
  49. package/scripts/citation-sweep-prose.test.mjs +1572 -0
  50. package/scripts/claim-lifecycle.test.mjs +185 -0
  51. package/scripts/claim-ticket.sh +417 -0
  52. package/scripts/claim-ticket.test.mjs +1121 -0
  53. package/scripts/closing-keyword-prose.test.mjs +193 -0
  54. package/scripts/cockpit-launch-idempotent-prose.test.mjs +165 -0
  55. package/scripts/cockpit-tick-nonblocking.test.mjs +210 -0
  56. package/scripts/compute-board.mjs +579 -0
  57. package/scripts/compute-board.test.mjs +1060 -0
  58. package/scripts/compute-spend.mjs +329 -0
  59. package/scripts/compute-spend.test.mjs +451 -0
  60. package/scripts/cross-repo-citation-prose.test.mjs +156 -0
  61. package/scripts/cwd-isolation-pins.mjs +83 -0
  62. package/scripts/dedupe-guard-prose.test.mjs +243 -0
  63. package/scripts/derive-testcmd.sh +239 -0
  64. package/scripts/derive-testcmd.test.mjs +380 -0
  65. package/scripts/diff-stats.mjs +231 -0
  66. package/scripts/diff-stats.test.mjs +408 -0
  67. package/scripts/dispatch-block-golden-prose.test.mjs +1024 -0
  68. package/scripts/dispatch-block-pins-prose.test.mjs +615 -0
  69. package/scripts/drop-merged-label.sh +173 -0
  70. package/scripts/drop-merged-label.test.mjs +480 -0
  71. package/scripts/expected-jobs-prose.test.mjs +80 -0
  72. package/scripts/filing-bar-seat-prose.test.mjs +242 -0
  73. package/scripts/filing-claim-bar-prose.test.mjs +166 -0
  74. package/scripts/finisher-dispatch-premise-prose.test.mjs +312 -0
  75. package/scripts/finisher-halt-prose.test.mjs +106 -0
  76. package/scripts/finisher-name-prose.test.mjs +134 -0
  77. package/scripts/finisher-own-tree-prose.test.mjs +285 -0
  78. package/scripts/finisher-pin-race-prose.test.mjs +339 -0
  79. package/scripts/fix-applier-correction-rules-prose.test.mjs +201 -0
  80. package/scripts/fix-applier-result-file-prose.test.mjs +100 -0
  81. package/scripts/fleet-bootstrap +155 -0
  82. package/scripts/fleet-heartbeat.mjs +272 -0
  83. package/scripts/fleet-heartbeat.test.mjs +450 -0
  84. package/scripts/fleet-provenance +207 -0
  85. package/scripts/fleet-provenance.test.mjs +64 -0
  86. package/scripts/fleet-run +148 -0
  87. package/scripts/fleet-run.test.mjs +90 -0
  88. package/scripts/fleet-state.mjs +400 -0
  89. package/scripts/fleet-state.test.mjs +373 -0
  90. package/scripts/fleet-tick-prose.test.mjs +299 -0
  91. package/scripts/fleet-tick.mjs +832 -0
  92. package/scripts/fleet-tick.test.mjs +1332 -0
  93. package/scripts/force-with-lease-reason-prose.test.mjs +184 -0
  94. package/scripts/frontmatter-allowlist.json +64 -0
  95. package/scripts/frontmatter-check.mjs +256 -0
  96. package/scripts/frontmatter-check.test.mjs +436 -0
  97. package/scripts/git-env.mjs +124 -0
  98. package/scripts/git-env.test.mjs +149 -0
  99. package/scripts/git-status-untracked-mode-sweep.test.mjs +216 -0
  100. package/scripts/gone-walk.test.mjs +213 -0
  101. package/scripts/gp-sep-invariant-prose.test.mjs +188 -0
  102. package/scripts/head-moved-after-label-prose.test.mjs +233 -0
  103. package/scripts/immutable-body-claim-prose.test.mjs +413 -0
  104. package/scripts/implementer-model-tier.test.mjs +643 -0
  105. package/scripts/inflight-citation-prose.test.mjs +144 -0
  106. package/scripts/inflight-exit2-prose.test.mjs +81 -0
  107. package/scripts/inflight-probe-guard-prose.test.mjs +109 -0
  108. package/scripts/inflight-scan-scope-prose.test.mjs +57 -0
  109. package/scripts/inflight.sh +1106 -0
  110. package/scripts/inflight.test.mjs +2984 -0
  111. package/scripts/injection-control-prose.test.mjs +404 -0
  112. package/scripts/install-root-audit.test.mjs +464 -0
  113. package/scripts/instrument-check-prose.test.mjs +235 -0
  114. package/scripts/instruments.sh +394 -0
  115. package/scripts/instruments.test.mjs +787 -0
  116. package/scripts/issue-tracker-prose.test.mjs +71 -0
  117. package/scripts/json.sh +248 -0
  118. package/scripts/json.test.mjs +364 -0
  119. package/scripts/ledger-dispatch.test.mjs +516 -0
  120. package/scripts/ledger-grammar.mjs +85 -0
  121. package/scripts/ledger-grammar.test.mjs +142 -0
  122. package/scripts/ledger-read-require-file.test.mjs +197 -0
  123. package/scripts/ledger.mjs +1753 -0
  124. package/scripts/ledger.test.mjs +3554 -0
  125. package/scripts/line-distance-prose.test.mjs +245 -0
  126. package/scripts/liveness-rationale-prose.test.mjs +83 -0
  127. package/scripts/locale-pin-prose.test.mjs +189 -0
  128. package/scripts/member-outcome-prose.test.mjs +167 -0
  129. package/scripts/member-outcomes-header.test.mjs +148 -0
  130. package/scripts/member-outcomes-prose.test.mjs +63 -0
  131. package/scripts/member-outcomes.mjs +231 -0
  132. package/scripts/member-outcomes.test.mjs +507 -0
  133. package/scripts/member-prompt-prose.test.mjs +161 -0
  134. package/scripts/member-record.mjs +605 -0
  135. package/scripts/member-record.test.mjs +516 -0
  136. package/scripts/member-write-guard.mjs +279 -0
  137. package/scripts/member-write-guard.test.mjs +211 -0
  138. package/scripts/merge-commit-probe-prose.test.mjs +122 -0
  139. package/scripts/merge-gate.mjs +262 -0
  140. package/scripts/merge-gate.test.mjs +613 -0
  141. package/scripts/muted-git-guard-sweep.test.mjs +493 -0
  142. package/scripts/net-ssh-precedence-prose.test.mjs +91 -0
  143. package/scripts/net-watchdog-prose.test.mjs +79 -0
  144. package/scripts/net.sh +409 -0
  145. package/scripts/net.test.mjs +211 -0
  146. package/scripts/no-ci-gate-prose.test.mjs +108 -0
  147. package/scripts/no-undo-audit.sh +1134 -0
  148. package/scripts/no-undo-audit.test.mjs +3965 -0
  149. package/scripts/no-wave.test.mjs +138 -0
  150. package/scripts/node-floor-sweep.test.mjs +611 -0
  151. package/scripts/pointer-target-prose.test.mjs +186 -0
  152. package/scripts/pr-overlap.mjs +417 -0
  153. package/scripts/pr-overlap.test.mjs +695 -0
  154. package/scripts/printf-die-sweep.test.mjs +384 -0
  155. package/scripts/prompt-renderer.mjs +39 -0
  156. package/scripts/prompt-renderer.test.mjs +68 -0
  157. package/scripts/prose-pin.mjs +808 -0
  158. package/scripts/prose-pin.test.mjs +1034 -0
  159. package/scripts/prove-merge.sh +228 -0
  160. package/scripts/prove-merge.test.mjs +995 -0
  161. package/scripts/pull-table-relabel-prose.test.mjs +60 -0
  162. package/scripts/quiet-payload-prose.test.mjs +222 -0
  163. package/scripts/reap.sh +1768 -0
  164. package/scripts/reap.test.mjs +4395 -0
  165. package/scripts/reaping-prose.test.mjs +159 -0
  166. package/scripts/refuter-scratch-prose.test.mjs +135 -0
  167. package/scripts/release-label-required-prose.test.mjs +71 -0
  168. package/scripts/release-label-split-prose.test.mjs +169 -0
  169. package/scripts/release-ticket.sh +1716 -0
  170. package/scripts/release-ticket.test.mjs +5106 -0
  171. package/scripts/renovate-release-contract.test.mjs +379 -0
  172. package/scripts/repo-root.mjs +544 -0
  173. package/scripts/repo-root.test.mjs +873 -0
  174. package/scripts/reporter-output-rule-prose.test.mjs +208 -0
  175. package/scripts/review-agent-report-only.test.mjs +49 -0
  176. package/scripts/review-core-cwd-isolation.test.mjs +374 -0
  177. package/scripts/review-core-reads.test.mjs +478 -0
  178. package/scripts/review-core-refuter-scratch.test.mjs +148 -0
  179. package/scripts/review-core-snapshot-path.test.mjs +777 -0
  180. package/scripts/review-core-specialist-scratch.test.mjs +189 -0
  181. package/scripts/review-core-testcmd.test.mjs +288 -0
  182. package/scripts/review-core-unrun.test.mjs +530 -0
  183. package/scripts/review-core-unverified-discriminant.test.mjs +208 -0
  184. package/scripts/review-core.mjs +1028 -0
  185. package/scripts/review-eval-resolver-path.test.mjs +55 -0
  186. package/scripts/review-eval.mjs +197 -0
  187. package/scripts/review-host-fixture.mjs +73 -0
  188. package/scripts/review-in-run-retry.test.mjs +187 -0
  189. package/scripts/review-no-vendor-dispatch.test.mjs +45 -0
  190. package/scripts/review-path-default.test.mjs +796 -0
  191. package/scripts/review-runner-spawns.test.mjs +93 -0
  192. package/scripts/review-runner.test.mjs +155 -0
  193. package/scripts/review-tier-audit.test.mjs +140 -0
  194. package/scripts/run-artifact-pr-prose.test.mjs +341 -0
  195. package/scripts/run-merge-bot-prose.test.mjs +1391 -0
  196. package/scripts/scratch-partition-invariant-prose.test.mjs +74 -0
  197. package/scripts/scripts-path-citation-sweep.test.mjs +73 -0
  198. package/scripts/section-between-guard-prose.test.mjs +378 -0
  199. package/scripts/select-dimensions.test.mjs +674 -0
  200. package/scripts/shared-refusal.test.mjs +388 -0
  201. package/scripts/shell-traps-prose.test.mjs +507 -0
  202. package/scripts/shortlist.mjs +355 -0
  203. package/scripts/shortlist.test.mjs +366 -0
  204. package/scripts/slow-transport.mjs +72 -0
  205. package/scripts/snapshot-repo.test.mjs +772 -0
  206. package/scripts/snapshot-runner-audience-prose.test.mjs +129 -0
  207. package/scripts/spend-view.test.mjs +312 -0
  208. package/scripts/staleness-qualifier-prose.test.mjs +251 -0
  209. package/scripts/staleness-verdict-prose.test.mjs +142 -0
  210. package/scripts/staleness.mjs +414 -0
  211. package/scripts/staleness.test.mjs +893 -0
  212. package/scripts/stalled-member-liveness-prose.test.mjs +219 -0
  213. package/scripts/stash-prohibition-prose.test.mjs +313 -0
  214. package/scripts/strip-comments.mjs +44 -0
  215. package/scripts/tier-check.mjs +468 -0
  216. package/scripts/tier-check.test.mjs +726 -0
  217. package/scripts/tier-guard-gate-prose.test.mjs +216 -0
  218. package/scripts/tier-outcomes-header.test.mjs +586 -0
  219. package/scripts/tier-outcomes.mjs +441 -0
  220. package/scripts/tier-outcomes.test.mjs +342 -0
  221. package/scripts/tier-roles.mjs +250 -0
  222. package/scripts/tier-roles.test.mjs +316 -0
  223. package/scripts/tracker-block-copy-prose.test.mjs +288 -0
  224. package/scripts/triage-labels-gloss-prose.test.mjs +97 -0
  225. package/scripts/unattended-git-sweep.test.mjs +142 -0
  226. package/scripts/verify-sha-exit2-prose.test.mjs +269 -0
  227. package/scripts/verify-sha.sh +117 -0
  228. package/scripts/verify-sha.test.mjs +693 -0
  229. package/scripts/watcher-degraded-block.test.mjs +372 -0
  230. package/scripts/watcher-key-prose.test.mjs +106 -0
  231. package/scripts/within-run-pair-prose.test.mjs +208 -0
  232. package/scripts/worktree-audit.sh +482 -0
  233. package/scripts/worktree-audit.test.mjs +1407 -0
  234. package/scripts/worktree-head-prose.test.mjs +276 -0
  235. package/scripts/worktree-listing-sweep.test.mjs +217 -0
  236. package/scripts/worktree-model-prose.test.mjs +216 -0
  237. package/scripts/worktree.sh +470 -0
  238. package/skills/next-ticket/SKILL.md +138 -0
  239. package/skills/run-team/SKILL.md +3603 -0
  240. package/skills/run-team/references/ci-and-staleness.md +75 -0
  241. package/skills/run-team/references/correction-tickets.md +37 -0
  242. package/skills/run-team/references/isolation.md +23 -0
  243. package/skills/run-team/references/member-lifecycle.md +73 -0
  244. package/skills/run-team/references/reaping.md +73 -0
  245. package/skills/sizing-a-ticket/SKILL.md +39 -0
@@ -0,0 +1,1332 @@
1
+ // Regression gate for the reconcile tick. Zero deps:
2
+ // node --test plugin/scripts/fleet-tick.test.mjs
3
+ //
4
+ // The pure half locks the guard table and the ledger reading — the whole point
5
+ // of #3 is that the table stops being prose the controller must remember, and
6
+ // the whole point of #1803 is that the counts stop being numbers the controller
7
+ // recites. A "simplification" that drops a row, or a reading that counts a
8
+ // settled member live, has to go red here.
9
+ import { test } from "node:test";
10
+ import assert from "node:assert/strict";
11
+ import { reconcile, formatLines, actionable, deriveRun, parseShortlist, unclaimed, refreshWhy } from "./fleet-tick.mjs";
12
+
13
+ // Every field named, so a test that cares about one number still states the
14
+ // rest — a defaulted field is a guard nobody is pinning.
15
+ const state = (over = {}) => ({
16
+ implCap: 2, reviewerCap: 6, maxReviews: 6,
17
+ implLive: 0, draining: null, tierMismatch: [], tierUnchecked: [], implNames: [],
18
+ heads: [], supply: 0, shortlistStatus: "ok", refresh: null,
19
+ reviewsLive: 0, fixLive: 0, fixDue: [], reviewDue: [],
20
+ mergeBotLive: 0, mergeQueue: 0, mergeHeld: 0, mergeConflictHeld: 0,
21
+ ...over,
22
+ });
23
+ const rowsOf = (s, role) => reconcile(s).filter((r) => r.role === role);
24
+ const row = (s, role) => rowsOf(s, role)[0];
25
+
26
+ // ---------------------------------------------------------------------------
27
+ // The implementer row.
28
+
29
+ test("implementers: free slots PULL the next unclaimed heads, one per slot, oldest first", () => {
30
+ const r = row(state({ heads: [412, 415, 420], supply: 9 }), "implementers");
31
+ assert.equal(r.action, "PULL #412 #415");
32
+ assert.equal(r.actual, 0);
33
+ assert.equal(r.target, 2);
34
+ assert.equal(r.acts, true);
35
+ });
36
+
37
+ test("implementers: a PULL never takes live past the cap", () => {
38
+ for (const implCap of [1, 2, 5, 8]) {
39
+ for (const implLive of [0, 1, 2, 5, 9]) {
40
+ const r = row(state({ implCap, implLive, heads: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] }), "implementers");
41
+ const n = r.action.startsWith("PULL") ? r.action.split(" ").length - 1 : 0;
42
+ assert.ok(n === 0 || implLive + n <= implCap, `cap ${implCap} live ${implLive} → ${r.action}`);
43
+ }
44
+ }
45
+ });
46
+
47
+ test("implementers: the PULL is bounded by the heads there are, not only by the deficit", () => {
48
+ assert.equal(row(state({ implCap: 5, heads: [7] }), "implementers").action, "PULL #7");
49
+ });
50
+
51
+ test("implementers: at cap nothing is pulled, however many heads are waiting", () => {
52
+ const r = row(state({ implLive: 2, heads: [1, 2, 3] }), "implementers");
53
+ assert.equal(r.action, "AT CAP");
54
+ assert.equal(r.acts, false);
55
+ });
56
+
57
+ test("implementers: nothing unclaimed suggests /triage and holds idle — never actionable", () => {
58
+ const r = row(state({ heads: [] }), "implementers");
59
+ assert.equal(r.action, "SUGGEST /triage, hold idle");
60
+ assert.equal(r.acts, false);
61
+ });
62
+
63
+ test("implementers: the backlog gate holds only when an unreviewed PR is left AND no reviewer slot is free", () => {
64
+ // Saturated: six units live, one PR still owed its review.
65
+ const held = row(state({ heads: [9], reviewsLive: 1, fixLive: 5, reviewDue: [501] }), "implementers");
66
+ assert.equal(held.action, "HOLD (review side saturated)");
67
+ assert.equal(held.acts, false);
68
+ // The narrowing: a deep review backlog with slots free is NOT a hold — the
69
+ // reviewer row dispatches into those slots on this same tick. The old gate
70
+ // held here at backlog >= 2.
71
+ const deep = row(state({ heads: [9], reviewDue: [501, 502, 503] }), "implementers");
72
+ assert.equal(deep.action, "PULL #9");
73
+ // Saturated slots with nothing owed is not a hold either.
74
+ assert.equal(row(state({ heads: [9], fixLive: 6 }), "implementers").action, "PULL #9");
75
+ });
76
+
77
+ test("implementers: the gate counts the slots this tick's own dispatches fill", () => {
78
+ // Five units live, one slot free, two PRs owed: the one free slot takes a
79
+ // review now, one PR is left owed and nothing is free — saturated.
80
+ const s = state({ heads: [9], reviewsLive: 0, fixLive: 5, reviewDue: [501, 502] });
81
+ assert.equal(row(s, "reviewers").action, "DISPATCH review PR#501");
82
+ assert.equal(row(s, "implementers").action, "HOLD (review side saturated)");
83
+ });
84
+
85
+ test("implementers: --max-reviews leaving a PR owed with slots free does not hold implementers", () => {
86
+ // The review side is throttled, not saturated: fix-appliers can still take
87
+ // the free slots, so more PRs are not a pipeline that gains nothing.
88
+ const s = state({ heads: [9], maxReviews: 1, reviewsLive: 1, reviewDue: [501] });
89
+ assert.equal(row(s, "implementers").action, "PULL #9");
90
+ });
91
+
92
+ test("implementers: draining holds the row and outranks every other branch", () => {
93
+ for (const over of [{}, { implLive: 2 }, { tierMismatch: ["impl-4"] }, { tierUnchecked: ["impl-4"] }, { reviewDue: [1], fixLive: 6 }]) {
94
+ const r = row(state({ heads: [7], draining: "maintainer asked", ...over }), "implementers");
95
+ assert.equal(r.action, "HOLD (draining)", JSON.stringify(over));
96
+ assert.equal(r.acts, false);
97
+ }
98
+ });
99
+
100
+ // #2255: a tier hold's detail names the step that clears it, so the row
101
+ // carries its own command when SKILL.md's prose is gone from context.
102
+ test("implementers: a tier mismatch holds the row, names the member, asks the controller to act, and names the replacement", () => {
103
+ const r = row(state({ heads: [7], tierMismatch: ["impl-412"] }), "implementers");
104
+ assert.equal(r.action, "HOLD (tier mismatch impl-412)");
105
+ assert.equal(r.acts, true, "the controller fixes a mismatch unattended — backing off on it is a stall");
106
+ assert.match(r.detail, /^unclaimed=1 supply=0 unreviewed=0 — /, "the counts stay in front of the clearing step");
107
+ assert.match(r.detail, /dispatch impl-412-b at its row's tier/);
108
+ });
109
+
110
+ test("implementers: a mismatched replacement names the NEXT retry letter, one per held member", () => {
111
+ const r = row(state({ tierMismatch: ["impl-8-b", "impl-9"] }), "implementers");
112
+ assert.equal(r.action, "HOLD (tier mismatch impl-8-b impl-9)");
113
+ assert.match(r.detail, /dispatch impl-8-c, impl-9-b each at its row's tier/);
114
+ assert.doesNotMatch(r.detail, /impl-8-b-b|impl-9-c/);
115
+ // `-z` is the grammar's last letter: no legal replacement name to print, so
116
+ // the row says so instead of naming one ledger.mjs would refuse.
117
+ assert.match(row(state({ tierMismatch: ["impl-8-z"] }), "implementers").detail, /impl-8-z has no retry letter left/);
118
+ });
119
+
120
+ test("implementers: a mismatch batch with some members named and some out of letters prints both clauses, `; `-joined", () => {
121
+ const counts = "unclaimed=0 supply=0 unreviewed=0";
122
+ assert.equal(row(state({ tierMismatch: ["impl-8-b", "impl-9-z"] }), "implementers").detail,
123
+ `${counts} — dispatch impl-8-c at its row's tier; impl-9-z has no retry letter left`);
124
+ assert.equal(row(state({ tierMismatch: ["impl-7-z", "impl-9-z"] }), "implementers").detail,
125
+ `${counts} — impl-7-z, impl-9-z have no retry letter left`);
126
+ });
127
+
128
+ test("implementers: an unchecked implementer holds the row and asks the controller to run the check; a mismatch outranks it", () => {
129
+ const r = row(state({ heads: [7], tierUnchecked: ["impl-412"] }), "implementers");
130
+ assert.equal(r.action, "HOLD (tier unchecked impl-412)");
131
+ assert.equal(r.acts, true, "running tier-check is the controller's own step — backing off on it is a stall");
132
+ assert.ok(r.detail.includes(
133
+ `run ~/.fleet/bin/fleet-run tier-check.mjs --batch <file> with [{"member":"impl-412","session":"<session>"}]`), r.detail);
134
+ const both = row(state({ heads: [7], tierMismatch: ["impl-9"], tierUnchecked: ["impl-412"] }), "implementers");
135
+ assert.equal(both.action, "HOLD (tier mismatch impl-9)");
136
+ assert.doesNotMatch(both.detail, /tier-check/, "the detail names the step for the hold the row prints, not the one it outranks");
137
+ });
138
+
139
+ test("implementers: several unchecked members share one batch file, one entry each", () => {
140
+ const r = row(state({ tierUnchecked: ["impl-7", "impl-8-b"] }), "implementers");
141
+ assert.ok(r.detail.includes(
142
+ `[{"member":"impl-7","session":"<session>"},{"member":"impl-8-b","session":"<session>"}]`), r.detail);
143
+ });
144
+
145
+ test("implementers: no tier hold, no clearing step in the detail", () => {
146
+ for (const over of [{ heads: [7] }, { draining: "x", tierUnchecked: ["impl-4"] }, {}]) {
147
+ assert.doesNotMatch(row(state(over), "implementers").detail, /—/, JSON.stringify(over));
148
+ }
149
+ });
150
+
151
+ test("implementers: the detail carries the numbers the branch turned on", () => {
152
+ const r = row(state({ heads: [4, 5, 6], supply: 57, reviewDue: [1] }), "implementers");
153
+ assert.match(r.detail, /unclaimed=3/);
154
+ assert.match(r.detail, /supply=57/);
155
+ assert.match(r.detail, /unreviewed=0/);
156
+ assert.match(row(state({ supply: null, shortlistStatus: "missing" }), "implementers").detail, /supply=\? unreviewed=0 shortlist=missing$/);
157
+ });
158
+
159
+ // ---------------------------------------------------------------------------
160
+ // The reviewer rows.
161
+
162
+ test("reviewers: nothing owed and nothing in flight is idle", () => {
163
+ const r = row(state(), "reviewers");
164
+ assert.equal(r.action, "IDLE OK");
165
+ assert.equal(r.target, 6);
166
+ assert.equal(r.acts, false);
167
+ });
168
+
169
+ test("reviewers: fix-appliers are named before reviews — finish what is started", () => {
170
+ const rs = rowsOf(state({ fixDue: [346, 348], reviewDue: [350, 351] }), "reviewers");
171
+ assert.deepEqual(rs.map((r) => r.action), ["DISPATCH fix-pr PR#346 PR#348", "DISPATCH review PR#350 PR#351"]);
172
+ assert.ok(rs.every((r) => r.acts));
173
+ // One free slot: the fix-applier takes it and the review waits.
174
+ const one = rowsOf(state({ fixLive: 5, fixDue: [346], reviewDue: [350] }), "reviewers");
175
+ assert.deepEqual(one.map((r) => r.action), ["DISPATCH fix-pr PR#346"]);
176
+ });
177
+
178
+ test("reviewers: dispatches never take live units past the reviewer cap", () => {
179
+ for (const reviewerCap of [1, 3, 6]) {
180
+ for (const [reviewsLive, fixLive] of [[0, 0], [1, 0], [0, 3], [2, 4], [4, 4]]) {
181
+ const rs = rowsOf(state({
182
+ reviewerCap, maxReviews: reviewerCap, reviewsLive, fixLive,
183
+ fixDue: [1, 2, 3, 4], reviewDue: [5, 6, 7, 8],
184
+ }), "reviewers");
185
+ const n = rs.filter((r) => r.action.startsWith("DISPATCH")).reduce((k, r) => k + r.action.match(/PR#/g).length, 0);
186
+ assert.ok(n === 0 || reviewsLive + fixLive + n <= reviewerCap,
187
+ `cap ${reviewerCap} live ${reviewsLive}+${fixLive} → ${rs.map((r) => r.action)}`);
188
+ }
189
+ }
190
+ });
191
+
192
+ test("reviewers: --max-reviews bounds reviews in flight, and a throttled review is a HOLD that says why", () => {
193
+ assert.equal(row(state({ maxReviews: 1, reviewDue: [350, 351] }), "reviewers").action, "DISPATCH review PR#350");
194
+ const held = row(state({ maxReviews: 1, reviewsLive: 1, reviewDue: [351] }), "reviewers");
195
+ assert.equal(held.action, "HOLD (max-reviews 1 in flight)");
196
+ assert.equal(held.acts, false);
197
+ // The bound is on REVIEWS: fix-appliers still take the free slots.
198
+ const rs = rowsOf(state({ maxReviews: 1, reviewsLive: 1, fixDue: [346], reviewDue: [351] }), "reviewers");
199
+ assert.deepEqual(rs.map((r) => r.action), ["DISPATCH fix-pr PR#346"]);
200
+ });
201
+
202
+ test("reviewers: work owed with every slot full is AT CAP", () => {
203
+ assert.equal(row(state({ fixLive: 6, fixDue: [1], reviewDue: [2] }), "reviewers").action, "AT CAP");
204
+ });
205
+
206
+ // ---------------------------------------------------------------------------
207
+ // The merge-bot row.
208
+
209
+ test("merge-bot: a queued, unheld PR with no bot live dispatches one", () => {
210
+ const r = row(state({ mergeQueue: 3 }), "merge-bot");
211
+ assert.equal(r.action, "DISPATCH merge-bot");
212
+ assert.equal(r.acts, true);
213
+ assert.match(r.detail, /merge-queue=3 held=0/);
214
+ });
215
+
216
+ test("merge-bot: never a second bot, an empty queue is idle, a fully held queue holds", () => {
217
+ assert.equal(row(state({ mergeBotLive: 1, mergeQueue: 9 }), "merge-bot").action, "AT CAP");
218
+ assert.equal(row(state({ mergeQueue: 0 }), "merge-bot").action, "IDLE OK");
219
+ const held = row(state({ mergeQueue: 2, mergeHeld: 2 }), "merge-bot");
220
+ assert.equal(held.action, "HOLD");
221
+ assert.equal(held.acts, false);
222
+ assert.equal(row(state({ mergeQueue: 3, mergeHeld: 2 }), "merge-bot").action, "DISPATCH merge-bot");
223
+ });
224
+
225
+ // ---------------------------------------------------------------------------
226
+ // The shortlist row.
227
+
228
+ test("shortlist: a refresh prints REFRESHED with its counts, and is actionable only when it changed the list", () => {
229
+ const changed = reconcile(state({ refresh: { ok: true, entries: 5, lifted: 1, changed: true, trigger: "unclaimed 0 < cap 2" } })).at(-1);
230
+ assert.equal(changed.role, "shortlist");
231
+ assert.equal(changed.action, "REFRESHED shortlist: 5 entries; 1 lifted");
232
+ assert.equal(changed.acts, true);
233
+ // Unchanged: every idle heartbeat tick refreshes while the shortlist is
234
+ // short of the cap, so an unconditionally actionable REFRESHED would pin the
235
+ // beat at its base interval all night — ADR 0008 §6's back-off, undone.
236
+ const same = reconcile(state({ refresh: { ok: true, entries: 0, lifted: 0, changed: false, trigger: "shortlist empty" } })).at(-1);
237
+ assert.equal(same.action, "REFRESHED shortlist: 0 entries; 0 lifted");
238
+ assert.equal(same.acts, false);
239
+ assert.match(same.detail, /unchanged/);
240
+ assert.equal(actionable(reconcile(state({ refresh: { ok: true, entries: 0, lifted: 0, changed: false, trigger: "x" } }))), false);
241
+ });
242
+
243
+ test("shortlist: a failed refresh is named and actionable, never a refusal of the tick", () => {
244
+ const rows = reconcile(state({ mergeQueue: 1, refresh: { ok: false, why: "shortlist.mjs exited 2: boom", trigger: "shortlist missing" } }));
245
+ const r = rows.at(-1);
246
+ assert.equal(r.action, "REFRESH FAILED");
247
+ assert.match(r.detail, /shortlist missing — shortlist\.mjs exited 2: boom/);
248
+ assert.equal(r.acts, true);
249
+ assert.equal(row(state({ mergeQueue: 1 }), "merge-bot").action, "DISPATCH merge-bot");
250
+ });
251
+
252
+ test("no refresh, no shortlist row", () => {
253
+ assert.deepEqual(reconcile(state()).map((r) => r.role), ["implementers", "reviewers", "merge-bot"]);
254
+ });
255
+
256
+ test("formatLines prints role, actual/target and the ACTION on one line each", () => {
257
+ assert.deepEqual(
258
+ formatLines(reconcile(state({
259
+ heads: [412], supply: 57, fixDue: [346], reviewDue: [350], mergeQueue: 2, mergeHeld: 1,
260
+ refresh: { ok: true, entries: 3, lifted: 0, changed: true, trigger: "unclaimed 1 < cap 2" },
261
+ }))),
262
+ [
263
+ "implementers 0/2 → PULL #412 (unclaimed=1 supply=57 unreviewed=0)",
264
+ "reviewers 0/6 → DISPATCH fix-pr PR#346 (reviews=0 fix-pr=0 fix-due=1 review-due=1 max-reviews=6)",
265
+ "reviewers 0/6 → DISPATCH review PR#350 (reviews=0 fix-pr=0 fix-due=1 review-due=1 max-reviews=6)",
266
+ "merge-bot 0/1 → DISPATCH merge-bot (merge-queue=2 held=1)",
267
+ "shortlist → REFRESHED shortlist: 3 entries; 0 lifted (unclaimed 1 < cap 2)",
268
+ ],
269
+ );
270
+ });
271
+
272
+ test("actionable: exactly the rows that name work the controller can do unattended", () => {
273
+ const acts = (over) => actionable(reconcile(state(over)));
274
+ assert.equal(acts({}), false, "an idle tick asks for nothing");
275
+ assert.equal(acts({ heads: [1] }), true, "PULL");
276
+ assert.equal(acts({ fixDue: [1] }), true, "DISPATCH fix-pr");
277
+ assert.equal(acts({ reviewDue: [1] }), true, "DISPATCH review");
278
+ assert.equal(acts({ mergeQueue: 1 }), true, "DISPATCH merge-bot");
279
+ assert.equal(acts({ implLive: 2, heads: [1] }), false, "AT CAP");
280
+ assert.equal(acts({ draining: "x", heads: [1] }), false, "HOLD (draining)");
281
+ });
282
+
283
+ // ---------------------------------------------------------------------------
284
+ // Reading the run: deriveRun() over `ledger.mjs read`'s payload and the open
285
+ // PR list. Rows are spelled the way ledger.mjs dispatch/settle write them.
286
+
287
+ const HEAD_A = "abc1234" + "0".repeat(33);
288
+ const HEAD_B = "def5678" + "0".repeat(33);
289
+ const pr = (number, labels = [], closes = [number + 1000], headRefOid = HEAD_B) => ({
290
+ number, labels: labels.map((name) => ({ name })),
291
+ closingIssuesReferences: closes.map((n) => ({ number: n })),
292
+ headRefOid,
293
+ });
294
+ const run = (ledger, prs = []) => deriveRun({ rows: [], dispatched: [], drain: null, ...ledger }, prs);
295
+
296
+ test("deriveRun: live implementers are the unsettled impl- tokens — the #1692 shape, read rather than recited", () => {
297
+ // #1692 was two sources disagreeing about the same fleet. There is one
298
+ // source now: two live tokens are two live implementers, whatever else the
299
+ // file says.
300
+ const r = run({
301
+ rows: ["#412 impl-412 · class=routine", "#415 impl-415", "#300 impl-300=PR#344 → PR#344", "#301 impl-301=bailed"],
302
+ dispatched: ["impl-412", "impl-415", "impl-300=PR#344", "impl-301=bailed"],
303
+ });
304
+ assert.equal(r.implLive, 2);
305
+ assert.deepEqual([...r.claimed].sort((a, b) => a - b), [300, 301, 412, 415]);
306
+ });
307
+
308
+ test("deriveRun: a member settled anywhere is settled, and a -b replacement is its own member", () => {
309
+ const r = run({
310
+ rows: ["#412 impl-412=killed · impl-412-b"],
311
+ dispatched: ["impl-412=killed", "impl-412-b"],
312
+ });
313
+ assert.equal(r.implLive, 1);
314
+ // A hand-edited row still carrying the bare token of a member `## Dispatched`
315
+ // records as settled: settled wins, because `settle` is the one writer of an
316
+ // outcome and a stale bare copy is what a whole-line `row` rewrite leaves.
317
+ assert.equal(run({ rows: ["#9 impl-9"], dispatched: ["impl-9=PR#12"] }).implLive, 0);
318
+ });
319
+
320
+ test("deriveRun: live reviewer units are in-flight reviews plus unsettled fix-appliers", () => {
321
+ const r = run({
322
+ rows: [
323
+ "#10 impl-10=PR#20 → PR#20 · review=wf:run1",
324
+ "#11 impl-11=PR#21 → PR#21 · review=wf:run2 reviewed=abc1234:2/1/0 · fix-pr-21",
325
+ "#12 impl-12=PR#22 → PR#22 · review=member:review-pr-22 reviewed=abc1234:0/0/0",
326
+ "#13 impl-13=PR#23 → PR#23 · review=wf:run3=failed",
327
+ "#14 impl-14=PR#24 → PR#24 · review=wf:run4=failed review=fallback:review-pr-24",
328
+ ],
329
+ dispatched: ["fix-pr-21"],
330
+ }, [pr(20), pr(21), pr(22), pr(23), pr(24)]);
331
+ assert.equal(r.reviewsLive, 2, "run1 and the fallback are in flight; run2 returned, run3 is dead");
332
+ assert.equal(r.fixLive, 1);
333
+ });
334
+
335
+ test("deriveRun: fix-pr is due on a returned review with survivors and no fix-applier since", () => {
336
+ const r = run({
337
+ rows: [
338
+ "#10 impl-10=PR#20 → PR#20 · review=wf:a reviewed=abc1234:2/0/0",
339
+ "#11 impl-11=PR#21 → PR#21 · review=wf:b reviewed=abc1234:0/3/1",
340
+ "#12 impl-12=PR#22 → PR#22 · review=wf:c reviewed=abc1234:1/0/0 · fix-pr-22=applied:def5678",
341
+ // Re-reviewed after its fix, and the second review found more.
342
+ "#13 impl-13=PR#23 → PR#23 · review=wf:d reviewed=abc1234:1/0/0 · fix-pr-23=applied:def5678 review=wf:e reviewed=def5678:1/0/0",
343
+ // A closed PR is nobody's work.
344
+ "#14 impl-14=PR#24 → PR#24 · review=wf:f reviewed=abc1234:4/0/0",
345
+ ],
346
+ dispatched: ["fix-pr-22=applied:def5678", "fix-pr-23=applied:def5678"],
347
+ }, [pr(20), pr(21), pr(22), pr(23)]);
348
+ assert.deepEqual(r.fixDue, [20, 23]);
349
+ });
350
+
351
+ test("deriveRun: review is due on open PRs that close an issue and carry no review token, oldest first", () => {
352
+ const r = run({
353
+ rows: [
354
+ "#10 impl-10=PR#30 → PR#30 · review=wf:a",
355
+ "#11 impl-11=PR#31 → PR#31",
356
+ "#12 impl-12=PR#32 → PR#32 · review=wf:b=failed",
357
+ ],
358
+ }, [
359
+ pr(33), pr(31), pr(30), pr(32),
360
+ pr(34, ["ready-to-merge"]), // signed off — not review work
361
+ pr(35, [], []), // closes no issue — not review work (#590)
362
+ ]);
363
+ assert.deepEqual(r.reviewDue, [31, 32, 33]);
364
+ });
365
+
366
+ test("deriveRun: a PR row keyed by the PR's own number is read as that PR's", () => {
367
+ // A PR this run's implementers did not open: `dispatch 350 fix-pr-350` keys
368
+ // its row `#350`, the same fallback ledger.mjs's memberRowIndex() takes.
369
+ const r = run({ rows: ["#350 review=wf:x reviewed=abc1234:1/0/0"] }, [pr(350)]);
370
+ assert.deepEqual(r.fixDue, [350]);
371
+ assert.deepEqual(r.reviewDue, []);
372
+ });
373
+
374
+ // #2083: a finisher that halts `past-pin` found commits past the head the
375
+ // review read. Once a review has RETURNED, `reviewedAny` holds it out of
376
+ // review-due for good, so marking the review failed cannot re-queue it —
377
+ // the halt itself does, until a new review is running or has returned.
378
+ test("deriveRun: a finisher halted past-pin re-queues the review while the head is past the reviewed one", () => {
379
+ const row = "#10 impl-10=PR#40 → PR#40 · review=wf:a reviewed=abc1234:0/0/0 · finisher-pr-40=halted:past-pin";
380
+ assert.deepEqual(run({ rows: [row] }, [pr(40, [], [10], HEAD_B)]).reviewDue, [40]);
381
+ // Settled only in `## Dispatched`, a bare copy on the row: settled anywhere is settled.
382
+ assert.deepEqual(run({
383
+ rows: ["#10 impl-10=PR#40 → PR#40 · review=wf:a reviewed=abc1234:0/0/0 · finisher-pr-40"],
384
+ dispatched: ["finisher-pr-40=halted:past-pin"],
385
+ }, [pr(40, [], [10], HEAD_B)]).reviewDue, [40]);
386
+ // A re-review that died before returning leaves it owed.
387
+ assert.deepEqual(run({ rows: [`${row} review=wf:b=failed`] }, [pr(40, [], [10], HEAD_B)]).reviewDue, [40]);
388
+ });
389
+
390
+ test("deriveRun: a head past reviewed= with no past-pin halt stays not due — a fix-applier's push is finisher duty 2's", () => {
391
+ const base = "#10 impl-10=PR#40 → PR#40 · review=wf:a reviewed=abc1234:1/0/0 · fix-pr-40=applied:def5678";
392
+ for (const row of [
393
+ base,
394
+ `${base} · finisher-pr-40=labelled`,
395
+ `${base} · finisher-pr-40`,
396
+ `${base} · finisher-pr-40=failed`,
397
+ // Every other halt cause escalates to a human; none re-queues a review.
398
+ `${base} · finisher-pr-40=halted:live-editor`,
399
+ `${base} · finisher-pr-40=halted:rebase`,
400
+ `${base} · finisher-pr-40=halted:other`,
401
+ // A later finisher attempt replaces the halted one, live or settled —
402
+ // by retry suffix (compute-board.mjs's laterAttempt ordering), never by
403
+ // row-text position: a row rewrite can leave `-b` sitting BEFORE the
404
+ // older halted token (#2083).
405
+ `${base} · finisher-pr-40=halted:past-pin · finisher-pr-40-b`,
406
+ `${base} · finisher-pr-40=halted:past-pin · finisher-pr-40-b=halted:live-editor`,
407
+ `${base} · finisher-pr-40-b · finisher-pr-40=halted:past-pin`,
408
+ `${base} · finisher-pr-40-b=halted:live-editor · finisher-pr-40=halted:past-pin`,
409
+ // Another PR's finisher on the row is not this PR's halt.
410
+ `${base} · finisher-pr-41=halted:past-pin`,
411
+ ]) {
412
+ assert.deepEqual(run({ rows: [row] }, [pr(40, [], [10], HEAD_B)]).reviewDue, [], row);
413
+ }
414
+ });
415
+
416
+ test("deriveRun: a past-pin halt is answered once the head is the reviewed one, or a review is running or returned after it", () => {
417
+ const halted = "#10 impl-10=PR#40 → PR#40 · review=wf:a reviewed=abc1234:0/0/0 · finisher-pr-40=halted:past-pin";
418
+ const not = (row, head) => assert.deepEqual(run({ rows: [row] }, [pr(40, [], [10], head)]).reviewDue, [], `${row} @ ${head}`);
419
+ not(halted, HEAD_A); // the reviewed head IS the PR head — nothing unread
420
+ not(halted, HEAD_A.toUpperCase());
421
+ not(`${halted} review=wf:b`, HEAD_B); // the re-review is in flight
422
+ not(`${halted} review=wf:b reviewed=def5678:0/0/0`, HEAD_B); // and returned
423
+ // A fix-applier's push after that re-review is duty 2's again, not a second re-review.
424
+ not(`${halted} review=wf:b reviewed=def5678:1/0/0 · fix-pr-40=applied:0123456`, "0123456" + "0".repeat(33));
425
+ // Signed off, or closing no issue, is no review work whatever the halt says.
426
+ assert.deepEqual(run({ rows: [halted] }, [pr(40, ["ready-to-merge"], [10], HEAD_B), pr(41, [], [], HEAD_B)]).reviewDue, []);
427
+ });
428
+
429
+ test("deriveRun: merge holds are held-behind rows whose premise PR is still open", () => {
430
+ const r = run({
431
+ rows: [
432
+ "#10 impl-10=PR#40 → PR#40 · held-behind:#38",
433
+ "#11 impl-11=PR#41 → PR#41 · held-behind:#39",
434
+ ],
435
+ }, [pr(38), pr(40, ["ready-to-merge"]), pr(41, ["ready-to-merge"])]);
436
+ assert.equal(r.mergeQueue, 2);
437
+ assert.equal(r.mergeHeld, 1, "#39 is no longer open, so #41's hold has lifted");
438
+ });
439
+
440
+ // #2064: merge-bot's `conflict-hold:#<pr>` — a conflict its local-rebase
441
+ // fallback would not force — feeds the same fix-due list a review's
442
+ // survivors do, and holds the merge until a fix-applier AFTER it settles.
443
+ const HOLD_ROW = (n, tail) => `#${n - 30} impl-${n - 30}=PR#${n} → PR#${n} · reviewed=abc1234:0/2/0 · ${tail}`;
444
+
445
+ test("deriveRun: a conflict hold is fix-due until a fix-applier after it lands, whatever settled before it", () => {
446
+ const r = run({
447
+ rows: [
448
+ HOLD_ROW(40, "conflict-hold:#40"),
449
+ HOLD_ROW(41, "conflict-hold:#41 · fix-pr-41=applied:def5678"),
450
+ HOLD_ROW(42, "conflict-hold:#42 · fix-pr-42=no-op"),
451
+ // A settle BEFORE the hold is stale: it cannot clear a newer conflict.
452
+ HOLD_ROW(43, "fix-pr-43=applied:def5678 · conflict-hold:#43"),
453
+ // Cleared once, then held again — the second hold is unresolved.
454
+ HOLD_ROW(44, "conflict-hold:#44 · fix-pr-44=applied:def5678 · conflict-hold:#44"),
455
+ // A fix-applier that died leaves the conflict where it was.
456
+ HOLD_ROW(45, "conflict-hold:#45 · fix-pr-45=failed"),
457
+ // A review after the cleared hold resets fixSince; the hold stays cleared.
458
+ HOLD_ROW(46, "conflict-hold:#46 · fix-pr-46=applied:def5678 · review=wf:x reviewed=def5678:0/1/0"),
459
+ // A closed PR is nobody's work.
460
+ HOLD_ROW(47, "conflict-hold:#47"),
461
+ ],
462
+ }, [40, 41, 42, 43, 44, 45, 46].map((n) => pr(n)));
463
+ assert.deepEqual(r.fixDue, [40, 43, 44, 45]);
464
+ });
465
+
466
+ test("deriveRun: a queued PR under a conflict hold is merge-held until its fix-applier SETTLES — dispatch alone does not lift it", () => {
467
+ const at = (tail) => run({ rows: [HOLD_ROW(40, tail)] }, [pr(40, ["ready-to-merge"])]);
468
+ const held = at("conflict-hold:#40");
469
+ assert.deepEqual([held.fixDue, held.mergeQueue, held.mergeHeld, held.mergeConflictHeld], [[40], 1, 1, 1]);
470
+ const working = at("conflict-hold:#40 · fix-pr-40");
471
+ assert.deepEqual(working.fixDue, [], "a live fix-applier is not re-offered");
472
+ assert.equal(working.mergeHeld, 1, "…and the merge bot does not re-select a PR still being fixed");
473
+ const landed = at("conflict-hold:#40 · fix-pr-40=applied:def5678");
474
+ assert.deepEqual([landed.fixDue, landed.mergeHeld, landed.mergeConflictHeld], [[], 0, 0]);
475
+ // Both sources on one PR count it once.
476
+ const both = run({ rows: [HOLD_ROW(40, "held-behind:#38 · conflict-hold:#40")] }, [pr(38), pr(40, ["ready-to-merge"])]);
477
+ assert.equal(both.mergeHeld, 1);
478
+ });
479
+
480
+ test("deriveRun: a conflict hold with a live review= in flight is not re-offered either — the merge hold still counts it", () => {
481
+ const r = run({ rows: ["#10 impl-10=PR#350 → PR#350 · conflict-hold:#350 review=wf:x"] }, [pr(350, ["ready-to-merge"])]);
482
+ assert.deepEqual(r.fixDue, [], "a review already running claims the row the same as a live fix-applier does");
483
+ assert.deepEqual([r.mergeQueue, r.mergeHeld, r.mergeConflictHeld], [1, 1, 1]);
484
+ });
485
+
486
+ test("deriveRun: a fix-applier settled in ## Dispatched clears a conflict hold even if a later row rewrite drops the =outcome suffix back to bare", () => {
487
+ const r = run({
488
+ rows: [HOLD_ROW(40, "conflict-hold:#40 · fix-pr-40")],
489
+ dispatched: ["fix-pr-40=applied:def5678"],
490
+ }, [pr(40, ["ready-to-merge"])]);
491
+ assert.deepEqual([r.fixDue, r.mergeHeld, r.mergeConflictHeld], [[], 0, 0],
492
+ "the member settled in ## Dispatched, not the row's own stale bare copy");
493
+ });
494
+
495
+ test("deriveRun: a redundant re-hold on an already-unresolved conflict does not reset a live fix-applier's fixSince", () => {
496
+ const r = run({ rows: [HOLD_ROW(40, "conflict-hold:#40 · fix-pr-40 · conflict-hold:#40")] }, [pr(40, ["ready-to-merge"])]);
497
+ assert.deepEqual(r.fixDue, [], "a live fix-applier working the first hold is not re-offered by a duplicate hold token");
498
+ assert.deepEqual([r.mergeHeld, r.mergeConflictHeld], [1, 1], "still held — the duplicate hold changes nothing about the merge gate");
499
+ });
500
+
501
+ test("deriveRun: a conflict hold is read in either spelling and on a PR-keyed row", () => {
502
+ assert.deepEqual(run({ rows: [HOLD_ROW(40, "conflict-hold-#40")] }, [pr(40)]).fixDue, [40]);
503
+ assert.deepEqual(run({ rows: ["#350 review=wf:x reviewed=abc1234:0/1/0 · conflict-hold:#350"] }, [pr(350)]).fixDue, [350]);
504
+ // `held-behind` rows and prose that merely mentions a conflict are not holds.
505
+ const prose = run({ rows: [HOLD_ROW(40, "(conflict vs #38, resolved by rebase-pr-40) merge-conflict-resolved:ef82065a")] }, [pr(40, ["ready-to-merge"])]);
506
+ assert.deepEqual([prose.fixDue, prose.mergeHeld], [[], 0]);
507
+ });
508
+
509
+ test("deriveRun: the merge bot is live while its ## Dispatched entry is unsettled", () => {
510
+ assert.equal(run({ dispatched: ["merge-bot-1"] }).mergeBotLive, 1);
511
+ assert.equal(run({ dispatched: ["merge-bot-1=done"] }).mergeBotLive, 0);
512
+ assert.equal(run({ dispatched: ["merge-bot-1=done", "merge-bot-2=killed", "merge-bot-3"] }).mergeBotLive, 1);
513
+ });
514
+
515
+ test("deriveRun: drain and tier mismatches come off the file", () => {
516
+ const r = run({
517
+ rows: ["#7 impl-7=tier-mismatch", "#8 impl-8=tier-mismatch · impl-8-b"],
518
+ dispatched: ["impl-7=tier-mismatch", "impl-8=tier-mismatch", "impl-8-b"],
519
+ drain: "maintainer asked",
520
+ });
521
+ assert.equal(r.draining, "maintainer asked");
522
+ assert.deepEqual(r.tierMismatch, ["impl-7"], "#8's replacement is the fix");
523
+ });
524
+
525
+ test("deriveRun: tier mismatch holds while the LATEST replacement is also tier-mismatch", () => {
526
+ const r = run({
527
+ rows: ["#8 impl-8=tier-mismatch · impl-8-b=tier-mismatch"],
528
+ dispatched: ["impl-8=tier-mismatch", "impl-8-b=tier-mismatch"],
529
+ });
530
+ assert.deepEqual(r.tierMismatch, ["impl-8-b"], "a replacement that is ALSO tier-mismatch keeps the row held");
531
+ });
532
+
533
+ // #1398: tier-check.mjs writes `tier-ok=<member>:<definition>` on a pass;
534
+ // the newest implementer of a ticket with no verdict holds as unchecked,
535
+ // live or settled alike.
536
+ test("deriveRun: the newest implementer with no tier verdict is unchecked, live or settled; tier-ok clears it", () => {
537
+ assert.deepEqual(run({ rows: ["#7 impl-7 · class=routine"] }).tierUnchecked, ["impl-7"]);
538
+ assert.deepEqual(run({ rows: ["#7 impl-7=bailed"] }).tierUnchecked, ["impl-7"], "a settled member is still owed its check");
539
+ const ok = run({ rows: ["#7 impl-7 · class=routine · tier-ok=impl-7:fleet-implementer"] });
540
+ assert.deepEqual([ok.tierUnchecked, ok.tierMismatch], [[], []]);
541
+ // A verdict names ITS member: another member's tier-ok clears nothing.
542
+ assert.deepEqual(run({ rows: ["#7 impl-7 · tier-ok=impl-17:fleet-implementer"] }).tierUnchecked, ["impl-7"]);
543
+ });
544
+
545
+ test("deriveRun: a settled tier-mismatch keeps its own hold and is never also unchecked", () => {
546
+ const r = run({ rows: ["#7 impl-7=tier-mismatch"], dispatched: ["impl-7=tier-mismatch"] });
547
+ assert.deepEqual([r.tierMismatch, r.tierUnchecked], [["impl-7"], []]);
548
+ // A member settled some other way before its check found the mismatch
549
+ // carries the verdict as a row token instead.
550
+ const token = run({ rows: ["#7 impl-7=bailed · tier-mismatch=impl-7:fleet-implementer"] });
551
+ assert.deepEqual([token.tierMismatch, token.tierUnchecked], [["impl-7"], []]);
552
+ });
553
+
554
+ test("deriveRun: only the newest member of a ticket counts toward the tier holds", () => {
555
+ const replaced = run({ rows: ["#8 impl-8=tier-mismatch · impl-8-b"], dispatched: ["impl-8=tier-mismatch", "impl-8-b"] });
556
+ assert.deepEqual([replaced.tierMismatch, replaced.tierUnchecked], [[], ["impl-8-b"]], "the replacement is what is owed a check now");
557
+ const checked = run({ rows: ["#8 impl-8=tier-mismatch · impl-8-b · tier-ok=impl-8-b:fleet-implementer"] });
558
+ assert.deepEqual([checked.tierMismatch, checked.tierUnchecked], [[], []]);
559
+ // The predecessor's own pass does not stand in for its replacement's.
560
+ const stale = run({ rows: ["#8 impl-8=killed · tier-ok=impl-8:fleet-implementer · impl-8-b"] });
561
+ assert.deepEqual(stale.tierUnchecked, ["impl-8-b"]);
562
+ // Nor does a predecessor killed before it was ever checked hold the row
563
+ // once its replacement has passed.
564
+ assert.deepEqual(run({ rows: ["#8 impl-8=killed · impl-8-b · tier-ok=impl-8-b:fleet-implementer"] }).tierUnchecked, []);
565
+ });
566
+
567
+ // PR #2302 review: the replacement climbs past the HIGHEST letter the ticket
568
+ // has used, not the held member's own — `-c` dispatched before `-b` left the
569
+ // tick naming `impl-7-c`, which ledger.mjs refuses as already dispatched.
570
+ test("deriveRun → implementers: a mismatch's replacement skips every retry letter the ticket already used", () => {
571
+ const step = (rows) => {
572
+ const d = run({ rows });
573
+ return row(state({ tierMismatch: d.tierMismatch, implNames: d.implNames }), "implementers").detail.split(" — ")[1];
574
+ };
575
+ assert.equal(step(["#7 impl-7=killed · impl-7-c=killed · impl-7-b=tier-mismatch"]), "dispatch impl-7-d at its row's tier");
576
+ assert.equal(step(["#7 impl-7-z=killed · impl-7-c=tier-mismatch"]), "impl-7-c has no retry letter left");
577
+ // Another ticket's letters are not this one's.
578
+ assert.equal(step(["#7 impl-7=tier-mismatch", "#8 impl-8-c=killed"]), "dispatch impl-7-b at its row's tier");
579
+ });
580
+
581
+ test("deriveRun: excluded rows claim their ticket while their premise still holds, and carry their premises", () => {
582
+ const r = run({ rows: ["#50 excluded · behind-pr:#44", "#51 excluded · behind-issue:#9 behind-pr:feat/x"] }, [pr(44)]);
583
+ assert.ok(r.claimed.has(50) && r.claimed.has(51));
584
+ assert.deepEqual(r.excluded, [
585
+ { n: 50, premises: [{ kind: "pr", target: "44" }] },
586
+ { n: 51, premises: [{ kind: "issue", target: "9" }, { kind: "pr", target: "feat/x" }] },
587
+ ]);
588
+ });
589
+
590
+ test("deriveRun: a behind-pr premise no longer open lifts the claim, but the row is still reported excluded", () => {
591
+ const r = run({ rows: ["#50 excluded · behind-pr:#44"] }, []);
592
+ assert.equal(r.claimed.has(50), false, "#44 is not in the open list — the premise has lifted");
593
+ assert.deepEqual(r.excluded, [{ n: 50, premises: [{ kind: "pr", target: "44" }] }]);
594
+ });
595
+
596
+ test("deriveRun: one still-open premise among several keeps the claim, even if another has lifted", () => {
597
+ const r = run({ rows: ["#50 excluded · behind-pr:#44 behind-pr:#45"] }, [pr(45)]);
598
+ assert.ok(r.claimed.has(50), "#45 is still open — #44 alone lifting is not enough");
599
+ });
600
+
601
+ test("deriveRun: the row text it does not own is accepted as it stands", () => {
602
+ // The accept side of every refusal below: freeform row text, the arrow, the
603
+ // board's own tokens and an empty ledger are the ordinary case.
604
+ assert.doesNotThrow(() => run({
605
+ rows: ["#324 impl-324=PR#346 → PR#346 · fix-pr-346=no-op · ruled:6-applies · ci=123:1:success · ports=16324 · tier=alt"],
606
+ dispatched: ["impl-324=PR#346", "fix-pr-346=no-op"],
607
+ }, [pr(346)]));
608
+ const empty = run({});
609
+ assert.equal(empty.implLive + empty.reviewsLive + empty.fixLive + empty.mergeBotLive, 0);
610
+ });
611
+
612
+ test("deriveRun: a token it cannot read refuses by naming it, never counts it live or gone", () => {
613
+ for (const [what, ledger, why] of [
614
+ ["an outcome outside the vocabulary", { rows: ["#9 impl-9=merged"] }, /impl-9.*'merged' is not an outcome/],
615
+ ["a malformed ## Dispatched entry", { dispatched: ["impl-9 oops"] }, /## Dispatched entry 'impl-9 oops'/],
616
+ ["a reviewed= with no counts", { rows: ["#9 review=wf:a reviewed=abc1234"] }, /reviewed=abc1234/],
617
+ ["a review= of no known kind", { rows: ["#9 review=bogus"] }, /review=bogus/],
618
+ ["a conflict hold naming another PR", { rows: ["#10 impl-10=PR#40 → PR#40 · conflict-hold:#38"] }, /conflict-hold:#38.*PR #40/],
619
+ ["a conflict hold on a row with no PR mention or PR-keyed impl token at all", { rows: ["conflict-hold:#40"] }, /no PR's/],
620
+ ]) {
621
+ assert.throws(() => run(ledger), why, what);
622
+ }
623
+ });
624
+
625
+ test("unclaimed: shortlist entries with no impl- or excluded row, in the file's order", () => {
626
+ const r = run({ rows: ["#2 impl-2", "#4 excluded · behind-pr:#1", "#5 impl-5=bailed"] }, [pr(1)]);
627
+ assert.deepEqual(unclaimed([1, 2, 3, 4, 5, 6].map((n) => ({ n, t: `t${n}` })), r), [1, 3, 6]);
628
+ });
629
+
630
+ test("unclaimed: a lifted behind-pr exclusion no longer claims its ticket, once it reaches the heads", () => {
631
+ const r = run({ rows: ["#4 excluded · behind-pr:#1"] }, []);
632
+ assert.deepEqual(unclaimed([1, 2, 3, 4].map((n) => ({ n, t: `t${n}` })), r), [1, 2, 3, 4]);
633
+ });
634
+
635
+ test("unclaimed: a behind-issue exclusion still claims its ticket while absent from entries", () => {
636
+ const r = run({ rows: ["#9 excluded · behind-issue:#5"] });
637
+ assert.deepEqual(unclaimed([1, 2, 3].map((n) => ({ n, t: `t${n}` })), r), [1, 2, 3]);
638
+ });
639
+
640
+ test("unclaimed: a behind-issue exclusion's ticket reappearing in entries is admitted — the ledger row is stale, the scan is not", () => {
641
+ const r = run({ rows: ["#9 excluded · behind-issue:#5"] });
642
+ assert.deepEqual(unclaimed([1, 9].map((n) => ({ n, t: `t${n}` })), r), [1, 9]);
643
+ });
644
+
645
+ test("unclaimed: a still-open behind-pr exclusion blocks its ticket even if it appears in entries", () => {
646
+ const r = run({ rows: ["#9 excluded · behind-pr:#44"] }, [pr(44)]);
647
+ assert.deepEqual(unclaimed([1, 9].map((n) => ({ n, t: `t${n}` })), r), [1]);
648
+ });
649
+
650
+ test("parseShortlist: shortlist.mjs's payload reads; anything else is unparsable, never a refusal", () => {
651
+ assert.deepEqual(parseShortlist('{"scanned":3,"shortlist":[{"n":7,"t":"a"}]}'),
652
+ { status: "ok", scanned: 3, entries: [{ n: 7, t: "a" }] });
653
+ for (const bad of ["", "{", "[]", '{"shortlist":[]}', '{"scanned":1,"shortlist":{}}', '{"scanned":1,"shortlist":[{"n":"7","t":"a"}]}',
654
+ '{"scanned":1,"shortlist":[{"n":0,"t":"a"}]}', '{"scanned":1,"shortlist":[{"n":-1,"t":"a"}]}']) {
655
+ assert.deepEqual(parseShortlist(bad), { status: "unparsable", scanned: null, entries: [] }, bad);
656
+ }
657
+ });
658
+
659
+ test("refreshWhy: short of the cap, missing or empty refreshes; draining never does", () => {
660
+ const base = { draining: null, status: "ok", entries: 5, unclaimed: 2, implCap: 2 };
661
+ assert.equal(refreshWhy(base), null);
662
+ assert.equal(refreshWhy({ ...base, unclaimed: 1 }), "unclaimed 1 < cap 2");
663
+ assert.equal(refreshWhy({ ...base, status: "missing", entries: 0, unclaimed: 0 }), "shortlist missing");
664
+ assert.equal(refreshWhy({ ...base, status: "unparsable", entries: 0, unclaimed: 0 }), "shortlist unparsable");
665
+ assert.equal(refreshWhy({ ...base, entries: 0, unclaimed: 0, implCap: 0 }), "shortlist empty");
666
+ assert.equal(refreshWhy({ ...base, status: "missing", draining: "x" }), null);
667
+ });
668
+
669
+ // ---------------------------------------------------------------------------
670
+ // The CLI half. Every case runs a COPY of the script from a stub directory,
671
+ // inside its own throwaway git repository, so the ledger and shortlist it
672
+ // reads are the case's own `.fleet/` files, resolved the way the real run
673
+ // resolves them — against the git common dir.
674
+
675
+ import { spawnSync } from "node:child_process";
676
+ import { mkdtempSync, mkdirSync, writeFileSync, chmodSync, rmSync, readFileSync, realpathSync, existsSync } from "node:fs";
677
+ import { tmpdir } from "node:os";
678
+ import { join } from "node:path";
679
+ import { fileURLToPath } from "node:url";
680
+
681
+ const SCRIPT = fileURLToPath(new URL("./fleet-tick.mjs", import.meta.url));
682
+ // Every non-builtin module the copied script needs at startup, direct import
683
+ // or transitive — and ledger.mjs with its own, because the tick reads the
684
+ // ledger through `ledger.mjs read`. An unlisted sibling is a module-not-found
685
+ // at startup: exit 1, a shape no case below expects.
686
+ const SIBLING_MODULES = ["arg.mjs", "fleet-state.mjs", "git-env.mjs", "ledger.mjs", "ledger-grammar.mjs"].map(
687
+ (m) => [m, fileURLToPath(new URL(`./${m}`, import.meta.url))],
688
+ );
689
+
690
+ // `pr list` for the open PRs, `issue view` for a behind-issue premise's state,
691
+ // `issue list --label in-progress` for the stall report's claimed count.
692
+ const GH_STUB = `#!/bin/sh
693
+ case "$1 $2" in
694
+ "pr list") [ -n "$PR_FAIL" ] && { echo "boom" >&2; exit 1; }; cat "$FIXTURE_PRS" ;;
695
+ "issue view")
696
+ echo "$3" >> "$ISSUE_VIEW_LOG"
697
+ [ -n "$ISSUE_VIEW_FAIL" ] && { echo "gh: issue view failed" >&2; exit 1; }
698
+ # Real gh answers for the repository an inherited GIT_DIR or GH_REPO names;
699
+ # this one answers CLOSED for every issue there, so a probe that forgot to
700
+ # scrub them lifts an exclusion the case's own repository still holds.
701
+ [ -n "$GIT_DIR$GIT_WORK_TREE$GH_REPO" ] && { echo '{"state":"CLOSED"}'; exit 0; }
702
+ exec jq -c --arg n "$3" '{state: (.[$n] // error("no such issue"))}' "$FIXTURE_ISSUE_STATES" ;;
703
+ "issue list")
704
+ [ -n "$CLAIMED_FAIL" ] && { echo "boom" >&2; exit 1; }
705
+ expr=""
706
+ while [ $# -gt 0 ]; do
707
+ case "$1" in --jq) shift; expr="$1" ;; esac
708
+ shift
709
+ done
710
+ exec jq -c "$expr" "$FIXTURE_CLAIMED" ;;
711
+ *) echo "unexpected gh $*" >&2; exit 1 ;;
712
+ esac
713
+ `;
714
+
715
+ // Stands in for shortlist.mjs, whose own suite is shortlist.test.mjs: logs
716
+ // that it ran, then either fails or writes the case's refreshed payload to the
717
+ // file the real one writes, and prints it with \`file\` the way the real one does.
718
+ const SHORTLIST_STUB = `import { writeFileSync, mkdirSync, appendFileSync, readFileSync } from "node:fs";
719
+ import { join } from "node:path";
720
+ appendFileSync(process.env.REFRESH_LOG, "ran\\n");
721
+ if (process.env.REFRESH_FAIL) { console.error("shortlist: could not answer"); process.exit(2); }
722
+ const payload = readFileSync(process.env.FIXTURE_REFRESH, "utf8");
723
+ const file = join(process.cwd(), ".fleet", "shortlist.json");
724
+ mkdirSync(join(process.cwd(), ".fleet"), { recursive: true });
725
+ writeFileSync(file, payload);
726
+ console.log(JSON.stringify({ file, ...JSON.parse(payload) }));
727
+ `;
728
+
729
+ // The ledger on disk, in the layout ledger.mjs's save() writes.
730
+ const ledgerText = ({ rows = [], dispatched = [], drain = null } = {}) => {
731
+ const list = (xs) => xs.map((x) => `- ${x}`).join("\n");
732
+ return `# Fleet run ledger\n\n## Rows\n\n${list(rows)}\n\n## Dispatched\n\n${list(dispatched)}\n\n## Filed\n\n\n\n## Ruled\n\n`
733
+ + (drain === null ? "" : `\n\n## Drain\n\n- ${drain}`) + "\n";
734
+ };
735
+ const shortlistText = (ns, scanned = ns.length) => JSON.stringify({ scanned, shortlist: ns.map((n) => ({ n, t: `t${n}` })) });
736
+
737
+ function runCli(args = [], {
738
+ prs = [], ledger, shortlist, refresh = shortlistText([]), refreshFail = false,
739
+ issueStates = {}, claimed = [], env: extraEnv = {}, defaultState = false, keep = false, beforeRun = () => {},
740
+ } = {}) {
741
+ // realpath, because on macOS tmpdir() is /var -> /private/var: a script COPY
742
+ // under the unresolved path never runs its own main(), since import.meta.url
743
+ // resolves the symlink and process.argv[1] does not.
744
+ const dir = realpathSync(mkdtempSync(join(tmpdir(), "fleet-tick-")));
745
+ const bin = join(dir, "bin");
746
+ const repo = join(dir, "repo");
747
+ mkdirSync(bin);
748
+ mkdirSync(join(repo, ".fleet"), { recursive: true });
749
+ assert.equal(spawnSync("git", ["init", "-q", repo], { encoding: "utf8" }).status, 0);
750
+ writeFileSync(join(bin, "gh"), GH_STUB);
751
+ chmodSync(join(bin, "gh"), 0o755);
752
+ const script = join(bin, "fleet-tick.mjs");
753
+ writeFileSync(script, readFileSync(SCRIPT));
754
+ for (const [name, path] of SIBLING_MODULES) writeFileSync(join(bin, name), readFileSync(path));
755
+ writeFileSync(join(bin, "shortlist.mjs"), SHORTLIST_STUB);
756
+ const fx = (name, content) => { const p = join(dir, name); writeFileSync(p, content); return p; };
757
+ if (ledger !== undefined) writeFileSync(join(repo, ".fleet", "ledger.md"), ledgerText(ledger));
758
+ if (shortlist !== undefined) writeFileSync(join(repo, ".fleet", "shortlist.json"), shortlist);
759
+ beforeRun(repo);
760
+ const refreshLog = fx("refresh.log", "");
761
+ const issueViewLog = fx("issue-view.log", "");
762
+ // Every case gets its own state file unless it names one: the default path
763
+ // resolves against the git common dir, and a shared streak and digest would
764
+ // make the fold cases order-dependent. `defaultState` opts out for the case
765
+ // whose subject IS that resolution.
766
+ const stateArg = args.includes("--state") || defaultState ? [] : ["--state", join(dir, "heartbeat.json")];
767
+ const r = spawnSync(process.execPath, [script, ...args, ...stateArg], {
768
+ cwd: repo, encoding: "utf8",
769
+ env: {
770
+ ...process.env, PATH: `${bin}:${process.env.PATH}`,
771
+ FIXTURE_PRS: fx("prs.json", JSON.stringify(prs)),
772
+ FIXTURE_CLAIMED: fx("claimed.json", JSON.stringify(claimed)),
773
+ FIXTURE_ISSUE_STATES: fx("issue-states.json", JSON.stringify(issueStates)),
774
+ FIXTURE_REFRESH: fx("refresh.json", refresh),
775
+ REFRESH_LOG: refreshLog, ISSUE_VIEW_LOG: issueViewLog,
776
+ ...(refreshFail ? { REFRESH_FAIL: "1" } : {}),
777
+ ...extraEnv,
778
+ },
779
+ });
780
+ r.refreshed = readFileSync(refreshLog, "utf8").split("\n").filter(Boolean).length;
781
+ r.issueViews = readFileSync(issueViewLog, "utf8").split("\n").filter(Boolean);
782
+ r.repo = repo;
783
+ r.dir = dir;
784
+ if (!keep) rmSync(dir, { recursive: true, force: true });
785
+ return r;
786
+ }
787
+ const lineOf = (r, role) => r.stdout.split("\n").filter((l) => l.startsWith(role));
788
+
789
+ test("CLI: the #1692 shape, read off the ledger — two live implementers at cap 2 pull nothing", () => {
790
+ const r = runCli([], {
791
+ ledger: { rows: ["#412 impl-412 · tier-ok=impl-412:fleet-implementer", "#415 impl-415 · tier-ok=impl-415:fleet-implementer"], dispatched: ["impl-412", "impl-415"] },
792
+ shortlist: shortlistText([412, 415, 420, 421, 422]),
793
+ });
794
+ assert.equal(r.status, 0, r.stderr);
795
+ assert.match(r.stdout, /^implementers 2\/2 → AT CAP/m);
796
+ assert.doesNotMatch(r.stdout, /PULL/);
797
+ assert.equal(r.refreshed, 0, "three unclaimed at cap 2 is not short of the cap");
798
+
799
+ // One settles: exactly one slot frees, and the next unclaimed head fills it.
800
+ const one = runCli([], {
801
+ ledger: { rows: ["#412 impl-412=PR#500 → PR#500 · tier-ok=impl-412:fleet-implementer", "#415 impl-415 · tier-ok=impl-415:fleet-implementer"], dispatched: ["impl-412=PR#500", "impl-415"] },
802
+ shortlist: shortlistText([412, 415, 420, 421, 422]),
803
+ });
804
+ assert.equal(one.status, 0, one.stderr);
805
+ assert.match(one.stdout, /^implementers 1\/2 → PULL #420 {3}\(/m);
806
+ });
807
+
808
+ test("CLI: a fresh run with no ledger reads zero live members, and no shortlist is depth 0 plus a refresh", () => {
809
+ const r = runCli([], { refresh: shortlistText([7, 8, 9], 12) });
810
+ assert.equal(r.status, 0, r.stderr);
811
+ assert.equal(r.refreshed, 1);
812
+ // Pulled from the file the refresh just wrote — not a tick of waiting.
813
+ assert.match(r.stdout, /^implementers 0\/2 → PULL #7 #8 {3}\(unclaimed=3 supply=12 unreviewed=0 shortlist=missing\)/m);
814
+ assert.match(r.stdout, /^shortlist {4}→ REFRESHED shortlist: 3 entries; 0 lifted {3}\(shortlist missing\)$/m);
815
+ });
816
+
817
+ test("CLI: an unparsable shortlist is depth 0 plus a refresh, never a refusal", () => {
818
+ const r = runCli([], { shortlist: "{not json", refresh: shortlistText([]) });
819
+ assert.equal(r.status, 0, r.stderr);
820
+ assert.equal(r.refreshed, 1);
821
+ assert.match(r.stdout, /^implementers 0\/2 → SUGGEST \/triage, hold idle {3}\(unclaimed=0 supply=0 unreviewed=0 shortlist=unparsable\)/m);
822
+ assert.match(r.stdout, /REFRESHED shortlist: 0 entries; 0 lifted {3}\(shortlist unparsable; unchanged\)/);
823
+ });
824
+
825
+ test("CLI: a permission-denied shortlist reads as unreadable, not unparsable — the fault is the filesystem's, not the JSON's", () => {
826
+ const r = runCli([], {
827
+ shortlist: shortlistText([1]), refresh: shortlistText([]),
828
+ beforeRun: (repo) => chmodSync(join(repo, ".fleet", "shortlist.json"), 0o000),
829
+ });
830
+ assert.equal(r.status, 0, r.stderr);
831
+ assert.equal(r.refreshed, 1, "unreadable, like unparsable, is a refresh trigger — never a refusal");
832
+ assert.match(r.stdout, /shortlist=unreadable/, "EACCES must not be mislabeled as malformed JSON");
833
+ assert.doesNotMatch(r.stdout, /shortlist=unparsable/);
834
+ });
835
+
836
+ test("CLI: a failed refresh prints REFRESH FAILED and every other row, at exit 0", () => {
837
+ const r = runCli([], { refreshFail: true, prs: [pr(60, ["ready-to-merge"])] });
838
+ assert.equal(r.status, 0, r.stderr);
839
+ assert.match(r.stdout, /^shortlist {4}→ REFRESH FAILED {3}\(shortlist missing — shortlist\.mjs exited 2: shortlist: could not answer\)$/m);
840
+ assert.match(r.stdout, /^merge-bot {4}0\/1 → DISPATCH merge-bot/m);
841
+ });
842
+
843
+ test("CLI: PULL names unclaimed heads only — claimed, bailed and excluded tickets are skipped", () => {
844
+ const r = runCli(["--implementer-cap", "3"], {
845
+ ledger: { rows: ["#1 impl-1=bailed · tier-ok=impl-1:fleet-implementer", "#2 impl-2 · tier-ok=impl-2:fleet-implementer", "#3 excluded · behind-pr:#99"], dispatched: ["impl-1=bailed", "impl-2"] },
846
+ shortlist: shortlistText([1, 2, 3, 4, 5, 6]),
847
+ prs: [pr(99)],
848
+ });
849
+ assert.equal(r.status, 0, r.stderr);
850
+ assert.match(r.stdout, /^implementers 1\/3 → PULL #4 #5 /m);
851
+ assert.equal(r.refreshed, 0, "three unclaimed at cap 3 is not short");
852
+ });
853
+
854
+ test("CLI: reviewer rows are named per PR, fix-appliers first, reviews oldest first", () => {
855
+ const r = runCli([], {
856
+ ledger: {
857
+ rows: [
858
+ "#10 impl-10=PR#346 → PR#346 · review=wf:a reviewed=abc1234:2/0/0",
859
+ "#11 impl-11=PR#350 → PR#350",
860
+ "#12 impl-12=PR#349 → PR#349",
861
+ ],
862
+ dispatched: ["impl-10=PR#346", "impl-11=PR#350", "impl-12=PR#349"],
863
+ },
864
+ shortlist: shortlistText([]),
865
+ prs: [pr(350), pr(349), pr(346)],
866
+ });
867
+ assert.equal(r.status, 0, r.stderr);
868
+ assert.deepEqual(lineOf(r, "reviewers").map((l) => l.replace(/ {3}\(.*$/, "")), [
869
+ "reviewers 0/6 → DISPATCH fix-pr PR#346",
870
+ "reviewers 0/6 → DISPATCH review PR#349 PR#350",
871
+ ]);
872
+ });
873
+
874
+ test("CLI: --max-reviews bounds the reviews one tick starts", () => {
875
+ const r = runCli(["--max-reviews", "1"], { shortlist: shortlistText([]), prs: [pr(51), pr(52), pr(53)] });
876
+ assert.equal(r.status, 0, r.stderr);
877
+ assert.match(r.stdout, /^reviewers {4}0\/6 → DISPATCH review PR#51 {3}\(.*max-reviews=1\)$/m);
878
+ const busy = runCli(["--max-reviews", "1"], {
879
+ ledger: { rows: ["#51 review=wf:x"] }, shortlist: shortlistText([]), prs: [pr(51), pr(52)],
880
+ });
881
+ assert.match(busy.stdout, /^reviewers {4}1\/6 → HOLD \(max-reviews 1 in flight\)/m);
882
+ // Default = the reviewer cap.
883
+ const open = runCli(["--reviewer-cap", "2"], { shortlist: shortlistText([]), prs: [pr(51), pr(52), pr(53)] });
884
+ assert.match(open.stdout, /^reviewers {4}0\/2 → DISPATCH review PR#51 PR#52 /m);
885
+ });
886
+
887
+ test("CLI: the narrowed backlog gate — a deep backlog with free reviewer slots still pulls", () => {
888
+ const r = runCli([], { shortlist: shortlistText([7, 8]), prs: [pr(51), pr(52), pr(53)] });
889
+ assert.equal(r.status, 0, r.stderr);
890
+ assert.match(r.stdout, /^implementers 0\/2 → PULL #7 #8 /m);
891
+ const saturated = runCli(["--reviewer-cap", "1"], {
892
+ ledger: { rows: ["#51 review=wf:x"] }, shortlist: shortlistText([7, 8]), prs: [pr(51), pr(52)],
893
+ });
894
+ assert.match(saturated.stdout, /^implementers 0\/2 → HOLD \(review side saturated\)/m);
895
+ });
896
+
897
+ test("CLI: drain holds the implementer row, stops refreshing, and keeps the review and merge rows firing", () => {
898
+ const r = runCli([], {
899
+ ledger: { rows: ["#9 impl-9=released"], dispatched: ["impl-9=released"], drain: "maintainer asked" },
900
+ prs: [pr(51), pr(60, ["ready-to-merge"])],
901
+ });
902
+ assert.equal(r.status, 0, r.stderr);
903
+ assert.match(r.stdout, /^implementers 0\/2 → HOLD \(draining\)/m);
904
+ assert.equal(r.refreshed, 0, "a draining run's missing shortlist is not a reason to restart supply");
905
+ assert.doesNotMatch(r.stdout, /REFRESH/);
906
+ assert.match(r.stdout, /^reviewers {4}0\/6 → DISPATCH review PR#51 /m);
907
+ assert.match(r.stdout, /^merge-bot {4}0\/1 → DISPATCH merge-bot /m);
908
+ });
909
+
910
+ test("CLI: merge-bot liveness and holds come off the ledger", () => {
911
+ const prs = [pr(38), pr(40, ["ready-to-merge"])];
912
+ const live = runCli([], { ledger: { dispatched: ["merge-bot-1"] }, shortlist: shortlistText([]), prs });
913
+ assert.match(live.stdout, /^merge-bot {4}1\/1 → AT CAP/m);
914
+ const held = runCli([], {
915
+ ledger: { rows: ["#10 impl-10=PR#40 → PR#40 · held-behind:#38"], dispatched: ["merge-bot-1=done"] },
916
+ shortlist: shortlistText([]), prs,
917
+ });
918
+ assert.match(held.stdout, /^merge-bot {4}0\/1 → HOLD {3}\(merge-queue=1 held=1/m);
919
+ const lifted = runCli([], {
920
+ ledger: { rows: ["#10 impl-10=PR#40 → PR#40 · held-behind:#38"], dispatched: ["merge-bot-1=done"] },
921
+ shortlist: shortlistText([]), prs: [pr(40, ["ready-to-merge"])],
922
+ });
923
+ assert.match(lifted.stdout, /^merge-bot {4}0\/1 → DISPATCH merge-bot {3}\(merge-queue=1 held=0\)/m);
924
+ });
925
+
926
+ test("CLI: a merge hold accepts both the held-behind:#M and held-behind-#M spellings", () => {
927
+ const colon = runCli([], {
928
+ ledger: { rows: ["#10 impl-10=PR#40 → PR#40 · held-behind:#38"], dispatched: ["merge-bot-1=done"] },
929
+ shortlist: shortlistText([]), prs: [pr(38), pr(40, ["ready-to-merge"])],
930
+ });
931
+ assert.match(colon.stdout, /^merge-bot {4}0\/1 → HOLD {3}\(merge-queue=1 held=1/m);
932
+ const hyphen = runCli([], {
933
+ ledger: { rows: ["#11 impl-11=PR#41 → PR#41 · held-behind-#38"], dispatched: ["merge-bot-1=done"] },
934
+ shortlist: shortlistText([]), prs: [pr(38), pr(41, ["ready-to-merge"])],
935
+ });
936
+ assert.match(hyphen.stdout, /^merge-bot {4}0\/1 → HOLD {3}\(merge-queue=1 held=1/m,
937
+ "run-merge-bot.md's own documented report format (#38) must be recognized too");
938
+ });
939
+
940
+ test("CLI: a conflict hold prints DISPATCH fix-pr and holds the merge bot until the fix-applier settles", () => {
941
+ const tick = (tail, dispatched) => runCli([], {
942
+ ledger: { rows: [`#10 impl-10=PR#40 → PR#40 · reviewed=abc1234:0/2/0 · ${tail}`], dispatched: ["merge-bot-1=done", ...dispatched] },
943
+ shortlist: shortlistText([]), prs: [pr(40, ["ready-to-merge"])],
944
+ }).stdout;
945
+ const held = tick("conflict-hold:#40", []);
946
+ assert.match(held, /^reviewers +0\/6 → DISPATCH fix-pr PR#40 /m);
947
+ assert.match(held, /^merge-bot {4}0\/1 → HOLD {3}\(merge-queue=1 held=1 — every queued candidate is held behind a lower PR or on a merge conflict no fix-pr has cleared\)$/m);
948
+ const working = tick("conflict-hold:#40 · fix-pr-40", ["fix-pr-40"]);
949
+ assert.doesNotMatch(working, /DISPATCH fix-pr/);
950
+ assert.match(working, /^merge-bot {4}0\/1 → HOLD {3}\(merge-queue=1 held=1/m);
951
+ const landed = tick("conflict-hold:#40 · fix-pr-40=applied:def5678", ["fix-pr-40=applied:def5678"]);
952
+ assert.doesNotMatch(landed, /DISPATCH fix-pr/);
953
+ assert.match(landed, /^merge-bot {4}0\/1 → DISPATCH merge-bot {3}\(merge-queue=1 held=0\)$/m);
954
+ });
955
+
956
+ test("CLI: a ledger token outside the grammar refuses the tick, printing no row", () => {
957
+ const r = runCli([], { ledger: { rows: ["#9 impl-9=merged"] }, shortlist: shortlistText([]) });
958
+ assert.equal(r.status, 2);
959
+ assert.equal(r.stdout.trim(), "");
960
+ assert.match(r.stderr, /^fleet-tick: .*impl-9.*'merged' is not an outcome/m);
961
+ });
962
+
963
+ test("CLI: a ledger ledger.mjs itself refuses is a refusal here too", () => {
964
+ // Two drain markers: ledger.mjs read exits 2 on the broken invariant.
965
+ const dir = runCli([], { shortlist: shortlistText([]), keep: true });
966
+ writeFileSync(join(dir.repo, ".fleet", "ledger.md"), `${ledgerText({ drain: "a" })}\n- b\n`);
967
+ const r = spawnSync(process.execPath, [join(dir.dir, "bin", "fleet-tick.mjs"), "--state", join(dir.dir, "hb.json")], {
968
+ cwd: dir.repo, encoding: "utf8",
969
+ env: { ...process.env, PATH: `${join(dir.dir, "bin")}:${process.env.PATH}`, FIXTURE_PRS: join(dir.dir, "prs.json") },
970
+ });
971
+ rmSync(dir.dir, { recursive: true, force: true });
972
+ assert.equal(r.status, 2, r.stderr);
973
+ assert.equal(r.stdout.trim(), "");
974
+ assert.match(r.stderr, /fleet-tick: ledger\.mjs read exited 2/);
975
+ });
976
+
977
+ test("CLI: a tier mismatch holds the implementer row until a replacement is dispatched", () => {
978
+ const r = runCli([], { ledger: { rows: ["#7 impl-7=tier-mismatch"], dispatched: ["impl-7=tier-mismatch"] }, shortlist: shortlistText([8, 9]) });
979
+ assert.match(r.stdout, /^implementers 0\/2 → HOLD \(tier mismatch impl-7\) +\(.* — dispatch impl-7-b at its row's tier\)$/m);
980
+ });
981
+
982
+ test("CLI: an implementer with no tier verdict on the ledger holds the implementer row until tier-check writes one", () => {
983
+ const r = runCli([], { ledger: { rows: ["#7 impl-7 · class=routine"], dispatched: ["impl-7"] }, shortlist: shortlistText([8, 9]) });
984
+ assert.match(r.stdout, /^implementers 1\/2 → HOLD \(tier unchecked impl-7\) +\(.* — run ~\/\.fleet\/bin\/fleet-run tier-check\.mjs --batch <file> with \[\{"member":"impl-7","session":"<session>"\}\]\)$/m);
985
+ const ok = runCli([], {
986
+ ledger: { rows: ["#7 impl-7 · class=routine · tier-ok=impl-7:fleet-implementer"], dispatched: ["impl-7"] },
987
+ shortlist: shortlistText([8, 9]),
988
+ });
989
+ assert.match(ok.stdout, /^implementers 1\/2 → PULL #8 /m);
990
+ });
991
+
992
+ test("CLI: a lifted exclusion premise triggers a refresh even with the shortlist full", () => {
993
+ const full = { shortlist: shortlistText([1, 2, 3]), refresh: shortlistText([1, 2, 3, 50]) };
994
+ const standing = runCli([], { ...full, ledger: { rows: ["#50 excluded · behind-pr:#44"] }, prs: [pr(44)] });
995
+ assert.equal(standing.refreshed, 0, "#44 is still open — the exclusion stands");
996
+ const lifted = runCli([], { ...full, ledger: { rows: ["#50 excluded · behind-pr:#44"] }, prs: [] });
997
+ assert.equal(lifted.refreshed, 1);
998
+ assert.match(lifted.stdout, /REFRESHED shortlist: 4 entries; 1 lifted {3}\(behind-pr:#44 no longer open\)/);
999
+ const issue = runCli([], { ...full, ledger: { rows: ["#50 excluded · behind-issue:#9"] }, issueStates: { 9: "CLOSED" } });
1000
+ assert.equal(issue.refreshed, 1);
1001
+ assert.deepEqual(issue.issueViews, ["9"]);
1002
+ const openIssue = runCli([], { ...full, ledger: { rows: ["#50 excluded · behind-issue:#9"] }, issueStates: { 9: "OPEN" } });
1003
+ assert.equal(openIssue.refreshed, 0);
1004
+ // Already back on the current file: the refresh that lifted it has run.
1005
+ const reflected = runCli([], {
1006
+ shortlist: shortlistText([1, 2, 50]), ledger: { rows: ["#50 excluded · behind-issue:#9"] }, issueStates: { 9: "CLOSED" },
1007
+ });
1008
+ assert.equal(reflected.refreshed, 0);
1009
+ assert.deepEqual(reflected.issueViews, [], "no probe for a premise the file already reflects");
1010
+ });
1011
+
1012
+ test("CLI: a lifted behind-pr exclusion names its ticket in the PULL row, with no refresh needed", () => {
1013
+ const r = runCli(["--implementer-cap", "1"], {
1014
+ shortlist: shortlistText([50]), ledger: { rows: ["#50 excluded · behind-pr:#44"] }, prs: [],
1015
+ });
1016
+ assert.equal(r.status, 0, r.stderr);
1017
+ assert.equal(r.refreshed, 0, "the open-PR list already proves #44 is gone — no refresh needed to know it");
1018
+ assert.match(r.stdout, /^implementers 0\/1 → PULL #50 /m);
1019
+ });
1020
+
1021
+ test("CLI: a behind-issue exclusion already reflected in the current file names its ticket in the PULL row", () => {
1022
+ // The confirmed live bug (#1803 review): a prior tick already refreshed and
1023
+ // printed "lifted", so the file has #50 back — but the ledger's `excluded`
1024
+ // row is untouched until a Pull rewrites it. This tick gets no refresh
1025
+ // trigger at all (the file already carries #50), so the fix has to live in
1026
+ // how a claim from that stale row is read, not in another gh call.
1027
+ const r = runCli(["--implementer-cap", "3"], {
1028
+ shortlist: shortlistText([1, 2, 50]), ledger: { rows: ["#50 excluded · behind-issue:#9"] }, issueStates: { 9: "CLOSED" },
1029
+ });
1030
+ assert.equal(r.status, 0, r.stderr);
1031
+ assert.equal(r.refreshed, 0, "already reflected — no refresh needed to admit it");
1032
+ assert.match(r.stdout, /^implementers 0\/3 → PULL #1 #2 #50 /m);
1033
+ });
1034
+
1035
+ test("CLI: a failed gh issue view probe is disclosed, not silently swallowed", () => {
1036
+ const full = { shortlist: shortlistText([1, 2, 3]), refresh: shortlistText([1, 2, 3, 50]) };
1037
+ const r = runCli([], {
1038
+ ...full, ledger: { rows: ["#50 excluded · behind-issue:#9"] }, issueStates: { 9: "CLOSED" },
1039
+ env: { ISSUE_VIEW_FAIL: "1" },
1040
+ });
1041
+ assert.equal(r.status, 0, r.stderr);
1042
+ assert.equal(r.refreshed, 0, "a failed probe cannot confirm the lift — the exclusion stands");
1043
+ assert.match(r.stderr, /fleet-tick: gh issue view 9 exited 1: gh: issue view failed — behind-issue:#9 premise unconfirmed, exclusion stands/);
1044
+ });
1045
+
1046
+ test("CLI: the six caller-stated flags are gone — each refuses as unknown", () => {
1047
+ for (const flag of ["--implementers", "--reviewers", "--merge-bots", "--pool", "--reviews-ready", "--merge-holds"]) {
1048
+ const r = runCli([flag, "1"], { shortlist: shortlistText([]) });
1049
+ assert.equal(r.status, 2, flag);
1050
+ assert.match(r.stderr, /accepted: --implementer-cap, --reviewer-cap, --max-reviews, --fold-unchanged, --state/, flag);
1051
+ assert.equal(r.stdout.trim(), "", flag);
1052
+ }
1053
+ });
1054
+
1055
+ test("CLI: caps must be positive integers, with no upper bound", () => {
1056
+ for (const bad of [["--implementer-cap", "0"], ["--reviewer-cap", "0"], ["--max-reviews", "0"], ["--implementer-cap=x"], ["--max-reviews="]]) {
1057
+ const r = runCli(bad, { shortlist: shortlistText([]) });
1058
+ assert.equal(r.status, 2, bad.join(" "));
1059
+ assert.equal(r.stdout.trim(), "");
1060
+ }
1061
+ const big = runCli(["--implementer-cap", "9", "--reviewer-cap", "12"], { shortlist: shortlistText([]) });
1062
+ assert.equal(big.status, 0, big.stderr);
1063
+ assert.match(big.stdout, /^implementers 0\/9 /m);
1064
+ assert.match(big.stdout, /^reviewers {4}0\/12 /m);
1065
+ });
1066
+
1067
+ test("CLI: a failed gh read refuses — it is not an empty backlog", () => {
1068
+ const r = runCli([], { env: { PR_FAIL: "1" }, shortlist: shortlistText([]) });
1069
+ assert.equal(r.status, 2);
1070
+ assert.equal(r.stdout.trim(), "");
1071
+ assert.match(r.stderr, /gh pr list/);
1072
+ });
1073
+
1074
+ test("CLI: a PR list at the limit refuses rather than serving a truncated one", () => {
1075
+ const r = runCli([], { prs: Array.from({ length: 200 }, (_, i) => pr(i + 1)), shortlist: shortlistText([]) });
1076
+ assert.equal(r.status, 2);
1077
+ assert.match(r.stderr, /truncated|capped/i);
1078
+ });
1079
+
1080
+ test("CLI: a gh row missing closingIssuesReferences refuses rather than counting as no-issue", () => {
1081
+ const r = runCli([], { prs: [{ number: 1, labels: [] }], shortlist: shortlistText([]) });
1082
+ assert.equal(r.status, 2);
1083
+ assert.equal(r.stdout.trim(), "");
1084
+ assert.match(r.stderr, /closingIssuesReferences/);
1085
+ });
1086
+
1087
+ test("CLI: a gh row missing headRefOid refuses rather than reading every past-pin halt as moved", () => {
1088
+ const { headRefOid, ...headless } = pr(1);
1089
+ const r = runCli([], { prs: [headless], shortlist: shortlistText([]) });
1090
+ assert.equal(r.status, 2);
1091
+ assert.equal(r.stdout.trim(), "");
1092
+ assert.match(r.stderr, /headRefOid/);
1093
+ });
1094
+
1095
+ test("CLI: a past-pin halt prints DISPATCH review for its PR (#2083)", () => {
1096
+ const r = runCli([], {
1097
+ ledger: { rows: ["#10 impl-10=PR#40 → PR#40 · review=wf:a reviewed=abc1234:0/0/0 · finisher-pr-40=halted:past-pin"] },
1098
+ shortlist: shortlistText([]), prs: [pr(40, [], [10], HEAD_B)],
1099
+ });
1100
+ assert.equal(r.status, 0, r.stderr);
1101
+ assert.match(r.stdout, /^reviewers {4}0\/6 → DISPATCH review PR#40 /m);
1102
+ });
1103
+
1104
+ test("CLI: an ambient GIT_DIR naming another repository cannot move the shortlist read", () => {
1105
+ const decoy = realpathSync(mkdtempSync(join(tmpdir(), "fleet-tick-decoy-")));
1106
+ spawnSync("git", ["init", "-q", decoy]);
1107
+ mkdirSync(join(decoy, ".fleet"));
1108
+ writeFileSync(join(decoy, ".fleet", "shortlist.json"), shortlistText([666]));
1109
+ const r = runCli([], { shortlist: shortlistText([7, 8]), env: { GIT_DIR: join(decoy, ".git") } });
1110
+ rmSync(decoy, { recursive: true, force: true });
1111
+ assert.equal(r.status, 0, r.stderr);
1112
+ assert.match(r.stdout, /^implementers 0\/2 → PULL #7 #8 /m);
1113
+ });
1114
+
1115
+ test("CLI: an inherited GIT_DIR cannot retarget the behind-issue premise probe", () => {
1116
+ const decoy = realpathSync(mkdtempSync(join(tmpdir(), "fleet-tick-decoy-gh-")));
1117
+ spawnSync("git", ["init", "-q", decoy]);
1118
+ const r = runCli([], {
1119
+ shortlist: shortlistText([1, 2, 3]), ledger: { rows: ["#50 excluded · behind-issue:#9"] }, issueStates: { 9: "OPEN" },
1120
+ env: { GIT_DIR: join(decoy, ".git"), GH_REPO: "someone/else" },
1121
+ });
1122
+ rmSync(decoy, { recursive: true, force: true });
1123
+ assert.equal(r.status, 0, r.stderr);
1124
+ assert.deepEqual(r.issueViews, ["9"], "the probe must still run");
1125
+ assert.equal(r.refreshed, 0, "#9 is OPEN in the case's own repository — the exclusion stands");
1126
+ });
1127
+
1128
+ // ---------------------------------------------------------------------------
1129
+ // The heartbeat's half - #357. The tick is the only writer of the back-off
1130
+ // streak and the fold digest, so these pin the contract fleet-heartbeat.mjs
1131
+ // reads rather than the heartbeat's own arithmetic (that is its test's job).
1132
+
1133
+ const IDLE = { shortlist: shortlistText([]), refresh: shortlistText([]) };
1134
+
1135
+ test("CLI: the quiet streak lengthens on an idle tick and resets on an actionable one", () => {
1136
+ const dir = realpathSync(mkdtempSync(join(tmpdir(), "fleet-tick-state-")));
1137
+ const path = join(dir, "heartbeat.json");
1138
+ runCli(["--state", path], IDLE);
1139
+ assert.equal(JSON.parse(readFileSync(path, "utf8")).quiet, 1);
1140
+ runCli(["--state", path], IDLE);
1141
+ assert.equal(JSON.parse(readFileSync(path, "utf8")).quiet, 2);
1142
+ runCli(["--state", path], { ...IDLE, shortlist: shortlistText([9]) });
1143
+ assert.equal(JSON.parse(readFileSync(path, "utf8")).quiet, 0);
1144
+ rmSync(dir, { recursive: true, force: true });
1145
+ });
1146
+
1147
+ test("CLI: --fold-unchanged folds a repeated idle tick to one line", () => {
1148
+ const dir = realpathSync(mkdtempSync(join(tmpdir(), "fleet-tick-fold-")));
1149
+ const path = join(dir, "heartbeat.json");
1150
+ const first = runCli(["--fold-unchanged", "--state", path], IDLE);
1151
+ assert.equal(first.status, 0, first.stderr);
1152
+ assert.ok(first.stdout.trim().split("\n").length >= 3);
1153
+ const second = runCli(["--fold-unchanged", "--state", path], IDLE);
1154
+ assert.deepEqual(second.stdout.trim().split("\n"), ["fleet-tick: unchanged, nothing to act on (quiet=2) — full rows on the next change"]);
1155
+ rmSync(dir, { recursive: true, force: true });
1156
+ });
1157
+
1158
+ test("CLI: --fold-unchanged never folds an actionable tick, even an identical one", () => {
1159
+ const dir = realpathSync(mkdtempSync(join(tmpdir(), "fleet-tick-fold-act-")));
1160
+ const path = join(dir, "heartbeat.json");
1161
+ const busy = { shortlist: shortlistText([9, 10]) };
1162
+ const first = runCli(["--fold-unchanged", "--state", path], busy);
1163
+ const second = runCli(["--fold-unchanged", "--state", path], busy);
1164
+ assert.equal(second.stdout, first.stdout);
1165
+ assert.match(second.stdout, /PULL #9 #10/);
1166
+ assert.equal(JSON.parse(readFileSync(path, "utf8")).quiet, 0);
1167
+ rmSync(dir, { recursive: true, force: true });
1168
+ });
1169
+
1170
+ test("CLI: --fold-unchanged does not fold when the rows change, even with nothing to act on", () => {
1171
+ const dir = realpathSync(mkdtempSync(join(tmpdir(), "fleet-tick-fold-differs-")));
1172
+ const path = join(dir, "heartbeat.json");
1173
+ runCli(["--fold-unchanged", "--state", path], IDLE);
1174
+ // A queued candidate, held behind a lower PR: still nothing to act on.
1175
+ const held = {
1176
+ ...IDLE, ledger: { rows: ["#10 impl-10=PR#40 → PR#40 · held-behind:#38 · tier-ok=impl-10:fleet-implementer"] },
1177
+ prs: [pr(38, [], []), pr(40, ["ready-to-merge"])],
1178
+ };
1179
+ const second = runCli(["--fold-unchanged", "--state", path], held);
1180
+ assert.match(second.stdout, /^merge-bot {4}0\/1 → HOLD\b/m);
1181
+ assert.doesNotMatch(second.stdout, /nothing to act on/);
1182
+ const third = runCli(["--fold-unchanged", "--state", path], held);
1183
+ assert.match(third.stdout, /^fleet-tick: unchanged, nothing to act on \(quiet=3\)/);
1184
+ rmSync(dir, { recursive: true, force: true });
1185
+ });
1186
+
1187
+ test("CLI: with no --state, the tick resolves the run's shared default", () => {
1188
+ const r = runCli([], { ...IDLE, defaultState: true, keep: true });
1189
+ const state = join(r.repo, ".fleet", "heartbeat.json");
1190
+ assert.equal(r.status, 0, r.stderr);
1191
+ assert.doesNotMatch(r.stderr, /WARNING/);
1192
+ assert.ok(existsSync(state));
1193
+ assert.equal(JSON.parse(readFileSync(state, "utf8")).quiet, 1);
1194
+ rmSync(r.dir, { recursive: true, force: true });
1195
+ });
1196
+
1197
+ // The prior run's liveness - #1597.
1198
+ const beat = (ms, interval, stopped = "") =>
1199
+ JSON.stringify({ quiet: 0, elapsed: 0, digest: "", beat: { at: Date.now() - ms, interval, stopped } });
1200
+
1201
+ test("CLI: a stale prior beat is reported, and reported FIRST, with the stranded claims and the supply", () => {
1202
+ const dir = realpathSync(mkdtempSync(join(tmpdir(), "fleet-tick-stall-")));
1203
+ const path = join(dir, "heartbeat.json");
1204
+ writeFileSync(path, beat(90 * 60_000, 1200));
1205
+ const r = runCli(["--state", path], { shortlist: shortlistText([9], 1), claimed: [{ number: 41 }, { number: 42 }, { number: 43 }] });
1206
+ assert.equal(r.status, 0, r.stderr);
1207
+ const lines = r.stdout.trim().split("\n");
1208
+ assert.match(lines[0], /^heartbeat STALLED/);
1209
+ assert.match(lines[1], /^implementers/);
1210
+ assert.match(lines[0], /3 ticket\(s\) claimed and in flight/);
1211
+ assert.match(lines[0], /pool supply 1/);
1212
+ rmSync(dir, { recursive: true, force: true });
1213
+ });
1214
+
1215
+ test("CLI: an unreadable shortlist makes the stall report's supply unknown, never zero", () => {
1216
+ const dir = realpathSync(mkdtempSync(join(tmpdir(), "fleet-tick-stall-supply-")));
1217
+ const path = join(dir, "heartbeat.json");
1218
+ writeFileSync(path, beat(90 * 60_000, 1200));
1219
+ const r = runCli(["--state", path], { shortlist: "{" });
1220
+ assert.match(r.stdout.split("\n")[0], /pool supply unknown/);
1221
+ rmSync(dir, { recursive: true, force: true });
1222
+ });
1223
+
1224
+ test("CLI: the stall is announced even when the reconcile then refuses", () => {
1225
+ const dir = realpathSync(mkdtempSync(join(tmpdir(), "fleet-tick-stall-refuse-")));
1226
+ const path = join(dir, "heartbeat.json");
1227
+ writeFileSync(path, beat(90 * 60_000, 1200));
1228
+ const r = runCli(["--state", path], { ...IDLE, claimed: [{ number: 41 }], env: { PR_FAIL: "1" } });
1229
+ assert.equal(r.status, 2);
1230
+ assert.match(r.stderr, /gh pr list failed/);
1231
+ assert.match(r.stdout, /heartbeat STALLED/);
1232
+ rmSync(dir, { recursive: true, force: true });
1233
+ });
1234
+
1235
+ test("CLI: an unreadable claim count is `unknown`, never zero", () => {
1236
+ const dir = realpathSync(mkdtempSync(join(tmpdir(), "fleet-tick-stall-unknown-")));
1237
+ const path = join(dir, "heartbeat.json");
1238
+ writeFileSync(path, beat(90 * 60_000, 1200));
1239
+ const r = runCli(["--state", path], { ...IDLE, env: { CLAIMED_FAIL: "1" } });
1240
+ assert.equal(r.status, 0, r.stderr);
1241
+ assert.match(r.stdout, /unknown ticket\(s\) claimed and in flight/);
1242
+ assert.match(r.stderr, /claimed ticket count unknown/);
1243
+ assert.match(r.stderr, /boom/);
1244
+ rmSync(dir, { recursive: true, force: true });
1245
+ });
1246
+
1247
+ // The claimed-count query is capped at CLAIMED_LIMIT (200). At exactly the cap
1248
+ // the list may be truncated, so the report must say the count is a floor
1249
+ // (`200+`); one below the cap it is exact and must carry no `+`. The stub
1250
+ // answers `--jq length` over the fixture array, so the array's size is the
1251
+ // count the tick reads. #1760.
1252
+ // Mutation-checked both ways against claimed()'s truncation branch: making it
1253
+ // `return n;` reds the 200 case ("…; 200 ticket(s) claimed and in flight…"
1254
+ // did not match /; 200\+ ticket/), and making it always return `${n}+` reds the
1255
+ // 199 case ("…; 199+ ticket(s) claimed and in flight…" did not match
1256
+ // /; 199 ticket/). The literal `199 ticket(s)` adjacency — no `+` allowed
1257
+ // between the digits and the space — is what refuses `199+`; the `; ` prefix
1258
+ // only anchors the match to the claimed-count field.
1259
+ test("CLI: a claim count AT the query cap is disclosed as a floor (`200+`); one below it is exact", () => {
1260
+ const dir = realpathSync(mkdtempSync(join(tmpdir(), "fleet-tick-stall-cap-")));
1261
+ const path = join(dir, "heartbeat.json");
1262
+ const stalled = (count) => {
1263
+ // Re-staled every call: each run records its own tick in the state file.
1264
+ writeFileSync(path, beat(90 * 60_000, 1200));
1265
+ const claimed = Array.from({ length: count }, (_, i) => ({ number: i + 1 }));
1266
+ const r = runCli(["--state", path], { ...IDLE, claimed });
1267
+ assert.equal(r.status, 0, r.stderr);
1268
+ const line = r.stdout.split("\n")[0];
1269
+ assert.match(line, /^heartbeat STALLED/);
1270
+ return line;
1271
+ };
1272
+ assert.match(stalled(200), /; 200\+ ticket\(s\) claimed and in flight/);
1273
+ assert.match(stalled(199), /; 199 ticket\(s\) claimed and in flight/);
1274
+ rmSync(dir, { recursive: true, force: true });
1275
+ });
1276
+
1277
+ test("CLI: a beat within the interval it promised is not reported at all", () => {
1278
+ const dir = realpathSync(mkdtempSync(join(tmpdir(), "fleet-tick-quiet-")));
1279
+ const path = join(dir, "heartbeat.json");
1280
+ writeFileSync(path, beat(20 * 60_000, 1200));
1281
+ assert.doesNotMatch(runCli(["--state", path], IDLE).stdout, /STALLED/);
1282
+ writeFileSync(path, beat(20 * 60_000, 300));
1283
+ assert.match(runCli(["--state", path], IDLE).stdout, /STALLED/);
1284
+ rmSync(dir, { recursive: true, force: true });
1285
+ });
1286
+
1287
+ test("CLI: the streak write carries the heartbeat's mark instead of erasing it, and writes its own", () => {
1288
+ const dir = realpathSync(mkdtempSync(join(tmpdir(), "fleet-tick-mark-carry-")));
1289
+ const path = join(dir, "heartbeat.json");
1290
+ const mark = { at: Date.now() - 60_000, interval: 300, stopped: "" };
1291
+ writeFileSync(path, JSON.stringify({ quiet: 3, elapsed: 7, digest: "old", beat: mark }));
1292
+ const r = runCli(["--state", path], IDLE);
1293
+ assert.equal(r.status, 0, r.stderr);
1294
+ const after = JSON.parse(readFileSync(path, "utf8"));
1295
+ assert.deepEqual(after.beat, mark);
1296
+ assert.equal(after.quiet, 4);
1297
+ assert.ok(after.ticked && after.ticked.at >= Date.now() - 5000);
1298
+ rmSync(dir, { recursive: true, force: true });
1299
+ });
1300
+
1301
+ test("CLI: a deliberate stop is reported with its reason, and a run that never beat says nothing", () => {
1302
+ const dir = realpathSync(mkdtempSync(join(tmpdir(), "fleet-tick-stopped-")));
1303
+ const path = join(dir, "heartbeat.json");
1304
+ writeFileSync(path, beat(6 * 60_000, 300, "context ceiling reached"));
1305
+ const r = runCli(["--state", path], IDLE);
1306
+ assert.equal(r.status, 0, r.stderr);
1307
+ assert.match(r.stdout, /stopped deliberately — recorded reason: context ceiling reached/);
1308
+ assert.doesNotMatch(r.stdout, /without a recorded reason/);
1309
+ writeFileSync(path, JSON.stringify({ quiet: 0, elapsed: 0, digest: "" }));
1310
+ assert.doesNotMatch(runCli(["--state", path], IDLE).stdout, /STALLED/);
1311
+ rmSync(dir, { recursive: true, force: true });
1312
+ });
1313
+
1314
+ test("CLI: a busy, fully-staffed fleet is not reported STALLED just because the queue never drained", () => {
1315
+ // `beat` refreshes only when the queue drains; a tick two minutes ago on a
1316
+ // completion edge is what tells a busy run from a dead one.
1317
+ const dir = realpathSync(mkdtempSync(join(tmpdir(), "fleet-tick-busy-not-stalled-")));
1318
+ const path = join(dir, "heartbeat.json");
1319
+ writeFileSync(path, JSON.stringify({
1320
+ quiet: 0, elapsed: 0, digest: "",
1321
+ beat: { at: Date.now() - 11 * 60_000, interval: 300, stopped: "" },
1322
+ ticked: { at: Date.now() - 2 * 60_000 },
1323
+ }));
1324
+ const r = runCli(["--state", path], {
1325
+ ledger: { rows: ["#1 impl-1 · tier-ok=impl-1:fleet-implementer", "#2 impl-2 · tier-ok=impl-2:fleet-implementer"], dispatched: ["impl-1", "impl-2"] },
1326
+ shortlist: shortlistText([3, 4, 5]), claimed: [{ number: 41 }],
1327
+ });
1328
+ assert.equal(r.status, 0, r.stderr);
1329
+ assert.doesNotMatch(r.stdout, /STALLED/);
1330
+ assert.match(r.stdout, /^implementers 2\/2 → AT CAP/m);
1331
+ rmSync(dir, { recursive: true, force: true });
1332
+ });