@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,832 @@
1
+ #!/usr/bin/env node
2
+ // The reconcile tick. run-team's Phase 3 is an event loop, and implementer
3
+ // refill was wired as an EDGE — "a member finished → refill its slot". That
4
+ // edge dies the moment live implementers reach 0, because 0 implementers emit
5
+ // no completion event, and "free capacity + a non-empty pool" is a LEVEL
6
+ // condition an edge-triggered loop cannot observe once it stops changing. #3:
7
+ // implementers sat at 0/target with pool 1 and ~57 `ready-for-agent` in supply
8
+ // until a human asked why nothing was being implemented. No error, no warning.
9
+ //
10
+ // So compute the deficit instead of remembering it. Every wake ends in one
11
+ // invocation (spec 2026-09-24 § 6: record, tick, act, beat), and each prints
12
+ // actual/target and a named ACTION per role — `PULL #412 #415`, `DISPATCH
13
+ // fix-pr PR#346`, `DISPATCH review PR#350`, `DISPATCH merge-bot`, `HOLD (…)`,
14
+ // `REFRESHED shortlist: …` — with run-team's guards applied in code rather than
15
+ // recalled from its table. You cannot forget what a script prints at you.
16
+ //
17
+ // WHERE THE NUMBERS COME FROM — nobody states them (#1803, ADR 0012 Decision 5):
18
+ //
19
+ // ledger `.fleet/ledger.md`, read through `ledger.mjs read` so the ledger
20
+ // keeps one parser, and its member tokens through
21
+ // ledger-grammar.mjs so it keeps one grammar. A member is live
22
+ // while its token is bare (`impl-412`) and settled once it reads
23
+ // `<member>=<outcome>` — `ledger.mjs dispatch` and `settle` are the
24
+ // only writers of either, so the file answers "who is live" where
25
+ // it once recorded only that someone was dispatched. Live
26
+ // implementers, live reviewer units (in-flight `review=` plus
27
+ // unsettled `fix-pr-`), the merge bot (`## Dispatched`), merge
28
+ // holds (`held-behind:#M`, and merge-bot's own
29
+ // `conflict-hold:#<pr>`), tier mismatches and the drain marker
30
+ // all come off it. A missing ledger is a fresh run: zero rows.
31
+ // shortlist `.fleet/shortlist.json`, shortlist.mjs's output, resolved against
32
+ // the git common dir as ledger.mjs resolves the ledger. Its
33
+ // entries minus every ticket with an `impl-` row, or an `excluded`
34
+ // row whose premise still holds, are the heads a PULL names; its
35
+ // `scanned` is the supply. Missing or unparsable is depth 0 and a
36
+ // refresh, never a refusal: the depth only ever bounds PULLs
37
+ // downward.
38
+ // gh The open PRs, by label and by whether they close an issue — the
39
+ // merge queue, and which PRs are owed a review.
40
+ //
41
+ // The pure half below is `reconcile()` over the counts `deriveRun()` reads off
42
+ // the ledger; main() does the I/O. Split so the guard table and the reading are
43
+ // both unit-testable without a network — fleet-tick.test.mjs.
44
+
45
+ import { parseMember, parseToken } from "./ledger-grammar.mjs";
46
+
47
+ // Every role's TARGET is its configured cap. Availability of work belongs in
48
+ // the ACTION, not the target: a reviewer target that shrank to the backlog
49
+ // would print `0/0 → idle` and read as "correctly sized" for the exact drained
50
+ // state that is the defect.
51
+ //
52
+ // The reviewer rows are computed first because the implementer row's gate
53
+ // reads what they leave: the slots this tick's own dispatches fill.
54
+ export function reconcile(s) {
55
+ const rev = reviewers(s);
56
+ return [implementers(s, rev.left), ...rev.rows, mergeBot(s), ...shortlistRows(s)];
57
+ }
58
+
59
+ // `acts` is on the row, set where the ACTION is chosen: the heartbeat backs off
60
+ // on "nothing to act on" and never on "output unchanged" (ADR 0008 §6), and the
61
+ // branch that picks the ACTION is the one place that knows which it is.
62
+ const mkRow = (role, actual, target, detail) => (action, { acts = false, extra = "" } = {}) => ({
63
+ role, actual, target, action, acts, detail: extra ? `${detail} — ${extra}` : detail,
64
+ });
65
+
66
+ // The clearing step a tier hold names in its detail (#2255). The tick reads no
67
+ // transcript and so does not know the session directory: `<session>` stays a
68
+ // placeholder the controller fills in, as `<file>` does — one batch file, one
69
+ // entry per held member (SKILL.md's phase-2 tier check).
70
+ const tierCheckStep = (members) => "run ~/.fleet/bin/fleet-run tier-check.mjs --batch <file> with "
71
+ + JSON.stringify(members.map((member) => ({ member, session: "<session>" })));
72
+
73
+ // A mismatch clears when the next attempt on the ticket is dispatched at its
74
+ // row's tier: one retry letter past the HIGHEST any impl member of that ticket
75
+ // has used, not past the held member's own — a controller can dispatch `-c`
76
+ // before `-b`, ledger.mjs refuses a name already dispatched, and the highest
77
+ // letter is what compute-board.mjs's laterAttempt reads as the latest attempt.
78
+ // No suffix is the `a` attempt (ledger-grammar.mjs orders it first). `-z` is
79
+ // the grammar's last, so past it there is no legal name to print.
80
+ function replaceStep(held, implNames) {
81
+ const named = [], stuck = [];
82
+ for (const name of held) {
83
+ const { family, number } = parseMember(name);
84
+ const top = [name, ...implNames].map(parseMember).filter((m) => m.number === number)
85
+ .map((m) => m.retry ?? "a").sort().at(-1);
86
+ if (top === "z") stuck.push(name);
87
+ else named.push(`${family}-${number}-${String.fromCharCode(top.charCodeAt(0) + 1)}`);
88
+ }
89
+ return [
90
+ named.length ? `dispatch ${named.join(", ")} ${named.length > 1 ? "each " : ""}at its row's tier` : "",
91
+ stuck.length ? `${stuck.join(", ")} ${stuck.length > 1 ? "have" : "has"} no retry letter left` : "",
92
+ ].filter(Boolean).join("; ");
93
+ }
94
+
95
+ function implementers(s, left) {
96
+ const row = mkRow("implementers", s.implLive, s.implCap,
97
+ `unclaimed=${s.heads.length} supply=${s.supply ?? "?"} unreviewed=${left.unreviewed}`
98
+ + (s.shortlistStatus === "ok" ? "" : ` shortlist=${s.shortlistStatus}`));
99
+
100
+ // Drain stops supply and nothing else (spec § 6 §5). Read from the file, so
101
+ // a replacement controller that never saw the drain is held by it too.
102
+ if (s.draining !== null) return row("HOLD (draining)");
103
+ // Held until a replacement at the right tier is dispatched (§ 6 §6). The
104
+ // controller can fix this unattended, so the row asks it to — and names the
105
+ // replacement in its detail (#2255), since the step lives otherwise only in
106
+ // SKILL.md prose, which is what a compaction loses.
107
+ if (s.tierMismatch.length) {
108
+ return row(`HOLD (tier mismatch ${s.tierMismatch.join(" ")})`, { acts: true, extra: replaceStep(s.tierMismatch, s.implNames) });
109
+ }
110
+ // Held until tier-check.mjs has run on the newest implementer and written
111
+ // its verdict to the ledger (#1398) — a Pull on top of an unchecked
112
+ // dispatch repeats whatever it got wrong. Running the check is the
113
+ // controller's own step, so it is asked to act, with the command in the
114
+ // detail (#2255).
115
+ if (s.tierUnchecked.length) {
116
+ return row(`HOLD (tier unchecked ${s.tierUnchecked.join(" ")})`, { acts: true, extra: tierCheckStep(s.tierUnchecked) });
117
+ }
118
+
119
+ const deficit = s.implCap - s.implLive;
120
+ if (deficit <= 0) return row("AT CAP");
121
+
122
+ // The review-backlog gate, NARROWED (§ 6 §4): more PRs into a review-bound
123
+ // pipeline buy nothing — but the pipeline is review-bound only when a PR is
124
+ // still owed its review after this tick's dispatches AND no reviewer slot is
125
+ // left for it. A deep backlog with free slots is a reviewer-row DISPATCH on
126
+ // this same tick, not a reason to idle an implementer; the old
127
+ // `backlog >= 2` gate held there and starved implementers (#590's harm).
128
+ // The merge queue never gates this row: a deep ready-to-merge queue adds no
129
+ // rebases per PR.
130
+ if (left.unreviewed >= 1 && left.free <= 0) return row("HOLD (review side saturated)");
131
+
132
+ if (s.heads.length) return row(`PULL ${s.heads.slice(0, deficit).map((n) => `#${n}`).join(" ")}`, { acts: true });
133
+
134
+ // Nothing unclaimed even after a refresh. `SUGGEST /triage` asks a
135
+ // MAINTAINER to tick tickets, and on the unattended night the heartbeat
136
+ // exists for there is nobody to ask — so it prints (the fold shows it once)
137
+ // but is not actionable, or it would pin the interval at the base all night.
138
+ return row("SUGGEST /triage, hold idle");
139
+ }
140
+
141
+ // Reviewer units (#1773 §3): an in-flight review = 1, each fix-applier = 1.
142
+ // Named in priority order — fix-appliers first, then reviews, oldest first —
143
+ // because finishing what is started beats starting more. Reviews are also
144
+ // bounded by `--max-reviews`, left at its default (the reviewer cap) since
145
+ // every review unit already counts against the session's own concurrency
146
+ // semaphore; the other slots still serve fix-appliers.
147
+ function reviewers(s) {
148
+ const detail = `reviews=${s.reviewsLive} fix-pr=${s.fixLive} fix-due=${s.fixDue.length}`
149
+ + ` review-due=${s.reviewDue.length} max-reviews=${s.maxReviews}`;
150
+ const row = mkRow("reviewers", s.reviewsLive + s.fixLive, s.reviewerCap, detail);
151
+ let free = Math.max(0, s.reviewerCap - s.reviewsLive - s.fixLive);
152
+ const fixes = s.fixDue.slice(0, free);
153
+ free -= fixes.length;
154
+ const reviews = s.reviewDue.slice(0, Math.min(free, Math.max(0, s.maxReviews - s.reviewsLive)));
155
+ free -= reviews.length;
156
+ const prs = (ns) => ns.map((n) => `PR#${n}`).join(" ");
157
+
158
+ const rows = [];
159
+ if (fixes.length) rows.push(row(`DISPATCH fix-pr ${prs(fixes)}`, { acts: true }));
160
+ if (reviews.length) rows.push(row(`DISPATCH review ${prs(reviews)}`, { acts: true }));
161
+ if (!rows.length) {
162
+ const owed = s.fixDue.length + s.reviewDue.length;
163
+ if (owed && free <= 0) rows.push(row("AT CAP"));
164
+ else if (s.reviewDue.length) rows.push(row(`HOLD (max-reviews ${s.maxReviews} in flight)`));
165
+ else rows.push(row("IDLE OK"));
166
+ }
167
+ return { rows, left: { unreviewed: s.reviewDue.length - reviews.length, free } };
168
+ }
169
+
170
+ function mergeBot(s) {
171
+ // Cap is 1 by invariant, not by configuration.
172
+ const row = mkRow("merge-bot", s.mergeBotLive, 1, `merge-queue=${s.mergeQueue} held=${s.mergeHeld}`);
173
+ if (s.mergeBotLive >= 1) return row("AT CAP");
174
+ if (s.mergeQueue === 0) return row("IDLE OK");
175
+ // `ready-to-merge` is the author's sign-off and nothing more. A bot
176
+ // dispatched against a queue whose candidates are all held — behind a lower
177
+ // open PR, or on a conflict merge-bot already refused to force (#2064) —
178
+ // spends a whole member re-deriving a verdict already recorded.
179
+ if (s.mergeQueue - s.mergeHeld <= 0) {
180
+ const why = s.mergeConflictHeld ? "behind a lower PR or on a merge conflict no fix-pr has cleared" : "behind a lower PR";
181
+ return row("HOLD", { extra: `every queued candidate is held ${why}` });
182
+ }
183
+ return row("DISPATCH merge-bot", { acts: true });
184
+ }
185
+
186
+ // The refresh this tick ran, if it ran one. A REFRESHED that changed the list
187
+ // is actionable — supply arrived. One that changed nothing is not: every idle
188
+ // heartbeat tick refreshes while the shortlist is short of the cap, and an
189
+ // unconditionally actionable REFRESHED would pin the beat at its base interval
190
+ // on exactly the quiet night ADR 0008 backs off on. A failed refresh IS
191
+ // actionable: a blind implementer row backing off tick after identical tick is
192
+ // #3's stall exactly.
193
+ function shortlistRows(s) {
194
+ const r = s.refresh;
195
+ if (r === null) return [];
196
+ if (!r.ok) return [{ role: "shortlist", action: "REFRESH FAILED", acts: true, detail: `${r.trigger} — ${r.why}` }];
197
+ return [{
198
+ role: "shortlist", action: `REFRESHED shortlist: ${r.entries} entries; ${r.lifted} lifted`, acts: r.changed,
199
+ detail: r.changed ? r.trigger : `${r.trigger}; unchanged`,
200
+ }];
201
+ }
202
+
203
+ export function formatLines(rows) {
204
+ const w = Math.max(...rows.map((r) => r.role.length));
205
+ return rows.map((r) => r.actual === undefined
206
+ ? `${r.role.padEnd(w)} → ${r.action} (${r.detail})`
207
+ : `${r.role.padEnd(w)} ${r.actual}/${r.target} → ${r.action} (${r.detail})`);
208
+ }
209
+
210
+ // Does this tick ask the controller for anything? Identity decides whether to
211
+ // FOLD the output; only this decides whether to back off (ADR 0008 §6). A tick
212
+ // printing `PULL #412` every five minutes because the controller has not acted
213
+ // is byte-identical each time, and backing off there would stretch the
214
+ // interval while work sat unclaimed.
215
+ export function actionable(rows) {
216
+ return rows.some((r) => r.acts);
217
+ }
218
+
219
+ // --------------------------------------------------------------------------
220
+ // Reading the run. Pure: `ledger.mjs read`'s payload and the open-PR list in,
221
+ // counts out. Throws LedgerError on a token it cannot read — a member counted
222
+ // live or gone on a guess is the over- or under-dispatch this file exists to
223
+ // prevent, so the tick refuses instead.
224
+
225
+ export class LedgerError extends Error {}
226
+
227
+ // A row's PR is its first `PR#<n>` mention — ledger.mjs rowPr()'s reading, so
228
+ // both the `→ PR#346` arrow and a settled `impl-324=PR#346` name it. A row
229
+ // with none is keyed by the PR's own number when it is about a PR at all (a PR
230
+ // this run's implementers did not open) — this is ledger.mjs's
231
+ // memberRowIndex() fallback specifically, which gates on the member being
232
+ // PR-bound before it ever reaches this fallback. deriveRun below applies the
233
+ // same row-key fallback to every row's own bookkeeping unconditionally,
234
+ // signal or not; only memberRowIndex()'s caller already knows it holds a
235
+ // PR-bound member. Ticket and PR numbers share GitHub's one number
236
+ // space, so a ticket's key never names an open PR.
237
+ export const PR_MENTION = /\bPR\s*#(\d+)\b/;
238
+ // shortlist.mjs's own spelling of an Exclusion row and its premises.
239
+ const EXCLUDED_ROW = /^#[0-9]+[ \t]+excluded(?=[ \t]|$)([\s\S]*)$/;
240
+ const PREMISE = /\bbehind-(pr|issue):#?([^\s,;]+)/g;
241
+ // #1773 §7: `review=wf:<runId>` | `review=member:review-pr-<n>` |
242
+ // `review=fallback:review-pr-<n>[-b]`, settled dead as `…=failed`; the result
243
+ // is `reviewed=<head>:<survived>/<refuted>/<unverified>`.
244
+ const REVIEW = /^review=(?:wf|member|fallback):[^=\s]+(=failed)?$/;
245
+ export const REVIEWED = /^reviewed=([0-9a-f]{7,40}):(\d+)\/(\d+)\/(\d+)$/i;
246
+ const HELD = /^held-behind[:-]#?(\d+)$/;
247
+ // #2064: merge-bot's durable record that its local-rebase fallback hit a
248
+ // conflict it would not force — written onto the held PR's own row at the
249
+ // point run-merge-bot.md says to report and halt, and spelled like
250
+ // `held-behind` so the two read alike. Distinct from an Exclusion, which
251
+ // gates a ticket's claim; this gates a reviewed PR's merge.
252
+ const CONFLICT_HOLD = /^conflict-hold[:-]#?(\d+)$/;
253
+ // #1398: tier-check.mjs's verdict on an implementer, `tier-ok=<member>:<def>`
254
+ // or `tier-mismatch=<member>:<def>`.
255
+ const TIER_VERDICT = /^tier-(ok|mismatch)=([^:\s]+):\S+$/;
256
+
257
+ export function deriveRun({ rows, dispatched, drain }, prs) {
258
+ // One entry per member name across `## Dispatched` and every row. A member
259
+ // settled ANYWHERE is settled: `settle` is the only writer of an outcome, and
260
+ // a bare copy beside it is what a whole-line `row` rewrite leaves behind.
261
+ const members = new Map();
262
+ const note = (t, where) => {
263
+ if (t.error) throw new LedgerError(`${where}: ${t.name}: ${t.error}`);
264
+ const m = members.get(t.name) ?? { name: t.name, family: t.family, number: t.number, outcome: null };
265
+ if (t.outcome !== null) m.outcome = t.outcome;
266
+ members.set(t.name, m);
267
+ };
268
+ for (const e of dispatched) {
269
+ const t = parseToken(e);
270
+ if (!t) throw new LedgerError(`## Dispatched entry '${e}' is not a member token — fix the ledger by hand before the tick can count from it`);
271
+ note(t, `## Dispatched entry '${e}'`);
272
+ }
273
+
274
+ const open = new Set(prs.map((p) => p.number));
275
+ const claimed = new Set();
276
+ const excluded = [];
277
+ const byPr = new Map();
278
+ // tier-check.mjs's verdict tokens (#1398), read off whichever row carries
279
+ // them: `tier-ok=<member>:<definition>` on a pass, `tier-mismatch=<member>:…`
280
+ // for a member found mismatched after it had already settled some other way
281
+ // (a live one is settled `tier-mismatch` instead). Neither parses as a member
282
+ // token nor as `review=`/`reviewed=`, so both always reach this loop's own
283
+ // `else` branch below, alongside HELD/CONFLICT_HOLD — one pass over every
284
+ // row's tokens covers all four.
285
+ const verdicts = { ok: new Set(), mismatch: new Set() };
286
+ for (const text of rows) {
287
+ const key = text.split(/\s/)[0];
288
+ const keyNum = /^#[0-9]+$/.test(key) ? Number(key.slice(1)) : null;
289
+ const where = `row '${text}'`;
290
+ const mention = PR_MENTION.exec(text);
291
+ const pr = mention ? Number(mention[1]) : keyNum;
292
+ // `conflictHold`: the row carries a conflict hold. `conflictCleared`: a
293
+ // fix-applier SETTLED (`applied:`/`no-op`) after the latest one — never
294
+ // merely dispatched, which is `fixSince`'s bar and too low for the merge
295
+ // hold: a live fix-applier is still working the conflict.
296
+ // `reviewedHead`: the latest `reviewed=<head>`. `pastPinHalt`: the latest
297
+ // finisher since that review settled `halted:past-pin` (#2083) — any
298
+ // later finisher attempt, live or settled, replaces it, and a later
299
+ // returned review answers it.
300
+ const st = {
301
+ inFlight: false, reviewedAny: false, survived: 0, fixSince: false, held: [],
302
+ conflictHold: false, conflictCleared: false, reviewedHead: null, pastPinHalt: false,
303
+ };
304
+ // The finisher-pr token currently deciding `pastPinHalt`, picked by
305
+ // retry suffix ("" < "b" < "c" …) the same way compute-board.mjs's
306
+ // laterAttempt does — never by row-text position (#2083 correction). A
307
+ // `-b` retry can sit before an older `halted:past-pin` token after a row
308
+ // rewrite, and text order must not read the stale one as the live
309
+ // finisher's replacement. Reset at each `reviewed=`, since `pastPinHalt`
310
+ // is defined relative to the latest one (see the comment above `st`).
311
+ let latestFinisher = null;
312
+ for (const tok of text.split(/\s+/).filter(Boolean)) {
313
+ const t = parseToken(tok);
314
+ if (t) {
315
+ note(t, where);
316
+ // A settled `failed`/`killed` fix-applier leaves survivors unfixed and
317
+ // no successor dispatched — the PR stays fix-due for a `-b`
318
+ // replacement. Only a live attempt, or one that actually landed
319
+ // (`applied:`/`no-op`), clears it. Read the outcome off the MERGED
320
+ // member record (`members`, built above) rather than this row's own
321
+ // copy of the token: `members` already implements "a member settled
322
+ // ANYWHERE is settled" for `implLive`/`fixLive`/etc. below, and a
323
+ // later, unrelated `row` rewrite that drops the `=outcome` suffix and
324
+ // puts back a bare copy must not un-settle what actually landed. A
325
+ // landed one also clears a conflict hold; a hold resets this below,
326
+ // so only a fix-applier after the latest hold ever counts. `note`
327
+ // above has just recorded this exact token, so the lookup below is
328
+ // never absent, and its outcome is this token's own unless an
329
+ // earlier row already settled it — never a reason to fall back to
330
+ // the row's own copy.
331
+ if (t.family === "fix-pr") {
332
+ const o = members.get(t.name).outcome;
333
+ const landed = o === "no-op" || /^applied:/.test(o);
334
+ if (o === null || landed) st.fixSince = true;
335
+ if (landed) st.conflictCleared = true;
336
+ }
337
+ if (t.family === "finisher-pr" && t.number === pr
338
+ && (!latestFinisher || (t.retry ?? "") > (latestFinisher.retry ?? ""))) {
339
+ latestFinisher = t;
340
+ st.pastPinHalt = members.get(t.name).outcome === "halted:past-pin";
341
+ }
342
+ continue;
343
+ }
344
+ if (tok.startsWith("review=")) {
345
+ const m = REVIEW.exec(tok);
346
+ if (!m) throw new LedgerError(`${where}: '${tok}' is not review=wf:<runId> | member:review-pr-<n> | fallback:review-pr-<n>, optionally =failed`);
347
+ st.inFlight = !m[1];
348
+ if (!m[1]) st.reviewedAny = true;
349
+ } else if (tok.startsWith("reviewed=")) {
350
+ const m = REVIEWED.exec(tok);
351
+ if (!m) throw new LedgerError(`${where}: '${tok}' is not reviewed=<head>:<survived>/<refuted>/<unverified>`);
352
+ latestFinisher = null;
353
+ Object.assign(st, {
354
+ inFlight: false, reviewedAny: true, survived: Number(m[2]), fixSince: false,
355
+ reviewedHead: m[1].toLowerCase(), pastPinHalt: false,
356
+ });
357
+ } else {
358
+ const h = HELD.exec(tok);
359
+ if (h) st.held.push(Number(h[1]));
360
+ const c = CONFLICT_HOLD.exec(tok);
361
+ if (c) {
362
+ // Bound to the row's own PR: a hold naming another PR is a
363
+ // misrecorded one, and read on a guess it would either hold the
364
+ // wrong PR or leave this one silently stalled.
365
+ if (Number(c[1]) !== pr) {
366
+ throw new LedgerError(`${where}: '${tok}' names PR #${c[1]}, but this row is ${pr === null ? "no PR's" : `PR #${pr}'s`} — a conflict hold goes on the held PR's own row`);
367
+ }
368
+ // A fresh hold is unresolved whatever settled before it, the way
369
+ // a fresh `reviewed=` resets `fixSince` above — UNLESS the row
370
+ // already carries an unresolved hold with nothing having cleared
371
+ // it since: a redundant re-hold (merge-bot retrying a PR it has
372
+ // already held, #2064) must not disturb a live fix-applier's
373
+ // `fixSince`, or a still-in-progress fix reappears in `fixDue`.
374
+ const alreadyUnresolved = st.conflictHold && !st.conflictCleared;
375
+ Object.assign(st, {
376
+ conflictHold: true, conflictCleared: false,
377
+ ...(alreadyUnresolved ? null : { fixSince: false }),
378
+ });
379
+ }
380
+ const v = TIER_VERDICT.exec(tok);
381
+ if (v) verdicts[v[1]].add(v[2]);
382
+ }
383
+ }
384
+ const ex = EXCLUDED_ROW.exec(text);
385
+ if (ex && keyNum !== null) {
386
+ const premises = [...ex[1].matchAll(PREMISE)].map(([, kind, target]) => ({ kind, target }));
387
+ // ADR 0013 §48: an `excluded` row claims its ticket only while its
388
+ // premise still holds. Lifted here only when EVERY premise is a
389
+ // verifiable, now-closed `behind-pr:#M` — the same rule a
390
+ // `held-behind` merge hold uses — since a mixed or `behind-issue`
391
+ // premise needs a live gh probe this pure half cannot make;
392
+ // unclaimed() covers that case once the refreshed shortlist re-admits
393
+ // the ticket.
394
+ const prLifted = premises.length > 0
395
+ && premises.every(({ kind, target }) => kind === "pr" && isDigits(target) && !open.has(Number(target)));
396
+ if (!prLifted) claimed.add(keyNum);
397
+ excluded.push({ n: keyNum, premises });
398
+ }
399
+ if (pr !== null && !byPr.has(pr)) byPr.set(pr, st);
400
+ }
401
+
402
+ const all = [...members.values()];
403
+ const live = (family) => all.filter((m) => m.family === family && m.outcome === null).length;
404
+ const impls = all.filter((m) => m.family === "impl");
405
+ for (const m of impls) claimed.add(m.number);
406
+ // Only the LATEST member for a ticket counts. A mismatch is fixed by
407
+ // dispatching a replacement (`impl-N-b`) at the right tier; until that
408
+ // replacement's own check passes, the row holds — a replacement that is
409
+ // ALSO mismatched keeps holding, and one not yet checked holds as
410
+ // unchecked. A member with no verdict at all holds whether it is live or
411
+ // settled: its transcript exists from dispatch, so the check can still
412
+ // run, and the tick never reads a transcript itself.
413
+ const newest = impls.filter((m, i) => !impls.some((o, j) => j > i && o.number === m.number));
414
+ const mismatched = (m) => m.outcome === "tier-mismatch" || verdicts.mismatch.has(m.name);
415
+ const tierMismatch = newest.filter(mismatched).map((m) => m.name);
416
+ const tierUnchecked = newest.filter((m) => !mismatched(m) && !verdicts.ok.has(m.name)).map((m) => m.name);
417
+ const isQueued = (p) => p.labels.some((l) => l && l.name === "ready-to-merge");
418
+ const queued = prs.filter(isQueued);
419
+ const asc = (a, b) => a - b;
420
+ const state = (n) => byPr.get(n);
421
+ const heldBehind = (st) => (st?.held ?? []).some((n) => open.has(n));
422
+ const conflictHeld = (st) => st !== undefined && st.conflictHold && !st.conflictCleared;
423
+ // The halt holds only while the head is still past what was reviewed: a
424
+ // `reviewed=` head (7-40 hex) prefix-matching gh's full headRefOid is the
425
+ // head that review read, and there is nothing more to review.
426
+ const pastPinDue = (st, head) => st !== undefined && st.pastPinHalt && !st.inFlight && st.reviewedHead !== null
427
+ && !String(head).toLowerCase().startsWith(st.reviewedHead);
428
+ return {
429
+ implLive: live("impl"),
430
+ fixLive: live("fix-pr"),
431
+ mergeBotLive: live("merge-bot"),
432
+ reviewsLive: [...byPr.values()].filter((st) => st.inFlight).length,
433
+ // A returned review with survivors, or a conflict hold no fix-applier has
434
+ // cleared — either with no fix-applier since, on a PR still open, with no
435
+ // newer review running. The hold term carries `!conflictCleared` because
436
+ // a later `reviewed=` resets `fixSince`, and a hold already cleared must
437
+ // not come back due with it.
438
+ fixDue: [...byPr.entries()]
439
+ .filter(([n, st]) => open.has(n) && ((st.reviewedHead !== null && st.survived > 0) || conflictHeld(st))
440
+ && !st.fixSince && !st.inFlight)
441
+ .map(([n]) => n).sort(asc),
442
+ // Open, not signed off, closing an issue (GitHub's own linked set — a
443
+ // chore PR closing nothing is review work nobody in the run will ever be
444
+ // dispatched against, #590), with no live or returned review on record —
445
+ // or (#2083) a returned review its finisher halted `past-pin` against: the
446
+ // head carries commits no reviewer read, so it is owed a review again
447
+ // until one is running or has returned. A head that moved past
448
+ // `reviewed=` with no such halt — a fix-applier's push — stays not due:
449
+ // finisher duty 2 verifies what it applied.
450
+ reviewDue: prs
451
+ .filter((p) => !isQueued(p) && p.closingIssuesReferences.length > 0
452
+ && (!state(p.number)?.reviewedAny || pastPinDue(state(p.number), p.headRefOid)))
453
+ .map((p) => p.number).sort(asc),
454
+ mergeQueue: queued.length,
455
+ // A `held-behind` hold lifts once its premise PR has left the open list —
456
+ // MERGED or CLOSED, the same lift rule as a `behind-pr` Exclusion. A
457
+ // conflict hold lifts only once a fix-applier after it has SETTLED
458
+ // `applied:`/`no-op` — not on dispatch, which is all `fixSince` asks.
459
+ mergeHeld: queued.filter((p) => heldBehind(state(p.number)) || conflictHeld(state(p.number))).length,
460
+ // How many of those are conflict holds — the HOLD row's wording, no field.
461
+ mergeConflictHeld: queued.filter((p) => conflictHeld(state(p.number))).length,
462
+ draining: drain ?? null,
463
+ tierMismatch,
464
+ // Every impl member the ledger names, settled or live: the retry letters
465
+ // a mismatch's replacement must climb past (replaceStep).
466
+ implNames: impls.map((m) => m.name),
467
+ tierUnchecked,
468
+ claimed,
469
+ excluded,
470
+ };
471
+ }
472
+
473
+ // The shortlist entries no `impl-` or `excluded` row has claimed, in the
474
+ // file's own oldest-first order. A `behind-pr:#M` exclusion is trusted from
475
+ // `run.claimed` alone — `open` is read fresh every tick, so there is nothing
476
+ // stale to defer to. An exclusion deriveRun cannot verify purely (a
477
+ // `behind-issue` or branch-named premise) is different: its row is rewritten
478
+ // only when a Pull dispatches the ticket (shortlist.mjs's own header, §3),
479
+ // never on its own, so once shortlist.mjs's live probe has re-admitted the
480
+ // ticket to these entries, that stale row no longer blocks it.
481
+ export function unclaimed(entries, run) {
482
+ const unverifiable = new Set(run.excluded
483
+ .filter((e) => e.premises.every(({ kind, target }) => kind !== "pr" || !isDigits(target)))
484
+ .map((e) => e.n));
485
+ return entries.map((e) => e.n).filter((n) => !run.claimed.has(n) || unverifiable.has(n));
486
+ }
487
+
488
+ // shortlist.mjs's payload, `{scanned, shortlist: [{n, t}]}`, or unparsable.
489
+ export function parseShortlist(text) {
490
+ const none = { status: "unparsable", scanned: null, entries: [] };
491
+ let d;
492
+ try {
493
+ d = JSON.parse(text);
494
+ } catch {
495
+ return none;
496
+ }
497
+ if (!d || typeof d !== "object" || !Number.isInteger(d.scanned) || d.scanned < 0 || !Array.isArray(d.shortlist)
498
+ || !d.shortlist.every((e) => e && Number.isInteger(e.n) && e.n > 0 && typeof e.t === "string")) return none;
499
+ return { status: "ok", scanned: d.scanned, entries: d.shortlist.map(({ n, t }) => ({ n, t })) };
500
+ }
501
+
502
+ // Why this tick refreshes the shortlist, or null (§ 6 §3). The premise-lifted
503
+ // trigger costs gh calls, so main() asks it only when these answer null.
504
+ export function refreshWhy({ draining, status, entries, unclaimed: k, implCap }) {
505
+ if (draining !== null) return null;
506
+ if (status !== "ok") return `shortlist ${status}`;
507
+ if (entries === 0) return "shortlist empty";
508
+ if (k < implCap) return `unclaimed ${k} < cap ${implCap}`;
509
+ return null;
510
+ }
511
+
512
+ // --------------------------------------------------------------------------
513
+ // I/O. Everything below runs only as a CLI — importing this file must never
514
+ // parse argv or touch the network, or the pure half stops being unit-testable.
515
+
516
+ import { execFileSync, spawnSync } from "node:child_process";
517
+ import { createHash } from "node:crypto";
518
+ import { readFileSync } from "node:fs";
519
+ import { dirname, join } from "node:path";
520
+ import { fileURLToPath, pathToFileURL } from "node:url";
521
+ import { parseArgs } from "node:util";
522
+ import { makeDie, isDigits } from "./arg.mjs";
523
+ import { gitEnv, workspaceDirFromGitCommonDir } from "./git-env.mjs";
524
+ import { statePath, readState, writeState, assessBeat, isStalled, stallReport } from "./fleet-state.mjs";
525
+
526
+ const NAME = "fleet-tick";
527
+ const SCRIPT_DIR = dirname(fileURLToPath(import.meta.url));
528
+ // Open PRs read per tick. At exactly this many the list may be truncated and
529
+ // nothing in the result says so, so it refuses — "no silent caps", same rule
530
+ // candidates.mjs enforces on its own query.
531
+ const PR_LIMIT = 200;
532
+ // Claimed tickets read per stall report. Same "no silent caps" rule as
533
+ // PR_LIMIT above, resolved the other way: the read below cannot REFUSE at the
534
+ // cap, because refusing would suppress the one announcement a dead run leaves
535
+ // behind. So it discloses instead — the line says the count is a floor.
536
+ const CLAIMED_LIMIT = 200;
537
+ const MAX_BUFFER = 64 * 1024 * 1024;
538
+ const GIT_TIMEOUT_MS = 10_000;
539
+
540
+ // die() shared with the other fleet scripts (writeSync-based, pipe-safe —
541
+ // see arg.mjs for the #176/#328/#363 rationale). This file parses its own
542
+ // options with node:util's parseArgs rather than arg()/has(), so die() and
543
+ // the isDigits() rule int() calls are all it shares.
544
+ const die = makeDie(NAME);
545
+
546
+ // Every input the controller used to state is read off the run now, so what
547
+ // is left is configuration, and all of it defaults.
548
+ const OPTIONS = {
549
+ // Defaults here, not threaded through int(): declared this way they still
550
+ // go through the guard below, where a hand-passed default went round it.
551
+ // 2/6 (#1773): no hard cap on either role, defaults only.
552
+ "implementer-cap": { type: "string", default: "2" },
553
+ "reviewer-cap": { type: "string", default: "6" },
554
+ // Reviews in flight at once. Default = the reviewer cap; run-team's own
555
+ // guidance is to leave it there rather than pass a tighter bound.
556
+ "max-reviews": { type: "string" },
557
+ // `--fold-unchanged` prints ONE line instead of the rows when this tick asks
558
+ // for nothing and says exactly what the last one said — what makes an
559
+ // unattended night affordable. Opt-in because folding is wrong on an edge:
560
+ // a controller that just acted needs the full rows.
561
+ "fold-unchanged": { type: "boolean", default: false },
562
+ // Path override, for tests. An empty value cannot be told from an absent one
563
+ // under parseArgs, and no path is legitimately empty, so empty resolves to
564
+ // the default.
565
+ state: { type: "string", default: "" },
566
+ };
567
+
568
+ function options() {
569
+ let values;
570
+ try {
571
+ ({ values } = parseArgs({ options: OPTIONS }));
572
+ } catch (e) {
573
+ // Unconditional catch, deliberately — parseArgs throws on the FIRST
574
+ // offending argument, so dropping any error code disables the guard for
575
+ // every argv where something else comes earlier.
576
+ die(`${e.message} — accepted: ${Object.keys(OPTIONS).map((f) => `--${f}`).join(", ")}`);
577
+ }
578
+ const int = (name) => {
579
+ const raw = values[name];
580
+ // #878: the digits rule, called rather than restated. Digits, not
581
+ // Number(): `Number("")` is 0, so `--max-reviews ""` — the shape an unset
582
+ // shell variable produces — would otherwise read as a real number.
583
+ if (!isDigits(String(raw).trim())) die(`--${name} must be a non-negative integer, got '${raw}'`);
584
+ return Number(raw);
585
+ };
586
+ const positive = (name) => {
587
+ const n = int(name);
588
+ if (n < 1) die(`--${name} must be at least 1, got ${n}`);
589
+ return n;
590
+ };
591
+ const reviewerCap = positive("reviewer-cap");
592
+ return {
593
+ implCap: positive("implementer-cap"), reviewerCap,
594
+ maxReviews: values["max-reviews"] === undefined ? reviewerCap : positive("max-reviews"),
595
+ fold: values["fold-unchanged"], state: values.state || statePath(NAME),
596
+ };
597
+ }
598
+
599
+ // The open PRs, validated. A failed read is not an empty pipeline: backlog 0 +
600
+ // merge-queue 0 is a plausible tick, so printing it off a failed query is the
601
+ // silent stall this script exists to end.
602
+ function openPrs() {
603
+ let out;
604
+ try {
605
+ out = execFileSync("gh", ["pr", "list", "--state", "open", "--limit", String(PR_LIMIT),
606
+ "--json", "number,labels,closingIssuesReferences,headRefOid"], { encoding: "utf8" });
607
+ } catch (e) {
608
+ // Never interpolates e.stderr or e.message: execFileSync already forwarded
609
+ // the child's stderr to ours, and Node builds e.message out of it, so
610
+ // either one emits every byte a second time (#176).
611
+ die(`gh pr list failed: ${e.code ?? (e.signal ? `killed by ${e.signal}` : `exit ${e.status}`)} — a failed read is not an empty queue`);
612
+ }
613
+ let prs;
614
+ try {
615
+ prs = JSON.parse(out);
616
+ } catch (e) {
617
+ die(`could not parse gh pr list output as JSON: ${e.message}`);
618
+ }
619
+ // closingIssuesReferences is checked, not defaulted: absent, it would read as
620
+ // an empty list and drop every open PR from review work. headRefOid likewise
621
+ // (#2083): absent, a `halted:past-pin` PR would read as moved forever.
622
+ if (!Array.isArray(prs) || prs.some((p) => !p || typeof p.number !== "number"
623
+ || !Array.isArray(p.labels) || !Array.isArray(p.closingIssuesReferences)
624
+ || typeof p.headRefOid !== "string")) {
625
+ die("gh pr list did not return {number,labels,closingIssuesReferences,headRefOid} rows");
626
+ }
627
+ if (prs.length === PR_LIMIT) {
628
+ die(`exactly ${PR_LIMIT} open PRs — the list is capped and may be truncated. Raise PR_LIMIT; a backlog that silently drops PRs is not a reconcile.`);
629
+ }
630
+ return prs;
631
+ }
632
+
633
+ // A child that did not exit 0, named with the last line it printed.
634
+ function failure(r, what) {
635
+ if (r.error) return `${what} did not run: ${r.error.code ?? r.error.message}`;
636
+ const last = String(r.stderr ?? "").trim().split("\n").at(-1);
637
+ return `${what} ${r.signal ? `killed by ${r.signal}` : `exited ${r.status}`}${last ? `: ${last}` : ""}`;
638
+ }
639
+
640
+ // Through `ledger.mjs read`, never parsed here, so the ledger keeps one parser
641
+ // — shortlist.mjs's rule. Its stderr passes straight through: its WARNING on an
642
+ // unresolved workspace is the operator's to see. A read that fails refuses the
643
+ // tick: counting a run nobody could read is the guess this file replaced.
644
+ function readLedger() {
645
+ const r = spawnSync(process.execPath, [join(SCRIPT_DIR, "ledger.mjs"), "read"], {
646
+ encoding: "utf8", maxBuffer: MAX_BUFFER, stdio: ["ignore", "pipe", "inherit"],
647
+ });
648
+ if (r.error || r.status !== 0) die(`${failure(r, "ledger.mjs read")} — the run cannot be counted from a ledger nobody could read`);
649
+ let d;
650
+ try {
651
+ d = JSON.parse(r.stdout);
652
+ } catch (e) {
653
+ die(`could not parse ledger.mjs read output: ${e.message}`);
654
+ }
655
+ const strings = (xs) => Array.isArray(xs) && xs.every((x) => typeof x === "string");
656
+ if (!d || !strings(d.rows) || !strings(d.dispatched) || !(d.drain === null || typeof d.drain === "string")) {
657
+ die("ledger.mjs read returned no {rows, dispatched, drain}");
658
+ }
659
+ return d;
660
+ }
661
+
662
+ // `.fleet/shortlist.json` beside the run's ledger: the workspace from `git
663
+ // rev-parse --git-common-dir`, GIT_DIR/GIT_WORK_TREE scrubbed (#1599) so an
664
+ // ambient one cannot answer for another repository. null when unresolvable —
665
+ // read as a missing shortlist, and the refresh then says why it could not run.
666
+ function shortlistPath() {
667
+ const r = spawnSync("git", ["rev-parse", "--git-common-dir"], { encoding: "utf8", timeout: GIT_TIMEOUT_MS, env: gitEnv() });
668
+ const workspace = workspaceDirFromGitCommonDir(r.stdout);
669
+ return workspace === null ? null : join(workspace, ".fleet", "shortlist.json");
670
+ }
671
+
672
+ function readShortlist(path) {
673
+ if (path === null) return { status: "missing", scanned: null, entries: [] };
674
+ let text;
675
+ try {
676
+ text = readFileSync(path, "utf8");
677
+ } catch (e) {
678
+ if (e.code === "ENOENT") return { status: "missing", scanned: null, entries: [] };
679
+ // Distinct from `unparsable`: that label's only other producer is
680
+ // genuinely malformed JSON, and a permissions/filesystem fault reported
681
+ // as a JSON-content fault sends the operator chasing the wrong repair.
682
+ return { status: "unreadable", scanned: null, entries: [], code: e.code ?? null, message: e.message };
683
+ }
684
+ return parseShortlist(text);
685
+ }
686
+
687
+ // An Exclusion whose premise has lifted, for a ticket the current file does
688
+ // not already carry (if it does, the refresh that lifted it has run). A
689
+ // `behind-pr:#M` reads off the open list already in hand; a `behind-issue:#M`
690
+ // costs one `gh issue view`. A branch-named `behind-pr` is left to the
691
+ // refresh itself: before its PR exists, "no open PR" is not "merged". Any
692
+ // probe that cannot answer leaves the exclusion standing.
693
+ function liftedPremise(excluded, entries, prs) {
694
+ const inFile = new Set(entries.map((e) => e.n));
695
+ const open = new Set(prs.map((p) => p.number));
696
+ for (const { n, premises } of excluded) {
697
+ if (inFile.has(n)) continue;
698
+ for (const { kind, target } of premises) {
699
+ if (!isDigits(target)) continue;
700
+ if (kind === "pr" && !open.has(Number(target))) return `behind-pr:#${target} no longer open`;
701
+ if (kind === "issue") {
702
+ // Scrubbed as shortlist.mjs's probeState() is: gh's remote resolution
703
+ // follows GIT_DIR/GIT_WORK_TREE, and GH_REPO outranks both.
704
+ const r = spawnSync("gh", ["issue", "view", target, "--json", "state"], { encoding: "utf8", env: gitEnv({ GH_REPO: "" }) });
705
+ if (r.error || r.status !== 0) {
706
+ // Disclosed, not dropped: every other gh call in this file either
707
+ // dies or logs its failure — a bare empty catch here would be the
708
+ // one silent exception in a file whose whole design goal is "no
709
+ // silent stall".
710
+ console.error(`${NAME}: ${failure(r, `gh issue view ${target}`)} — behind-issue:#${target} premise unconfirmed, exclusion stands`);
711
+ continue;
712
+ }
713
+ let st = null;
714
+ try { st = JSON.parse(r.stdout).state; } catch { /* unanswered: the exclusion stands */ }
715
+ if (st === "CLOSED" || st === "MERGED") return `behind-issue:#${target} ${st}`;
716
+ }
717
+ }
718
+ }
719
+ return null;
720
+ }
721
+
722
+ // shortlist.mjs, run by the tick itself (§ 6 §3). Its per-ticket stderr is
723
+ // captured and dropped rather than billed to the controller's context; only a
724
+ // failure's last line rides along.
725
+ function refresh() {
726
+ const r = spawnSync(process.execPath, [join(SCRIPT_DIR, "shortlist.mjs")], {
727
+ encoding: "utf8", maxBuffer: MAX_BUFFER, stdio: ["ignore", "pipe", "pipe"],
728
+ });
729
+ if (r.error || r.status !== 0) return { ok: false, why: failure(r, "shortlist.mjs") };
730
+ const p = parseShortlist(r.stdout);
731
+ if (p.status !== "ok") return { ok: false, why: "shortlist.mjs printed no {scanned, shortlist}" };
732
+ return { ok: true, ...p };
733
+ }
734
+
735
+ // How many tickets a dead run stranded. `in-progress` is the claim label
736
+ // claim-ticket.sh adds and candidates.mjs's query EXCLUDES — which is why a
737
+ // stranded ticket is invisible to the next run's scans, and why this count is
738
+ // the actionable half of the report. null for unknown, never 0: a failed query
739
+ // reporting "0 claimed" says the dead run stranded nothing.
740
+ function claimed() {
741
+ const r = spawnSync("gh", ["issue", "list", "--label", "in-progress", "--state", "open",
742
+ "--limit", String(CLAIMED_LIMIT), "--json", "number", "--jq", "length"], { encoding: "utf8" });
743
+ if (r.error || r.status !== 0) {
744
+ // Disclosed, not dropped: a real gh failure must be distinguishable from
745
+ // the deliberately-undiagnosed case.
746
+ const why = r.error
747
+ ? `gh did not run: ${r.error.code ?? r.error.message}`
748
+ : `gh ${r.signal ? `killed by ${r.signal}` : `exited ${r.status}`}`;
749
+ const tail = (r.stderr ?? "").trim().split("\n").slice(-5).join("\n");
750
+ console.error(`${NAME}: ${why} — claimed ticket count unknown${tail ? `\n${tail}` : ""}`);
751
+ return null;
752
+ }
753
+ const n = Number(r.stdout.trim());
754
+ if (!Number.isInteger(n) || n < 0) return null;
755
+ // At exactly the cap the list may be truncated, so the report says so.
756
+ return n === CLAIMED_LIMIT ? `${n}+` : n;
757
+ }
758
+
759
+ function main() {
760
+ const { fold, state: path, ...caps } = options();
761
+ const current = readShortlist(shortlistPath());
762
+
763
+ // The PRIOR run's liveness, before anything that can refuse — #1597. The gh
764
+ // read and the ledger read below both exit 2 on failure, and a stall
765
+ // announced after them is a stall a gh outage can silence. The supply it
766
+ // reports is the local shortlist file's, which no outage can take away.
767
+ const priorState = readState(path, NAME);
768
+ const verdict = assessBeat({ beat: priorState.beat, ticked: priorState.ticked, now: Date.now() });
769
+ if (isStalled(verdict)) console.log(stallReport(verdict, { claimed: claimed(), supply: current.scanned }));
770
+
771
+ // Every read happens before anything prints: a partial tick is worse than no
772
+ // tick, because half a reconcile still reads like a reconcile.
773
+ const prs = openPrs();
774
+ let run;
775
+ try {
776
+ run = deriveRun(readLedger(), prs);
777
+ } catch (e) {
778
+ if (e instanceof LedgerError) die(e.message);
779
+ throw e;
780
+ }
781
+
782
+ // Pull from the current file first; refresh when it is short, absent, or an
783
+ // exclusion has lifted — and top the PULL up from what the refresh found,
784
+ // so a slot the current file could not fill does not wait a tick for it.
785
+ let heads = unclaimed(current.entries, run);
786
+ let supply = current.scanned;
787
+ let fresh = null;
788
+ const trigger = refreshWhy({ draining: run.draining, status: current.status, entries: current.entries.length,
789
+ unclaimed: heads.length, implCap: caps.implCap })
790
+ ?? (run.draining === null ? liftedPremise(run.excluded, current.entries, prs) : null);
791
+ if (trigger) {
792
+ const r = refresh();
793
+ if (r.ok) {
794
+ const excludedSet = new Set(run.excluded.map((x) => x.n));
795
+ heads = [...new Set([...heads, ...unclaimed(r.entries, run)])];
796
+ supply = r.scanned;
797
+ fresh = {
798
+ ok: true, trigger, entries: r.entries.length,
799
+ lifted: r.entries.filter((e) => excludedSet.has(e.n)).length,
800
+ changed: r.entries.map((e) => e.n).join(",") !== current.entries.map((e) => e.n).join(","),
801
+ };
802
+ } else {
803
+ fresh = { ok: false, trigger, why: r.why };
804
+ }
805
+ }
806
+
807
+ const rows = reconcile({
808
+ ...caps, ...run, heads, supply, shortlistStatus: current.status, refresh: fresh,
809
+ });
810
+ const lines = formatLines(rows);
811
+
812
+ // The back-off streak and the fold digest, written on EVERY tick: an edge
813
+ // tick that dispatched is the clearest possible "there is work here". Digest,
814
+ // not the lines themselves, so the file stays readable. Re-read rather than
815
+ // reusing priorState: this must be the freshest snapshot, or this tick
816
+ // reverts whatever the heartbeat wrote while the reads above were in flight.
817
+ const prev = readState(path, NAME);
818
+ const digest = createHash("sha256").update(lines.join("\n")).digest("hex");
819
+ const acts = actionable(rows);
820
+ // `ticked`, fleet-tick's own liveness key (#1597 follow-up): written on
821
+ // every invocation unconditionally — this tick running IS the occurrence.
822
+ writeState(path, NAME, prev, { quiet: acts ? 0 : prev.quiet + 1, digest, ticked: { at: Date.now() } });
823
+
824
+ // Fold only when BOTH hold: nothing to act on, and nothing new to say.
825
+ if (fold && !acts && digest === prev.digest) {
826
+ console.log(`fleet-tick: unchanged, nothing to act on (quiet=${prev.quiet + 1}) — full rows on the next change`);
827
+ return;
828
+ }
829
+ for (const line of lines) console.log(line);
830
+ }
831
+
832
+ if (import.meta.url === pathToFileURL(process.argv[1] || "").href) main();