@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,1753 @@
1
+ #!/usr/bin/env node
2
+ // The run ledger. A controller's context is the least durable thing in a fleet
3
+ // run: it compacts, and a controller that has lost the pool or the dispatch map
4
+ // redoes finished work. Two duplicate tickets shipped in one run from exactly
5
+ // that.
6
+ //
7
+ // Rows are rewritten in place, one per ticket. `filed` and `ruled` are
8
+ // append-only, because their whole purpose is to outlive the reasoning that
9
+ // produced them; `filed` appends at most one row per issue (#2087).
10
+ //
11
+ // `dispatch`, `settle` and `drain` (#1799) exist so a reader can derive every
12
+ // liveness count from this file alone, rather than from row text a controller
13
+ // typed by hand: `dispatch` writes a member's live token onto its row and
14
+ // appends it to `## Dispatched`, `settle` rewrites that token to
15
+ // `<member>=<outcome>` in both places (an implementer's settle to `PR#M` also
16
+ // folds the PR's own `#M` row into its ticket's, #1876), and `drain` writes the
17
+ // one marker that stops supply. The token grammar is
18
+ // ledger-grammar.mjs's. `## Dispatched` gains an entry per dispatch and never
19
+ // loses or reorders one — settling annotates an entry in place — which is what
20
+ // lets `merge-bot-<n>` be counted from it.
21
+ //
22
+ // Writer policy (#531, reversing #151's item #7): the controller owns run
23
+ // state (`row`/`settle`/`dispatch`/`drain`/`ruled`); filers append filings
24
+ // with `filed`; all writes are serialized by `<file>.lock`. Every write
25
+ // subcommand rewrites the WHOLE file from what it loaded, so two unlocked
26
+ // writers are last-writer-wins — measured, 8 concurrent `filed` kept 2-5 of 8
27
+ // rows — and the lock is what lets a second kind of writer exist at all. The
28
+ // reasoning for each part of the lock lives at acquireLock() below.
29
+
30
+ import { readFileSync, writeFileSync, mkdirSync, existsSync, renameSync, openSync, writeSync, closeSync, unlinkSync } from "node:fs";
31
+ import { dirname, resolve, join } from "node:path";
32
+ import { spawnSync, execFileSync } from "node:child_process";
33
+ import { makeDie, isFlagLike, hasEqualsForm, isDigits } from "./arg.mjs";
34
+ import { gitEnv, workspaceDirFromGitCommonDir } from "./git-env.mjs";
35
+ import { parseMember, parseToken, memberTokens, nextMergeBot } from "./ledger-grammar.mjs";
36
+
37
+ const NAME = "ledger";
38
+
39
+ // die() shared with the other fleet scripts (writeSync-based, pipe-safe —
40
+ // see arg.mjs for the #176/#328/#363 rationale). arg()/has() themselves are
41
+ // NOT shared here: this file splices its flags out of argv and refuses in its
42
+ // own wording (#362), where arg() refuses under a message generated from the
43
+ // flag name.
44
+ //
45
+ // Their RULES are shared, which is a different thing (#567). isFlagLike() and
46
+ // hasEqualsForm() are arg.mjs's refusal rules as exported predicates; the
47
+ // three guards below call them and supply their own die() text. This file
48
+ // used to restate the expressions instead, and nothing failed when a
49
+ // restatement drifted from the original — shared-refusal.test.mjs is what
50
+ // fails now, and it reds even on a re-inlined copy that changes no behaviour
51
+ // at all, which is the only kind a behavioural test cannot see.
52
+ const die = makeDie(NAME);
53
+
54
+ // The cause of a failed child process, for `check`'s repository probe and its
55
+ // tracker query — each captures the child's stderr instead of forwarding it, so
56
+ // what the child printed reaches no terminal and this string is the only copy
57
+ // of it (#638).
58
+ //
59
+ // Trim BEFORE choosing, not after. A whitespace-only stderr is truthy, so it
60
+ // wins a choice made on the raw values and then trims away to nothing, leaving
61
+ // the reader an empty parenthesis where the reason belongs; choosing on the
62
+ // trimmed text falls through to the next candidate instead. `?? ""` per
63
+ // candidate, so a field that is absent contributes nothing — where the same
64
+ // choice made with `||` around a `String()` hands back the text `undefined` as
65
+ // the cause when no candidate is set at all (measured).
66
+ //
67
+ // Keep the END when it overruns, and say so. A CLI prints its warnings ahead of
68
+ // the error that killed it, so keeping the first bytes discards the cause and
69
+ // hands back a string cut mid-word that reads as the whole of what was printed
70
+ // — the marker is what stops it reading that way. Capped either way, marker
71
+ // included: every caller ships this inside a machine-parsed payload on stdout,
72
+ // where a megabyte of child stderr is a problem however the cause was chosen.
73
+ const CAUSE_MAX = 500;
74
+ function cause(...candidates) {
75
+ const raw = candidates.map((c) => String(c ?? "").trim()).find(Boolean);
76
+ if (!raw) return "";
77
+ return raw.length > CAUSE_MAX ? `…${raw.slice(-(CAUSE_MAX - 1))}` : raw;
78
+ }
79
+
80
+ // The budget every `git` child in this file gets, in milliseconds.
81
+ //
82
+ // Both git probes ran UNBOUNDED before #1199, while the `gh` query between
83
+ // them carried 20 s. That asymmetry was the defect: measured with a `git` that
84
+ // answers and then never returns, `check` — the fleet's pre-filing duplicate
85
+ // guard — was still running at 60 s having written nothing at all to stdout,
86
+ // where the same shape on the `gh` side degrades at its own bound and still
87
+ // prints a payload. The author bounded `gh` precisely because a child can
88
+ // stall; the two `git` children were left with no bound to reach.
89
+ //
90
+ // 10 s, and the number is chosen against the FALSE FAILURE rather than against
91
+ // the stall — net_fetch_budget's rule in net.sh, applied to a local call.
92
+ // These are `rev-parse` probes, not fetches: measured across five concurrent
93
+ // copies of the whole suite (the fleet's own normal condition), both stayed at
94
+ // p50 11-15 ms and max 24.7 ms, so this is ~400x the worst latency observed
95
+ // under load. Generous on purpose, because a probe killed while HEALTHY does
96
+ // not fail loudly here — defaultLedgerPath() degrades to a cwd-relative
97
+ // ledger and only warns (a pre-existing fallback #155 leaves alone, not
98
+ // something it introduces). It also stays under the `gh` bound beside it —
99
+ // though "dominant" overstates that relationship: a normal invocation
100
+ // without `--file` pays this same budget TWICE in sequence, once here and
101
+ // once more in repoCheck() below, before ever reaching `gh` at all. At
102
+ // default settings that TIES `gh`'s own 20 s bound when both probes stall,
103
+ // and can EXCEED it — up to GIT_TIMEOUT_MS + 20 s — when only one stalls and
104
+ // `gh` still runs (measured). `check`'s worst case is the sum of whichever
105
+ // of the three children actually stall, not a single fixed term.
106
+ //
107
+ // `LEDGER_GIT_TIMEOUT` is this script's OWN override, in seconds, and it can
108
+ // only ever SHORTEN. The rule and the reasons for it are net_budget's, in
109
+ // net.sh: a knob that could lengthen the bound is one more way for
110
+ // configuration to remove it, and each script keeping its own variable is why
111
+ // that helper takes the override's value rather than its name. A value that is
112
+ // not a positive whole number below the default is not an error and not a
113
+ // bound either — the default stands, in silence. isDigits() is arg.mjs's own
114
+ // predicate, so the accepted spelling is the shell rule's `*[!0-9]*` and not a
115
+ // second reading of it; net_budget's extra six-digit clause guards a shell
116
+ // integer overflow that has no counterpart here, and the `<` below already
117
+ // rejects every value that clause would have.
118
+ function gitBudget(defaultSeconds, override) {
119
+ const seconds = isDigits(String(override)) ? Number(override) : 0;
120
+ return (seconds > 0 && seconds < defaultSeconds ? seconds : defaultSeconds) * 1000;
121
+ }
122
+ const GIT_TIMEOUT_MS = gitBudget(10, process.env.LEDGER_GIT_TIMEOUT);
123
+
124
+ // There is ONE ledger per run, and it lives in the main checkout. Members run
125
+ // from their own worktrees, where a cwd-relative `.fleet/ledger.md` does not
126
+ // exist — `check` then warns and reports every subject as safe to file, which
127
+ // is precisely the duplicate-filing guard failing open. Resolve against the
128
+ // git COMMON dir (shared by every worktree) rather than the cwd, via
129
+ // git-env.mjs's workspaceDirFromGitCommonDir() — the resolution itself is
130
+ // shared with fleet-state.mjs and board.mjs since #1658, and only the
131
+ // filename and the warning below are this caller's own. No canonicalisation
132
+ // is asked for: that is board.mjs's opt-in, and taking it here would change
133
+ // the path this function RETURNS (and `check` prints) without changing which
134
+ // file it names.
135
+ function defaultLedgerPath() {
136
+ // GIT_DIR/GIT_WORK_TREE scrubbed (#1599, gitEnv()): unlike the tracker-query
137
+ // probe below in this same file, this call passed no env at all until now.
138
+ // An ambient GIT_DIR answers `--git-common-dir` for a DIFFERENT repository,
139
+ // so the ONE ledger every run's duplicate-filing guard reads gets resolved
140
+ // underneath THAT repository instead of the caller's own — measured
141
+ // directly against a checkout of this repo: `GIT_DIR=/tmp/other/.git node
142
+ // ledger.mjs row 357 "…"` wrote `/tmp/other/.fleet/ledger.md`, silently, at
143
+ // exit 0, and `check` then reads whatever ledger (or absence of one) lives
144
+ // there and reports every subject safe to file.
145
+ const r = spawnSync("git", ["rev-parse", "--git-common-dir"], { encoding: "utf8", timeout: GIT_TIMEOUT_MS, env: gitEnv() });
146
+ // No separate `r.status === 0` gate: every failure mode reproducible here
147
+ // (no repository, an unresolvable GIT_DIR, a permission-denied `.git`, a
148
+ // corrupt worktree pointer, a missing `git` binary, a timed-out probe)
149
+ // leaves `r.stdout` empty, which workspaceDirFromGitCommonDir() already
150
+ // reads as `null` on its own — see its own docstring for that contract.
151
+ const workspace = workspaceDirFromGitCommonDir(r.stdout);
152
+ if (workspace === null) {
153
+ // Could not resolve the shared git dir → fall back to a cwd-relative path.
154
+ // That re-opens the worktree fail-open this resolution exists to close (a
155
+ // member reads a cwd-local ledger, not the run's), so say so rather than
156
+ // degrading the duplicate-filing guard in silence. Since #1199 this probe
157
+ // is bounded too, and an ETIMEDOUT stall prints byte-identical stderr to
158
+ // an instant "not a repository" failure without naming which — the
159
+ // sibling probe in runCheck() already names it via cause(); match that
160
+ // shape here rather than leaving this one generic.
161
+ const why = cause(r.error && r.error.message, r.stderr);
162
+ console.error(`${NAME}: WARNING could not resolve --git-common-dir${why ? `: ${why}` : ""}; using cwd-relative .fleet/ledger.md (duplicate-filing guard may be degraded)`);
163
+ return ".fleet/ledger.md";
164
+ }
165
+ return join(workspace, ".fleet", "ledger.md");
166
+ }
167
+
168
+ const argv = process.argv.slice(2);
169
+ // Both flags are read by EXACT token below (`indexOf`), so the `--flag=value`
170
+ // spelling matches neither — and an unmatched token is not refused, it lands
171
+ // in `rest`, where `check`'s `rest.join(" ")` folds it into the SUBJECT. That
172
+ // loses the path AND corrupts the text being checked: measured, `check
173
+ // --file=<other-ledger> "<subject that ledger has already filed>"` exits 0
174
+ // "safe to file" where the space-separated form exits 1 ALREADY FILED, and
175
+ // `--file <missing> check --require-file=true dup` exits 0 where the bare flag
176
+ // exits 2. It failed loudly only where the token happened to land in the
177
+ // SUBCOMMAND slot — argv[0] once the splices below have run, which a leading
178
+ // `--file=x` does — and `unknown subcommand` is not the same refusal. That one
179
+ // sample is why the `=` form read as already covered. So scan the whole argv
180
+ // — which is why the sliced `argv` is passed rather than left to default to
181
+ // process.argv, and why the scan is not anchored to a position.
182
+ //
183
+ // The same refusals arg.mjs gives the scripts that route through its arg() and
184
+ // has(), in this reader's own wording (#362) — and since #567 that parity is
185
+ // the shared hasEqualsForm() predicate itself rather than a claim about two
186
+ // expressions that were free to drift apart.
187
+ // Flag names lived here AND in OWN_FLAGS below with no shared source — a
188
+ // future flag added to the indexOf() calls without a matching OWN_FLAGS
189
+ // entry would parse normally but never be refused in a `check` subject
190
+ // (measured: added `--another-file` the same way, `check -another-file …`
191
+ // silently accepted at exit 0). One name each, declared once, reused by
192
+ // the indexOf() calls and OWN_FLAGS below. Not by the hasEqualsForm() calls
193
+ // right below, which keep their own literal text on purpose —
194
+ // shared-refusal.test.mjs pins that pair's source verbatim against arg.mjs's
195
+ // rule (#567), so interpolating them here would fail that pin without
196
+ // fixing anything it exists to catch.
197
+ const FILE_FLAG_NAME = "file";
198
+ const REQUIRE_FILE_FLAG_NAME = "require-file";
199
+ if (hasEqualsForm("file", argv)) die("--file needs a space-separated value, not --file=");
200
+ if (hasEqualsForm("require-file", argv)) die("--require-file is a boolean flag, not --require-file=");
201
+ const fileIdx = argv.indexOf(`--${FILE_FLAG_NAME}`);
202
+ const file = fileIdx === -1 ? defaultLedgerPath() : argv[fileIdx + 1];
203
+ // #362: `--file` took whatever token followed it, so `--file --require-file`
204
+ // made the FLAG the path and the splice below then ate it — `--require-file`,
205
+ // the flag whose entire job is to turn a missing ledger into a hard failure,
206
+ // silently absent, and the duplicate-filing check answering "safe to file" at
207
+ // exit 0 where the correct invocation exits 2 (measured). A caller gating on
208
+ // that exit code files the duplicate. `if (!file)` below only ever caught a
209
+ // truly trailing `--file` — it still does, in its own wording; this guard is
210
+ // additive.
211
+ //
212
+ // Refusing a `--`-prefixed value forfeits a path that legitimately begins
213
+ // with `--`. That is not a local choice: isFlagLike() below IS arg.mjs's rule,
214
+ // so this reader forfeits exactly what every script routing through arg()
215
+ // forfeits, no more and no less — the set of them being whatever `grep -lE
216
+ // '^const arg = makeArg|^import .*defineFlags' scripts/*.mjs | grep -v test`
217
+ // reports: a makeArg binding, or a defineFlags() table whose arg()/numArg()
218
+ // are built on it. Anchored on the binding and the import, because the
219
+ // unanchored `grep -l makeArg` matched this comment and so listed ledger.mjs,
220
+ // the one script this paragraph says does NOT route through arg(). A single
221
+ // leading `-`, or a `--` anywhere but the front, is still a path.
222
+ //
223
+ // The `file &&` term is load-bearing and must not fold into isFlagLike(),
224
+ // which answers TRUE for an absent value: without it a truly trailing `--file`
225
+ // would land on this clause's wording instead of the pre-existing "given with
226
+ // no path" one below, which is the behaviour #362's own Measured block records
227
+ // as already correct and which ledger.test.mjs pins.
228
+ if (fileIdx !== -1 && file && isFlagLike(file)) die("--file needs a path");
229
+ if (fileIdx !== -1) argv.splice(fileIdx, 2);
230
+ if (!file) die("--file given with no path");
231
+ const requireFileIdx = argv.indexOf(`--${REQUIRE_FILE_FLAG_NAME}`);
232
+ const requireFile = requireFileIdx !== -1;
233
+ if (requireFileIdx !== -1) argv.splice(requireFileIdx, 1);
234
+
235
+ const [cmd, ...rest] = argv;
236
+ if (!cmd) die("usage: ledger.mjs [--file <path>] [--require-file] row|filed|ruled|check|read|dispatch|settle|drain [args]");
237
+
238
+ const ROWS = "## Rows";
239
+ const DISPATCHED = "## Dispatched";
240
+ const FILED = "## Filed";
241
+ const RULED = "## Ruled";
242
+ const DRAIN = "## Drain";
243
+
244
+ // What a section header looks like on disk, defined once because a second
245
+ // copy drifts: the parser slices sections with it, and the readability flag
246
+ // below is set from it. Anchored to a real line start (or string start), not
247
+ // a bare substring search — otherwise an escaped entry that merely CONTAINS
248
+ // the text "## Filed" (never a physical line, just a run of characters inside
249
+ // a one-line entry) is found by indexOf() before the genuine header and the
250
+ // whole section is sliced from the wrong offset.
251
+ const headerRe = (name) => new RegExp(`(^|\\n)${name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(\\n|$)`);
252
+
253
+ // One entry is always exactly one physical line on disk. Escape backslash
254
+ // first, then newline, so a `\` in entry text can never be mistaken for the
255
+ // start of an escape sequence introduced by this encoding. Without this, an
256
+ // entry containing a real newline — or a line that happens to look like
257
+ // `## Filed` or `- #999 ...` — gets misparsed on reload: real records
258
+ // silently drop, or phantom ones get injected.
259
+ function escapeText(s) {
260
+ return s.replace(/\\/g, "\\\\").replace(/\n/g, "\\n");
261
+ }
262
+ function unescapeText(s) {
263
+ return s.replace(/\\(\\|n)/g, (_, c) => (c === "n" ? "\n" : "\\"));
264
+ }
265
+
266
+ // #584: a `--`-prefixed token in `check`'s free-text tail used to fold
267
+ // straight into the duplicate-filing subject, so a misspelled flag searched
268
+ // for a DIFFERENT subject and read "safe to file" where the correct spelling
269
+ // answers ALREADY FILED at exit 1. A `--` token can legitimately BE that data
270
+ // (arg.mjs's refuseUnknown() comment names why sweep() stays out of this file),
271
+ // so what separates a stray flag from data is length: `check`'s documented
272
+ // calling convention hands the subject as ONE argument, so an unquoted stray
273
+ // reveals itself by making the tail longer than that one argument allows.
274
+ // `check --requre-file "widget guard missing"` is a two-element tail; `check
275
+ // "--require-file silently absent when value missing"` is one. A one-element
276
+ // tail is accepted unchanged, whatever it starts with; a multi-element tail
277
+ // carrying a `--`-prefixed element is refused by name. Structural, not a
278
+ // distance threshold.
279
+ //
280
+ // `check`'s tail ALONE — narrower than #584's first pass, which called this
281
+ // from `filed`, `row` and `ruled` too. The length rule is only sound where
282
+ // the documented convention IS one quoted argument, and `check` is the only
283
+ // subcommand where it is: both places that instruct a caller to run it spell
284
+ // it `ledger.mjs check "<subject>"` (run-team/SKILL.md's finisher step,
285
+ // review-and-fix.md's filing step), while run-team/SKILL.md's ledger section
286
+ // spells the other three `filed <issue> <subject>`, `row <ticket> <text>` and
287
+ // `ruled <pr> <decision>` — a bare multi-word tail, as did this file's own
288
+ // usage strings for them. Applied there, the rule refused what the docs
289
+ // prescribe: measured on the tree ahead of this narrowing, `filed 999 the
290
+ // --basee flag is unread`, `row 42 the --basee flag is unread` and `ruled 77
291
+ // the --basee flag is unread` each exited 2, where the tree before #584
292
+ // (07dc927) answered all three at exit 0. #1161 ruled the guard back to
293
+ // `check` rather than respelling three conventions SKILL.md carries, two
294
+ // other tickets holding that file open.
295
+ //
296
+ // Stated here and nowhere else (#1557). This paragraph is the one copy of why
297
+ // the rule is `check`'s alone; arg.mjs's refuseUnknown() comment and
298
+ // ledger.test.mjs's two stray-tail blocks each used to carry their own, and
299
+ // now point here instead. Anything that reads on the docs or the
300
+ // measurement belongs in this paragraph, not beside a caller.
301
+ //
302
+ // Narrowing it does not keep #584's signature whole on those three: only the
303
+ // ID-slot vector survives — a stray flag one token to the LEFT is still
304
+ // refused by refuseStrayInId() below. The tail-slot vector does not: a
305
+ // stray `--` word inside filed/row/ruled's tail is now accepted as data (no
306
+ // rule can tell it apart from the subject a caller typed), so `filed 999
307
+ // --typo-flag some new subject` exits 0 and writes a row a later `check
308
+ // "some new subject"` cannot exact-match — a near-miss at best, the same
309
+ // wrong-subject shape #584 closed, reopened here on the tail. That is the
310
+ // cost of taking the ticket's option 2 (narrow the guard rather than
311
+ // requote the docs, #1161) instead of option 1; it is why it is the
312
+ // DOCUMENTED convention, not the hazard, that decides where the length rule
313
+ // may be read at all.
314
+ //
315
+ // The cost `check` keeps is real and is what #365's AC prices, so it is
316
+ // stated rather than denied: a legitimate subject carrying a `--` word
317
+ // anywhere, given unquoted, was accepted before this guard and is refused by
318
+ // it — `check the --basee flag is unread` answered at exit 0 before and exits
319
+ // 2 now. Quoting the subject accepts it unchanged. The trade the ticket ruled
320
+ // for is that this refusal is loud and recoverable where the wrong-subject
321
+ // answer it replaces was silent. One residual of that trade is not this
322
+ // file's to close: SKILL.md's ledger section spells `check <subject>`
323
+ // unquoted inside the same entry that spells `filed <issue> <subject>`, where
324
+ // the two instructions that tell a caller to RUN it quote the subject.
325
+ //
326
+ // Narrowed on `check` too, not closed: a lone stray with no subject beside it
327
+ // is a one-element tail, so it is still taken as the subject and answered at
328
+ // exit 0. Harmless because it then searches for a string nothing matches, and
329
+ // ledger.test.mjs's degenerate-subject case pins it so it stays deliberate.
330
+ //
331
+ // #1744: one dash short is the same slip, and the `--` test let it through —
332
+ // `check -require-file widget guard missing` scored "-require-file widget
333
+ // guard missing" and answered exit 0 where the correctly-spelled call answers
334
+ // ALREADY FILED at exit 1. That test cannot simply lose a dash: single-dash
335
+ // words are ordinary free text in this repo's subjects — another tool's short
336
+ // flag (`grep -q`, `git branch -D`), a lone `-` standing in for a dash, a
337
+ // negative number. Measured when this was written, 23 of the repo's 1068
338
+ // issue titles carry one as a whitespace-split word, 20 of them letter-led,
339
+ // so neither the prefix nor a `-<letter>` shape tells the slip apart. A NAME
340
+ // does, the way arg.mjs's stray() tells a stray from a value (#463): a
341
+ // single-dash word is refused only when one more dash, ahead of any `=value`,
342
+ // makes it a flag this script reads — OWN_FLAGS, the two spliced out of argv
343
+ // above. None of those titles carries one. It sits behind the same length
344
+ // gate, so a one-argument subject is still accepted whatever it opens with.
345
+ //
346
+ // Left open, deliberately: a second slip on top of the missing dash
347
+ // (`-requre-file`), and a short form this script never defined (`-f`).
348
+ // Reaching either takes a shape or distance rule rather than a name, and
349
+ // `-f` is exactly the other-tool short flag above; both still fold into the
350
+ // subject.
351
+ const OWN_FLAGS = [`--${FILE_FLAG_NAME}`, `--${REQUIRE_FILE_FLAG_NAME}`].map((f) => f.toLowerCase());
352
+ // The one-dash name clause below, before #1766, matched only a's FIRST
353
+ // whitespace-split word (ahead of any `=value`), not the whole element: a
354
+ // quoted multi-word tail element (`check "-require-file widget" guard
355
+ // missing`, one argv element) reconstructed to "--require-file widget"
356
+ // under a whole-token match, which is not in OWN_FLAGS, so it fell through
357
+ // to exit 0 — the same verdict flip #1744 exists to refuse, just via a
358
+ // quoted shape rather than a bare token. Splitting first mirrored the `--`
359
+ // clause above it, which already matches on startsWith rather than
360
+ // requiring the whole element. #1766 below widened the split to check
361
+ // EVERY word of the element, not only the first — see that paragraph for
362
+ // why the first-word version stopped being enough.
363
+ //
364
+ // #1766: that first-word, exact-case split still missed four shapes of the
365
+ // same name, each confirmed by direct probe against the shipped script: a
366
+ // case-variant spelling (`-REQUIRE-FILE`), whitespace ahead of the dash —
367
+ // including U+00A0, which `\s` already matches, but the FIRST-word split
368
+ // still lost the real word to the empty token that whitespace leaves at
369
+ // index 0 — and the flag name landing anywhere but first in a quoted
370
+ // multi-word element (`"widget -require-file"`, the mirror of the shape
371
+ // just above, where #1744's fix only checked the front). None of the four
372
+ // changes the rule itself — still a NAME match against OWN_FLAGS, never a
373
+ // prefix or shape test — only how a word is pulled out of the element:
374
+ // every whitespace-split word, lower-cased, before the OWN_FLAGS lookup —
375
+ // OWN_FLAGS itself is lower-cased once at declaration above, so this clause
376
+ // stays correct even if FILE_FLAG_NAME/REQUIRE_FILE_FLAG_NAME ever gain a
377
+ // capital letter.
378
+ //
379
+ // #1850: the per-word test above only ever builds the ONE-dash-PREPENDED
380
+ // form of a word (`-${word...}`), so it matches a word already spelled with
381
+ // one dash but never a word already spelled with this script's own TWO-dash
382
+ // flag name — that spelling comes out of the split as `--require-file`,
383
+ // prepending one more dash makes `---require-file`, and OWN_FLAGS only holds
384
+ // `--require-file`. The outer `startsWith("--")` clause above only reaches a
385
+ // two-dash name when it leads the WHOLE tail element; the same name landing
386
+ // anywhere else in a quoted multi-word element — trailing, in the middle, or
387
+ // alone behind leading whitespace — was invisible to both clauses and folded
388
+ // back into the subject: the identical verdict flip #1744 and #1766 exist to
389
+ // refuse, one dash count over. Reproducible on `main` before #1766 too;
390
+ // #1766 only made it visible by contrast, once the one-dash mirror shape
391
+ // started being refused. Fixed the same way #1744 chose for the one-dash
392
+ // case — a NAME match, never a prefix or shape test — by also checking a
393
+ // word's own AS-SPELLED form against OWN_FLAGS, alongside the
394
+ // one-dash-prepended form already there.
395
+ //
396
+ // #1851: a Unicode format character (general category Cf — U+200B zero-width
397
+ // space, U+2060 word joiner, U+00AD soft hyphen, the bidi controls, …) is
398
+ // invisible and sits outside `\s`, so the split above never cut on it and it
399
+ // rode along inside the word: `\u200B-require-file` reads as `-require-file`
400
+ // yet never equalled an own-flag spelling, and scored as subject text. Each
401
+ // word now has every Cf code point stripped before either lookup, so it is
402
+ // looked up as the word a reader sees — wherever the character sits, ahead of
403
+ // the dash, inside the name, or behind it. Stripped, not split on: a word
404
+ // any OTHER Cf character sits inside of stays one word (`pre\u200B-file` is
405
+ // `pre-file`, not a `-file`). And stripped AFTER the `\s` split, not before:
406
+ // U+FEFF is the one code point in both Cf and `\s` — the one exception to
407
+ // the sentence just above, since it keeps splitting a word in two there the
408
+ // way it always did — and a strip ahead of the split would join
409
+ // `widget\uFEFF-require-file` into one word and stop refusing it. Own names
410
+ // are ASCII, so only a word that is an own-flag spelling plus Cf characters
411
+ // is newly refused.
412
+ // Cf also holds a few VISIBLE marks (the Arabic number signs U+0600–0605,
413
+ // among others); stripping them costs a refusal only of such a mark glued to
414
+ // an own-flag name, which no subject carries.
415
+ //
416
+ // #1904: invisible characters OUTSIDE Cf — U+3164 and the other Hangul
417
+ // fillers (letters), U+034F and the variation selectors (combining marks) —
418
+ // are text rather than format controls, so the Cf strip above let them ride
419
+ // inside the word exactly as a zero-width space rode before it. The strip is
420
+ // now the union of Cf and Default_Ignorable_Code_Point, the property Unicode
421
+ // itself keeps for code points a renderer shows nothing for: one property
422
+ // rather than a hand-curated block list, which would miss the members no
423
+ // ticket named (U+17B4, the Mongolian selectors U+180B–180F, …). A union,
424
+ // not DICP alone: DICP leaves out the visible Cf marks just above, so
425
+ // swapping it in would drop cases #1851 already refuses. Same site and the
426
+ // same after-the-split order as #1851; U+FEFF stays the one code point in
427
+ // both the strip and `\s`, no DICP member adding another. An emoji's own
428
+ // presentation selector (U+FE0F) is stripped too, which costs nothing: only
429
+ // a word that is an own-flag spelling once stripped is refused.
430
+ //
431
+ // Left open, deliberately: blank-rendering code points outside both
432
+ // properties (U+2800 braille blank, among others), which Unicode classes as
433
+ // ordinary visible symbols; and a Cf character ahead of a NON-own `--word`
434
+ // leading a tail element, which the outer `startsWith("--")` clause misses
435
+ // exactly as it misses ordinary whitespace there.
436
+ function refuseStrayInCheckTail(tail) {
437
+ if (tail.length <= 1) return;
438
+ const stray = tail.find(
439
+ (a) =>
440
+ a.startsWith("--") ||
441
+ a.split(/\s+/).some((word) => {
442
+ const name = word.replace(/[\p{Cf}\p{Default_Ignorable_Code_Point}]/gu, "").split("=")[0].toLowerCase();
443
+ return OWN_FLAGS.includes(name) || OWN_FLAGS.includes(`-${name}`);
444
+ }),
445
+ );
446
+ if (stray) die(`unknown flag ${stray} in subject — quote the subject as one argument`);
447
+ }
448
+
449
+ // The id slot ahead of `filed`/`row`/`ruled`'s tail is a hazard of its own,
450
+ // and the only one of the three a rule can act on. refuseStrayInCheckTail()
451
+ // above is not read on those subcommands at all (#1161), and would not
452
+ // catch this shape if it were: a stray flag one token earlier lands in
453
+ // `issue`/`ticket`/`pr`, and the tail left behind carries no `--` element to
454
+ // find. Nor could that helper be read over the whole of `rest` instead —
455
+ // that refuses `filed <issue> "--flag-like subject"` too, a two-element
456
+ // tail with a `--` element, pinned here as must-keep-working. A legitimate
457
+ // id is bare digits, optionally `#`-prefixed, and never carries a leading
458
+ // dash at all — single or double — so this slot refuses ANY leading dash,
459
+ // not only a double one (#1678). The free-text tail cannot take that same
460
+ // test: a subject can legitimately open with a double-dash-leading word —
461
+ // exactly what `--flag-like subject text` above and check's own
462
+ // dash-leading-subject pin exist to keep working. A single-dash-leading word
463
+ // is ordinary subject text too, which is why check's tail refuses one only
464
+ // by name (#1744, on refuseStrayInCheckTail() above). So only the id slot
465
+ // can take the bare prefix test at all, for the same no-free-text reason
466
+ // given above.
467
+ function refuseStrayInId(value, what) {
468
+ if (value.startsWith("-")) die(`unknown flag ${value} — expected ${what}`);
469
+ }
470
+
471
+ // Set by load(), the only function that reads the file, so `ledger.ok` can
472
+ // report what the parse saw rather than what a later stat() guesses (#231).
473
+ let ledgerParsed = false;
474
+
475
+ function load() {
476
+ if (!existsSync(file)) return { rows: [], filed: [], ruled: [], dispatched: [], drain: null };
477
+ let text;
478
+ try {
479
+ text = readFileSync(file, "utf8");
480
+ } catch (e) {
481
+ die(`cannot read ${file}: ${e.message}`);
482
+ }
483
+ const section = (name) => {
484
+ const m = headerRe(name).exec(text);
485
+ if (!m) return [];
486
+ const start = m.index + m[1].length + name.length;
487
+ const after = text.slice(start);
488
+ const end = after.search(/\n## /);
489
+ return (end === -1 ? after : after.slice(0, end))
490
+ .split("\n").map((l) => l.trim()).filter((l) => l.startsWith("- "))
491
+ .map((l) => unescapeText(l.slice(2)));
492
+ };
493
+ // Set here, past the read and the early return, so it can only be true of a
494
+ // file this function actually opened and recognised as a ledger.
495
+ ledgerParsed = headerRe(FILED).test(text);
496
+ // A ledger written before #1799 has neither `## Dispatched` nor `## Drain`,
497
+ // which reads as nothing dispatched through `dispatch` and no drain — the
498
+ // truth about that file, not a default standing in for it.
499
+ const drainEntries = section(DRAIN);
500
+ // One marker per run: the `drain` command's own `created` guard refuses a
501
+ // second call rather than overwrite the standing reason. A second entry
502
+ // reaching this file some other way (hand edit, merge, an older writer) is
503
+ // the same invariant broken on disk, and narrowing to `[0]` here would
504
+ // drop it with no warning at all — the read-side half of that guard.
505
+ if (drainEntries.length > 1) {
506
+ die(`${file} has ${drainEntries.length} \`## Drain\` entries — one marker per run`);
507
+ }
508
+ return {
509
+ rows: section(ROWS), filed: section(FILED), ruled: section(RULED),
510
+ dispatched: section(DISPATCHED), drain: drainEntries[0] ?? null,
511
+ };
512
+ }
513
+
514
+ // `## Drain` is written only once there is a marker to hold: an empty section
515
+ // under that name would read, to anyone scanning the file by eye, as a run
516
+ // that is draining.
517
+ function save(d) {
518
+ const list = (entries) => entries.map((r) => `- ${escapeText(r)}`).join("\n");
519
+ const out =
520
+ `# Fleet run ledger\n\n${ROWS}\n\n` + list(d.rows) +
521
+ `\n\n${DISPATCHED}\n\n` + list(d.dispatched) +
522
+ `\n\n${FILED}\n\n` + list(d.filed) +
523
+ `\n\n${RULED}\n\n` + list(d.ruled) +
524
+ (d.drain === null ? "" : `\n\n${DRAIN}\n\n` + list([d.drain])) + "\n";
525
+ try {
526
+ mkdirSync(dirname(file), { recursive: true });
527
+ // Write to a sibling temp file and rename over the target. rename is
528
+ // atomic on a POSIX filesystem — a crash mid-write leaves the temp file
529
+ // corrupt but never truncates the durability file itself. The temp name
530
+ // carries the pid: a shared `${file}.tmp` let one writer rename another's
531
+ // temp file out from under it, and the loser died on ENOENT (#531).
532
+ const tmp = `${file}.${process.pid}.tmp`;
533
+ writeFileSync(tmp, out);
534
+ renameSync(tmp, file);
535
+ } catch (e) {
536
+ die(`cannot write ${file}: ${e.message}`);
537
+ }
538
+ console.error(` wrote ${file}`);
539
+ }
540
+
541
+ // ── The write lock (#531) ────────────────────────────────────────────────────
542
+ //
543
+ // Held from before load() through save() on every write subcommand, because
544
+ // save() rewrites the whole document from what load() read: without it two
545
+ // writers each load, append and save, and whichever renames last silently
546
+ // discards the other's row. Reads (`check`, `read`) take no lock — the rename
547
+ // already hands them either the old file or the new one, never a torn one.
548
+ //
549
+ // `<file>.lock` is created O_EXCL and holds its owner's pid. Creating it and
550
+ // writing the pid are two steps, so a waiter can read an empty or partial
551
+ // lock in between: anything that is not a canonical positive integer counts
552
+ // as a LIVE holder — keep waiting, and never hand it to process.kill, where
553
+ // NaN is a TypeError crash rather than a wait. That empty or partial lock
554
+ // never clears on its own, either: nothing revisits and finishes writing it
555
+ // — the writer that would have finished died before the second step. Same
556
+ // permanent wedge as a leftover reap lock below, same fix: the operator
557
+ // removes it by hand once nothing is writing.
558
+ //
559
+ // A holder that died without releasing — SIGKILL always, and so does any
560
+ // signal this file leaves unhandled (SIGQUIT, SIGABRT, a segfault: only a
561
+ // normal exit and the three catchable signals below run the `exit` event
562
+ // that releases it) — is taken over, but only under a second O_EXCL lock,
563
+ // `<file>.lock.reap`, and only after RE-READING the lock under it, finding
564
+ // the same dead pid, and RE-CHECKING that pid is still dead. Unlink-then-
565
+ // create, or a bare rename, lets two waiters that both saw the dead pid each
566
+ // remove the other's FRESH lock and write at once; the re-read is what makes
567
+ // the takeover safe. The re-check narrows the one window the re-read leaves
568
+ // (#2088), and the order the two run in is what narrows it: isDead(deadPid)
569
+ // runs before the re-read, not after, so a live writer that takes the lock in
570
+ // the gap between them is caught by the read that follows, not hidden behind
571
+ // one taken before it arrived. Read first, and a recycled pid that came back
572
+ // to life in that same gap would still read back as itself and still check
573
+ // dead — the order this replaces would delete that live holder's fresh lock. A
574
+ // recycled pid that became a new writer this same way — dead holder's lock
575
+ // reaped by someone else, then re-created by the new owner of that very pid —
576
+ // still writes the same content and would still pass the re-read alone, but
577
+ // the isDead() ahead of it now catches that writer live, before the read ever
578
+ // runs. Only that exact pid reused a second time, inside this narrower gap,
579
+ // can still slip through. Under the reap lock no other waiter can replace the
580
+ // lock's content outside that gap, so a pid still dead immediately before the
581
+ // read that follows it is the dead holder, and a live one is left alone to be
582
+ // waited on like any live holder. A reap lock is held for one liveness check,
583
+ // one read and one unlink, and one left behind by any of those same abrupt
584
+ // deaths in that window is deliberately NOT reclaimed: waiters time out naming
585
+ // the holder, and the operator removes it. Fail closed.
586
+ //
587
+ // A dead holder whose pid was recycled reads as live until the timeout.
588
+ // Accepted: an mtime/age heuristic instead would take over a live writer on a
589
+ // slow disk, which is the row loss this lock exists to prevent.
590
+ //
591
+ // A live-looking holder can also be a zombie: a pid whose process exited but
592
+ // whose parent never `wait()`-ed on it. The OS keeps that pid reserved until
593
+ // reaped, so `process.kill(pid, 0)` still succeeds and isDead() reads it as
594
+ // alive — but unlike the two wedges above, that clears on its own once the
595
+ // pid is reaped (the parent's own exit is normally enough to trigger this),
596
+ // and the next writer's death check then takes the lock over like any other
597
+ // dead holder. No hand removal needed.
598
+ //
599
+ // The wait is bounded — 10 s by default — and the timeout is die(), exit 2,
600
+ // having written nothing. `LEDGER_LOCK_TIMEOUT_MS` overrides it and, like
601
+ // `LEDGER_GIT_TIMEOUT` above, can only ever SHORTEN it.
602
+ //
603
+ // What the lock does NOT cover: `check` -> `gh issue create` -> `filed` is
604
+ // three commands, and each takes the lock (or not) alone, so two filers can
605
+ // both read `clean` before either records. Accepted (#531): the measured
606
+ // same-run accidental duplicate, #298 -> #302, was filed minutes apart, and a
607
+ // claim/reserve subcommand closing that window was ruled out.
608
+ const LOCK = `${file}.lock`;
609
+ const REAP = `${LOCK}.reap`;
610
+ const LOCK_WAIT_MS = (() => {
611
+ const v = process.env.LEDGER_LOCK_TIMEOUT_MS;
612
+ const ms = isDigits(String(v)) ? Number(v) : 0;
613
+ return ms > 0 && ms < 10_000 ? ms : 10_000;
614
+ })();
615
+ let lockHeld = false;
616
+
617
+ const parsePid = (text) => (/^[1-9][0-9]*$/.test(text) ? Number(text) : null);
618
+
619
+ // null when there is no lock to read — it was released between our failed
620
+ // create and this read, and the next create attempt is the right response.
621
+ function readLock() {
622
+ try {
623
+ return readFileSync(LOCK, "utf8");
624
+ } catch (e) {
625
+ if (e.code === "ENOENT") return null;
626
+ die(`cannot read ${LOCK}: ${e.message}`);
627
+ }
628
+ }
629
+
630
+ // ESRCH alone is dead. EPERM is a live process we may not signal, and any
631
+ // other error is not evidence of death either.
632
+ function isDead(pid) {
633
+ try {
634
+ process.kill(pid, 0);
635
+ return false;
636
+ } catch (e) {
637
+ return e.code === "ESRCH";
638
+ }
639
+ }
640
+
641
+ // true when the takeover ran (whatever it found under the reap lock), so the
642
+ // caller retries the create at once; false when another waiter holds the
643
+ // reap lock, so the caller waits like any other contended lock.
644
+ function reapDeadHolder(deadPid) {
645
+ let fd;
646
+ try {
647
+ fd = openSync(REAP, "wx");
648
+ } catch (e) {
649
+ if (e.code === "EEXIST") return false;
650
+ die(`cannot create ${REAP}: ${e.message}`);
651
+ }
652
+ try {
653
+ closeSync(fd);
654
+ // Dead again, not just when the caller looked: that pid may have been
655
+ // reused since, so isDead runs first, fresh, right here — before the
656
+ // exact-match re-read, not after it. Exact match only: a waiter that
657
+ // got here first may already have reaped the dead lock and taken a
658
+ // fresh one of its own.
659
+ if (isDead(deadPid) && readLock() === String(deadPid)) {
660
+ // Already gone is already the outcome this call wants: an operator
661
+ // clearing a wedged lock by hand between the read above and here must
662
+ // not turn our own cleanup into an uncaught crash.
663
+ try {
664
+ unlinkSync(LOCK);
665
+ } catch (e) {
666
+ if (e.code !== "ENOENT") throw e;
667
+ }
668
+ }
669
+ } finally {
670
+ unlinkSync(REAP);
671
+ }
672
+ return true;
673
+ }
674
+
675
+ function releaseLock() {
676
+ if (!lockHeld) return;
677
+ lockHeld = false;
678
+ try {
679
+ if (readFileSync(LOCK, "utf8") === String(process.pid)) unlinkSync(LOCK);
680
+ } catch {
681
+ // Nothing to release, or nothing this process can do about it on its way
682
+ // out: exit handlers cannot fail usefully.
683
+ }
684
+ }
685
+
686
+ async function acquireLock() {
687
+ try {
688
+ mkdirSync(dirname(file), { recursive: true });
689
+ } catch (e) {
690
+ die(`cannot write ${file}: ${e.message}`);
691
+ }
692
+ process.on("exit", releaseLock);
693
+ for (const sig of ["SIGTERM", "SIGINT", "SIGHUP"]) process.on(sig, () => process.exit(2));
694
+ const deadline = Date.now() + LOCK_WAIT_MS;
695
+ for (;;) {
696
+ let fd = null;
697
+ try {
698
+ fd = openSync(LOCK, "wx");
699
+ } catch (e) {
700
+ if (e.code !== "EEXIST") die(`cannot create ${LOCK}: ${e.message}`);
701
+ }
702
+ if (fd !== null) {
703
+ try {
704
+ writeSync(fd, String(process.pid));
705
+ } catch (e) {
706
+ // Ours, and empty or partial: every waiter reads it as live, and
707
+ // releaseLock() will not match it, so it goes now or never.
708
+ closeSync(fd);
709
+ unlinkSync(LOCK);
710
+ die(`cannot write ${LOCK}: ${e.message}`);
711
+ }
712
+ closeSync(fd);
713
+ lockHeld = true;
714
+ return;
715
+ }
716
+ const holder = readLock();
717
+ if (holder === null) {
718
+ // Ordinarily transient — released between our failed create above and
719
+ // this read — so retrying the create at once beats sleeping first.
720
+ // But that same shape recurs FOREVER if reading it fails for a reason
721
+ // this read can never clear: a `.lock` path that is a dangling
722
+ // symlink reports EEXIST to the create (the dirent exists) and ENOENT
723
+ // to every read (its target does not). Bounding it here is what keeps
724
+ // that case inside the 10 s wait this lock promises rather than
725
+ // spinning past it at 100% CPU.
726
+ if (Date.now() >= deadline) die(`cannot lock ${file} — ${LOCK} exists but cannot be read`);
727
+ continue;
728
+ }
729
+ const pid = parsePid(holder);
730
+ const dead = pid !== null && isDead(pid);
731
+ if (dead && reapDeadHolder(pid)) continue;
732
+ if (Date.now() >= deadline) {
733
+ // `dead` here but still not taken over means this call's own reap
734
+ // attempt found `${REAP}` already there right now — the same instant a
735
+ // reaper SIGKILLed between its own create and unlink leaves behind
736
+ // forever (see the write-lock header comment above `LOCK`/`REAP`), and
737
+ // indistinguishable at this instant from a live reaper mid-takeover.
738
+ // Naming the pid alone points an operator at a process that no longer
739
+ // exists; naming `${REAP}` is what lets them find the file
740
+ // `run-team/SKILL.md`'s runbook tells them to remove by hand, once
741
+ // nothing is writing.
742
+ if (dead) {
743
+ die(`cannot lock ${file} — held by pid ${pid}, which is dead; ${REAP} is blocking its takeover — if nothing is currently writing, remove it by hand`);
744
+ }
745
+ // No pid at all is the other permanent wedge the header describes: an
746
+ // empty or partial `${LOCK}` whose writer died before writing its pid,
747
+ // read as live forever by design. There is no process to point at, so
748
+ // name `${LOCK}` itself — the file the same runbook says to remove.
749
+ if (pid === null) {
750
+ die(`cannot lock ${file} — ${LOCK} holds ${JSON.stringify(holder)}, not a pid, so it is never taken over — if nothing is currently writing, remove it by hand`);
751
+ }
752
+ die(`cannot lock ${file} — held by pid ${pid}`);
753
+ }
754
+ // A timer, not a blocking sleep: a waiter holds no lock, so a SIGTERM
755
+ // that arrives while it waits should end it now, and the handlers above
756
+ // only run when the event loop is free to run them.
757
+ await new Promise((r) => setTimeout(r, 5 + Math.random() * 15));
758
+ }
759
+ }
760
+
761
+ // Read ahead of the dispatch, not inside one branch of it. This guard used to
762
+ // live in runCheck(), so `check` refused a missing ledger under the flag and
763
+ // the other four subcommands ignored it entirely: `read --require-file` on an
764
+ // absent file printed the empty payload at exit 0, byte-identical to a real
765
+ // empty ledger on both streams, and `row --require-file` CREATED the very file
766
+ // whose absence the flag exists to refuse (#816). One flag read in one place is
767
+ // also what docs/specs/2026-07-23-fleet-plugin-design.md's `ledger.mjs` row
768
+ // already documents
769
+ // — "Exit 2 on any subcommand — ... `--require-file` with no ledger file" — so
770
+ // the implementation is what had drifted, not the contract.
771
+ //
772
+ // Ahead of load() rather than after it: load() answers "absent" and "present
773
+ // but unparseable" with the same empty lists, which is the ambiguity this flag
774
+ // exists to break, so the answer must not be taken from it. `check`'s own
775
+ // wording and exit code are unchanged — it reached this same die() first
776
+ // either way, before its stray-tail and usage guards — and the WARNING left
777
+ // behind in runCheck() is now unreachable under the flag by construction
778
+ // rather than by an `if` that repeats the condition.
779
+ //
780
+ // Also ahead of "unknown subcommand" validation: `--require-file` against a
781
+ // missing file with a bogus subcommand reports the require-file refusal, not
782
+ // a usage error. Deliberate/accepted, not reordered — the doc line above
783
+ // bundles both under one undifferentiated exit 2, with no ordering between them.
784
+ if (requireFile && !existsSync(file)) die(`--require-file given but ledger file does not exist: ${file}`);
785
+
786
+ const WRITE_COMMANDS = new Set(["row", "filed", "ruled", "dispatch", "settle", "drain"]);
787
+ if (WRITE_COMMANDS.has(cmd)) await acquireLock();
788
+ const data = load();
789
+
790
+ // The payload subcommands end by falling out of this chain, never by calling
791
+ // process.exit(). On a pipe, process.stdout.write is async and process.exit()
792
+ // discards whatever is still queued, so a payload past the buffer arrives cut
793
+ // — at exit 0, which types a corrupt read as a successful one (#246).
794
+ // candidates.mjs states the same reason at its own exit line; this was the
795
+ // second script on that shape. The consumer that made it visible is board.mjs,
796
+ // which reads `read` through execFileSync — a pipe — and accepts its ledger
797
+ // only as a path, so nothing on the caller's side could work around it: a
798
+ // grown ledger served a cockpit whose board was empty at HTTP 200.
799
+ //
800
+ // The chain is `else if` so that not exiting does not send a good subcommand
801
+ // on into the unknown-subcommand die() below it.
802
+ //
803
+ // `check` reaches both of its exits that way too, though only one of them
804
+ // could be an assignment where it stood. Its terminal exit was the last
805
+ // statement of its branch and became one directly. Its already-filed exit sits
806
+ // mid-branch, where falling through would run the near-miss ranking and the
807
+ // tracker search that exit exists to skip — so `check`'s branch is a function
808
+ // now (runCheck, below the chain), and a `return` is what skips them (#808).
809
+ //
810
+ // What that leaves is a property of every payload this file emits rather than
811
+ // of whichever branches a sweep happened to reach: none of them reaches
812
+ // process.exit(), and none of their exit codes moved in getting there. A
813
+ // `check` arm is the one to re-read this against, because its payload is
814
+ // bounded by the LEDGER rather than by argv — `match` is a row read straight
815
+ // out of `data.filed`, and `near` is sliced from it — so both arms reach the
816
+ // cut on a ledger no caller can bound, which is why they are the arms the
817
+ // suite drives through a pipe.
818
+ if (cmd === "read") {
819
+ console.log(JSON.stringify(data));
820
+ } else if (cmd === "row") {
821
+ const [ticket, ...textParts] = rest;
822
+ if (!ticket || textParts.length === 0) die("usage: ledger.mjs row <ticket> <text>");
823
+ // A stray flag here becomes the row KEY, which is what the rewrite-in-place
824
+ // lookup below matches on — so the real ticket's next `row` call finds no
825
+ // match and appends a second row instead of rewriting the first.
826
+ refuseStrayInId(ticket, "a ticket number");
827
+ const key = ticket.startsWith("#") ? ticket : `#${ticket}`;
828
+ const line = `${key} ${textParts.join(" ")}`;
829
+ // Every reader parses member tokens anywhere in a row's text, so a token
830
+ // with an outcome outside its family's vocabulary would land as a permanent
831
+ // settle — `settle merge-bot-1 done` then refuses as "already settled as
832
+ // dispatched" (#2139). Refused before anything is written, new row or
833
+ // rewrite alike; a well-formed token, live or settled, still goes through.
834
+ const malformed = memberTokens(line).find((t) => t.error !== null);
835
+ if (malformed) die(`row ${key}: malformed member token '${malformed.name}=${malformed.outcome}' — ${malformed.error}`);
836
+ const i = data.rows.findIndex((r) => r.split(/\s/)[0] === key);
837
+ const created = i === -1;
838
+ if (created) {
839
+ data.rows.push(line);
840
+ } else {
841
+ data.rows[i] = line;
842
+ }
843
+ // Logged only after save() returns — a failed write must not claim a row
844
+ // was recorded when it never made it to disk.
845
+ save(data);
846
+ console.error(created ? ` new row ${key}` : ` rewrote row ${key}`);
847
+ console.log(JSON.stringify({ ticket: key, line, created }));
848
+ } else if (cmd === "filed") {
849
+ const [issue, ...subjectParts] = rest;
850
+ if (!issue || subjectParts.length === 0) die("usage: ledger.mjs filed <issue> <subject>");
851
+ // A stray flag here shifts the issue number into the subject, so the row it
852
+ // writes no longer answers the subject a later `check` asks about — that
853
+ // check reports not-filed at exit 0 where the correctly-spelled filing makes
854
+ // it report already-filed at exit 1.
855
+ refuseStrayInId(issue, "an issue number");
856
+ const subject = subjectParts.join(" ");
857
+ const id = issue.replace(/^#/, "");
858
+ // isDigits() gates id the same way the sibling ticket/PR check gates key
859
+ // (line ~1527): left unvalidated, a non-digit id becomes a `#<id> ` prefix
860
+ // subjectOf()'s digits-only regex (#933) cannot strip, so a near-duplicate
861
+ // `check` against that row silently degrades from the hard "already
862
+ // filed" block to a soft near-miss suggestion instead.
863
+ if (!isDigits(id)) die(`'${issue}' is not an issue number`);
864
+ // Both callers retry once on a failure they observed, and an observed
865
+ // failure is not proof the write failed — a timeout after the row landed
866
+ // reads as one — so a repeat filing of an issue already on file is a no-op
867
+ // (#2087). Identity is the issue number alone, matched NUMERICALLY — so a
868
+ // non-canonical spelling (`08`) still dedupes against `8` — as the token
869
+ // between `#` and the first whitespace: never `check`'s fuzzy subject
870
+ // matcher, and never a prefix test, which would dedupe #8 against #80.
871
+ // The existing row wins, subject and all — a retry reworded is still the
872
+ // same filing.
873
+ const existing = data.filed.find((row) => Number(row.match(/^#(\S+)/)?.[1]) === Number(id));
874
+ if (existing !== undefined) {
875
+ console.error(` already recorded: ${existing}`);
876
+ console.log(JSON.stringify({ issue, subject, total: data.filed.length, alreadyRecorded: true, row: existing }));
877
+ } else {
878
+ data.filed.push(`#${id} ${subject}`);
879
+ save(data);
880
+ console.log(JSON.stringify({ issue, subject, total: data.filed.length }));
881
+ }
882
+ } else if (cmd === "ruled") {
883
+ const [pr, ...decisionParts] = rest;
884
+ if (!pr || decisionParts.length === 0) die("usage: ledger.mjs ruled <pr> <decision>");
885
+ // Nothing reads this section back — save() is its only consumer — so the
886
+ // harm here is the narrowest of the three: a permanently wrong decision
887
+ // record in an append-only file, with no verdict riding on it. Guarded
888
+ // anyway, because that record is what the subcommand exists to write.
889
+ refuseStrayInId(pr, "a PR number");
890
+ const decision = decisionParts.join(" ");
891
+ data.ruled.push(`#${pr.replace(/^#/, "")} ${decision}`);
892
+ save(data);
893
+ console.log(JSON.stringify({ pr, decision, total: data.ruled.length }));
894
+ } else if (cmd === "check") {
895
+ runCheck();
896
+ } else if (cmd === "dispatch") {
897
+ runDispatch();
898
+ } else if (cmd === "settle") {
899
+ runSettle();
900
+ } else if (cmd === "drain") {
901
+ // One marker per run. A second `drain` — a replacement controller that
902
+ // cannot tell whether its predecessor got this far — is answered with the
903
+ // standing marker at exit 0, not by overwriting the reason it records.
904
+ // Trimmed because load() trims every entry it reads back.
905
+ const reason = rest.join(" ").trim();
906
+ if (!reason) die('usage: ledger.mjs drain "<reason>"');
907
+ const created = data.drain === null;
908
+ if (created) {
909
+ data.drain = reason;
910
+ save(data);
911
+ } else {
912
+ console.error(` already draining: ${data.drain}`);
913
+ }
914
+ console.log(JSON.stringify({ drain: data.drain, created }));
915
+ } else {
916
+ die(`unknown subcommand '${cmd}' — expected row, filed, ruled, check, read, dispatch, settle or drain`);
917
+ }
918
+
919
+ // `check` alone of the subcommands leaves its arm early: the already-filed
920
+ // answer is complete before the near-miss ranking and the tracker query below
921
+ // it, whose results that answer would only discard. A function is what makes
922
+ // leaving early expressible — `process.exitCode` and a `return`, reaching the
923
+ // same exit by the same path every other subcommand takes, where an arm of the
924
+ // chain had only `process.exit()` and the payload it abandoned (#808).
925
+ // Hoisted, so the dispatch chain above stays the file's spine.
926
+ function runCheck() {
927
+ // The first check of a run legitimately has no file yet, so absence alone
928
+ // cannot be an error — but a silent "safe to file" for every check when
929
+ // the path is simply wrong (typo'd --file) is a fail-open that no caller
930
+ // would notice. Warn loudly by default; --require-file makes absence a
931
+ // hard failure for callers that know the file must already exist — and that
932
+ // refusal is read ahead of the dispatch now, not here, because four other
933
+ // subcommands needed the same one (#816). Reaching this line at all means
934
+ // the flag was absent.
935
+ //
936
+ // `ledger.ok` is the parse's answer, not this stat()'s: load() sets it only
937
+ // for a file it opened and found a `## Filed` header in, so a --file landing
938
+ // on some other existing file reports `ok:false` rather than a positive
939
+ // machine-readable claim that the ledger was read. The warning below stays
940
+ // on existence because that is the question it answers, and --require-file's
941
+ // contract is absence rather than shape — so the two are two observations
942
+ // now, each true of its own question, where before they were one that was
943
+ // true of neither. Narrower, not airtight: a ledger truncated AFTER the
944
+ // header still parses, with the rows below it lost (#231).
945
+ const ledger = { ok: ledgerParsed };
946
+ if (!existsSync(file)) {
947
+ console.error(
948
+ `${NAME}: WARNING — ledger file not found: ${file}. Every check will read "safe to file" until it exists.`,
949
+ );
950
+ } else if (!ledger.ok) {
951
+ // #817: the existence probe above is silent once `file` exists, so a
952
+ // `--file` landing on a real-but-wrong path — a typo'd neighbour, a
953
+ // corrupted "## Filed" header, a 0-byte file — got the SAME silence as a
954
+ // clean read. `ledger.ok` (above) already tells the machine-readable half
955
+ // apart; this is that same "opened it, it did not parse" fact stated on
956
+ // stderr, in wording that does not borrow "file not found" — the file
957
+ // demonstrably exists, so claiming otherwise would be a fresh version of
958
+ // the defect #231 removed from the JSON half.
959
+ console.error(
960
+ `${NAME}: WARNING — ${file} exists but does not look like a ledger (no "${FILED}" header found). Every check will read "safe to file" until it is fixed.`,
961
+ );
962
+ }
963
+ refuseStrayInCheckTail(rest);
964
+ const subject = rest.join(" ");
965
+ // Quoted here, unlike the three usage strings above, because
966
+ // refuseStrayInCheckTail() is the reason: `check` is the subcommand whose tail
967
+ // must arrive as ONE argument, and this is the only spelling of its call
968
+ // inside the script (#1161). The other three take their tail as the words a
969
+ // caller typed.
970
+ if (!subject) die("usage: ledger.mjs check \"<subject>\"");
971
+ const norm = (s) => s.toLowerCase().replace(/[^a-z0-9]+/g, " ").trim();
972
+ const tokenSet = (s) => new Set(norm(s).split(/\s+/).filter(Boolean));
973
+ const target = tokenSet(subject);
974
+ if (target.size === 0) die(`normalised subject is empty — '${subject}' has no alphanumeric tokens to check`);
975
+ // Substring matching collides both ways: a short generic subject ("line")
976
+ // matches everything (false "already filed" silently loses a finding),
977
+ // while an all-punctuation subject normalises to "" and matches anything
978
+ // too. Token-set matching fixes both, with a deliberate asymmetric bias —
979
+ // a false "already filed" is invisible and bad, a false "not filed" just
980
+ // creates a duplicate someone closes — so equal sets OR a >=4-token subset
981
+ // both count as a match, catching real near-duplicate rewordings without
982
+ // matching short generic overlaps.
983
+ const isMatch = (filedTokens) => {
984
+ const [small, big] = filedTokens.size <= target.size ? [filedTokens, target] : [target, filedTokens];
985
+ // Both acceptance rules are size tests, so they gate the subset walk
986
+ // instead of following it: a pair qualifying under neither is refused
987
+ // without walking the smaller set, one qualifying under either is walked
988
+ // once. Testing set equality as a separate walk, as this did, re-walked a
989
+ // same-size near-miss that cleared the subset floor for an answer the
990
+ // first walk had already produced — equal sizes are exactly the case
991
+ // where the two walks are the same walk.
992
+ // Not `small.isSubsetOf(big)`: that's Node v22.0.0+, above this repo's
993
+ // declared >=20.11.0 floor (#1954; node-floor-sweep.test.mjs reds it).
994
+ return (small.size === big.size || small.size >= 4) && [...small].every((t) => big.has(t));
995
+ };
996
+ // Strip the leading `#NNN ` issue number: it is metadata, not part of the
997
+ // finding's subject. Left in, it becomes a stray token the checked subject
998
+ // never carries, so a filed row can never be a subset of a longer check
999
+ // subject — the >=4-token rule silently never fires and duplicates get filed.
1000
+ const subjectOf = (filedRow) => filedRow.replace(/^#\d+\s+/, "");
1001
+ const match = data.filed.find((f) => isMatch(tokenSet(subjectOf(f))));
1002
+ if (match) {
1003
+ console.error(`${NAME}: ALREADY FILED — ${match}`);
1004
+ // `ledger` rides on this arm too, where it can only be true. A consumer
1005
+ // testing `!payload.ledger.ok` otherwise reads the field's absence as
1006
+ // falsy — "never read" — on the one answer that proves it was read.
1007
+ console.log(JSON.stringify({ subject, found: true, match, ledger, verdict: "already-filed" }));
1008
+ // Exit 1 means "do not file this again" — the strong signal. Exit 3 is also
1009
+ // non-zero but weaker: tracker rows to review, not a ruling. A caller that
1010
+ // checks only the exit status stops on both, which errs toward not
1011
+ // duplicating.
1012
+ //
1013
+ // exitCode + return, not exit(): the payload above is `match`, a row read
1014
+ // straight out of the ledger, and `filed` caps neither the subject it
1015
+ // stores nor the ledger it stores it into — so this is the branch whose
1016
+ // payload is bounded by the LEDGER rather than by argv, and measured, an
1017
+ // ordinary four-word check against one wide filed row arrived cut at the
1018
+ // pipe buffer. The code it arrived under was already this 1, so what the
1019
+ // exit lost was the payload alone, the `verdict` field parsing consumers
1020
+ // read included (#808). The `return` is what keeps the ranking and the
1021
+ // tracker query below unreached; nothing after it assigns exitCode on
1022
+ // this path, so 1 is what the process leaves with.
1023
+ process.exitCode = 1;
1024
+ return;
1025
+ }
1026
+
1027
+ // Near-miss reporting. The subset match above answers exactly one question —
1028
+ // "was this near-verbatim wording already filed" — and answers it well. It
1029
+ // says nothing about the same finding described in DIFFERENT words, which is
1030
+ // how a second discoverer actually words it: one measured run rediscovered
1031
+ // #114 five times, each in its own phrasing, and the check caught none of
1032
+ // them. Rank the filed list by token overlap and hand the top rows back with
1033
+ // a score, instead of collapsing all of that into `found: false`.
1034
+ //
1035
+ // Scored on its own token set, deliberately not the exact path's. Stopwords
1036
+ // and the singular fold only sharpen a ranking, but folding them into
1037
+ // isMatch() would widen what counts as ALREADY FILED — the one behaviour
1038
+ // here that callers gate on and that must not move.
1039
+ // Widened for #153: modals, negations and temporals ("should", "never",
1040
+ // "still"...) are noise words that are never the subject's distinctive
1041
+ // term, yet the old, shorter list let them survive to outrank one — "the
1042
+ // guard should never fail open on a fork" picked "should guard never" over
1043
+ // content words a reader would actually search for. Measured zero fallout:
1044
+ // this file's suite is unchanged by the widening (see the "term selection"
1045
+ // tests). Two adjacent ideas were considered and rejected, not attempted
1046
+ // here: preferring identifier-shaped tokens (`CI`, `gh`) over long ordinary
1047
+ // words — but norm() below has already stripped the punctuation that would
1048
+ // mark a token as an identifier, so that needs a different pipeline, not a
1049
+ // different stoplist — and real frequency weighting, which stays the named
1050
+ // upgrade path until something measured demands it. Neither would be
1051
+ // reachable by widening a stoplist anyway.
1052
+ const STOP = new Set((
1053
+ "the a an of to in is it its and or for on with that this from at by " +
1054
+ "should would could can may might must will shall ought " +
1055
+ "not never cannot nor " +
1056
+ "still already now then soon yet always once again when while before after until since"
1057
+ ).split(" "));
1058
+ // One pipeline, two callers. The scoring path and the query path filter on the
1059
+ // same floor and the same stoplist, and writing that expression out twice is
1060
+ // what let them drift — the coupling test below pins that they agree, and a
1061
+ // single definition is what makes the pin structural rather than hopeful.
1062
+ // It is also the only place the `>= 3` floor exists, so one mutation reaches
1063
+ // both consumers.
1064
+ const contentWords = (s) => norm(s).split(/\s+/).filter((t) => t.length >= 3 && !STOP.has(t));
1065
+ const scoreTokens = (s) => new Set(contentWords(s).map((t) => t.replace(/s$/, "")));
1066
+ // Overlap coefficient (shared / smaller set), not Jaccard. A filed row carries
1067
+ // a source tag like `(review-pr-108)` and other metadata the checked subject
1068
+ // can never contain, so the union is dominated by tokens with no chance of
1069
+ // matching: Jaccard drives every row to a similar small number and the
1070
+ // ranking stops discriminating. Dividing by the smaller set also keeps the
1071
+ // score indifferent to which side is more verbose.
1072
+ const overlap = (a, b) => {
1073
+ if (a.size === 0 || b.size === 0) return 0;
1074
+ let shared = 0;
1075
+ for (const t of a) if (b.has(t)) shared++;
1076
+ return shared / Math.min(a.size, b.size);
1077
+ };
1078
+ const round2 = (n) => Math.round(n * 100) / 100;
1079
+ const scored = scoreTokens(subject);
1080
+ // No floor was tuned here: the measured #114 rewording shares exactly one
1081
+ // content word, and a threshold picked to look tidy would drop the very case
1082
+ // this exists for. The top-3 cap, not the floor, is what keeps the output
1083
+ // short. `rankedNear`'s filter still imposes one, because it tests the
1084
+ // ROUNDED score: a raw overlap below 0.005 rounds to 0.00, so a row that
1085
+ // DOES share a content word is dropped from both `near` and `nearTotal`,
1086
+ // with no line reporting it. That cutoff is not a chosen number — it sits
1087
+ // wherever round2's two decimals land and moves only if that precision does.
1088
+ // Filtering on the raw score instead is not the free fix it looks like: it
1089
+ // admits such a row at a display score of `0.00` (measured), so honest
1090
+ // output would need a wider precision, not just a different filter.
1091
+ const NEAR_SHOWN = 3;
1092
+ // The floor at which a near-miss stops being decoration and becomes the
1093
+ // verdict's own answer — `soft-hit` rather than `clean` (#388). A tuning
1094
+ // value, deliberately named and deliberately here beside the display cap
1095
+ // rather than inlined in the verdict below.
1096
+ //
1097
+ // Chosen from the rows #388 measured: the near-misses a reader went on to
1098
+ // confirm as the genuinely adjacent issue scored from 0.20 up to 0.45, so a
1099
+ // floor at 0.20 admits them. #388 also records an adjacent row at 0.09, which
1100
+ // this floor does not reach — the floor buys a short answer, never
1101
+ // completeness, and the rows themselves stay printed and stay in the payload
1102
+ // at every verdict for exactly that reason. Raise it and adjacent rows fall
1103
+ // back to `clean`; lower it and every check reporting a soft hit is what
1104
+ // gives.
1105
+ const NEAR_SOFT_HIT = 0.2;
1106
+ const rankedNear = data.filed
1107
+ .map((row) => ({ row, score: round2(overlap(scored, scoreTokens(subjectOf(row)))) }))
1108
+ .filter((n) => n.score > 0)
1109
+ .sort((a, b) => b.score - a.score);
1110
+ const near = rankedNear.slice(0, NEAR_SHOWN);
1111
+ // The cap is a display budget, and it says nothing about the rows it drops:
1112
+ // scores tie across it routinely — measured, five rows at 1.00 with the
1113
+ // caller shown three — so the cut is arbitrary among equals. A bare
1114
+ // three-row list is then indistinguishable from a complete one, which is
1115
+ // the "no silent caps" rule `candidates.mjs`'s `refuseIfCapped` legislates one script over
1116
+ // (#154). It enforces that rule by refusing outright; refusing is wrong
1117
+ // here — these rows are advisory context for a decision, not the work queue,
1118
+ // and a single tracker hit already forces exit 3. Report the COUNT withheld
1119
+ // and the best score among them, never the rows: printing the rows would
1120
+ // give back the length the cap exists to take away, while the count and the
1121
+ // top withheld score are what tell a caller whether the cut cost it
1122
+ // anything.
1123
+ const withheld = rankedNear.slice(NEAR_SHOWN);
1124
+
1125
+ // The ledger can only see what THIS run recorded. An issue that already
1126
+ // exists on the tracker but never reached this `filed` list — filed by an
1127
+ // earlier run, by the maintainer, by hand — is structurally invisible to
1128
+ // every match above, and that is the measured failure: #114 was rediscovered
1129
+ // five times in one run and `check` reported it safe to file every time. Ask
1130
+ // the tracker.
1131
+ //
1132
+ // gh ANDs the search terms, so every extra term can only narrow the result —
1133
+ // keep the query SHORT: three of the subject's most distinctive words.
1134
+ // Measured against the live tracker, "candidates opposite states" returns
1135
+ // #114. Whether a fourth term helps or hurts turns on whether it happens to
1136
+ // occur in the target issue's text — gh searches bodies, not just titles —
1137
+ // which the subject cannot know: "code" leaves #114 in, "open" drops it. So
1138
+ // three is a recall-preserving floor, not a measured optimum. Longest-first is a crude stand-in for distinctiveness (no
1139
+ // corpus to weigh terms against) and the >= 3 filter erases short but
1140
+ // distinctive identifiers like `CI` or `gh`; upgrade to a real frequency
1141
+ // weighting if the query starts missing.
1142
+ //
1143
+ // #153 widened STOP (above) to stop modals/negations/temporals from
1144
+ // outranking real content words, and stops there — this is a pin, not a
1145
+ // retune. Two things it deliberately leaves broken: longest-first still
1146
+ // prefers a long ordinary word over a short distinctive one ("postgres"
1147
+ // still loses to "exhausted"/"sustained"; "cap" still loses to
1148
+ // "silently"/"surfaced"), because fixing that is the frequency-weighting
1149
+ // upgrade above, not a stoplist edit; and the >= 3 filter still erases `CI`
1150
+ // and `PR` outright, because norm() has already destroyed the punctuation
1151
+ // that would mark them as identifiers worth keeping short — a different
1152
+ // pipeline, not a different stoplist or a lower floor (lowering it
1153
+ // interacts with every one of these and had no test of its own until this
1154
+ // issue added one). A tracker search that returns nothing is reported
1155
+ // below as "no matches for this query", not as "no related issues" — a
1156
+ // three-term heuristic query coming up empty establishes that the query
1157
+ // found nothing, not that the tracker has nothing.
1158
+ //
1159
+ // norm() has already stripped punctuation, which is also what keeps a subject
1160
+ // containing `is:open` or `file.mjs:164` from smuggling a qualifier into the
1161
+ // search and silently changing what was searched for.
1162
+ const terms = [...new Set(contentWords(subject))]
1163
+ .sort((a, b) => b.length - a.length)
1164
+ .slice(0, 3);
1165
+ const query = terms.join(" ");
1166
+ // How many tracker rows the caller is shown. gh is asked for one MORE than
1167
+ // this (below): its list arrives with no total, so a full page and a
1168
+ // truncated one are byte-identical, and the extra row's presence is the only
1169
+ // truncation signal available — #154. Cheap: one row, one query, and it is
1170
+ // ranked alongside the rest rather than discarded.
1171
+ const TRACKER_SHOWN = 5;
1172
+ let tracker;
1173
+ if (terms.length === 0) {
1174
+ // An empty --search matches every issue in the repo, which would report
1175
+ // every subject as a tracker hit. Not searching is the honest answer.
1176
+ // `hits` is omitted, not `[]` — the tracker was never read, so an empty
1177
+ // list here would be a claim of cleanliness this branch never earned
1178
+ // (issue #152: a consumer testing `.length` must not read this as clean).
1179
+ tracker = { ok: false, query: null, error: "subject has no distinctive terms to search for" };
1180
+ } else {
1181
+ // gh resolves "the repository" from the child process's cwd, which
1182
+ // defaults to THIS process's cwd — the caller's, not the ledger's. The
1183
+ // ledger itself is resolved from --file or defaultLedgerPath()'s
1184
+ // --git-common-dir above; in the documented flow (no --file, run from
1185
+ // the repo) the two agree, but an explicit --file naming a ledger
1186
+ // outside the caller's repo diverges silently: the query searches the
1187
+ // wrong tracker and reports a confident, empty result (#155). Bind gh's
1188
+ // cwd to the ledger's OWN repository instead of leaving it implicit. No
1189
+ // --repo flag needed — gh's remote-based resolution does the rest once it
1190
+ // is pointed at the right directory, and a worktree ledger (shared .git,
1191
+ // own working tree) still resolves to the same repo either way.
1192
+ //
1193
+ // cwd is not the whole story: inherited git vars outrank it, so an
1194
+ // ambient GIT_DIR/GIT_WORK_TREE retargets BOTH the probe below and gh's
1195
+ // own remote resolution at the other repository, and the #155
1196
+ // confident-empty result comes straight back with `ok: true` on it.
1197
+ // Plausible here: a git hook, `rebase --exec`, `bisect run`. Scrub them
1198
+ // off both children — the fleet's own fixtures already do exactly this
1199
+ // (inflight.test.mjs).
1200
+ //
1201
+ // GH_REPO is the same hazard one layer up, and worse: gh reads it BEFORE
1202
+ // it ever consults git, so no amount of git-var hygiene covers it and the
1203
+ // bound cwd is simply ignored. Measured against a live tracker with the
1204
+ // cwd binding in place: `GH_REPO=<some other real repo>` searched that
1205
+ // repo and returned `{"ok":true,"hits":[],"verdict":"clean"}` — #155
1206
+ // verbatim, in the documented flow, no --file divergence needed. Not
1207
+ // hypothetical here either: this repo's own
1208
+ // .github/workflows/release-label.yml exports GH_REPO to every step that
1209
+ // shells out to gh.
1210
+ // Empty string is the documented fall-back-to-cwd value (measured — unset
1211
+ // and "" behave alike), so this composes with cwd rather than fighting it.
1212
+ //
1213
+ // With all three off, the ledger and the queried tracker cannot disagree.
1214
+ const queryEnv = { ...process.env, GH_REPO: "" };
1215
+ delete queryEnv.GIT_DIR;
1216
+ delete queryEnv.GIT_WORK_TREE;
1217
+ let ledgerDir = dirname(resolve(file));
1218
+ // `check` runs before the run's FIRST ledger write, and `.fleet/` is
1219
+ // gitignored and created lazily by save()'s mkdirSync — so on a fresh
1220
+ // clone or worktree the ledger's own directory does not exist yet, while
1221
+ // `git -C` requires one that does (exit 128, "cannot change to ...").
1222
+ // Climb to the nearest existing ancestor: same repository, and probing
1223
+ // the missing directory instead reported every first `check` as not being
1224
+ // in a repository and dropped the tracker query outright.
1225
+ while (!existsSync(ledgerDir) && dirname(ledgerDir) !== ledgerDir) ledgerDir = dirname(ledgerDir);
1226
+ const repoCheck = spawnSync("git", ["-C", ledgerDir, "rev-parse", "--show-toplevel"], { encoding: "utf8", env: queryEnv, timeout: GIT_TIMEOUT_MS });
1227
+ if (repoCheck.status !== 0) {
1228
+ // More than one cause lands here: a ledger path genuinely outside any
1229
+ // repository, but also git missing entirely (spawn ENOENT, so `status`
1230
+ // is null and `null !== 0`), a dubious-ownership refusal, an unreadable
1231
+ // `.git` gitfile, and since #1199 a probe that overran GIT_TIMEOUT_MS —
1232
+ // spawnSync reports that the same way ENOENT arrives, `status` null with
1233
+ // the reason in `error.message`, so it needs no arm of its own and
1234
+ // cause() names it (`spawnSync git ETIMEDOUT`) without this branch
1235
+ // having to. Do not name one of them — carry git's own reason,
1236
+ // because this call leaves stdio at the default pipe, so git's stderr
1237
+ // reaches no terminal and this string is the only place the cause is
1238
+ // ever seen (the same call the gh catch below makes, #176). The CAUSE is
1239
+ // capped for the same reason: it ships on stdout inside `tracker.error`
1240
+ // — see cause(), which owns both that cap and the choice between the
1241
+ // fields a failed git can put a reason in. Empty here is a tolerable
1242
+ // answer where it is not for the gh catch below: the message this
1243
+ // interpolates into still names the probe that failed and the path it
1244
+ // failed on.
1245
+ //
1246
+ // That cap covers the cause and NOTHING else. `tracker.error` as a whole
1247
+ // is deliberately unbounded here, because the directory interpolates
1248
+ // raw: the field measured 1100 characters from a 557-character
1249
+ // directory, a cause already cut to 500, and 43 of fixed text (#940).
1250
+ // Capping the directory would buy the payload no ceiling — `subject`
1251
+ // and `tracker.query` ride in the same JSON uncapped: as JSON fields
1252
+ // from a 3000-character subject word they measure 3012 and 3010
1253
+ // characters respectively (the 2-char gap is `query` being a shorter
1254
+ // key than `subject`, not a difference in the values) — and it would
1255
+ // cut the path the probe actually failed on, which is what this
1256
+ // message is for.
1257
+ // cause() is the wrong instrument for it twice over: it keeps the END,
1258
+ // so on a path it drops the root and returns a `…`-prefixed string that
1259
+ // reads like a path and is not one, and what it exists to contain is a
1260
+ // child's stderr, which nothing bounds, where the climb above leaves
1261
+ // this a path that exists.
1262
+ //
1263
+ // Either way there is no repository for the query to bind to — the same
1264
+ // state as this process's own cwd not being a repo, which already
1265
+ // degrades via the generic `!tracker.ok` branch below. Reuse that: no
1266
+ // gh invocation, no separate "unchecked" shape.
1267
+ const why = cause(repoCheck.error && repoCheck.error.message, repoCheck.stderr);
1268
+ tracker = { ok: false, query, error: `cannot resolve the ledger's repository (${ledgerDir})${why ? `: ${why}` : ""}` };
1269
+ } else {
1270
+ const ghCwd = repoCheck.stdout.trim();
1271
+ try {
1272
+ const out = execFileSync(
1273
+ "gh",
1274
+ ["issue", "list", "--search", query, "--state", "all", "--limit", String(TRACKER_SHOWN + 1),
1275
+ "--json", "number,title,state,url"],
1276
+ { encoding: "utf8", timeout: 20000, stdio: ["ignore", "pipe", "pipe"], cwd: ghCwd, env: queryEnv },
1277
+ );
1278
+ // Parsing inside the try on purpose: gh can exit 0 and still print
1279
+ // something that is not the JSON asked for. A parse failure is a failed
1280
+ // tracker read, not a clean tracker.
1281
+ const parsed = JSON.parse(out);
1282
+ // Parseable is not the same as the shape asked for. Without this, a gh
1283
+ // printing a JSON array that is not an issue list escalates to exit 3 and
1284
+ // prints "TRACKER HIT — #undefined" — a confident hit blocking a filing
1285
+ // that is in fact unverified. Throw into the catch below: an unreadable
1286
+ // answer is a failed tracker read, exactly like unparseable output.
1287
+ //
1288
+ // Validated: exactly those fields the hit line below interpolates that
1289
+ // have no defined absent-value. `title` is deliberately not among them —
1290
+ // the row builder substitutes `h.title || ""` for it, in the row and in
1291
+ // the score alike, so a row that OMITS `title` and carries every other
1292
+ // field still describes itself truthfully. Validating `title` here would
1293
+ // degrade that row to `unverified` over the one field the hit line does
1294
+ // not need, which is the opposite of what a guard against undescribable
1295
+ // hits is for (#232).
1296
+ //
1297
+ // Absence is the whole of that claim, deliberately: a `title` that is
1298
+ // PRESENT and not a string is not handled here or anywhere below —
1299
+ // `h.title || ""` keeps a truthy non-string, and scoreTokens then calls
1300
+ // `.toLowerCase()` on it, so the read degrades to `unverified` reporting
1301
+ // a TypeError where a tracker reason belongs. That is #643's, which
1302
+ // rules on field TYPE where this guard rules on field PRESENCE.
1303
+ if (!Array.isArray(parsed) || parsed.some((h) => !h || typeof h.number !== "number"
1304
+ || typeof h.state !== "string" || typeof h.url !== "string")) {
1305
+ throw new Error("gh returned JSON that is not an issue list");
1306
+ }
1307
+ // Every row gh returned is validated above, the probe row included: a
1308
+ // malformed row anywhere means the read is untrustworthy, and this
1309
+ // degrades to `unverified`, which never turns a hit into a clean bill.
1310
+ //
1311
+ // Rank the whole fetched window, THEN cut. Ranking only the first five
1312
+ // would hand back gh's own window order wearing a score order's
1313
+ // clothes, and the probe row was fetched to be ranked, not just
1314
+ // counted. What the cut cannot repair is that gh chose the window at
1315
+ // all — six rows are still a window, and re-sorting one does not widen
1316
+ // it — so `truncated` REPORTS that rather than pretending otherwise.
1317
+ const rankedHits = parsed
1318
+ .map((h) => ({
1319
+ number: h.number, title: h.title || "", state: h.state, url: h.url,
1320
+ score: round2(overlap(scored, scoreTokens(h.title || ""))),
1321
+ }))
1322
+ .sort((a, b) => b.score - a.score);
1323
+ tracker = { ok: true, query, hits: rankedHits.slice(0, TRACKER_SHOWN), truncated: rankedHits.length > TRACKER_SHOWN };
1324
+ } catch (e) {
1325
+ // Every gh failure lands here — no network, no auth, rate limit, gh not
1326
+ // installed (ENOENT), a timeout, unparseable output. None of them may
1327
+ // produce a bare "safe to file": that is the same fail-open class the
1328
+ // --git-common-dir resolution above already closed once. Degrade to the
1329
+ // ledger-only answer and say so.
1330
+ // Capped, and deliberately still carrying the stderr — the opposite call
1331
+ // from the fleet's other gh catches (#176). Those omit it because
1332
+ // execFileSync forwarded the child's bytes to our stderr already, so
1333
+ // interpolating emits them twice; this call sets `stdio`, which turns
1334
+ // that forwarding OFF, so this string is the only place the cause is
1335
+ // ever seen. What it must not be is unbounded: it lands in
1336
+ // `tracker.error`, which ships on stdout as part of a machine-parsed
1337
+ // contract, and a megabyte of gh stderr inside a JSON field is a payload
1338
+ // problem wherever the forwarding argument lands. cause() owns both that
1339
+ // cap and which end of an overrunning stderr survives it.
1340
+ //
1341
+ // stderr first, then the message: on a non-zero exit Node builds the
1342
+ // message out of the same bytes prefixed by the command, so it is the
1343
+ // LONGER copy of the cause, not a smaller fallback (#176, measured
1344
+ // again here). The message earns its place wherever stderr holds no
1345
+ // cause — and stderr holds none in three shapes, only one of which is
1346
+ // the field being absent: no `stderr` property at all on the output
1347
+ // this file refused to parse or refused the shape of, the property
1348
+ // present but `undefined` on a spawn Node never started, and present
1349
+ // but EMPTY on a child killed before it printed. Measured on Node
1350
+ // v26.7.0 — "carries no stderr field at all" covered the first shape
1351
+ // only. It also earns its place on a stderr with no cause in it, where
1352
+ // it still names the command that failed.
1353
+ //
1354
+ // Except where Node aborted the child, and there the order flips.
1355
+ // `e.code` carries the abort — ETIMEDOUT, ENOENT, EACCES — and Node
1356
+ // does not set it on an ordinary non-zero exit, so it separates the
1357
+ // failures gh explained for itself from the ones only Node can
1358
+ // explain. A timeout is named in `e.code` and `e.message` and NOWHERE
1359
+ // in `e.stderr`, which on a timeout holds whatever gh printed before
1360
+ // the kill: measured end to end, a gh that warned about cached
1361
+ // credentials and then hung reported that warning as the cause of a
1362
+ // 20-second stall and named the timeout nowhere (#638). The flip moves
1363
+ // exactly one failure, the timeout that printed something — the other
1364
+ // aborts leave `e.stderr` undefined, so the message already won there.
1365
+ // A Node that did set `e.code` on a plain non-zero exit would degrade
1366
+ // to "Command failed" plus those same bytes, the longer copy; the
1367
+ // accept-unchanged test below pins that string exactly, so it would
1368
+ // say so loudly rather than this arm drifting in silence.
1369
+ //
1370
+ // Nothing this arm can currently throw reaches the literal last resort:
1371
+ // every failure that lands here carries a message. It stays because an
1372
+ // empty `tracker.error` is precisely what makes the warning below name
1373
+ // no reason, which is the defect this arm was filed for.
1374
+ //
1375
+ // `hits` omitted here too, same reason as the no-terms branch above:
1376
+ // the search never ran, so there is no empty result to report.
1377
+ tracker = { ok: false, query, error: (e.code ? cause(e.message, e.stderr) : cause(e.stderr, e.message)) || "gh failed without saying why" };
1378
+ }
1379
+ }
1380
+ }
1381
+
1382
+ // The best score each half of the answer carries, read once off the same
1383
+ // sorted head the report below prints from and the verdict under it uses —
1384
+ // one derivation, so stderr and the payload cannot disagree about what was
1385
+ // found.
1386
+ //
1387
+ // Both lists are sorted best-first before they are cut, so the leading row
1388
+ // carries the best score of everything fetched: a 0 at the head of `hits`
1389
+ // means every row gh returned scored 0, and the withheld near-misses can only
1390
+ // score at or below `rankedNear`'s head. `rankedNear`, not the displayed
1391
+ // slice — the display cap must not be able to move a verdict.
1392
+ const bestHit = tracker.ok && tracker.hits.length ? tracker.hits[0].score : 0;
1393
+ const bestNear = rankedNear.length ? rankedNear[0].score : 0;
1394
+
1395
+ for (const n of near) console.error(`${NAME}: near-miss ${n.score.toFixed(2)} — ${n.row}`);
1396
+ if (withheld.length) {
1397
+ console.error(`${NAME}: ${withheld.length} further near-miss${withheld.length === 1 ? "" : "es"} not shown — highest withheld ${withheld[0].score.toFixed(2)}; the cap dropped them, not the score`);
1398
+ }
1399
+ if (!tracker.ok) {
1400
+ console.error(`${NAME}: WARNING — TRACKER NOT CHECKED (${tracker.error}). An issue that exists on the tracker but was never recorded in this run is invisible to the answer below.`);
1401
+ console.error(`${NAME}: not previously filed in this run's ledger — ledger-only answer, tracker unchecked`);
1402
+ } else if (tracker.hits.length) {
1403
+ // Inside the branch that has already established `hits` is present, so no
1404
+ // `?? []` guard is needed. The loop stays FIRST: every hit is listed before
1405
+ // the summary that counts them, and a test pins that order.
1406
+ //
1407
+ // The score reaches the row, and the row's own word follows it. `TRACKER
1408
+ // HIT` is imperative, blocking language, and a row the scorer rates 0.00
1409
+ // rendered in it was indistinguishable from a genuine duplicate — measured,
1410
+ // and recovered from only by readers who went and searched the tracker by
1411
+ // hand (#388). Under this heading stderr and the verdict now say the same
1412
+ // thing: a set with a scoring row is a hit, a set without one is rows to
1413
+ // read.
1414
+ const heading = bestHit > 0 ? "TRACKER HIT" : "TRACKER ROW";
1415
+ for (const h of tracker.hits) {
1416
+ console.error(`${NAME}: ${heading} — #${h.number} (${h.state}, score ${h.score.toFixed(2)}) ${h.title} — ${h.url}`);
1417
+ }
1418
+ // `more than N`, never `N`: with the probe row back, the exact count is
1419
+ // precisely what is not known, and printing `5` for it is the silent cap
1420
+ // restated as a number (#154).
1421
+ console.error(bestHit > 0
1422
+ ? `${NAME}: not in this run's filed list, but ${tracker.truncated ? `more than ${TRACKER_SHOWN}` : tracker.hits.length} tracker issue(s) match '${query}' — review before filing`
1423
+ : `${NAME}: not in this run's filed list; the tracker rows matching '${query}' all score 0.00 against this subject — gh matched something the title-based score cannot see, so read them, but they are not a finding of duplication`);
1424
+ if (tracker.truncated) {
1425
+ console.error(`${NAME}: the list above is CAPPED at ${TRACKER_SHOWN} — gh returned more and reports no total, so these are the best-scoring of a window gh chose, not of the tracker.`);
1426
+ }
1427
+ } else {
1428
+ // Not "found no related issues" — that asserts the tracker has nothing,
1429
+ // when all that is actually established is that a ${terms.length}-term
1430
+ // heuristic query came back empty (#153). A query built from a few
1431
+ // longest-surviving words can miss the very issue it should have found
1432
+ // (see the STOP comment above); "no matches for this query" says what was
1433
+ // established and leaves the rest unclaimed.
1434
+ console.error(`${NAME}: not previously filed; tracker search '${query}' (${terms.length} term${terms.length === 1 ? "" : "s"}) returned no matches — not a certification the tracker has nothing on this`);
1435
+ }
1436
+ // Named explicitly so a consumer does not have to reconstruct it from
1437
+ // `tracker.ok` plus `tracker.hits` — issue #152.
1438
+ //
1439
+ // The scores decide, not the presence of rows (#388). Both halves of the
1440
+ // answer were measured reporting the opposite of what their own numbers said:
1441
+ // `tracker-hit` over rows this file rates 0.00, and `clean` printed directly
1442
+ // above near-miss rows that named the right issue. Nothing new is computed
1443
+ // here — the scores were already in the payload and already on stderr; the
1444
+ // verdict simply stopped ignoring them.
1445
+ //
1446
+ // `soft-hit` is the answer for signal that is not a duplicate finding: rows
1447
+ // worth reading, at an exit code that does not claim the filing is settled.
1448
+ // It covers each of those, because they leave the caller in the same
1449
+ // position — a tracker set with no scoring row, or a filed row at or above
1450
+ // the near-miss floor.
1451
+ //
1452
+ // Order matters. `!tracker.ok` short-circuits before `tracker.hits` is read,
1453
+ // which is required: hits is absent, not `[]`, on that branch. `unverified`
1454
+ // stays ahead of the near-miss floor too — a tracker nobody read is the
1455
+ // weaker answer of the two and may not be dressed up as the stronger one.
1456
+ const verdict = !tracker.ok
1457
+ ? "unverified"
1458
+ : bestHit > 0
1459
+ ? "tracker-hit"
1460
+ : tracker.hits.length || bestNear >= NEAR_SOFT_HIT
1461
+ ? "soft-hit"
1462
+ : "clean";
1463
+ // Exit 0 is what a `check "$s" && gh issue create` chain reads as safe, and
1464
+ // `soft-hit` is precisely the answer that is not — so it is named on stderr
1465
+ // as well as in the payload, in the voice of the decision it asks for.
1466
+ if (verdict === "soft-hit") {
1467
+ console.error(`${NAME}: SOFT HIT — related rows above, none of them established as a duplicate. Read them and decide; do not read this exit code as safe to file.`);
1468
+ }
1469
+ // `nearTotal` alongside `near`, and `tracker.truncated` alongside `hits`:
1470
+ // both lists are capped and neither cap was previously visible from the
1471
+ // payload a consumer parses (#154). They differ in what is knowable —
1472
+ // the ledger is fully in hand, so the near-miss total is exact, while gh
1473
+ // reports no total, so the tracker can only say that more exist.
1474
+ // `ledger.ok` beside `tracker.ok`, and deliberately NOT inside `verdict`:
1475
+ // the two halves each report their own readability, which is what makes an
1476
+ // unread ledger distinguishable from one read and found empty — those
1477
+ // payloads were otherwise identical in every field (#231). Folding it into
1478
+ // the verdict instead would answer `unverified` for the run's FIRST check
1479
+ // on any fresh clone, where `.fleet/` does not exist until save() creates
1480
+ // it — see the comment on the repository probe above.
1481
+ console.log(JSON.stringify({ subject, found: false, match: null, near, nearTotal: rankedNear.length, ledger, tracker, verdict }));
1482
+ // Exit 3 — a new code — for "the ledger is clean but the tracker is not".
1483
+ // 1 would mean ALREADY FILED in this run, which a tracker hit does not
1484
+ // establish; 2 is taken by die(). Near-misses stay exit 0: they are a ranked
1485
+ // suggestion, not a finding of duplication. Exit 0 covers "clean",
1486
+ // "unverified" and "soft-hit" alike, which `verdict` names explicitly and the
1487
+ // exit code deliberately still does not: minting a code for unverified would
1488
+ // break `check "$s" && gh issue create` on every offline run (ruled against
1489
+ // in #152), and a soft hit is the same kind of answer — advisory rows, no
1490
+ // established duplicate — so it inherits that ruling rather than reopening
1491
+ // it. The exit code is a pure function of `verdict`; only `tracker-hit`
1492
+ // blocks, so a verdict added later leaves 3 alone unless it says so here.
1493
+ //
1494
+ // A hit set scoring 0.00 no longer forces 3 (#388). gh can match an issue
1495
+ // body the title-based score cannot see, which is why those rows are still
1496
+ // printed and still shipped in the payload — but the instruction the callers
1497
+ // carry makes exit 3 binding, and #388 measured what that costs: every
1498
+ // recorded case of a hard stop over rows this file rates zero was survived
1499
+ // only by a reader who overrode it and searched the tracker by hand, and
1500
+ // obeying it would have dropped a real deferral.
1501
+ //
1502
+ // exitCode, not exit(): this is the last statement of the branch, so
1503
+ // assigning and falling out reaches the same codes by the same path every
1504
+ // other subcommand now takes, and stops abandoning the payload at the pipe
1505
+ // buffer. `near` is sliced from `data.filed`, so this payload is
1506
+ // ledger-bounded and did reach the cut — measured, four filed rows of
1507
+ // ~230 KB against a four-word argv arrived cut at exit 0, the "clean, safe
1508
+ // to file" signal.
1509
+ process.exitCode = verdict === "tracker-hit" ? 3 : 0;
1510
+ }
1511
+
1512
+ // ── dispatch / settle (#1799) ────────────────────────────────────────────────
1513
+ //
1514
+ // Hoisted beside runCheck() for the same reason: each has several refusals
1515
+ // ahead of its one write, and the chain above stays the file's spine. Every
1516
+ // helper below is a function declaration, not a `const`, because the chain
1517
+ // calls into them before execution ever reaches this line.
1518
+
1519
+ // A row's key is its first word, `#<ticket>` — the same lookup `row` rewrites by.
1520
+ function rowKey(r) {
1521
+ return r.split(/\s/)[0];
1522
+ }
1523
+
1524
+ // A row's PR is its first `PR#<n>` mention: the `→ PR#346` arrow or the
1525
+ // implementer's settled `impl-324=PR#346` token, which name the same PR.
1526
+ // compute-board.mjs parseRow() reads the settled token (#1820), so the row a
1527
+ // PR-bound member lands on is the card the cockpit shows that PR on.
1528
+ function rowPr(r) {
1529
+ const m = /\bPR\s*#(\d+)\b/.exec(r);
1530
+ return m ? Number(m[1]) : null;
1531
+ }
1532
+
1533
+ // Whether a row carries the member's token — live only, settled only, or
1534
+ // either when `live` is not given.
1535
+ function carries(row, name, live) {
1536
+ return memberTokens(row).some((t) => t.name === name && (live === undefined || (t.outcome === null) === live));
1537
+ }
1538
+
1539
+ // The row a member's token belongs on: an implementer's is its ticket's row; a
1540
+ // PR-bound member's is the row whose PR is its PR, else one keyed by that PR's
1541
+ // own number (a PR this run's implementers did not open). -1 when there is
1542
+ // none yet. A merge bot works no ticket and never has one.
1543
+ function memberRowIndex(member) {
1544
+ if (member.bound === null) return -1;
1545
+ if (member.bound === "pr") {
1546
+ const i = data.rows.findIndex((r) => rowPr(r) === member.number);
1547
+ if (i !== -1) return i;
1548
+ }
1549
+ return data.rows.findIndex((r) => rowKey(r) === `#${member.number}`);
1550
+ }
1551
+
1552
+ function unknownMember(name) {
1553
+ return `unknown member '${name}' — expected impl-<N>, fix-pr-<M> or finisher-pr-<M> (a -b replacement suffix allowed), or merge-bot-<n>`;
1554
+ }
1555
+
1556
+ // `## Dispatched` gains an entry per dispatch and never loses or reorders one
1557
+ // (this file's header comment states the invariant `settle` and `nextMergeBot`
1558
+ // both rely on). The exact-name lookups in runDispatch() and runSettle() below
1559
+ // used to key off `parseToken(e)?.name`, which reads a token this grammar
1560
+ // cannot parse the same as "no match" — silently treating a corrupted entry as
1561
+ // an absent member and letting a dispatch or settle proceed as though nothing
1562
+ // were there (measured: a malformed row let a duplicate dispatch through).
1563
+ // Refuse loudly, naming the entry, before either lookup runs.
1564
+ function refuseMalformedDispatched() {
1565
+ const bad = data.dispatched.find((e) => parseToken(e) === null);
1566
+ if (bad !== undefined) {
1567
+ die(`## Dispatched has an entry '${bad}' this grammar cannot parse — fix the ledger by hand before dispatch or settle can trust it`);
1568
+ }
1569
+ }
1570
+
1571
+ function runDispatch() {
1572
+ const usage = "usage: ledger.mjs dispatch <ticket|pr> <member>, or dispatch merge-bot";
1573
+ if (rest.length === 0 || rest.length > 2) die(usage);
1574
+ const [key, name] = rest.length === 2 ? rest : [null, rest[0]];
1575
+ // The id-slot rule `row`/`filed`/`ruled` apply, on whichever slot leads.
1576
+ refuseStrayInId(key ?? name, key === null ? "a member name" : "a ticket or PR number");
1577
+ // Read ahead of every lookup below that trusts `## Dispatched` by name,
1578
+ // including `nextMergeBot()`'s own read of it.
1579
+ refuseMalformedDispatched();
1580
+
1581
+ // `merge-bot` bare is the merge-bot case of this command (spec § 4 item 2,
1582
+ // which § 6 folds `dispatched` into): the ledger names the bot, 1 + the
1583
+ // merge-bot entries already in `## Dispatched`, so the controller never
1584
+ // counts. An explicit `merge-bot-<n>` is accepted only when it is that one.
1585
+ const member = parseMember(name === "merge-bot" ? nextMergeBot(data.dispatched) : name);
1586
+ if (!member) die(unknownMember(name));
1587
+ if (member.bound === null) {
1588
+ if (key !== null) die(`merge bots work no ticket or PR — ${usage}`);
1589
+ const next = nextMergeBot(data.dispatched);
1590
+ if (member.name !== next) die(`${member.name} is not next — the next merge bot this run is ${next}; \`dispatch merge-bot\` names it`);
1591
+ } else if (key === null) {
1592
+ die(`${member.name} works a ticket or PR — ${usage}`);
1593
+ }
1594
+ const keyNum = key === null ? null : key.replace(/^#/, "");
1595
+ if (keyNum !== null && !isDigits(keyNum)) die(`'${key}' is not a ticket or PR number`);
1596
+
1597
+ // Draining stops supply and nothing else: fix-appliers, finishers and merge
1598
+ // bots keep going until the open PRs are merged (spec § 6 §5). Read from
1599
+ // the file, so a replacement controller that never saw the drain is held by
1600
+ // it all the same.
1601
+ if (member.family === "impl" && data.drain !== null) {
1602
+ die(`the run is draining (${data.drain}) — no implementer dispatch; drain stops supply`);
1603
+ }
1604
+
1605
+ // One token per member for the whole run. A settled token on a row counts
1606
+ // too — a `row`-written record the ledger never saw dispatched.
1607
+ const settledOnRow = data.rows.flatMap(memberTokens).find((t) => t.name === member.name && t.outcome !== null);
1608
+ const prior =
1609
+ data.dispatched.find((e) => parseToken(e).name === member.name) ??
1610
+ (settledOnRow && `${settledOnRow.name}=${settledOnRow.outcome}`);
1611
+ if (prior !== undefined) {
1612
+ die(`${member.name} was already dispatched this run (${prior}) — a replacement takes a name of its own (a -b, -c … suffix)`);
1613
+ }
1614
+
1615
+ // A replacement (`-b`, `-c` …) works the same ticket or PR as its
1616
+ // predecessor: two live tokens for one family+number would double-count
1617
+ // liveness ("live implementers = unsettled impl- tokens", spec § 6 §2).
1618
+ // Checked across both places a token can be live — `## Dispatched` and a
1619
+ // row `row` wrote directly — so the refusal holds regardless of which one
1620
+ // last wrote it.
1621
+ const liveSibling = [...data.dispatched.map(parseToken), ...data.rows.flatMap(memberTokens)]
1622
+ .find((t) => t.family === member.family && t.number === member.number && t.name !== member.name && t.outcome === null);
1623
+ if (liveSibling) {
1624
+ die(`${liveSibling.name} is still live — \`settle ${liveSibling.name} killed\` (or its real outcome) before dispatching ${member.name}`);
1625
+ }
1626
+
1627
+ let i = -1;
1628
+ if (member.bound === "ticket") {
1629
+ if (Number(keyNum) !== member.number) die(`${member.name} works ticket #${member.number}, not #${keyNum}`);
1630
+ i = memberRowIndex(member);
1631
+ } else if (member.bound === "pr") {
1632
+ if (Number(keyNum) === member.number) {
1633
+ i = memberRowIndex(member);
1634
+ } else {
1635
+ // `<ticket|pr>`: the ticket whose row carries this PR names it as well.
1636
+ i = data.rows.findIndex((r) => rowKey(r) === `#${Number(keyNum)}`);
1637
+ if (i === -1 || rowPr(data.rows[i]) !== member.number) {
1638
+ die(`${member.name} works PR #${member.number}, and row #${keyNum} carries no PR#${member.number}`);
1639
+ }
1640
+ }
1641
+ }
1642
+
1643
+ let line = null;
1644
+ const created = member.bound !== null && i === -1;
1645
+ if (created) {
1646
+ line = `#${member.number} ${member.name}`;
1647
+ data.rows.push(line);
1648
+ } else if (i !== -1) {
1649
+ // A row `row` already wrote the live token into (SKILL.md's phase 2
1650
+ // does) keeps it as it is rather than gaining a second copy.
1651
+ const row = data.rows[i];
1652
+ line = carries(row, member.name, true) ? row : `${row} · ${member.name}`;
1653
+ data.rows[i] = line;
1654
+ }
1655
+ data.dispatched.push(member.name);
1656
+ save(data);
1657
+ console.error(` dispatched ${member.name}`);
1658
+ console.log(JSON.stringify({
1659
+ member: member.name, ticket: line === null ? null : rowKey(line), line, created, total: data.dispatched.length,
1660
+ }));
1661
+ }
1662
+
1663
+ function runSettle() {
1664
+ const usage = "usage: ledger.mjs settle <member> <outcome>";
1665
+ // `settle impl-412 PR#420`, or the one token it writes — `settle
1666
+ // impl-412=PR#420` — which is how the spec's record-before-tick table
1667
+ // spells every settlement.
1668
+ if (!(rest.length === 2 || (rest.length === 1 && rest[0].includes("=")))) die(usage);
1669
+ refuseStrayInId(rest[0], "a member name");
1670
+ const parsed = parseToken(rest.length === 2 ? `${rest[0]}=${rest[1]}` : rest[0]);
1671
+ if (!parsed) die(unknownMember(rest[0].split("=")[0]));
1672
+ if (parsed.error) die(`${parsed.name}: ${parsed.error}`);
1673
+ const { name, outcome } = parsed;
1674
+ const token = `${name}=${outcome}`;
1675
+ // Same guard as runDispatch(): a `## Dispatched` entry this grammar cannot
1676
+ // parse must refuse the lookup below, not read as "not this member" and
1677
+ // let settle proceed against a corrupted section.
1678
+ refuseMalformedDispatched();
1679
+
1680
+ const di = data.dispatched.findIndex((e) => parseToken(e).name === name);
1681
+ const entry = di === -1 ? null : parseToken(data.dispatched[di]);
1682
+ const settled = [entry, ...data.rows.flatMap(memberTokens).filter((t) => t.name === name)]
1683
+ .filter((t) => t !== null && t.outcome !== null);
1684
+ const other = settled.find((t) => t.outcome !== outcome);
1685
+ if (other) die(`${name} is already settled as ${other.outcome} — a settled member stays settled; a replacement takes a name of its own`);
1686
+
1687
+ const liveRows = data.rows.flatMap((r, i) => (carries(r, name, true) ? [i] : []));
1688
+ const liveEntry = entry !== null && entry.outcome === null;
1689
+ const payload = (i, changed) => ({
1690
+ member: name, outcome, ticket: i === -1 ? null : rowKey(data.rows[i]), line: i === -1 ? null : data.rows[i], changed,
1691
+ });
1692
+ if (!liveEntry && liveRows.length === 0) {
1693
+ if (settled.length === 0) die(`no live ${name} in the ledger — \`dispatch\` it first`);
1694
+ // The same outcome again: already on record, so nothing is written.
1695
+ console.log(JSON.stringify(payload(data.rows.findIndex((r) => carries(r, name)), false)));
1696
+ return;
1697
+ }
1698
+
1699
+ // #1876: capture whether the row this settle is about to write to already
1700
+ // named a PR, before the rewrite below touches it. The fold further down
1701
+ // must refuse to run once a row already has PR-specific content on it —
1702
+ // see the fold's own comment for why.
1703
+ const targetBefore = liveRows[0] ?? memberRowIndex(parsed);
1704
+ const priorPr = targetBefore === -1 ? null : rowPr(data.rows[targetBefore]);
1705
+ // A live token `row` wrote is settled like one `dispatch` wrote; `##
1706
+ // Dispatched` only records what `dispatch` did.
1707
+ if (liveEntry) data.dispatched[di] = token;
1708
+ for (const i of liveRows) data.rows[i] = data.rows[i].split(/(\s+)/).map((w) => (w === name ? token : w)).join("");
1709
+ let i = liveRows[0] ?? -1;
1710
+ if (i === -1) {
1711
+ // Dispatched, but a later whole-line `row` rewrote the row without its
1712
+ // token: put the settled one back, so the row a human reads agrees with
1713
+ // `## Dispatched`.
1714
+ i = memberRowIndex(parsed);
1715
+ if (i !== -1 && !carries(data.rows[i], name)) data.rows[i] = `${data.rows[i]} · ${token}`;
1716
+ }
1717
+ // #1876: the tick owes an open PR a review while its implementer is still
1718
+ // live, so a PR-bound member can be dispatched before this settle names the
1719
+ // PR here — and memberRowIndex() then finds no row naming it, so
1720
+ // runDispatch() keys a row of its own to the PR. Once this row names the PR
1721
+ // too, two rows would: the cockpit draws two cards and the tick's
1722
+ // first-row-wins `byPr` reads one. Fold that row's tokens onto this one, in
1723
+ // order, so later PR-bound writes find the one row through rowPr(). Only
1724
+ // an implementer settles to `PR#M` (ledger-grammar.mjs), and only when the
1725
+ // settling row named NO PR before this write: `rowPr()` and the tick's
1726
+ // `PR_MENTION` both read the FIRST `PR#` mention on a row, so a row that
1727
+ // already named one — this PR via a hand-written `→ PR#M` arrow, or a
1728
+ // different PR from an earlier attempt — would let the fold misattribute
1729
+ // its content to the wrong PR, or bury the row's own fresher
1730
+ // `review=`/`reviewed=` state under the folded row's older one (the tick
1731
+ // reads only the LAST). The candidate row must itself carry a live or
1732
+ // settled PR-bound token for this exact PR — never an unrelated row that
1733
+ // merely shares the key (an Exclusion row, say, on a mistyped PR number) —
1734
+ // unless the row holds nothing past its key at all, in which case there is
1735
+ // nothing it could be but an empty fallback and nothing to lose by
1736
+ // folding it. Never one an implementer already claims as its own.
1737
+ const prNum = outcome.startsWith("PR#") ? Number(outcome.slice("PR#".length)) : null;
1738
+ const j = prNum === null || i === -1 || priorPr !== null ? -1
1739
+ : data.rows.findIndex((r) => {
1740
+ if (rowKey(r) !== `#${prNum}` || memberTokens(r).some((t) => t.family === "impl")) return false;
1741
+ const tail = r.slice(`#${prNum}`.length).trim();
1742
+ return tail === "" || memberTokens(r).some((t) => t.bound === "pr" && t.number === prNum);
1743
+ });
1744
+ if (j !== -1) {
1745
+ const tail = data.rows[j].slice(`#${prNum}`.length).trim();
1746
+ if (tail !== "") data.rows[i] = `${data.rows[i]} · ${tail}`;
1747
+ data.rows.splice(j, 1);
1748
+ if (j < i) i -= 1;
1749
+ }
1750
+ save(data);
1751
+ console.error(` settled ${token}`);
1752
+ console.log(JSON.stringify(payload(i, true)));
1753
+ }