@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,3086 @@
1
+ // Smoke test for the HTTP layer, plus the transcript-reading layer underneath
2
+ // the spend panel — no gh, no build loop. Boots the static server against a temp
3
+ // dir and asserts it serves board.json and the page.
4
+ import { test } from "node:test";
5
+ import assert from "node:assert/strict";
6
+ import { mkdtempSync, mkdirSync, writeFileSync, utimesSync, statSync, chmodSync, rmSync, readFileSync, existsSync, symlinkSync, realpathSync } from "node:fs";
7
+ import { tmpdir } from "node:os";
8
+ import { dirname, join } from "node:path";
9
+ import { spawnSync, spawn } from "node:child_process";
10
+ import { createServer } from "node:net";
11
+ import { fileURLToPath } from "node:url";
12
+ import { createBoardServer, mapCi, encodeProjectDir, findSubagentsDir, spendDirPin, gatherSpend, faultText, resolveCockpitInstance, cockpitPorts, probeCockpitWorkspace } from "./board.mjs";
13
+ import { readOmpMember } from "./member-record.mjs";
14
+ import { stripComments } from "./strip-comments.mjs";
15
+ import { gitEnv } from "./git-env.mjs";
16
+
17
+ const SCRIPT = fileURLToPath(new URL("./board.mjs", import.meta.url));
18
+
19
+ // mapCi regression gate — pins the ci-state verdict mapping, incl. the two paths
20
+ // an "empty repo" live test cannot reach: a completed not-green run → red, and a
21
+ // no-run-yet / still-running state → unknown (never a false red).
22
+ test("mapCi: completed green → green", () => {
23
+ assert.equal(mapCi(JSON.stringify({ status: "completed", verdict: "green" })), "green");
24
+ });
25
+ test("mapCi: completed not-green → red", () => {
26
+ assert.equal(mapCi(JSON.stringify({ status: "completed", verdict: "not-green" })), "red");
27
+ });
28
+ test("mapCi: still-running → unknown (never a false red)", () => {
29
+ assert.equal(mapCi(JSON.stringify({ status: "in_progress", verdict: "not-green" })), "unknown");
30
+ });
31
+ test("mapCi: no run yet (status null) → unknown, not red", () => {
32
+ assert.equal(mapCi(JSON.stringify({ status: null, verdict: "not-green" })), "unknown");
33
+ });
34
+ // ci-state.mjs (#111) added verdict: "no-ci" for a repo with no workflow
35
+ // configured. mapCi has no branch for that string, so what protects the board
36
+ // is the trailing `return "unknown"` — and only a payload that gets PAST the
37
+ // status gate can reach it. A real no-ci payload carries status null, which the
38
+ // gate swallows before it; written that way this test took the same
39
+ // branch as its sibling above and stayed green while `verdict === "no-ci"` was
40
+ // mutated to return "green". `status: "completed"` is the whole pin: it is the
41
+ // shape that reaches the last line, so a silent no-ci→green mapping fails here
42
+ // and nowhere else.
43
+ test("mapCi: no-ci verdict past the status gate → unknown, not silently mapped", () => {
44
+ assert.equal(mapCi(JSON.stringify({ status: "completed", verdict: "no-ci" })), "unknown");
45
+ });
46
+ // A non-empty payload that will not parse is a THIRD state, and the return
47
+ // value cannot carry it: "unknown" is pinned above and stays pinned — a false
48
+ // red is worse than no verdict — so the distinction leaves through stderr or
49
+ // not at all. Before #1593 runCiState()'s EXIT-0 arm handed a payload like
50
+ // this straight through untested, so a write cut mid-JSON on a green verdict
51
+ // reached mapCi looking exactly like a PR whose first run has not started,
52
+ // and that PR's red-ci flag — the top of the attention strip — stayed down
53
+ // with nothing said. #1593 closed that arm the same way #875 closed the
54
+ // non-zero one: an unparseable exit-0 payload is now a failed read, refused
55
+ // by runCiState() itself and never handed to mapCi at all. This test still
56
+ // earns its line because mapCi() is exported and total over any string a
57
+ // caller hands it, not just this file's own runCiState()/gather() wiring —
58
+ // see the direct-call comment below the gatherCi() driver.
59
+ test("mapCi: an unparseable payload → unknown, and says so on stderr, naming the PR", () => {
60
+ let v;
61
+ const errs = withStderr(() => { v = mapCi("not json", 6051); });
62
+ assert.equal(v, "unknown");
63
+ assert.equal(errs.length, 1, "expected one stderr line, got " + JSON.stringify(errs));
64
+ assert.match(errs[0], /6051/, "the line has to name the PR whose flag is suppressed");
65
+ });
66
+
67
+ // An ABSENT payload is not a garbage one, and the difference is why the warn
68
+ // sits after this guard rather than before it: every path that reaches mapCi
69
+ // with null went through runCiState()'s own stderr line first, so warning here
70
+ // would report the same failed read twice.
71
+ test("mapCi: an absent payload (null) → unknown, silently — runCiState already reported it", () => {
72
+ let v;
73
+ const errs = withStderr(() => { v = mapCi(null, 6052); });
74
+ assert.equal(v, "unknown");
75
+ assert.deepEqual(errs, []);
76
+ });
77
+
78
+ // The other half of that split, and the whole reason the guard above tests
79
+ // null rather than falsiness. An EMPTY payload used to be a failed read that
80
+ // nobody reported: before #1593, runCiState() returned stdout unconditionally
81
+ // at exit 0, emptiness untested, so a lost stdout write on a green verdict
82
+ // came back as "" and reached here having said nothing. A `!ciJson` guard
83
+ // cannot tell that from the null above and answers "unknown" in silence — the
84
+ // same disappearance #605 exists to end, one arm over from the arm it fixed.
85
+ // #1593 closed that path too: runCiState()'s exit-0 guard now parse-checks
86
+ // `out` before emptiness even gets here (JSON.parse("") throws), refuses it
87
+ // as a failed read, and says so on stderr with its own wording ("never
88
+ // answered" — see the gather()-level test for that below), so this exact
89
+ // disappearance can no longer happen through the real call site. This test
90
+ // pins mapCi()'s own contract for that input regardless — a `!ciJson` guard
91
+ // swallowing "" as though it had been reported would still be wrong for any
92
+ // OTHER caller of an exported function — and is the only thing separating the
93
+ // two guards below: the pair above and below it both pass under either guard.
94
+ test("mapCi: an empty payload → unknown, and says so — a lost write is not an absent one", () => {
95
+ let v;
96
+ const errs = withStderr(() => { v = mapCi("", 6056); });
97
+ assert.equal(v, "unknown");
98
+ assert.equal(errs.length, 1, "expected one stderr line, got " + JSON.stringify(errs));
99
+ assert.match(errs[0], /6056/, "the line has to name the PR whose flag is suppressed");
100
+ });
101
+
102
+ // The false-positive half, and the reason it is a test rather than an argument.
103
+ // "no run yet", "still running" and "no-ci" are the states this mapping is
104
+ // DESIGNED to answer unknown for — they are readings, not read failures. A warn
105
+ // that cannot tell them from a garbage payload prints a line for every PR
106
+ // awaiting its first run, on every ~15s tick, and the useful line drowns in it.
107
+ test("mapCi: a legitimately unknown state — status null, in_progress, no-ci — stays silent", () => {
108
+ const errs = withStderr(() => {
109
+ mapCi(JSON.stringify({ status: null, verdict: "not-green" }), 6053);
110
+ mapCi(JSON.stringify({ status: "in_progress", verdict: "not-green" }), 6053);
111
+ mapCi(JSON.stringify({ status: "completed", verdict: "no-ci" }), 6053);
112
+ });
113
+ assert.deepEqual(errs, []);
114
+ });
115
+
116
+ // #1170: JSON.parse("null") succeeds and yields d === null, and null alone
117
+ // among parsed payloads has no properties to read — every other one boxes and
118
+ // reads its status as undefined — so the status gate threw a TypeError back
119
+ // out of mapCi. mapCi runs inside gather()'s per-PR loop, so a bare "null" for
120
+ // one PR would take out that tick's whole board.json rewrite: under `serve`
121
+ // the throw is uncaught until the whole-tick catch, which logs and leaves the
122
+ // previous board.json standing, while the one-shot build path exits through
123
+ // main().catch and dies loudly. Written as a conditional because this repo's
124
+ // ci-state.mjs puts nothing on stdout but JSON.stringify of an object literal,
125
+ // so it cannot emit a bare "null" — the guard is defence in depth against a
126
+ // producer that can. Silence is the pin the comment claims and the assertion
127
+ // nobody wrote: every parseable payload with no status to read answers without
128
+ // a line, and the guard has to join that class rather than start warning.
129
+ test("mapCi: a JSON payload that parses to null → unknown, not a thrown TypeError", () => {
130
+ let v;
131
+ const errs = withStderr(() => { v = mapCi("null", 1170); });
132
+ assert.equal(v, "unknown");
133
+ assert.deepEqual(errs, [], "silent, like every other payload with no status to read");
134
+ });
135
+ // The other half: a payload that already answered "unknown" still does, so the
136
+ // guard narrowed nothing. It does not discriminate an over-guard — one
137
+ // rejecting every non-plain-object answers exactly as this guard does for every
138
+ // JSON value, since reaching a verdict at all takes a plain object such a guard
139
+ // passes through, so no fixture separates the two.
140
+ test("mapCi: parsed payloads with no status still classify unknown, not thrown", () => {
141
+ let v, w;
142
+ const errs = withStderr(() => { v = mapCi("true", 1170); w = mapCi("[]", 1170); });
143
+ assert.equal(v, "unknown");
144
+ assert.equal(w, "unknown");
145
+ assert.deepEqual(errs, [], "silent, like every other payload with no status to read");
146
+ });
147
+
148
+ // `serve` rebuilds every ~15s and calls mapCi once per PR per tick, so a broken
149
+ // payload is broken on every tick and the gate is the whole difference between
150
+ // one line and a flood. Keyed per PR rather than globally, because a global
151
+ // gate would let the first broken PR mask every later one for the rest of the
152
+ // run — silence that looks identical to the bug being fixed here.
153
+ test("an unparseable payload warns ONCE per PR across ticks, and a second PR is not masked", () => {
154
+ assert.equal(withStderr(() => mapCi("not json", 6054)).length, 1, "tick 1 reports");
155
+ assert.deepEqual(withStderr(() => mapCi("not json", 6054)), [], "tick 2 stays quiet");
156
+ assert.equal(withStderr(() => mapCi("{ trunc", 6055)).length, 1, "another PR still gets its line");
157
+ });
158
+
159
+ // #262 put a payload on stdout at exit 2 for a quota refusal, and runCiState()
160
+ // was reading "stdout is non-empty" as "a verdict was read". mapCi alone cannot
161
+ // see that: it is handed a string and never learns which exit code produced it,
162
+ // so every pin above stayed green while a rate-limited outage overwrote a PR's
163
+ // last-known-good CI with "unknown" — the carry-forward gather() documents as
164
+ // "On failure, carry the previous board's value for that PR". The seam is
165
+ // gather(), so the gate has to sit there.
166
+ //
167
+ // scriptDir is injected, so both arms drive the REAL runCiState()/gather()
168
+ // against a ci-state whose exit code and stdout are exactly what the arm needs;
169
+ // the stub `gh` only has to feed the PR loop, since every other gh read in
170
+ // gather() degrades through tryRun(). Out of process, because gather() reads
171
+ // process.argv and would otherwise read the test runner's.
172
+ //
173
+ // `prs` and `ticks` default to the single PR and the single gather() every arm
174
+ // below needs; the warn-once row is the one that raises them, because a gate
175
+ // that spends one line per process and one that spends one per tick are
176
+ // indistinguishable inside a single-tick, single-PR run.
177
+ function gatherCi({ ciStateBody, prevCi, prs = [42], ticks = 1 }) {
178
+ const cwd = mkdtempSync(join(tmpdir(), "board-gather-"));
179
+ const bin = mkdtempSync(join(tmpdir(), "board-gather-bin-"));
180
+ const scriptDir = mkdtempSync(join(tmpdir(), "board-gather-scripts-"));
181
+ writeFileSync(join(scriptDir, "ci-state.mjs"), ciStateBody);
182
+ const rows = JSON.stringify(prs.map((n) => ({ number: n, state: "OPEN", labels: [], title: "t" })));
183
+ writeFileSync(join(bin, "gh"),
184
+ `#!/bin/sh\ncase "$1 $2" in\n"pr list") echo '${rows}' ;;\n*) exit 1 ;;\nesac\n`);
185
+ chmodSync(join(bin, "gh"), 0o755);
186
+ writeFileSync(join(cwd, "prev.json"), JSON.stringify({ tickets: prs.map((n) => ({ pr: n, ci: prevCi })) }));
187
+ // serve()'s shape, not a loop for its own sake: one process, gather() called
188
+ // again per tick, which is the only place a warn-once gate is observable.
189
+ const driver = `const { gather } = await import(${JSON.stringify(SCRIPT)});
190
+ let r;
191
+ for (let i = 0; i < ${ticks}; i++) r = await gather({ ledgerFile: ${JSON.stringify(join(cwd, "nope.md"))},
192
+ prevFile: ${JSON.stringify(join(cwd, "prev.json"))},
193
+ scriptDir: ${JSON.stringify(scriptDir)}, interval: 15 });
194
+ console.log(JSON.stringify(r.ci));`;
195
+ const r = spawnSync(process.execPath, ["--input-type=module", "-e", driver], {
196
+ cwd, encoding: "utf8", env: { ...process.env, PATH: `${bin}:${process.env.PATH}` },
197
+ });
198
+ assert.equal(r.status, 0, r.stdout + r.stderr);
199
+ // stderr comes back too: gather() reports through it. mapCi's own
200
+ // PR-in-the-warn-text wiring is no longer observable from here, though:
201
+ // since #1593 runCiState() only ever hands mapCi an already-parseable
202
+ // payload, so mapCi's JSON.parse catch — the only code that reads its `pr`
203
+ // argument — can never fire through this call site. That argument's
204
+ // presence at the real call site is pinned as source text instead (see the
205
+ // #605 test below); what IS observable here is runCiState()'s own two
206
+ // salvage arms, each carrying the PR and exit disposition in its own
207
+ // stderr line.
208
+ const ci = JSON.parse(r.stdout.trim().split("\n").pop());
209
+ return { ci: ci[42], ciAll: ci, stderr: r.stderr };
210
+ }
211
+
212
+ // The regression itself. This payload is what ci-state.mjs emits on a quota
213
+ // refusal: it carries no `status`, so if it ever reaches mapCi the answer is
214
+ // "unknown" and the previous red is gone.
215
+ const RATE_LIMITED_EXIT_2 = `import { writeSync } from "node:fs";
216
+ writeSync(1, JSON.stringify({ pr: 42, verdict: "rate-limited", reasons: ["quota"] }) + "\\n");
217
+ process.exit(2);`;
218
+
219
+ test("gather: a rate-limited ci-state — exit 2 WITH a payload — carries the previous board's CI value", () => {
220
+ assert.equal(gatherCi({ ciStateBody: RATE_LIMITED_EXIT_2, prevCi: "red" }).ci, "red");
221
+ });
222
+
223
+ // The other direction, and the reason this pair is not one test: a runCiState()
224
+ // that returned null for every non-zero exit would satisfy the arm above and
225
+ // make the board blind to red CI, which is the failure the carry-forward exists
226
+ // to prevent. Exit 1 is a real verdict and must still beat the previous value —
227
+ // prev is "green" here precisely so a passing "red" can only have come from
228
+ // mapCi reading this payload, never from the carry-forward.
229
+ const NOT_GREEN_EXIT_1 = `import { writeSync } from "node:fs";
230
+ writeSync(1, JSON.stringify({ pr: 42, status: "completed", verdict: "not-green", reasons: ["x"] }) + "\\n");
231
+ process.exit(1);`;
232
+
233
+ test("gather: exit 1 is a verdict, not a failed read — it still overrides the previous value", () => {
234
+ assert.equal(gatherCi({ ciStateBody: NOT_GREEN_EXIT_1, prevCi: "green" }).ci, "red");
235
+ });
236
+
237
+ // ── the salvage arm: an exit code alone never made a payload a verdict ───────
238
+ //
239
+ // #875. The gate reads the exit code because #262 retired "stdout is non-empty"
240
+ // as the proxy for "the child answered". The exit code is the other half of
241
+ // that same proxy: it says the child reached its own exit path, not that its
242
+ // payload arrived whole. Measured against stubs shaped like ci-state.mjs,
243
+ // `e.status !== 2 && out.trim()` accepted all four rows that reach it —
244
+ // not-green and no-ci, the real exit-1 verdicts, alongside the exit-1 write cut
245
+ // mid-JSON and the signal kill mid-payload — while parsing the salvaged bytes
246
+ // separates them exactly, which is why the parse is the discriminator. The
247
+ // exit-0 row is not a fifth here: this gate lives in runCiState()'s catch
248
+ // block, and a child that exits 0 never throws into it. Since #1593 exit 0
249
+ // gets the mirroring check on runCiState()'s success path instead (see the
250
+ // UNPARSEABLE_EXIT_0 test below) — a second gate, not this one widened.
251
+ //
252
+ // The accept side first, and the reason the discriminator is a PARSE rather
253
+ // than the exit status. no-ci is a REAL verdict that shares exit 1 — ci-state
254
+ // only moves it to exit 0 under --declare-no-ci, which this call never passes —
255
+ // and its `status` is null. So the other candidate remedy, "treat an abnormal
256
+ // status the way exit 2 is treated", is not merely insufficient (the cut-off
257
+ // row below exits 1 with no signal at all); tightened far enough to catch that
258
+ // row it starts refusing THIS one, resurrecting a red for a PR that has no run
259
+ // behind it any more. prev is "red" precisely so only a refusal could produce
260
+ // it: the answer this tick owns is its own "unknown".
261
+ const NO_CI_EXIT_1 = `import { writeSync } from "node:fs";
262
+ writeSync(1, JSON.stringify({ pr: 42, status: null, verdict: "no-ci", reasons: ["no workflows configured"] }) + "\\n");
263
+ process.exit(1);`;
264
+
265
+ test("gather: a complete no-ci verdict at exit 1 is an answer, not a failed read — it is not carried forward (#875)", () => {
266
+ assert.equal(gatherCi({ ciStateBody: NO_CI_EXIT_1, prevCi: "red" }).ci, "unknown");
267
+ });
268
+
269
+ // The refuse side. One write, cut mid-JSON, under two dispositions: the bytes
270
+ // are held apart from the exit code deliberately, because the bytes are all
271
+ // these two rows share and the disposition is the whole difference between them
272
+ // — exit 1 is the salvage arm #875 narrowed; exit 0 (further down) got the
273
+ // same narrowing from #1593, closing the arm #875 had deliberately left alone.
274
+ const TRUNCATED_WRITE = `import { writeSync } from "node:fs";
275
+ writeSync(1, "warning: gh took the slow path\\n{\\"pr\\": 42, \\"status\\": \\"comp");`;
276
+ const UNPARSEABLE_EXIT_1 = `${TRUNCATED_WRITE}
277
+ process.exit(1);`;
278
+
279
+ // prev="red" is the assertion: the payload is unusable, so this tick has no
280
+ // reading of its own and #262's carry-forward is the entire point. Returning
281
+ // the bytes anyway spends a PR's last-known red on an "unknown" nobody
282
+ // measured — the regression the exit-code gate was added to prevent, arriving
283
+ // through the gate itself. The stderr line has to name the PR and say the
284
+ // payload was refused: "ci-state failed" alone cannot be told apart from the
285
+ // read never having happened, and an operator looking at a carried-forward
286
+ // value needs to know a payload arrived and was thrown away.
287
+ test("gather: a payload cut mid-JSON at exit 1 is not a verdict — the previous CI value stands (#875)", () => {
288
+ const r = gatherCi({ ciStateBody: UNPARSEABLE_EXIT_1, prevCi: "red" });
289
+ assert.equal(r.ci, "red");
290
+ assert.match(r.stderr, /--pr 42/);
291
+ assert.match(r.stderr, /parse/);
292
+ });
293
+
294
+ // The signal half of the same class, and its own row because `status` is null
295
+ // here rather than a number: the diagnostic has to say the child was KILLED,
296
+ // since "exit null" is not a thing an operator can act on, and a fix that
297
+ // keyed only on nonzero exit codes would let this row through on a falsy
298
+ // status. SIGKILL rather than SIGTERM so the stub cannot handle it and exit
299
+ // cleanly instead.
300
+ const KILLED_MID_PAYLOAD = `import { writeSync } from "node:fs";
301
+ writeSync(1, '{"pr": 42, "status": "comp');
302
+ process.kill(process.pid, "SIGKILL");`;
303
+
304
+ test("gather: a signal-killed ci-state that wrote half a payload carries the previous value forward (#875)", () => {
305
+ const r = gatherCi({ ciStateBody: KILLED_MID_PAYLOAD, prevCi: "red" });
306
+ assert.equal(r.ci, "red");
307
+ assert.match(r.stderr, /SIGKILL/);
308
+ });
309
+
310
+ // The cost of the refusal line, which the single-tick rows above cannot see.
311
+ // serve() re-gathers on a timer in ONE process, and a truncation has a cause
312
+ // that outlives the tick that hit it, so an ungated line is spent again on
313
+ // every tick for as long as the cause lasts — the flood mapCi's `ci-parse` pin
314
+ // near the top of this file exists to prevent, arriving through the arm #875
315
+ // added. Two PRs because the gate's key is the other half of it: keyed on its
316
+ // channel alone, the first refused payload would silence every later PR's line
317
+ // for the rest of the run, which is the silence the sibling gate was written
318
+ // against. Both PRs still carry their previous value forward — the gate is
319
+ // about what is SAID, never about what is read.
320
+ test("gather: a refused salvage payload warns ONCE per PR across ticks, and a second PR is not masked", () => {
321
+ const r = gatherCi({ ciStateBody: UNPARSEABLE_EXIT_1, prevCi: "red", prs: [42, 43], ticks: 3 });
322
+ assert.deepEqual(r.ciAll, { 42: "red", 43: "red" });
323
+ const refusals = r.stderr.split("\n").filter((l) => /will not parse/.test(l));
324
+ assert.equal(refusals.length, 2, `expected one line per PR, got ${JSON.stringify(refusals)}`);
325
+ assert.ok(refusals.some((l) => /--pr 42/.test(l)), r.stderr);
326
+ assert.ok(refusals.some((l) => /--pr 43/.test(l)), r.stderr);
327
+ });
328
+
329
+ // #1593. Before this fix, exit 0 was the one arm #875 had deliberately left
330
+ // alone: runCiState() returned stdout unconditionally on a successful exit —
331
+ // emptiness untested, parseability untested — so this same truncated write,
332
+ // delivered at exit 0 instead of exit 1, was the one unparseable payload that
333
+ // still reached mapCi, which mapped it to "unknown" and discarded the PR's
334
+ // last-known CI value — the #262 regression the salvage gate exists to
335
+ // prevent, surviving on the one arm #875 left alone. This used to be #605's
336
+ // wiring pin too (the only vehicle that reached mapCi's PR-keyed warn through
337
+ // gather() rather than a direct unit call) — that vehicle is gone now that
338
+ // runCiState() salvages both arms: mapCi is never called at all on this path
339
+ // any more, so the assertion below pins the carry-forward outcome #1593 fixes,
340
+ // not the #605 wiring. The #605 pin itself is restored separately, as a
341
+ // source-text assertion (see the test after this one) — the only way left to
342
+ // catch the PR argument being dropped from a call that can no longer be
343
+ // driven to observably differ by argument alone.
344
+ const UNPARSEABLE_EXIT_0 = `${TRUNCATED_WRITE}
345
+ process.exit(0);`;
346
+
347
+ test("gather: a payload cut mid-JSON at exit 0 is not a verdict either — the previous CI value stands (#1593)", () => {
348
+ const r = gatherCi({ ciStateBody: UNPARSEABLE_EXIT_0, prevCi: "red" });
349
+ assert.equal(r.ci, "red");
350
+ assert.match(r.stderr, /--pr 42/);
351
+ assert.match(r.stderr, /exit 0/);
352
+ assert.match(r.stderr, /parse/);
353
+ });
354
+
355
+ // #1593, empty half: an empty payload at exit 0 is not a corrupted one — the
356
+ // child never answered at all — and "left a payload that will not parse" is
357
+ // the wrong diagnosis for it, the same distinction the empty/status-2 branch
358
+ // draws for a non-zero exit (see runCiState()). Measured before this fix: an
359
+ // empty `out` at exit 0 fell into the same JSON.parse catch as truncated
360
+ // bytes and got the same "left a payload that will not parse" wording, even
361
+ // though nothing arrived to leave.
362
+ const EMPTY_EXIT_0 = `process.exit(0);`;
363
+ test("gather: an empty payload at exit 0 says the child never answered, not that it left unparseable bytes", () => {
364
+ const r = gatherCi({ ciStateBody: EMPTY_EXIT_0, prevCi: "red" });
365
+ assert.equal(r.ci, "red");
366
+ assert.match(r.stderr, /--pr 42/);
367
+ assert.match(r.stderr, /exit 0/);
368
+ assert.match(r.stderr, /never answered/);
369
+ assert.doesNotMatch(r.stderr, /will not parse/);
370
+ });
371
+
372
+ // #605, restored: runCiState() now guarantees mapCi only ever receives an
373
+ // already-parseable payload from this call site (#1593 closed the exit-0 gap
374
+ // #875 had left mapCi's own parse-catch to cover), so mapCi's JSON.parse catch
375
+ // — the only code that reads its `pr` argument — can never fire through
376
+ // gather(), and no assertion on gather()'s board output can any longer tell
377
+ // `mapCi(out, p.number)` apart from `mapCi(out)`. A source-text pin is the
378
+ // only remaining way to catch that argument being dropped by accident.
379
+ test("gather: the real call site still hands mapCi the PR number, not just the payload (#605)", () => {
380
+ const src = readFileSync(SCRIPT, "utf8");
381
+ assert.match(src, /\bmapCi\(out, p\.number\)/);
382
+ });
383
+
384
+ // The channel-collision regression: runCiState()'s two salvage arms — the
385
+ // catch block's non-zero-exit gate and #1593's exit-0 gate — used to share the
386
+ // SAME warnOnce channel ("ci-salvage"), keyed only on the PR. That let a PR
387
+ // that hit one arm on an early tick silence a later, structurally different
388
+ // failure on the OTHER arm for the rest of the run: no stderr line, no other
389
+ // signal. Driven here with a stateful stub that answers exit-1-truncated on
390
+ // its first invocation and exit-0-truncated on its second, for the SAME PR —
391
+ // both warnings must print.
392
+ test("gather: a PR that hits the exit-1 salvage then the exit-0 guard gets BOTH warnings, not just the first", () => {
393
+ const markerDir = mkdtempSync(join(tmpdir(), "board-dualarm-"));
394
+ const marker = join(markerDir, "tick");
395
+ const DUAL_ARM = `import { writeSync, existsSync, writeFileSync } from "node:fs";
396
+ const marker = ${JSON.stringify(marker)};
397
+ const first = !existsSync(marker);
398
+ if (first) writeFileSync(marker, "1");
399
+ writeSync(1, "warning: gh took the slow path\\n{\\"pr\\": 42, \\"status\\": \\"comp");
400
+ process.exit(first ? 1 : 0);`;
401
+ const r = gatherCi({ ciStateBody: DUAL_ARM, prevCi: "red", ticks: 2 });
402
+ assert.equal(r.ci, "red", "both arms are refusals; the carry-forward value must survive both ticks");
403
+ assert.match(r.stderr, /\(exit 1\) left a payload that will not parse/, "tick 1's salvage warning must print");
404
+ assert.match(r.stderr, /\(exit 0\) left a payload that will not parse/,
405
+ "tick 2's exit-0 warning must print too, not be swallowed by a shared channel");
406
+ });
407
+
408
+ // #786: `gh issue list`/`gh pr list` rows had no per-row shape guard. A row
409
+ // missing `number` is the real "reaches the page as literal `undefined`" case
410
+ // — compute-board.mjs joins rows to the ledger BY number, so a numberless row
411
+ // collided with every other one on the shared `undefined` key. A row missing
412
+ // `title` was never that: compute-board.mjs's titleFor() already falls
413
+ // through a falsy PR title to the real issue title, and an issue row with no
414
+ // title already fell through to the `#<number>` placeholder — both worked
415
+ // before this fix. `labels`, unguarded either way, was the real regression:
416
+ // a non-array or null-containing `labels` array crashes gather() outright,
417
+ // worse than any `undefined` on the page.
418
+ //
419
+ // Stubs both `gh` reads directly rather than reusing gatherCi's fixed PR row,
420
+ // and stubs ci-state.mjs to answer "unknown" unconditionally — the PR loop
421
+ // only needs to complete without throwing, its verdict is not what these
422
+ // tests pin. Out of process for the same reason as gatherCi: gather() reads
423
+ // process.argv and would otherwise read the test runner's.
424
+ function gatherRows({ issuesJson, prsJson }) {
425
+ const cwd = mkdtempSync(join(tmpdir(), "board-gather-rows-"));
426
+ const bin = mkdtempSync(join(tmpdir(), "board-gather-rows-bin-"));
427
+ const scriptDir = mkdtempSync(join(tmpdir(), "board-gather-rows-scripts-"));
428
+ writeFileSync(join(scriptDir, "ci-state.mjs"), "process.stdout.write('{}');\n");
429
+ writeFileSync(join(bin, "gh"),
430
+ `#!/bin/sh\ncase "$1 $2" in\n"issue list") echo '${issuesJson}' ;;\n"pr list") echo '${prsJson}' ;;\n*) exit 1 ;;\nesac\n`);
431
+ chmodSync(join(bin, "gh"), 0o755);
432
+ const driver = `const { gather } = await import(${JSON.stringify(SCRIPT)});
433
+ const r = await gather({ ledgerFile: ${JSON.stringify(join(cwd, "nope.md"))},
434
+ prevFile: null, scriptDir: ${JSON.stringify(scriptDir)}, interval: 15 });
435
+ console.log(JSON.stringify({ issues: r.issues, prs: r.prs }));`;
436
+ const r = spawnSync(process.execPath, ["--input-type=module", "-e", driver], {
437
+ cwd, encoding: "utf8", env: { ...process.env, PATH: `${bin}:${process.env.PATH}` },
438
+ });
439
+ assert.equal(r.status, 0, r.stdout + r.stderr);
440
+ return { ...JSON.parse(r.stdout.trim().split("\n").pop()), stderr: r.stderr };
441
+ }
442
+
443
+ // tryParse only checks that gh's stdout is valid JSON, not that it is an
444
+ // array — a syntactically-valid object payload used to reach withNumber's
445
+ // `for...of` and throw "rows is not iterable", contrary to this PR's own
446
+ // premise that tryParse "establishes... that it is an array" (#786 review).
447
+ test("gather: a non-array gh payload degrades to an empty list, not a crash", () => {
448
+ const r = gatherRows({ issuesJson: JSON.stringify({ not: "an array" }), prsJson: "[]" });
449
+ assert.deepEqual(r.issues, []);
450
+ assert.match(r.stderr, /gh issue list: expected an array of rows/);
451
+ });
452
+
453
+ test("gather: a well-formed issue/PR row passes through unchanged", () => {
454
+ const r = gatherRows({
455
+ issuesJson: JSON.stringify([{ number: 9, title: "real title", labels: [] }]),
456
+ prsJson: JSON.stringify([{ number: 10, state: "OPEN", title: "real pr title", labels: [] }]),
457
+ });
458
+ assert.deepEqual(r.issues, [{ number: 9, title: "real title", labels: [] }]);
459
+ assert.deepEqual(r.prs, [{ number: 10, state: "OPEN", title: "real pr title", labels: [] }]);
460
+ });
461
+
462
+ test("gather: an issue row with no number is dropped, loudly, not placed as undefined", () => {
463
+ const r = gatherRows({ issuesJson: JSON.stringify([{ title: "orphan" }]), prsJson: "[]" });
464
+ assert.deepEqual(r.issues, []);
465
+ assert.match(r.stderr, /gh issue list: dropping row with no usable number/);
466
+ });
467
+
468
+ test("gather: an issue row missing its title reads as its number, not undefined", () => {
469
+ const r = gatherRows({ issuesJson: JSON.stringify([{ number: 55 }]), prsJson: "[]" });
470
+ assert.equal(r.issues.length, 1);
471
+ assert.equal(r.issues[0].number, 55);
472
+ assert.equal(r.issues[0].title, "#55");
473
+ });
474
+
475
+ test("gather: a PR row with no number is dropped, loudly, not placed as undefined", () => {
476
+ const r = gatherRows({ issuesJson: "[]", prsJson: JSON.stringify([{ title: "orphan pr", state: "OPEN" }]) });
477
+ assert.deepEqual(r.prs, []);
478
+ assert.match(r.stderr, /gh pr list: dropping row with no usable number/);
479
+ });
480
+
481
+ // #2108. gh stops a `list` read at `--limit` — 30 when the flag is absent —
482
+ // with exit 0 and no warning, so this stub does the same: it holds `issues`
483
+ // ready-for-agent tickets and `prs` open PRs and hands back at most the limit
484
+ // it was asked for. A gather() that dropped its --limit would be cut at 30
485
+ // here exactly as it would be against GitHub, and one that stopped checking
486
+ // for a full page would render the cut list as the whole one. The driver runs
487
+ // the real computeBoard() over gather()'s answer: the board is the subject.
488
+ function gatherCapped({ issues, prs }) {
489
+ const cwd = mkdtempSync(join(tmpdir(), "board-gather-capped-"));
490
+ const bin = mkdtempSync(join(tmpdir(), "board-gather-capped-bin-"));
491
+ const scriptDir = mkdtempSync(join(tmpdir(), "board-gather-capped-scripts-"));
492
+ writeFileSync(join(scriptDir, "ci-state.mjs"), "process.stdout.write('{}');\n");
493
+ writeFileSync(join(scriptDir, "ledger.mjs"),
494
+ `process.stdout.write(${JSON.stringify(JSON.stringify({ rows: [], filed: [], ruled: [] }))});\n`);
495
+ writeFileSync(join(bin, "gh"), `#!/usr/bin/env node
496
+ const a = process.argv.slice(2);
497
+ const i = a.indexOf("--limit");
498
+ const limit = i === -1 ? 30 : Number(a[i + 1]);
499
+ const rows = (n, row) => Array.from({ length: Math.min(n, limit) }, (_, k) => row(k + 1));
500
+ if (a[0] === "issue" && a[1] === "list") process.stdout.write(JSON.stringify(rows(${issues}, (n) => ({ number: n, title: "t", labels: [] }))));
501
+ else if (a[0] === "pr" && a[1] === "list") process.stdout.write(JSON.stringify(rows(${prs}, (n) => ({ number: 1000 + n, state: "OPEN", title: "t", labels: [] }))));
502
+ else process.exit(1);
503
+ `);
504
+ chmodSync(join(bin, "gh"), 0o755);
505
+ const driver = `const { gather } = await import(${JSON.stringify(SCRIPT)});
506
+ const { computeBoard } = await import(${JSON.stringify(fileURLToPath(new URL("./compute-board.mjs", import.meta.url)))});
507
+ const inputs = await gather({ ledgerFile: ${JSON.stringify(join(cwd, "ledger.md"))},
508
+ prevFile: null, scriptDir: ${JSON.stringify(scriptDir)}, interval: 15 });
509
+ const b = computeBoard(inputs);
510
+ console.log(JSON.stringify({ prs: inputs.prs.length, poolCards: b.tickets.filter((t) => t.column === "POOL").length,
511
+ queue: b.queue, capNotice: b.capNotice }));`;
512
+ const r = spawnSync(process.execPath, ["--input-type=module", "-e", driver], {
513
+ cwd, encoding: "utf8", env: { ...process.env, PATH: `${bin}:${process.env.PATH}` },
514
+ });
515
+ assert.equal(r.status, 0, r.stdout + r.stderr);
516
+ return JSON.parse(r.stdout.trim().split("\n").pop());
517
+ }
518
+
519
+ test("#2108: a pool read that fills its --limit renders as a floor and says so, never as an exact count", () => {
520
+ const b = gatherCapped({ issues: 150, prs: 0 });
521
+ assert.equal(b.poolCards, 100, "gather() no longer asks for 100 ready-for-agent tickets");
522
+ assert.equal(b.queue.pool, "100+", "a full page of the pool read was rendered as the exact pool size");
523
+ assert.equal(b.queue.supply, "100+");
524
+ assert.match(b.capNotice ?? "", /ready-for-agent read hit its --limit/);
525
+ assert.doesNotMatch(b.capNotice, /open-PR/, "a pool cap was reported as an open-PR cap too");
526
+ });
527
+
528
+ test("#2108: an open-PR read that fills its --limit is disclosed on the board", () => {
529
+ const b = gatherCapped({ issues: 0, prs: 150 });
530
+ assert.equal(b.prs, 100, "gather() no longer asks for 100 open PRs");
531
+ assert.match(b.capNotice ?? "", /open-PR read hit its --limit/);
532
+ assert.doesNotMatch(b.capNotice, /ready-for-agent/, "an open-PR cap was reported as a pool cap too");
533
+ assert.equal(b.queue.pool, 0, "an open-PR cap turned the pool count into a floor");
534
+ });
535
+
536
+ test("#2108: reads one short of their limit, and past gh's bare default of 30, are exact and silent", () => {
537
+ // The input the guard must ACCEPT: 99 is a complete answer, not a capped
538
+ // one, and 35 is more than gh returns when `--limit` goes missing.
539
+ const b = gatherCapped({ issues: 99, prs: 35 });
540
+ assert.equal(b.queue.pool, 99);
541
+ assert.equal(b.prs, 35, "the open-PR read fell back to gh's default of 30");
542
+ assert.equal(b.capNotice, null, "a read under its limit raised the capped-read notice");
543
+ });
544
+
545
+ test("#2108: a pool read AND an open-PR read that both fill their --limit are both disclosed", () => {
546
+ const b = gatherCapped({ issues: 150, prs: 150 });
547
+ assert.equal(b.queue.pool, "100+", "a simultaneous pool cap was not rendered as a floor");
548
+ assert.equal(b.prs, 100, "gather() no longer asks for 100 open PRs");
549
+ assert.match(b.capNotice ?? "", /ready-for-agent read hit its --limit/, "a simultaneous pool cap was not disclosed");
550
+ assert.match(b.capNotice ?? "", /open-PR read hit its --limit/, "a simultaneous open-PR cap was not disclosed");
551
+ // The two substring matches above would both still pass if the two phrases
552
+ // ran together with no separator, or a different one, between them — this
553
+ // pins the exact joined string so that gap cannot hide behind them.
554
+ assert.equal(b.capNotice,
555
+ "the ready-for-agent read hit its --limit, so POOL may be missing tickets" +
556
+ "; the open-PR read hit its --limit, so a PR past it shows REVIEW with CI unknown",
557
+ "capNotice must join simultaneous cap messages with '; ', not run them together or use a different separator");
558
+ });
559
+
560
+ // #1820 read MERGED from gh; #1840 scoped that read to the ledger's own row
561
+ // PRs. One batched `gh api graphql` query asks about exactly the row PRs that
562
+ // need it — absent from the open list, carrying no `MERGED <sha>` token, and
563
+ // not carried forward as MERGED by #1841 — whatever their merge age. That
564
+ // replaced `gh pr list --state merged --limit 100`, which covered only the
565
+ // repo's 100 most recent merges (about six days, measured 2026-09-25).
566
+ //
567
+ // The stub `gh` is a fake GitHub, not an echo of gather(): `api graphql`
568
+ // answers every `ALIAS: pullRequest(number: N)` field in the query from
569
+ // `states`, and a number missing there reads the way GitHub answers a number
570
+ // that is not a PR (measured 2026-09-26, gh 2.101.0): the alias comes back
571
+ // null beside a NOT_FOUND error, and gh exits 1 with the whole body on
572
+ // stdout. `pr list --state merged` still answers with `window`, the most
573
+ // recent merges, so a read that fell back to the window would be caught
574
+ // missing the old PR rather than passing by accident. Every invocation's
575
+ // argv is logged, so a test can count merged reads. The driver runs the real
576
+ // computeBoard() over gather()'s answer: the card's column is the subject.
577
+ function gatherMerged({ rows, prs = [], prev = null, states = {}, fail = false, emptyRepo = false }) {
578
+ const cwd = mkdtempSync(join(tmpdir(), "board-gather-merged-"));
579
+ const bin = mkdtempSync(join(tmpdir(), "board-gather-merged-bin-"));
580
+ const scriptDir = mkdtempSync(join(tmpdir(), "board-gather-merged-scripts-"));
581
+ const log = join(cwd, "gh-calls.jsonl");
582
+ writeFileSync(join(scriptDir, "ci-state.mjs"), "process.stdout.write('{}');\n");
583
+ writeFileSync(join(scriptDir, "ledger.mjs"),
584
+ `process.stdout.write(${JSON.stringify(JSON.stringify({ rows, filed: [], ruled: [] }))});\n`);
585
+ const window = Array.from({ length: 100 }, (_, i) => ({ number: 5000 + i, state: "MERGED" }));
586
+ const config = { prs: prs.map((n) => ({ number: n, state: "OPEN", title: "t", labels: [] })), window, states, fail, emptyRepo, log };
587
+ writeFileSync(join(bin, "gh"), `#!/usr/bin/env node
588
+ const fs = require("node:fs");
589
+ const c = ${JSON.stringify(config)};
590
+ const a = process.argv.slice(2);
591
+ fs.appendFileSync(c.log, JSON.stringify(a) + "\\n");
592
+ const out = (v) => process.stdout.write(JSON.stringify(v));
593
+ if (a[0] === "issue" && a[1] === "list") out([]);
594
+ else if (a[0] === "pr" && a[1] === "list" && a.includes("merged")) out(c.window);
595
+ else if (a[0] === "pr" && a[1] === "list") out(c.prs);
596
+ else if (a[0] === "api" && a[1] === "graphql") {
597
+ if (c.fail) { process.stderr.write("gh: HTTP 502: Bad Gateway\\n"); process.exit(1); }
598
+ if (c.emptyRepo) { out({ data: { repository: {} } }); process.exit(0); }
599
+ const q = a[a.indexOf("-f") + 1];
600
+ const repository = {}; const errors = [];
601
+ for (const [, alias, n] of q.matchAll(/(\\w+)\\s*:\\s*pullRequest\\s*\\(\\s*number\\s*:\\s*(\\d+)\\s*\\)/g)) {
602
+ const state = c.states[n];
603
+ repository[alias] = state ? { number: Number(n), state } : null;
604
+ if (!state) errors.push({ type: "NOT_FOUND", path: ["repository", alias], message: "Could not resolve to a PullRequest with the number of " + n + "." });
605
+ }
606
+ out(errors.length ? { data: { repository }, errors } : { data: { repository } });
607
+ if (errors.length) { process.stderr.write("gh: " + errors.map((e) => e.message).join("\\n") + "\\n"); process.exit(1); }
608
+ }
609
+ else process.exit(1);
610
+ `);
611
+ chmodSync(join(bin, "gh"), 0o755);
612
+ const prevFile = join(cwd, "prev.json");
613
+ if (prev) writeFileSync(prevFile, JSON.stringify(prev));
614
+ const driver = `const { gather } = await import(${JSON.stringify(SCRIPT)});
615
+ const { computeBoard } = await import(${JSON.stringify(fileURLToPath(new URL("./compute-board.mjs", import.meta.url)))});
616
+ const inputs = await gather({ ledgerFile: ${JSON.stringify(join(cwd, "ledger.md"))},
617
+ prevFile: ${JSON.stringify(prevFile)}, scriptDir: ${JSON.stringify(scriptDir)}, interval: 15 });
618
+ const b = computeBoard(inputs);
619
+ console.log(JSON.stringify({ merged: inputs.merged, columns: Object.fromEntries(b.tickets.map((t) => [t.pr, t.column])) }));`;
620
+ const r = spawnSync(process.execPath, ["--input-type=module", "-e", driver], {
621
+ cwd, encoding: "utf8", env: { ...process.env, PATH: `${bin}:${process.env.PATH}` },
622
+ });
623
+ assert.equal(r.status, 0, r.stdout + r.stderr);
624
+ const calls = readFileSync(log, "utf8").trim().split("\n").map((l) => JSON.parse(l));
625
+ // Any read that could answer "merged": the scoped query, or a fallback to
626
+ // the old window. Both count, so a regression to the window cannot hide.
627
+ const mergedReads = calls.filter((c) => c[0] === "api" || c.includes("merged"));
628
+ const asked = (c) => [...c[c.indexOf("-f") + 1].matchAll(/pullRequest\s*\(\s*number\s*:\s*(\d+)\s*\)/g)].map((m) => Number(m[1]));
629
+ return { ...JSON.parse(r.stdout.trim().split("\n").pop()), mergedReads, asked, stderr: r.stderr };
630
+ }
631
+
632
+ test("#1840: a row PR merged outside the most-recent-100 window renders MERGED with no previous board", () => {
633
+ const r = gatherMerged({ rows: ["#907 impl-907=PR#930"], states: { 930: "MERGED" } });
634
+ assert.equal(r.columns[930], "MERGED", r.stderr);
635
+ assert.deepEqual(r.merged, [930]);
636
+ assert.equal(r.mergedReads.length, 1);
637
+ assert.deepEqual(r.asked(r.mergedReads[0]), [930]);
638
+ });
639
+
640
+ test("#1840: a tick whose row PRs are all open, token-MERGED or carried forward makes no merged read", () => {
641
+ const r = gatherMerged({
642
+ rows: [
643
+ "#901 impl-901=PR#931",
644
+ "#902 impl-902=PR#932 → MERGED 73b356de",
645
+ "#903 impl-903=PR#933",
646
+ "#904 impl-904",
647
+ "#905 excluded · behind-pr:#931",
648
+ ],
649
+ prs: [931],
650
+ prev: { tickets: [{ issue: 903, pr: 933, column: "MERGED", sinceEnteredStage: 1 }] },
651
+ });
652
+ assert.deepEqual(r.mergedReads, [], "nothing needed a merged read, so none was made");
653
+ assert.deepEqual(r.merged, []);
654
+ assert.equal(r.columns[931], "REVIEW");
655
+ assert.equal(r.columns[932], "MERGED");
656
+ assert.equal(r.columns[933], "MERGED");
657
+ });
658
+
659
+ test("#1840: the merged lookup is ONE gh invocation asking about exactly the row PRs that need it", () => {
660
+ const r = gatherMerged({
661
+ rows: [
662
+ "#901 impl-901=PR#931",
663
+ "#902 impl-902=PR#932 → MERGED 73b356de",
664
+ "#903 impl-903=PR#933",
665
+ "#906 impl-906=PR#930",
666
+ "#907 impl-907=PR#940",
667
+ "#908 impl-908=PR#950",
668
+ "#909 impl-909=PR#960",
669
+ ],
670
+ prs: [931],
671
+ prev: { tickets: [{ issue: 903, pr: 933, column: "MERGED", sinceEnteredStage: 1 }] },
672
+ states: { 930: "MERGED", 940: "CLOSED", 950: "MERGED", 960: "OPEN" },
673
+ });
674
+ assert.equal(r.mergedReads.length, 1, JSON.stringify(r.mergedReads));
675
+ assert.deepEqual(r.asked(r.mergedReads[0]).sort((a, b) => a - b), [930, 940, 950, 960],
676
+ "open 931, token-MERGED 932 and carried-forward 933 are not asked about");
677
+ assert.deepEqual(r.merged, [930, 950]);
678
+ assert.equal(r.columns[930], "MERGED");
679
+ assert.equal(r.columns[940], "REVIEW", "closed unmerged stays REVIEW");
680
+ assert.equal(r.columns[950], "MERGED");
681
+ assert.equal(r.columns[960], "REVIEW", "open but beyond the open list is not merged");
682
+ });
683
+
684
+ test("#1840: a failed merged lookup keeps #1841's rule — carried forward stays MERGED, the rest reads REVIEW", () => {
685
+ const r = gatherMerged({
686
+ rows: ["#903 impl-903=PR#933", "#907 impl-907=PR#930"],
687
+ prev: { tickets: [{ issue: 903, pr: 933, column: "MERGED", sinceEnteredStage: 1 }] },
688
+ states: { 930: "MERGED" },
689
+ fail: true,
690
+ });
691
+ assert.equal(r.mergedReads.length, 1);
692
+ assert.deepEqual(r.merged, []);
693
+ assert.equal(r.columns[933], "MERGED");
694
+ assert.equal(r.columns[930], "REVIEW");
695
+ assert.match(r.stderr, /merged read .*failed/);
696
+ });
697
+
698
+ // A row whose PR number GitHub cannot resolve as a PR — a typo, or an
699
+ // amendment-2a row keyed by an issue number — makes gh exit 1, but the body
700
+ // still answers every other number. Refusing the whole answer would let one
701
+ // bad row put every cold-start merged PR back in REVIEW on every tick.
702
+ test("#1840: one unresolvable number does not poison the batch — the PRs gh did answer still count", () => {
703
+ const r = gatherMerged({
704
+ rows: ["#907 impl-907=PR#930", "#908 impl-908=PR#1840"],
705
+ states: { 930: "MERGED" },
706
+ });
707
+ assert.equal(r.mergedReads.length, 1);
708
+ assert.deepEqual(r.merged, [930]);
709
+ assert.equal(r.columns[930], "MERGED");
710
+ assert.equal(r.columns[1840], "REVIEW");
711
+ });
712
+
713
+ // #1840 review: real GitHub always answers every requested `p<N>` alias
714
+ // (null or an object), never omits one — so `data.repository` present with
715
+ // NONE of the requested keys is not a shape the API produces, only a
716
+ // corrupted/truncated one, and readMerged() must not read it as "checked,
717
+ // nothing merged": it has to fail loudly (log + carry-forward/REVIEW) the
718
+ // same as any other unusable answer, not silently.
719
+ test("#1840: an object data.repository naming none of the requested PRs is a failed read, not a clean zero-merged answer", () => {
720
+ const r = gatherMerged({
721
+ rows: ["#907 impl-907=PR#930", "#908 impl-908=PR#931"],
722
+ emptyRepo: true,
723
+ });
724
+ assert.equal(r.mergedReads.length, 1);
725
+ assert.deepEqual(r.merged, []);
726
+ assert.match(r.stderr, /merged read \(2 PRs\) failed \(exit 0\) with no usable answer/,
727
+ "an empty-but-object repository must still log a failed-read line, not read as a clean empty answer");
728
+ assert.equal(r.columns[930], "REVIEW");
729
+ assert.equal(r.columns[931], "REVIEW");
730
+ });
731
+
732
+ // `state` and `title` used to default to a sentinel ("UNKNOWN" / `#<number>`)
733
+ // on a PR row. Both defaults are gone: `state`'s only consumer is
734
+ // `pr.state === "OPEN"` (compute-board.mjs), already false for `undefined`
735
+ // exactly as it was for "UNKNOWN" — an inert guard. `title`'s default made a
736
+ // titleless PR row unconditionally truthy, which SILENTLY DISABLED titleFor()'s
737
+ // existing fallback to the real issue title (see compute-board.test.mjs for
738
+ // the column-placement pin this can't reach — `open`, the boolean `state`
739
+ // feeds, is itself never read past that comparison). Raw passthrough, pinned
740
+ // here as gather()'s actual output shape.
741
+ test("gather: a PR row missing state/title passes through raw, not coerced to a sentinel", () => {
742
+ const r = gatherRows({ issuesJson: "[]", prsJson: JSON.stringify([{ number: 77 }]) });
743
+ assert.equal(r.prs.length, 1);
744
+ // Round-tripped through JSON (gatherRows' driver), so an undefined value
745
+ // survives as an absent key, not a key holding `undefined` — same as what
746
+ // JSON.stringify(model) already does to board.json on every real tick.
747
+ assert.deepEqual(r.prs[0], { number: 77, labels: [] });
748
+ });
749
+
750
+ // The #786 regression review reproduced this live: `labels` was the one field
751
+ // this PR's own guard comment claimed was covered ("a row without a usable
752
+ // field... doesn't fail the tick") but was never actually guarded — a
753
+ // non-array `labels` throws `TypeError: ... .map is not a function`, crashing
754
+ // gather() entirely rather than degrading the row.
755
+ test("gather: a non-array labels field degrades to [], not a TypeError crash", () => {
756
+ const r = gatherRows({
757
+ issuesJson: JSON.stringify([{ number: 1, title: "t", labels: "not-an-array" }]),
758
+ prsJson: JSON.stringify([{ number: 2, title: "t", state: "OPEN", labels: "not-an-array" }]),
759
+ });
760
+ assert.deepEqual(r.issues[0].labels, []);
761
+ assert.deepEqual(r.prs[0].labels, []);
762
+ });
763
+
764
+ // The second reproduced crash: a `labels` array whose elements are the right
765
+ // TYPE (an array) but a WRONG-shaped or null element throws reading `.name`.
766
+ test("gather: a malformed element inside labels is dropped, not the whole row", () => {
767
+ const r = gatherRows({
768
+ issuesJson: JSON.stringify([{ number: 1, title: "t", labels: [{ name: "keep" }, null, {}] }]),
769
+ prsJson: "[]",
770
+ });
771
+ assert.deepEqual(r.issues[0].labels, ["keep"]);
772
+ });
773
+
774
+ test("createBoardServer serves board.json and the page", async () => {
775
+ const dir = mkdtempSync(join(tmpdir(), "board-"));
776
+ writeFileSync(join(dir, "board.json"), JSON.stringify({ generatedAt: 1, tickets: [], attention: [] }));
777
+ writeFileSync(join(dir, "board.html"), "<!doctype html><title>cockpit</title>");
778
+ const server = createBoardServer(dir);
779
+ await new Promise((res) => server.listen(0, res));
780
+ const port = server.address().port;
781
+
782
+ const j = await fetch(`http://localhost:${port}/board.json`);
783
+ assert.equal(j.status, 200);
784
+ assert.equal((await j.json()).generatedAt, 1);
785
+
786
+ const h = await fetch(`http://localhost:${port}/`);
787
+ assert.equal(h.status, 200);
788
+ assert.match(await h.text(), /cockpit/);
789
+
790
+ const nf = await fetch(`http://localhost:${port}/nope`);
791
+ assert.equal(nf.status, 404);
792
+
793
+ await new Promise((res) => server.close(res));
794
+ });
795
+
796
+ // ── the spend transcript layer ────────────────────────────────────────────────
797
+ // Both bugs this file now pins were invisible to the pure-module tests, because
798
+ // both live in the I/O that feeds them: a wrong path and a wrong summation. Each
799
+ // failed silently as "panel hidden" or "plausible but 3x too big".
800
+
801
+ test("findSubagentsDir picks the session with the newest transcript", () => {
802
+ const home = mkdtempSync(join(tmpdir(), "spend-home-"));
803
+ const proj = join(home, ".omp", "agent", "sessions", "-x");
804
+ const older = join(proj, "2026-09-08T13-13-27-300Z_11111111-aaaa-aaaa-aaaa-aaaaaaaaaaaa");
805
+ const newer = join(proj, "2026-09-09T02-00-00-000Z_22222222-bbbb-bbbb-bbbb-bbbbbbbbbbbb");
806
+ mkdirSync(older, { recursive: true });
807
+ mkdirSync(newer, { recursive: true });
808
+ // Ranking reads the newest *.jsonl mtime, so stamp the TRANSCRIPTS, not the
809
+ // dirs. Stamp both explicitly rather than sleeping for a clock tick: both are
810
+ // created inside the same millisecond on a fast filesystem, `mtimeMs` ties,
811
+ // and the sort is stable — a tie would resolve to readdir order and the
812
+ // OLDER directory would win on name.
813
+ writeFileSync(join(older, "agent-a.jsonl"), "");
814
+ utimesSync(join(older, "agent-a.jsonl"), new Date(1000), new Date(1000));
815
+ writeFileSync(join(newer, "agent-b.jsonl"), "");
816
+ utimesSync(join(newer, "agent-b.jsonl"), new Date(9000), new Date(9000));
817
+
818
+ assert.equal(findSubagentsDir(home, join(home, "x")), newer);
819
+ // Unresolvable path is a bug, not an empty run — it must be distinguishable.
820
+ assert.ok(findSubagentsDir(home, "/nonexistent").error);
821
+ });
822
+
823
+ test("session ranking uses transcript mtime, not directory mtime", () => {
824
+ // Regression: a directory's mtime moves when an entry is CREATED, never when a
825
+ // file inside it is appended to. Ranking on it tracked the last agent spawn,
826
+ // so a session that spawned all its agents early lost to a newer, idle one —
827
+ // and since the cockpit starts before the first agent spawns, that was the
828
+ // common case at run start. The board would show a PREVIOUS run's spend.
829
+ //
830
+ // The two rankings only disagree when the newest DIRECTORY is not the one
831
+ // holding the newest TRANSCRIPT, so the fixture has to build exactly that and
832
+ // nothing weaker. Creating the busy dir's transcript LAST — the shape this
833
+ // test had before — bumps that dir's own mtime as a side effect, so both
834
+ // rankings then pick `busy` for different reasons and the test stayed green
835
+ // with the fix fully reverted. Stamp all four times explicitly, files before
836
+ // dirs: creating a file is the one operation that moves its parent's mtime,
837
+ // and rewriting an existing file's mtime does not.
838
+ const home = mkdtempSync(join(tmpdir(), "spend-home-"));
839
+ const proj = join(home, ".omp", "agent", "sessions", "-x");
840
+ const busy = join(proj, "2026-09-08T13-13-27-300Z_aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"); // spawned its agents early, still appending
841
+ const idle = join(proj, "2026-09-09T02-00-00-000Z_bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb"); // spawned one last agent, then went quiet
842
+ mkdirSync(busy, { recursive: true });
843
+ mkdirSync(idle, { recursive: true });
844
+ writeFileSync(join(busy, "agent-b.jsonl"), "");
845
+ writeFileSync(join(idle, "agent-i.jsonl"), "");
846
+ utimesSync(join(busy, "agent-b.jsonl"), new Date(9000), new Date(9000)); // newest TRANSCRIPT
847
+ utimesSync(join(idle, "agent-i.jsonl"), new Date(1000), new Date(1000));
848
+ utimesSync(busy, new Date(1000), new Date(1000));
849
+ utimesSync(idle, new Date(9000), new Date(9000)); // newest DIRECTORY
850
+
851
+ assert.equal(findSubagentsDir(home, join(home, "x")), busy);
852
+ });
853
+
854
+ test("one unreadable session directory loses the ranking instead of sinking the lookup", () => {
855
+ // Regression: newestTranscriptMs' readdirSync sat outside its per-file try and
856
+ // inside findSubagentsDir's, so one bad sibling turned the WHOLE lookup into
857
+ // { error } and the board rendered "spend unavailable" over a perfectly
858
+ // readable live session — a blackout where the per-file catch beside it
859
+ // already chose degradation. A candidate we cannot read must score 0 and lose.
860
+ //
861
+ // The bad sibling is a regular FILE where a directory is expected: EISDIR/
862
+ // ENOTDIR is the same uncaught throw and, unlike a permission bit, it still
863
+ // throws when the suite runs as root.
864
+ const home = mkdtempSync(join(tmpdir(), "spend-home-"));
865
+ const proj = join(home, ".omp", "agent", "sessions", "-x");
866
+ const good = join(proj, "2026-09-08T13-13-27-300Z_aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa");
867
+ mkdirSync(good, { recursive: true });
868
+ writeFileSync(join(good, "agent-a.jsonl"), "");
869
+ const badName = "2026-09-09T02-00-00-000Z_bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb";
870
+ mkdirSync(join(proj, badName, "nested"), { recursive: true });
871
+ chmodSync(join(proj, badName), 0o000);
872
+ try {
873
+ assert.equal(findSubagentsDir(home, join(home, "x")), good);
874
+ } finally {
875
+ chmodSync(join(proj, badName), 0o755);
876
+ }
877
+ });
878
+
879
+ // ── #1716: the omp tree ───────────────────────────────────────────────────────
880
+ // Shaped like the real ~/.omp/agent/sessions/<encoded-cwd>/ (the same shape
881
+ // member-record.test.mjs's real-tree fixture pins): each session's MAIN
882
+ // transcript is a plain `<ISO>_<uuid>.jsonl` FILE sibling to its `<ISO>_<uuid>/`
883
+ // DIRECTORY, which holds one `<AgentId>.jsonl` per member, plus a directory
884
+ // per member that dispatched members of its own. Lines are the measured
885
+ // shapes member-record.mjs's foldOmpTranscript comment records.
886
+ const OMP_A = "2026-09-08T13-13-27-300Z_01a08126-ee04-7095-a695-14e3249f1127";
887
+ const OMP_B = "2026-09-09T02-00-00-000Z_cafef00d-cafe-cafe-cafe-cafef00dcafe";
888
+
889
+ function ompTranscript({ agent, task, model = "claude-opus-5", turns = [] } = {}) {
890
+ const lines = [
891
+ { type: "session", version: 3, id: "s1", timestamp: "2026-09-08T15:11:49.444Z", cwd: "/w" },
892
+ { type: "session_init", id: "i1", parentId: null, timestamp: "2026-09-08T15:11:49.495Z", task, agent, resolvedModelIdentity: `anthropic/${model}` },
893
+ ...turns.map((u, i) => ({
894
+ type: "message", id: `m${i}`, parentId: "i1", timestamp: "2026-09-08T15:12:00.000Z",
895
+ message: { role: "assistant", content: [{ type: "text", text: "ok" }], model, usage: { ...u, totalTokens: 0, cost: { total: 0.01 } } },
896
+ })),
897
+ ];
898
+ return lines.map((l) => JSON.stringify(l)).join("\n") + "\n";
899
+ }
900
+
901
+ // A $HOME whose cwd sits under it, so the encoded project dir is the
902
+ // home-relative form (`-dev-repo`) and needs no realpath of a cwd that does
903
+ // not exist. encodeProjectDir is the real encoder, not a hand-rolled path.
904
+ function ompHome() {
905
+ const home = mkdtempSync(join(tmpdir(), "spend-omp-home-"));
906
+ const cwd = join(home, "dev", "repo");
907
+ const proj = join(home, ".omp", "agent", "sessions", encodeProjectDir(cwd, { home }));
908
+ mkdirSync(proj, { recursive: true });
909
+ return { home, cwd, proj };
910
+ }
911
+
912
+ // One session: its member transcripts (a `/` in a name nests it, the way a
913
+ // member's own members are laid out) stamped `mtime`, and its main-session
914
+ // file beside the directory, stamped NOW so it is the newest transcript in
915
+ // the whole tree — a lookup or a gather that reads it cannot pass.
916
+ function ompSession(proj, name, members, mtime) {
917
+ const dir = join(proj, name);
918
+ mkdirSync(dir, { recursive: true });
919
+ for (const [agent, text] of Object.entries(members)) {
920
+ const file = join(dir, `${agent}.jsonl`);
921
+ mkdirSync(dirname(file), { recursive: true });
922
+ writeFileSync(file, text);
923
+ if (mtime != null) utimesSync(file, new Date(mtime), new Date(mtime));
924
+ }
925
+ writeFileSync(join(proj, `${name}.jsonl`), ompTranscript({ turns: [{ input: 1, output: 1, cacheRead: 1, cacheWrite: 999_999 }] }));
926
+ return dir;
927
+ }
928
+
929
+ test("findSubagentsDir on omp picks this workspace's newest session DIRECTORY — never the main-session file beside it, never a stray dir", () => {
930
+ const { home, cwd, proj } = ompHome();
931
+ const older = ompSession(proj, OMP_A, { "impl-1": ompTranscript() }, 1000);
932
+ const newer = ompSession(proj, OMP_B, { "impl-2": ompTranscript() }, 9000);
933
+ // Not `<ISO>_<uuid>`, and holding the newest member-shaped transcript of all.
934
+ mkdirSync(join(proj, "notes"));
935
+ writeFileSync(join(proj, "notes", "x.jsonl"), "");
936
+ utimesSync(join(proj, "notes", "x.jsonl"), new Date(20000), new Date(20000));
937
+
938
+ // No session tree at all yet: resolves cleanly, does not error.
939
+ assert.equal(findSubagentsDir(home, cwd), newer);
940
+ utimesSync(join(older, "impl-1.jsonl"), new Date(30000), new Date(30000));
941
+ assert.equal(findSubagentsDir(home, cwd), older, "the ranking reads member transcripts, so it follows them");
942
+ });
943
+
944
+ test("findSubagentsDir on omp follows a NESTED member's mtime, not just the session dir's top-level files", () => {
945
+ // #1867 review: a session whose only fresh activity is a member ONE LEVEL
946
+ // DOWN (its own further fan-out — a dispatcher blocked on its task tool
947
+ // while its specialists run) must still outrank a stale sibling session.
948
+ // Regression for a scan bounded to a session dir's direct children only.
949
+ const { home, cwd, proj } = ompHome();
950
+ const liveViaNested = ompSession(proj, OMP_A, { "impl-1": ompTranscript() }, 1000);
951
+ const staleSibling = ompSession(proj, OMP_B, { "impl-2": ompTranscript() }, 5000);
952
+ const nestedFile = join(liveViaNested, "review-pr-9", "Security.jsonl");
953
+ mkdirSync(dirname(nestedFile), { recursive: true });
954
+ writeFileSync(nestedFile, ompTranscript({ agent: "fleet-review-correctness" }));
955
+ utimesSync(nestedFile, new Date(90000), new Date(90000));
956
+
957
+ assert.equal(findSubagentsDir(home, cwd), liveViaNested,
958
+ "the nested member's fresher mtime must win the ranking, not lose to staleSibling's stale top-level file");
959
+ });
960
+
961
+ test("findSubagentsDir: an EACCES resolving the omp encoding (not ENOENT) surfaces as an error", () => {
962
+ // #1867 review: ompSessionDirs's catch around encodeProjectDir must only
963
+ // swallow ENOENT ("this cwd doesn't exist" — the documented case). Any
964
+ // other error (EACCES on an ancestor, here) is a real fault and must
965
+ // propagate, never be silently relabelled as "no omp session".
966
+ const home = mkdtempSync(join(tmpdir(), "spend-eacces-home-"));
967
+ const outer = mkdtempSync(join(tmpdir(), "spend-eacces-outer-"));
968
+ const blocked = join(outer, "blocked");
969
+ mkdirSync(blocked);
970
+ const cwd = join(blocked, "sub", "repo");
971
+ mkdirSync(cwd, { recursive: true });
972
+ chmodSync(blocked, 0o000);
973
+ try {
974
+ const result = findSubagentsDir(home, cwd);
975
+ assert.ok(result && typeof result === "object" && "error" in result, "it must surface as a lookup error, the same as any other real fault");
976
+ } finally {
977
+ chmodSync(blocked, 0o755);
978
+ }
979
+ });
980
+
981
+ test("with no session tree present the lookup is an error that names where it looked", () => {
982
+ const home = mkdtempSync(join(tmpdir(), "spend-omp-home-"));
983
+ const r = findSubagentsDir(home, join(home, "dev", "repo"));
984
+ assert.match(r.error, /\.omp[\\/]agent[\\/]sessions/);
985
+ });
986
+
987
+ test("the pin's launchMs gate holds on an omp tree: a session predating launch is followed, the first to write on its watch latches", () => {
988
+ const { home, cwd, proj } = ompHome();
989
+ const mine = ompSession(proj, OMP_A, { "impl-1": ompTranscript() }, Date.now() - 100000);
990
+ const theirs = ompSession(proj, OMP_B, { "impl-2": ompTranscript() }, Date.now() - 200000);
991
+ const pin = spendDirPin(undefined, home, cwd);
992
+ assert.equal(pin(), mine, "before anything writes on this pin's watch, it answers from the heuristic's newest");
993
+ utimesSync(join(theirs, "impl-2.jsonl"), new Date(Date.now() + 1000), new Date(Date.now() + 1000));
994
+ assert.equal(pin(), theirs, "and re-picks — neither was trustworthy to cache yet");
995
+ utimesSync(join(mine, "impl-1.jsonl"), new Date(Date.now() + 50000), new Date(Date.now() + 50000));
996
+ assert.equal(pin(), theirs, "and holds, because theirs was first to write on this pin's watch");
997
+ assert.equal(findSubagentsDir(home, cwd), mine, "the fixture really did flip — this test proves nothing otherwise");
998
+ });
999
+
1000
+ test("an omp session's per-member rows carry exactly readOmpMember's totals, model and role", () => {
1001
+ const { proj } = ompHome();
1002
+ const members = {
1003
+ "impl-7": ompTranscript({ agent: "fleet-implementer", task: "Implement ticket 7", turns: [
1004
+ { input: 3, output: 40, cacheRead: 500, cacheWrite: 7000 },
1005
+ { input: 1, output: 60, cacheRead: 9000, cacheWrite: 1100 },
1006
+ ] }),
1007
+ "review-pr-9": ompTranscript({ task: "Review PR 9", model: "claude-sonnet-5", turns: [{ input: 2, output: 20, cacheRead: 300, cacheWrite: 4000 }] }),
1008
+ // Nested one level: a member's own member, which readOmpMember books by depth.
1009
+ "review-pr-9/Security": ompTranscript({ task: "Check security", model: "claude-haiku-4-5", turns: [{ input: 1, output: 5, cacheRead: 100, cacheWrite: 2500 }] }),
1010
+ // Dispatched this second, no assistant turn yet — readOmpMember answers null.
1011
+ Fresh: ompTranscript({ agent: "fleet-implementer", task: "Implement ticket 8" }),
1012
+ };
1013
+ const dir = ompSession(proj, OMP_A, members);
1014
+ const expected = Object.entries(members)
1015
+ .map(([agent, text]) => readOmpMember(text, join(dir, `${agent}.jsonl`), agent, agent.split("/").length - 1))
1016
+ .filter(Boolean);
1017
+ // One member per role, so each role bucket below IS one member's row.
1018
+ assert.equal(new Set(expected.map((m) => m.role)).size, 3, `fixture: ${expected.map((m) => m.role)}`);
1019
+
1020
+ const s = gatherSpend({ dir });
1021
+ assert.equal(s.ok, true);
1022
+ assert.equal(s.skipped, 0);
1023
+ const sum = (k) => expected.reduce((n, m) => n + m[k], 0);
1024
+ // The main-session file beside the dir (999,999 cache-write) is not a member,
1025
+ // and the turn-less one has spent nothing, so neither is in these.
1026
+ assert.deepEqual(
1027
+ { agents: s.totals.agents, cacheWrite: s.totals.cacheWrite, output: s.totals.output, cacheRead: s.totals.cacheRead },
1028
+ { agents: 3, cacheWrite: sum("tokens_cache_create"), output: sum("tokens_out"), cacheRead: sum("tokens_cache_read") },
1029
+ );
1030
+ for (const m of expected) {
1031
+ const row = s.top.find((r) => r.label === m.member);
1032
+ assert.ok(row, `no row labelled ${m.member}: ${JSON.stringify(s.top)}`);
1033
+ assert.deepEqual({ role: row.role, model: row.model, cacheWrite: row.cacheWrite },
1034
+ { role: m.role, model: m.model, cacheWrite: m.tokens_cache_create }, m.member);
1035
+ const bucket = s.roles.find((r) => r.role === m.role);
1036
+ assert.deepEqual({ cacheWrite: bucket.cacheWrite, output: bucket.output, cacheRead: bucket.cacheRead },
1037
+ { cacheWrite: m.tokens_cache_create, output: m.tokens_out, cacheRead: m.tokens_cache_read }, m.member);
1038
+ }
1039
+ });
1040
+
1041
+ test("an omp session's tool table is attributed per member and merged (#1717)", () => {
1042
+ // Lines in the measured tool shapes member-record.mjs's foldOmpTranscript
1043
+ // comment records: a `toolCall` block on the assistant message, and each
1044
+ // result a `toolResult` message line of its own.
1045
+ const msg = (message) => JSON.stringify({ type: "message", id: "m", parentId: "i1", timestamp: "2026-09-08T15:12:00.000Z", message });
1046
+ const turn = (cacheWrite, ...calls) => msg({
1047
+ role: "assistant", model: "claude-opus-5",
1048
+ content: calls.map(([id, name]) => ({ type: "toolCall", id, name, arguments: {} })),
1049
+ usage: { input: 1, output: 1, cacheRead: 0, cacheWrite, totalTokens: 0, cost: { total: 0.01 } },
1050
+ });
1051
+ const res = (id, toolName, chars) => msg({
1052
+ role: "toolResult", toolCallId: id, toolName, content: [{ type: "text", text: "x".repeat(chars) }], details: {}, isError: false, timestamp: 0,
1053
+ });
1054
+ const { proj } = ompHome();
1055
+ const dir = ompSession(proj, OMP_A, {
1056
+ "impl-7": [turn(5000, ["a", "read"]), res("a", "read", 300), turn(600, ["b", "bash"]), res("b", "bash", 100), turn(200)].join("\n") + "\n",
1057
+ // A nested member's table merges in too: readOmpSpend books every member at any depth.
1058
+ "impl-7/Scout": [turn(4000, ["c", "read"]), res("c", "read", 50), turn(900)].join("\n") + "\n",
1059
+ });
1060
+ const s = gatherSpend({ dir });
1061
+ assert.equal(s.ok, true);
1062
+ assert.equal(s.totals.cacheWrite, 10_700);
1063
+ assert.deepEqual(s.tools.map((t) => [t.tool, t.calls, t.resultChars, t.cacheWrite]), [["read", 2, 350, 1500], ["bash", 1, 100, 200]]);
1064
+ // Only 1,700 of the 10,700 total ends up attributed: each member's FIRST
1065
+ // turn follows no result, so both first turns (5,000 + 4,000 = 9,000) stay
1066
+ // outside the table.
1067
+ assert.equal(s.attributedPct.toFixed(2), "15.89");
1068
+ });
1069
+
1070
+ test("an omp session's damaged count is real, not a hardcoded 0 (#1717 review)", () => {
1071
+ // The `damaged` block (#916): a mid-file tear
1072
+ // now costs more than its own turn's totals once the same fold also feeds
1073
+ // the tool table, so this reader has to count it rather than assume 0.
1074
+ const msg = (message) => JSON.stringify({ type: "message", id: "m", parentId: "i1", timestamp: "2026-09-08T15:12:00.000Z", message });
1075
+ const turn = (cacheWrite) => msg({ role: "assistant", model: "claude-opus-5", content: [{ type: "text", text: "ok" }], usage: { input: 1, output: 1, cacheRead: 0, cacheWrite, totalTokens: 0, cost: { total: 0.01 } } });
1076
+ const TORN = '{"type":"message","message":{"role":"ass';
1077
+ const { proj } = ompHome();
1078
+ const dir = ompSession(proj, OMP_A, {
1079
+ // The tear sits BETWEEN two good turns, so their spend still counts.
1080
+ "impl-7": [turn(1000), TORN, turn(500)].join("\n") + "\n",
1081
+ });
1082
+ const s = gatherSpend({ dir });
1083
+ assert.equal(s.ok, true);
1084
+ assert.equal(s.totals.cacheWrite, 1500, "the surrounding turns still fold — only the torn line itself is lost");
1085
+ assert.equal(s.damaged, 1);
1086
+ assert.equal(s.skipped, 0, "booked, not skipped — a damaged line costs its own turn, never the whole member");
1087
+ });
1088
+
1089
+ test("an omp session's torn LAST line stays silent — the tear a live write legitimately produces", () => {
1090
+ const msg = (message) => JSON.stringify({ type: "message", id: "m", parentId: "i1", timestamp: "2026-09-08T15:12:00.000Z", message });
1091
+ const turn = (cacheWrite) => msg({ role: "assistant", model: "claude-opus-5", content: [{ type: "text", text: "ok" }], usage: { input: 1, output: 1, cacheRead: 0, cacheWrite, totalTokens: 0, cost: { total: 0.01 } } });
1092
+ const TORN = '{"type":"message","message":{"role":"ass';
1093
+ const { proj } = ompHome();
1094
+ // No trailing newline: the torn write is the final element of the split,
1095
+ // the same discriminator foldOmpTranscript's own `malformedNonLastLines` relies on.
1096
+ const dir = ompSession(proj, OMP_A, { "impl-7": [turn(1000), TORN].join("\n") });
1097
+ const s = gatherSpend({ dir });
1098
+ assert.equal(s.ok, true);
1099
+ assert.equal(s.totals.cacheWrite, 1000);
1100
+ assert.equal(s.damaged, 0);
1101
+ });
1102
+
1103
+ test("one bad transcript in an omp session is skipped and named, not a blackout of the members beside it", () => {
1104
+ // readOmpSession lets a wrong-harness refusal propagate (a whole-tree scrape
1105
+ // must refuse loudly); on the live panel that is one transcript's fault, so
1106
+ // it lands in `skipped` exactly as a broken transcript does.
1107
+ const { proj } = ompHome();
1108
+ const dir = ompSession(proj, OMP_A, { "impl-7": ompTranscript({ turns: [{ input: 1, output: 1, cacheRead: 1, cacheWrite: 1000 }] }) });
1109
+ writeFileSync(join(dir, "Stray.jsonl"), JSON.stringify({ type: "assistant", sessionId: "x", message: { id: "m", usage: {} } }) + "\n");
1110
+ let s;
1111
+ const errs = withStderr(() => { s = gatherSpend({ dir }); });
1112
+ assert.equal(s.ok, true);
1113
+ assert.equal(s.totals.cacheWrite, 1000, "the good member still counts");
1114
+ assert.equal(s.skipped, 1);
1115
+ assert.equal(errs.length, 1);
1116
+ assert.match(errs[0], /Stray\.jsonl/);
1117
+ });
1118
+
1119
+ // #1894: a transcript foldOmpTranscript reads no assistant-with-usage line out
1120
+ // of has no model, so ompMemberRecord answers null and readOmpSpend books
1121
+ // nothing — without a throw, so `skipped` stays 0 as well. `damaged` is then
1122
+ // the only thing that says the directory held a transcript at all, and the
1123
+ // `!agents.length` branch used to read `skipped` alone: an --spend-dir
1124
+ // operator was told the directory "holds no agent transcripts", and the
1125
+ // heuristic's panel simply hid — a destroyed session rendered as one that had
1126
+ // not started.
1127
+ test("an omp session whose only transcript is wholly corrupt reports the damage, not an empty directory (#1894)", () => {
1128
+ const { proj } = ompHome();
1129
+ // Every line unparseable — the ticket's own reproduction, via --spend-dir.
1130
+ const allGarbage = ompSession(proj, OMP_A, { "impl-7": "garbage\n{not json\nmore garbage\n" });
1131
+ let s;
1132
+ const errs = withStderr(() => { s = gatherSpend({ dir: allGarbage, explicit: true }); });
1133
+ assert.equal(s?.ok, false, JSON.stringify(s));
1134
+ assert.match(s.error, /3 damaged transcript lines/);
1135
+ assert.deepEqual(errs.filter((e) => /holds no agent transcripts/.test(e)), [], "the directory holds a transcript; saying otherwise is the defect");
1136
+ // Its header parses and only the line its spend lives on is lost — the
1137
+ // same null from ompMemberRecord, reached from the heuristic, which used to
1138
+ // return the silent `null` that hides the panel.
1139
+ const initOnly = JSON.stringify({ type: "session_init", id: "i1", parentId: null, timestamp: "2026-09-08T15:11:49.495Z", task: "t", agent: "fleet-implementer" });
1140
+ const headerIntact = ompSession(proj, OMP_B, { "impl-8": `${initOnly}\n{"type":"message","message":{"role":"ass\n` });
1141
+ const h = gatherSpend({ dir: headerIntact });
1142
+ assert.equal(h?.ok, false, JSON.stringify(h));
1143
+ assert.match(h.error, /1 damaged transcript line\b/);
1144
+ });
1145
+
1146
+ test("--spend-dir naming the encoded-cwd PROJECT directory is refused, not silently scraped whole (#1302-style)", () => {
1147
+ // gatherSpend's `explicit` path hands readOmpSpend one directory, which
1148
+ // ompSessionTranscripts then walks recursively with no name check of its
1149
+ // own — so naming the project dir (the parent `-dev-repo` directory
1150
+ // findSubagentsDir resolves FROM, never the thing itself) instead of one
1151
+ // of its `<ISO>_<uuid>` session children used to be silently accepted
1152
+ // whole: every session under it booked as "agents", including the
1153
+ // project's own main-session transcript.
1154
+ const { proj } = ompHome();
1155
+ ompSession(proj, OMP_A, { "impl-1": ompTranscript() });
1156
+ let s;
1157
+ const errs = withStderr(() => { s = gatherSpend({ dir: proj, explicit: true }); });
1158
+ assert.equal(s?.ok, false, JSON.stringify(s));
1159
+ assert.match(s.error, /is not an omp .* session directory/);
1160
+ assert.deepEqual(errs.filter((e) => /is not an omp/.test(e)).length > 0, true, "the refusal must actually reach stderr, not just the return value");
1161
+ });
1162
+
1163
+ test("an omp session losing one transcript whole and another to damaged lines names both, not 'all 1 unreadable' (#1894)", () => {
1164
+ // The `skipped`-only wording counts whole files: beside a second transcript
1165
+ // lost to damaged lines it would claim one transcript was ALL there was.
1166
+ const { proj } = ompHome();
1167
+ const dir = ompSession(proj, OMP_A, { "impl-7": "garbage\n{not json\n" });
1168
+ writeFileSync(join(dir, "Stray.jsonl"), JSON.stringify({ type: "assistant", sessionId: "x", message: { id: "m", usage: {} } }) + "\n");
1169
+ let s;
1170
+ withStderr(() => { s = gatherSpend({ dir }); }); // Stray's skip line is the skips gate's, not under test
1171
+ assert.equal(s.ok, false);
1172
+ assert.doesNotMatch(s.error, /all 1 transcripts/);
1173
+ // One assertion pinning both substrings AND their relative order — two
1174
+ // independent assert.match calls each pass regardless of which clause
1175
+ // comes first, so a swap of the unshift/push that builds `lost` (reversing
1176
+ // the skipped-clause and the damaged-clause) would slip through unnoticed.
1177
+ assert.match(s.error, /1 transcript unreadable; 2 damaged transcript lines/);
1178
+ });
1179
+
1180
+ test("an omp session whose only transcript is a live write's torn first line is still 'nothing yet', not damage (#1894)", () => {
1181
+ // The input the new branch must ACCEPT: a member dispatched this second has
1182
+ // one partial line and no newline after it. That tail is exactly what
1183
+ // foldOmpTranscript declines to count, so this stays the silent null.
1184
+ const { proj } = ompHome();
1185
+ const dir = ompSession(proj, OMP_A, { "impl-7": '{"type":"session_init","id":"i1","par' });
1186
+ assert.equal(gatherSpend({ dir }), null);
1187
+ });
1188
+
1189
+ // ── #1583/#1679: the pin ──────────────────────────────────────────────────────
1190
+ //
1191
+ // Two sessions under ONE project directory is the mode this whole ticket is
1192
+ // about, and no test above drives it across TIME: every findSubagentsDir() case
1193
+ // builds its fixture, asks once, and stops. The lookup ran inside gatherSpend()
1194
+ // on every tick (~15s), so the second session merely had to write to take the
1195
+ // panel over, with nothing on the page or on stderr saying it had.
1196
+ //
1197
+ // #1679 narrowed what counts as a trustworthy first answer: a directory whose
1198
+ // own newest transcript PREDATES the pin's construction can be a previous
1199
+ // run's session, so it is never latched, only followed — the tests below now
1200
+ // drive that distinction directly instead of assuming "the first non-null
1201
+ // answer" was always safe to cache.
1202
+ test("the pin does not latch a session that predates it — it keeps following the heuristic until one writes on its watch", () => {
1203
+ const home = mkdtempSync(join(tmpdir(), "spend-home-"));
1204
+ const proj = join(home, ".omp", "agent", "sessions", "-x");
1205
+ const mine = join(proj, "2026-09-08T13-13-27-300Z_aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa");
1206
+ const theirs = join(proj, "2026-09-09T02-00-00-000Z_bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb");
1207
+ mkdirSync(mine, { recursive: true });
1208
+ mkdirSync(theirs, { recursive: true });
1209
+ writeFileSync(join(mine, "agent-a.jsonl"), "");
1210
+ writeFileSync(join(theirs, "agent-b.jsonl"), "");
1211
+ // Both predate the pin below — stamped well in the past, the same as a
1212
+ // session that was already running before this server launched.
1213
+ utimesSync(join(mine, "agent-a.jsonl"), new Date(Date.now() - 100000), new Date(Date.now() - 100000));
1214
+ utimesSync(join(theirs, "agent-b.jsonl"), new Date(Date.now() - 200000), new Date(Date.now() - 200000));
1215
+
1216
+ const pin = spendDirPin(undefined, home, join(home, "x"));
1217
+ assert.equal(pin(), mine, "before anything writes on this pin's watch, it still answers from the heuristic's newest");
1218
+
1219
+ // `theirs` writes AFTER the pin exists — real activity "on my watch", the
1220
+ // one signal the old `??=` pin had no way to ask for.
1221
+ utimesSync(join(theirs, "agent-b.jsonl"), new Date(), new Date());
1222
+ assert.equal(pin(), theirs, "and re-picks, because neither candidate was trustworthy to cache yet");
1223
+
1224
+ // Now it must hold — touching `mine` again, even to a later mtime than
1225
+ // `theirs`, must not flip the pin back: `theirs` was the first to clear
1226
+ // the bar and that is what latches, not "whichever is newest this tick".
1227
+ utimesSync(join(mine, "agent-a.jsonl"), new Date(Date.now() + 50000), new Date(Date.now() + 50000));
1228
+ assert.equal(pin(), theirs, "and now holds, because theirs was first to write on this pin's watch");
1229
+ assert.equal(findSubagentsDir(home, join(home, "x")), mine, "the fixture really did flip — this test proves nothing otherwise");
1230
+ });
1231
+
1232
+ test("no session at launch is not an answer to pin — the first one to write on this pin's watch wins, and then holds", () => {
1233
+ // The launch path this script actually has: the cockpit starts in run-team
1234
+ // phase 0, BEFORE the first agent spawns, so the project directory routinely
1235
+ // holds no subagents directory at all. Pinning that `null` would hide the
1236
+ // spend panel for the entire run — the existing degradation is "hidden until
1237
+ // agents land", not "hidden for good", and this is the assertion that keeps
1238
+ // the pin from being written as "whatever the first call returned".
1239
+ const home = mkdtempSync(join(tmpdir(), "spend-home-"));
1240
+ const proj = join(home, ".omp", "agent", "sessions", "-x");
1241
+ mkdirSync(proj, { recursive: true });
1242
+ const pin = spendDirPin(undefined, home, join(home, "x"));
1243
+ assert.equal(pin(), null, "no session yet is the normal state at run start, not a fault");
1244
+
1245
+ const first = join(proj, "2026-09-08T13-13-27-300Z_11111111-aaaa-aaaa-aaaa-aaaaaaaaaaaa");
1246
+ mkdirSync(first, { recursive: true });
1247
+ // Written after the pin already exists — this run's own first activity,
1248
+ // not a stale fixture mtime from before launch. The mtime is SET, not left
1249
+ // to the write: Linux stamps it from the kernel's coarse clock, so a file
1250
+ // written right after spendDirPin() read Date.now() can carry an mtime
1251
+ // BEFORE that launchMs and never latch — measured 2026-09-23 in node:26 on
1252
+ // Linux, 2378/5000 writes stamped earlier than a Date.now() taken just
1253
+ // before them (the flake in CI runs 35834153934 and 35834344502).
1254
+ // utimesSync from a later Date.now() cannot land below launchMs.
1255
+ writeFileSync(join(first, "agent-a.jsonl"), "");
1256
+ utimesSync(join(first, "agent-a.jsonl"), new Date(), new Date());
1257
+ assert.equal(pin(), first, "the first real answer, once it postdates launch, latches");
1258
+
1259
+ const second = join(proj, "2026-09-09T02-00-00-000Z_22222222-bbbb-bbbb-bbbb-bbbbbbbbbbbb");
1260
+ mkdirSync(second, { recursive: true });
1261
+ writeFileSync(join(second, "agent-b.jsonl"), "");
1262
+ utimesSync(join(second, "agent-b.jsonl"), new Date(Date.now() + 50000), new Date(Date.now() + 50000));
1263
+ assert.equal(pin(), first, "and holds against a newer session exactly as a launch-time pin does");
1264
+ });
1265
+
1266
+ test("a transcript stamped a few ms before launchMs is followed, never latched — the pin latches on the first write at or after launchMs itself", (t) => {
1267
+ // #1729: every test above stamps mtimes far from launchMs — 100s before it,
1268
+ // or from a Date.now() taken after it (#1722) — so nothing pinned what
1269
+ // spendDirPin() does a few milliseconds either side of it. The window is
1270
+ // real: a transcript written just ahead of this server's launch lands
1271
+ // there, and so can one written just AFTER it, because Linux stamps mtimes
1272
+ // from the kernel's coarse clock (#1722 measured writes reading back
1273
+ // earlier than a Date.now() taken before them). The rule is a strict
1274
+ // `newest < launchMs` with no skew allowance: such a session is still
1275
+ // ANSWERED — the panel renders it that tick — but not cached, so it is
1276
+ // followed tick by tick and latches on its first write stamped at or
1277
+ // after launchMs, which a live session's next append provides.
1278
+ //
1279
+ // launchMs is one Date.now() read inside spendDirPin(), so the clock is
1280
+ // mocked for that read alone: launchMs becomes a known constant and every
1281
+ // stamp below is an exact offset from it, with no wall clock anywhere. The
1282
+ // stamp AT launchMs must read back as exactly launchMs — one that landed a
1283
+ // fraction above it would let a `<=` mutant through — so that is asserted
1284
+ // rather than trusted. Node 26 round-trips millisecond stamps exactly on
1285
+ // APFS and Linux overlayfs alike (measured, #1729); a whole second is a
1286
+ // free hedge, leaving no fractional part for a seconds conversion to lose.
1287
+ const launchMs = Date.UTC(2026, 0, 1);
1288
+ const stamp = (f, ms) => utimesSync(f, new Date(ms), new Date(ms));
1289
+ const home = mkdtempSync(join(tmpdir(), "spend-home-"));
1290
+ const proj = join(home, ".omp", "agent", "sessions", "-x");
1291
+ const mine = join(proj, "2026-09-08T13-13-27-300Z_aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa");
1292
+ const theirs = join(proj, "2026-09-09T02-00-00-000Z_bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb");
1293
+ mkdirSync(mine, { recursive: true });
1294
+ mkdirSync(theirs, { recursive: true });
1295
+ const mineLog = join(mine, "agent-a.jsonl");
1296
+ const theirsLog = join(theirs, "agent-b.jsonl");
1297
+ writeFileSync(mineLog, "");
1298
+ writeFileSync(theirsLog, "");
1299
+ stamp(mineLog, launchMs - 5);
1300
+ stamp(theirsLog, launchMs - 60000);
1301
+
1302
+ const clock = t.mock.method(Date, "now", () => launchMs);
1303
+ const pin = spendDirPin(undefined, home, join(home, "x"));
1304
+ clock.mock.restore();
1305
+
1306
+ assert.equal(pin(), mine, "5 ms before launch is still this tick's answer — the panel renders it");
1307
+
1308
+ // A second session overtakes it while still 1 ms short of launchMs. A pin
1309
+ // that had latched `mine` would ignore this; one that only followed it
1310
+ // re-picks, and re-picking at 1 ms is the proof there is no skew allowance
1311
+ // either — any tolerance of 1 ms or more would latch `theirs` right here.
1312
+ stamp(theirsLog, launchMs - 1);
1313
+ assert.equal(pin(), theirs, "and was never cached: a session 1 ms before launch takes the answer over");
1314
+
1315
+ // `mine` appends again, stamped exactly ON launchMs: "at or after" is the
1316
+ // latch condition, so this is the write that latches. It is also the
1317
+ // heuristic's newest, so this tick alone cannot tell latched from
1318
+ // followed — the next assertion is what does.
1319
+ stamp(mineLog, launchMs);
1320
+ assert.equal(statSync(mineLog).mtimeMs, launchMs, "the stamp sits exactly on launchMs — `<` vs `<=` is untested otherwise");
1321
+ assert.equal(pin(), mine, "the write at launchMs makes it the answer again");
1322
+
1323
+ stamp(theirsLog, launchMs + 50000);
1324
+ assert.equal(pin(), mine, "and holds against a newer session, which only a latch at launchMs itself explains");
1325
+ assert.equal(findSubagentsDir(home, join(home, "x")), theirs, "the fixture really did flip — this test proves nothing otherwise");
1326
+ });
1327
+
1328
+ test("an unresolvable transcript tree is never pinned — one stderr line across ticks either way, panel hidden and never zeroed", () => {
1329
+ // #1679: `{ error }` is no longer latched (see the recovery test below), so
1330
+ // the one-line-per-fault promise can no longer come from caching upstream —
1331
+ // it comes from gatherSpend's own warnOnce gate, keyed on the message,
1332
+ // which needs nothing cached above it to hold.
1333
+ const home = mkdtempSync(join(tmpdir(), "spend-home-"));
1334
+ const pin = spendDirPin(undefined, home, "/nonexistent");
1335
+
1336
+ let first, second;
1337
+ const errs = withStderr(() => {
1338
+ first = gatherSpend({ dir: pin() });
1339
+ second = gatherSpend({ dir: pin() });
1340
+ });
1341
+ assert.equal(errs.length, 1, "expected one line across two ticks, got " + JSON.stringify(errs));
1342
+ for (const s of [first, second]) {
1343
+ assert.equal(s.ok, false, "the tag the page hides on");
1344
+ assert.ok(s.error, "and a reason, never a zeroed total");
1345
+ assert.equal(s.totals, undefined, "an unresolvable directory must not report spend at all");
1346
+ }
1347
+ });
1348
+
1349
+ test("an unresolvable transcript tree recovers on its very next tick, because { error } is never latched", () => {
1350
+ // The bug #1679 fixed: the old `pinned ??= findSubagentsDir(...)` treated
1351
+ // `{ error }` as a permanent answer, so a TRANSIENT fault (EACCES on a
1352
+ // directory mid permission-change, EMFILE, EIO — not just the "project dir
1353
+ // absent" case the original comment reasoned about) hid the panel forever
1354
+ // even once the tree became readable again.
1355
+ const home = mkdtempSync(join(tmpdir(), "spend-home-"));
1356
+ const proj = join(home, ".omp", "agent", "sessions", "-x");
1357
+ const sess = join(proj, "2026-09-08T13-13-27-300Z_aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa");
1358
+ mkdirSync(sess, { recursive: true });
1359
+ writeFileSync(join(sess, "agent-a.jsonl"), "");
1360
+ chmodSync(proj, 0o000);
1361
+ try {
1362
+ const pin = spendDirPin(undefined, home, join(home, "x"));
1363
+ const faulted = pin();
1364
+ assert.ok(faulted.error, "a scandir EACCES is exactly the 'unresolvable' shape the old pin latched forever");
1365
+ chmodSync(proj, 0o755);
1366
+ assert.equal(pin(), sess, "the very next tick recovers, because the fault was never cached");
1367
+ } finally {
1368
+ chmodSync(proj, 0o755);
1369
+ }
1370
+ });
1371
+
1372
+ test("--spend-dir's directory replaces the heuristic outright, including one the heuristic could resolve", () => {
1373
+ // The override half of the flag: named explicitly, the session ranking is not
1374
+ // a tie-breaker, a fallback, or a second opinion. The fixture gives the
1375
+ // heuristic a perfectly resolvable session to pick so that "the explicit one
1376
+ // wins" is a real preference and not the absence of an alternative.
1377
+ const home = mkdtempSync(join(tmpdir(), "spend-home-"));
1378
+ const heuristic = join(home, ".omp", "agent", "sessions", "-x", "2026-09-08T13-13-27-300Z_aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa");
1379
+ mkdirSync(heuristic, { recursive: true });
1380
+ writeFileSync(join(heuristic, "agent-a.jsonl"), "");
1381
+ const named = mkdtempSync(join(tmpdir(), "spend-named-"));
1382
+
1383
+ assert.equal(findSubagentsDir(home, join(home, "x")), heuristic, "the heuristic has an answer of its own here");
1384
+ const pin = spendDirPin(named, home, join(home, "x"));
1385
+ assert.equal(pin(), named);
1386
+ assert.equal(pin(), named, "and is not re-decided on a later tick either");
1387
+ });
1388
+
1389
+ test("gatherSpend reads a handed-in null as a resolution, not as an absent argument", () => {
1390
+ // `dir ?? findSubagentsDir()` could not tell "my caller resolved this and
1391
+ // there is no session yet" from "nobody resolved it", so a pinned null ran
1392
+ // the lookup a second time inside the same tick — and answered from it,
1393
+ // which is the unpinned source this ticket exists to remove. The fixture
1394
+ // makes that observable: $HOME here DOES hold a resolvable session, so a
1395
+ // re-resolve would return a panel instead of nothing.
1396
+ const home = mkdtempSync(join(tmpdir(), "spend-home-"));
1397
+ const live = join(home, ".omp", "agent", "sessions", encodeProjectDir(process.cwd(), { home }), "2026-09-08T13-13-27-300Z_aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa");
1398
+ mkdirSync(live, { recursive: true });
1399
+ writeFileSync(join(live, "agent-x.jsonl"), TURN.map((l) => JSON.stringify(l)).join("\n") + "\n");
1400
+ const realHome = process.env.HOME;
1401
+ process.env.HOME = home;
1402
+ try {
1403
+ assert.ok(gatherSpend({}).ok, "the control: with no dir argument at all, that session IS found");
1404
+ assert.equal(gatherSpend({ dir: null }), null, "a resolved-to-nothing caller must not be re-resolved");
1405
+ } finally { process.env.HOME = realHome; }
1406
+ });
1407
+
1408
+ // The acceptance criterion end to end, and the only row here that can fail on
1409
+ // serve() dropping the pin between the resolution and the tick: every
1410
+ // assertion above is reachable with `spendDir:` never threaded into gather()
1411
+ // at all. A REAL server, two sessions under one project directory, and the
1412
+ // second one writing between two ticks — the exact shape the panel used to
1413
+ // alternate on, at the interval it used to alternate at.
1414
+ //
1415
+ // #1679: both fixture sessions predate the server's own launch (ancient
1416
+ // synthetic mtimes), the same shape as a workspace that already had
1417
+ // unrelated sessions sitting there when this `serve` started — neither is
1418
+ // trustworthy to latch on sight any more. So the session that WRITES first
1419
+ // ON THIS SERVER'S WATCH is what latches, not whichever the heuristic
1420
+ // happened to already prefer between two equally-untrusted candidates.
1421
+ test("CLI: a live serve keeps the panel on the session that wrote first on its watch, even as another writes later", async () => {
1422
+ // realpath, not the bare mkdtemp path: on darwin $TMPDIR is under /var, a
1423
+ // symlink to /private/var, and the child's process.cwd() reports the RESOLVED
1424
+ // form — encoding the unresolved one puts the fixture where nothing looks.
1425
+ const cwd = realpathSync(mkdtempSync(join(tmpdir(), "spend-pin-cwd-")));
1426
+ const home = mkdtempSync(join(tmpdir(), "spend-pin-home-"));
1427
+ const bin = mkdtempSync(join(tmpdir(), "spend-pin-bin-"));
1428
+ // gh fails on every call and the reads degrade, so this stays offline and off
1429
+ // this repo's live issue list. Prepended rather than replacing PATH: gather()
1430
+ // shells out to `node` for the ledger read.
1431
+ writeFileSync(join(bin, "gh"), "#!/bin/sh\nexit 1\n");
1432
+ chmodSync(join(bin, "gh"), 0o755);
1433
+ const proj = join(home, ".omp", "agent", "sessions", encodeProjectDir(cwd, { home }));
1434
+ const mine = join(proj, "2026-09-08T13-13-27-300Z_aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa");
1435
+ const theirs = join(proj, "2026-09-09T02-00-00-000Z_bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb");
1436
+ mkdirSync(mine, { recursive: true });
1437
+ mkdirSync(theirs, { recursive: true });
1438
+ // With no sidecar the panel labels an agent by its filename stem, so the
1439
+ // board itself names which session it read — no second fixture needed for it.
1440
+ const turn = TURN.map((l) => JSON.stringify(l)).join("\n") + "\n";
1441
+ writeFileSync(join(mine, "session-a.jsonl"), turn);
1442
+ utimesSync(join(mine, "session-a.jsonl"), new Date(9000), new Date(9000));
1443
+ writeFileSync(join(theirs, "session-b.jsonl"), turn);
1444
+ utimesSync(join(theirs, "session-b.jsonl"), new Date(1000), new Date(1000));
1445
+
1446
+ const p = spawn(process.execPath, serveArgs(["--port", "0", "--interval", "1"]), {
1447
+ cwd, stdio: ["ignore", "ignore", "pipe"],
1448
+ env: { ...process.env, HOME: home, PATH: `${bin}:${process.env.PATH}` },
1449
+ });
1450
+ try {
1451
+ const jsonPath = join(cwd, ".fleet", "board.json");
1452
+ const until = (pred, what) => withTimeout((async () => {
1453
+ for (;;) {
1454
+ let b = null;
1455
+ try { b = JSON.parse(readFileSync(jsonPath, "utf8")); } catch { /* not written yet, or mid-rename */ }
1456
+ if (b && pred(b)) return b;
1457
+ await new Promise((r) => setTimeout(r, 50));
1458
+ }
1459
+ })(), 20000, what);
1460
+
1461
+ // Wait for the server to have ticked at least once before touching either
1462
+ // fixture's mtime — this pins spendDirPin()'s launchMs strictly before the
1463
+ // touch below, which is the only way the touch can land ON its watch.
1464
+ await until((b) => b.spend?.ok, "the first tick that reads a transcript");
1465
+
1466
+ // `mine` writes on this server's watch: this is what latches it, per
1467
+ // #1679's rule — not merely being the heuristic's current favorite.
1468
+ utimesSync(join(mine, "session-a.jsonl"), new Date(), new Date());
1469
+ const minedAt = Date.now();
1470
+ const first = await until((b) => b.spend?.ok && b.generatedAt > minedAt, "a tick generated after session-a writes on this server's watch");
1471
+ assert.equal(first.spend.top[0].label, "session-a", "the session that wrote on this server's watch is read");
1472
+
1473
+ // The other session writes later: a second run starting, an agent landing.
1474
+ utimesSync(join(theirs, "session-b.jsonl"), new Date(), new Date());
1475
+ const flippedAt = Date.now();
1476
+ assert.equal(findSubagentsDir(home, cwd), theirs,
1477
+ "the fixture no longer flips the heuristic — this test would prove nothing");
1478
+
1479
+ // Strictly a board GENERATED after the flip, not merely a different one: a
1480
+ // tick that started before it could answer "session-a" for the old reason.
1481
+ const later = await until((b) => b.spend?.ok && b.generatedAt > flippedAt, "a tick generated after the flip");
1482
+ assert.equal(later.spend.top[0].label, "session-a",
1483
+ "a later tick re-picked the newest session instead of answering from the pin");
1484
+ } finally { p.kill("SIGKILL"); }
1485
+ });
1486
+
1487
+ test("one unreadable transcript does not take the whole panel down", () => {
1488
+ const dir = fixture(TURN);
1489
+ mkdirSync(join(dir, "agent-trap.jsonl")); // a directory where a file is expected
1490
+ const s = gatherSpend({ dir });
1491
+ assert.equal(s.totals.cacheWrite, 1000); // the good agent still counted
1492
+ assert.equal(s.skipped, 1);
1493
+ });
1494
+
1495
+ // One assistant turn, the omp envelope's own shape (member-record.mjs's
1496
+ // foldOmpTranscript comment): one usage object per turn, no fold-back needed.
1497
+ const TURN = [
1498
+ { type: "session", version: 3, id: "s1", timestamp: "2026-09-08T15:11:49.444Z", cwd: "/w" },
1499
+ { type: "message", id: "m1", parentId: "s1", timestamp: "2026-09-08T15:12:00.000Z",
1500
+ message: { role: "assistant", content: [{ type: "text", text: "ok" }], model: "claude-opus-5",
1501
+ usage: { input: 2, output: 1, cacheRead: 50, cacheWrite: 1000, totalTokens: 0, cost: { total: 0.01 } } } },
1502
+ ];
1503
+
1504
+ function fixture(lines) {
1505
+ const dir = mkdtempSync(join(tmpdir(), "spend-"));
1506
+ writeFileSync(join(dir, "agent-x.jsonl"), lines.map((l) => JSON.stringify(l)).join("\n") + "\n");
1507
+ return dir;
1508
+ }
1509
+
1510
+ // A pair of tool calls, each its own assistant turn (omp's envelope has no
1511
+ // notion of "one turn split across several lines" — every JSONL line is
1512
+ // already a complete, self-contained turn), followed by their results and a
1513
+ // billing turn. Regression: summing usage across turns inflated totals; the
1514
+ // tell was the panel disagreeing with itself — by-role total 4.2x the
1515
+ // by-tool total, both claiming to be the same number.
1516
+ const TOOL_TURNS = [
1517
+ { type: "session", version: 3, id: "s1", timestamp: "2026-09-08T15:11:49.444Z", cwd: "/w" },
1518
+ { type: "message", id: "m1", parentId: "s1", timestamp: "2026-09-08T15:11:59.000Z",
1519
+ message: { role: "assistant", stopReason: "toolUse", content: [{ type: "toolCall", id: "t1", name: "Bash", arguments: {}, intent: "x" }],
1520
+ model: "claude-opus-5", usage: { input: 1, output: 1, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { total: 0 } } } },
1521
+ { type: "message", id: "m2", parentId: "m1", timestamp: "2026-09-08T15:11:59.100Z",
1522
+ message: { role: "assistant", stopReason: "toolUse", content: [{ type: "toolCall", id: "t2", name: "Read", arguments: {}, intent: "x" }],
1523
+ model: "claude-opus-5", usage: { input: 1, output: 1, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { total: 0 } } } },
1524
+ ];
1525
+
1526
+ test("tool calls across a session's turns are all counted", () => {
1527
+ const s = gatherSpend({ dir: fixture(TOOL_TURNS) });
1528
+ const by = Object.fromEntries(s.tools.map((t) => [t.tool, t.calls]));
1529
+ assert.equal(by.Bash, 1);
1530
+ assert.equal(by.Read, 1);
1531
+ });
1532
+
1533
+ test("by-tool attribution never exceeds the cache_creation it is a share of", () => {
1534
+ // The invariant the double-count broke: both panels are views of one number.
1535
+ const s = gatherSpend({
1536
+ dir: fixture([
1537
+ ...TOOL_TURNS,
1538
+ { type: "message", id: "m3", parentId: "m2", timestamp: "2026-09-08T15:11:59.500Z",
1539
+ message: { role: "toolResult", toolCallId: "t1", toolName: "Bash", content: [{ type: "text", text: "x".repeat(300) }], details: {}, isError: false, timestamp: 0 } },
1540
+ { type: "message", id: "m4", parentId: "m3", timestamp: "2026-09-08T15:11:59.600Z",
1541
+ message: { role: "toolResult", toolCallId: "t2", toolName: "Read", content: [{ type: "text", text: "x".repeat(100) }], details: {}, isError: false, timestamp: 0 } },
1542
+ { type: "message", id: "m5", parentId: "m4", timestamp: "2026-09-08T15:12:00.000Z",
1543
+ message: { role: "assistant", content: [{ type: "text", text: "ok" }], model: "claude-opus-5",
1544
+ usage: { input: 0, output: 5, cacheRead: 0, cacheWrite: 400, totalTokens: 0, cost: { total: 0.01 } } } },
1545
+ ]),
1546
+ });
1547
+ const toolTotal = s.tools.reduce((n, t) => n + t.cacheWrite, 0);
1548
+ assert.ok(toolTotal <= s.totals.cacheWrite, `${toolTotal} > ${s.totals.cacheWrite}`);
1549
+ // The two consecutive result turns both get attributed, 300:100 of the 400.
1550
+ const by = Object.fromEntries(s.tools.map((t) => [t.tool, t.cacheWrite]));
1551
+ assert.equal(by.Bash, 300);
1552
+ assert.equal(by.Read, 100);
1553
+ });
1554
+
1555
+ test("a toolResult whose content is a STRING does not throw", () => {
1556
+ // The trap that once turned into a silently absent panel via the outer catch.
1557
+ const s = gatherSpend({
1558
+ dir: fixture([
1559
+ ...TOOL_TURNS,
1560
+ { type: "message", id: "m3", parentId: "m2", timestamp: "2026-09-08T15:11:59.500Z",
1561
+ message: { role: "toolResult", toolCallId: "t1", toolName: "Bash", content: "plain prose, not an array", details: {}, isError: false, timestamp: 0 } },
1562
+ ...TURN,
1563
+ ]),
1564
+ });
1565
+ assert.equal(s.totals.cacheWrite, 1000);
1566
+ });
1567
+
1568
+ // gatherSpend reports through stderr, so read console.error rather than spawning
1569
+ // the CLI — the transcript tree the CLI resolves lives under $HOME, and these
1570
+ // fixtures do not.
1571
+ function withStderr(fn) {
1572
+ const lines = [];
1573
+ const real = console.error;
1574
+ console.error = (...a) => lines.push(a.join(" "));
1575
+ try { fn(); } finally { console.error = real; }
1576
+ return lines;
1577
+ }
1578
+
1579
+ function rawFixture(text) {
1580
+ const dir = mkdtempSync(join(tmpdir(), "spend-"));
1581
+ writeFileSync(join(dir, "agent-x.jsonl"), text);
1582
+ return dir;
1583
+ }
1584
+ const oneLineTurn = (id, cw) => JSON.stringify({
1585
+ type: "message", id, parentId: "s1", timestamp: "2026-09-08T15:12:00.000Z",
1586
+ message: { role: "assistant", content: [{ type: "text", text: "ok" }], model: "claude-opus-5",
1587
+ usage: { input: 0, output: 7, cacheRead: 0, cacheWrite: cw, totalTokens: 0, cost: { total: 0 } } },
1588
+ });
1589
+ const TORN = '{"type":"message","message":{"role":"ass';
1590
+ // Hoisted rather than spelled out at each use: several tests below feed the
1591
+ // SAME mid-file tear, each checking a different fact about it (the count
1592
+ // itself, the sum across sibling transcripts, the count beside an unrelated
1593
+ // skip). Spelled out per site, one can be edited and the others stay green —
1594
+ // measured, the whole suite passes with the copies drifted apart.
1595
+ const MIDFILE_TEAR = [oneLineTurn("m_a", 1000), TORN, oneLineTurn("m_c", 500)].join("\n") + "\n";
1596
+
1597
+ test("a torn LAST line stays silent — the tear every tick legitimately produces", () => {
1598
+ // The false-positive half, and the reason the discriminator has to exist at
1599
+ // all: `serve` rebuilds every ~15s, so warning per bad line would print a
1600
+ // line every tick for every transcript still being appended to. No trailing
1601
+ // newline — the torn write is the final element of the split.
1602
+ const dir = rawFixture([oneLineTurn("m_a", 1000), TORN].join("\n"));
1603
+ let s;
1604
+ const errs = withStderr(() => { s = gatherSpend({ dir }); });
1605
+ assert.deepEqual(errs, []);
1606
+ // ...and everything before the tear still parsed.
1607
+ assert.equal(s.totals.cacheWrite, 1000);
1608
+ });
1609
+
1610
+ // #1654: every test above this one holds the `skips` gate's KEY and its
1611
+ // MESSAGE on the same transcript, in the same directory, so a mutation that
1612
+ // keys `warnOnce("skips", ...)` on the bare basename (`f`) instead of the
1613
+ // full path (`file`) — leaving the message's `${file}` untouched — passes
1614
+ // every one of them: the message still names the right file, and nothing
1615
+ // above ever gives two DIFFERENT full paths the SAME basename. It is exactly
1616
+ // the shape a long-lived `serve` process hits in practice: findSubagentsDir()
1617
+ // re-resolves to a new session directory as fleet runs start and finish, and
1618
+ // two sessions whose agents both land on a generic transcript name (here
1619
+ // "agent-x.jsonl", same as every fixture above) are a basename collision
1620
+ // waiting to happen. Measured: with the key narrowed from `file` to `f`,
1621
+ // this is the only test in the file that fails — dir B's line never prints,
1622
+ // because dir A's identical-basename skip already claimed the (mutated) key.
1623
+ test("two session dirs whose transcripts share a basename each get their own skip line", () => {
1624
+ const dirA = mkdtempSync(join(tmpdir(), "spend-collide-a-"));
1625
+ const dirB = mkdtempSync(join(tmpdir(), "spend-collide-b-"));
1626
+ mkdirSync(join(dirA, "agent-x.jsonl")); // directory where a file is expected -> EISDIR, unreadable
1627
+ mkdirSync(join(dirB, "agent-x.jsonl")); // same basename, different session dir
1628
+ const errs = withStderr(() => {
1629
+ gatherSpend({ dir: dirA });
1630
+ gatherSpend({ dir: dirB });
1631
+ });
1632
+ assert.equal(errs.length, 2, "expected one skip line per directory, got " + JSON.stringify(errs));
1633
+ assert.equal(errs.filter((e) => e.includes(dirA)).length, 1, "dir A's own path must appear, got " + JSON.stringify(errs));
1634
+ assert.equal(errs.filter((e) => e.includes(dirB)).length, 1, "dir B's own path must appear, got " + JSON.stringify(errs));
1635
+ });
1636
+
1637
+ test("#916: a damaged mid-file line reaches the MODEL as a count, not stderr alone", () => {
1638
+ // #916: a damaged mid-file line has no STDERR line at all — readOmpSpend
1639
+ // never warns per damaged line, only per whole-unreadable transcript — so
1640
+ // stderr is the one channel board.html twice says it does not have: the
1641
+ // board is launched backgrounded and the operator is watching the page,
1642
+ // which is the argument that put `skipped` in the DOM and then
1643
+ // `metaErrors` (#602) beside it. Measured on the tree before this fix,
1644
+ // MIDFILE_TEAR: gatherSpend returned
1645
+ // totals,roles,top,reviewPct,tools,attributedPct,skipped,metaErrors,since,ok
1646
+ // — `skipped` 0, `metaErrors` 0, `error` undefined, no field naming the
1647
+ // damage — and spendView's whole decision came back BYTE-FOR-BYTE
1648
+ // identical to the intact run's, 1500 cache-write rendered with the same
1649
+ // note as 1800. `damaged` is this fault's channel, counted the same way
1650
+ // and reaching the browser by the same route.
1651
+ const dir = rawFixture(MIDFILE_TEAR);
1652
+ let s;
1653
+ withStderr(() => { s = gatherSpend({ dir }); });
1654
+ assert.equal(s.damaged, 1);
1655
+ // Distinct from `skipped`, which is why it is its own field: this
1656
+ // transcript CONTRIBUTED, so `skipped` (which means "contributed
1657
+ // nothing") may not carry it. Folding the count into it passes without
1658
+ // this test.
1659
+ assert.equal(s.skipped, 0);
1660
+ });
1661
+
1662
+ test("#916: several damaged lines in one transcript count as several, not as one", () => {
1663
+ // The shape that separates a count from a flag — a boolean promoted to
1664
+ // `damaged: 1` satisfies every other case in this block. The magnitude is the
1665
+ // reason the field exists rather than a `damaged: true`: the stderr gate fires
1666
+ // once per PATH, so before this the second tear was invisible on that channel
1667
+ // too (measured: two tears in one file, one line, no number anywhere).
1668
+ const dir = rawFixture([oneLineTurn("m_a", 1000), TORN, TORN, oneLineTurn("m_c", 500)].join("\n") + "\n");
1669
+ let s;
1670
+ withStderr(() => { s = gatherSpend({ dir }); });
1671
+ assert.equal(s.damaged, 2);
1672
+ });
1673
+
1674
+ test("#916: damaged lines sum across transcripts, the way skipped does", () => {
1675
+ // The panel's counts are per-TICK totals over the whole session dir, never
1676
+ // per-file: an assignment instead of a sum reads 2 here (the last file's own
1677
+ // count) and stays green on every single-transcript case above.
1678
+ const dir = rawFixture(MIDFILE_TEAR);
1679
+ writeFileSync(join(dir, "agent-y.jsonl"),
1680
+ [oneLineTurn("m_d", 100), TORN, TORN, oneLineTurn("m_e", 200)].join("\n") + "\n");
1681
+ let s;
1682
+ withStderr(() => { s = gatherSpend({ dir }); });
1683
+ assert.equal(s.damaged, 3);
1684
+ });
1685
+
1686
+ test("#916: a torn LAST line counts as no damage — the false-positive half", () => {
1687
+ // Silence on stderr was never the whole contract: the tear every tick
1688
+ // legitimately produces must not inflate the tally either, or every
1689
+ // transcript still being appended to parks a permanent "spend
1690
+ // under-reported" note on the panel and the note stops meaning anything.
1691
+ const dir = rawFixture([oneLineTurn("m_a", 1000), TORN].join("\n"));
1692
+ let s;
1693
+ assert.deepEqual(withStderr(() => { s = gatherSpend({ dir }); }), []);
1694
+ assert.equal(s.damaged, 0);
1695
+ });
1696
+
1697
+ test("#916: a mid-file tear and a torn tail in ONE file count only the mid-file one", () => {
1698
+ // The position boundary, re-drawn now that the answer is a number rather than
1699
+ // a flag: the two tests above hold one tear per file, so each is satisfied by
1700
+ // a count that has dropped the `i !== lines.length - 1` discriminator
1701
+ // entirely — one file carrying BOTH tears is the only shape that reads 2
1702
+ // under that mutation. No trailing newline, so the last TORN is genuinely the
1703
+ // final element of the split.
1704
+ const dir = rawFixture([oneLineTurn("m_a", 1000), TORN, oneLineTurn("m_c", 500), TORN].join("\n"));
1705
+ let s;
1706
+ withStderr(() => { s = gatherSpend({ dir }); });
1707
+ assert.equal(s.damaged, 1);
1708
+ assert.equal(s.totals.cacheWrite, 1500);
1709
+ });
1710
+
1711
+ test("#916: a damaged transcript beside an unreadable one reports both tallies", () => {
1712
+ // Two different faults in one tick, and the panel names them separately. Also
1713
+ // the invariant the increment's PLACEMENT carries: `damaged` is summed
1714
+ // past the throw-capable work and before the agent is pushed,
1715
+ // so a transcript that ends up `skipped` — "contributed nothing" — can never
1716
+ // also report damaged lines. Incrementing inside the per-file catch, or
1717
+ // hoisting the sum above attributeTools, breaks that and reds here.
1718
+ // Directory-where-a-file-is-expected for EISDIR, as above.
1719
+ const dir = rawFixture(MIDFILE_TEAR);
1720
+ mkdirSync(join(dir, "agent-y.jsonl"));
1721
+ let s;
1722
+ withStderr(() => { s = gatherSpend({ dir }); });
1723
+ assert.equal(s.damaged, 1);
1724
+ assert.equal(s.skipped, 1);
1725
+ });
1726
+
1727
+ // Repeat calls with the SAME dir object must stay quiet: gatherSpend being
1728
+ // called again on an unchanged fault is not a new fault. The test below this
1729
+ // one covers the complementary axis — two calls with DIFFERENT `dir.error`
1730
+ // values must both reach stderr, which only a message-keyed gate (not a
1731
+ // channel-keyed or empty-keyed one) can tell apart from this one.
1732
+ test("the no-spend-dir gate warns once per distinct fault, not once per tick", () => {
1733
+ const dir = { error: "no session directory under ~/.omp/agent/sessions for this cwd" };
1734
+ assert.equal(withStderr(() => gatherSpend({ dir })).length, 1, "tick 1 reports");
1735
+ assert.deepEqual(withStderr(() => gatherSpend({ dir })), [], "tick 2 stays quiet");
1736
+ });
1737
+
1738
+ // #1190: the gate used to key on the empty string, so its composite key was
1739
+ // the constant `no-spend-dir\0` regardless of `dir.error`'s text. The FIRST
1740
+ // spend-dir fault in a process consumed that slot, and a later fault with a
1741
+ // genuinely different message never reached stderr for the rest of the run.
1742
+ // The test above binds one `dir` object and calls twice, which discriminates
1743
+ // once-per-process from once-per-tick but is silent on this axis — both the
1744
+ // empty key and a message key pass it. This one calls with two DIFFERENT
1745
+ // `dir.error` values, which only a message key can tell apart.
1746
+ test("the no-spend-dir gate keys on the message, so a second, different fault also reaches stderr", () => {
1747
+ const a = { error: "no transcript dir for cwd /tmp/impl-1190-a (looked in /tmp/impl-1190-a/.omp/agent/sessions/x)" };
1748
+ const b = { error: "transcript lookup failed: EACCES: permission denied, scandir '/tmp/impl-1190-b'" };
1749
+ const first = withStderr(() => gatherSpend({ dir: a }));
1750
+ assert.equal(first.length, 1, "first fault reports");
1751
+ assert.match(first[0], /looked in \/tmp\/impl-1190-a/, "first fault's own message reaches stderr");
1752
+ const second = withStderr(() => gatherSpend({ dir: b }));
1753
+ assert.equal(second.length, 1, "second, different fault also reports");
1754
+ assert.match(second[0], /EACCES: permission denied/, "second fault's own message reaches stderr");
1755
+ // Steady state is unchanged: the SAME fault repeating still costs one line
1756
+ // per process, not one per tick.
1757
+ assert.deepEqual(withStderr(() => gatherSpend({ dir: a })), [], "repeating the first fault stays quiet");
1758
+ assert.deepEqual(withStderr(() => gatherSpend({ dir: b })), [], "repeating the second fault stays quiet");
1759
+ });
1760
+
1761
+ test("an unreadable dir reports an error rather than posing as an empty run", () => {
1762
+ // The distinction that hid the path bug: a hidden panel meant both "nothing
1763
+ // yet" and "this is broken", so the broken case never surfaced.
1764
+ const s = gatherSpend({ dir: join(tmpdir(), "definitely-not-here-12345") });
1765
+ assert.ok(s.error, "expected an error object, got " + JSON.stringify(s));
1766
+ // The TAG, not the message: the page routes on `ok` alone (#959), so a
1767
+ // producer that stops emitting it hides the panel no matter what `error` says.
1768
+ assert.equal(s.ok, false);
1769
+ });
1770
+
1771
+ test("every gatherSpend return carries the tag the page routes on (#959)", () => {
1772
+ // One test over all four returns, because the defect was a MISSING tag on one
1773
+ // of them, and a per-return test is what leaves the next one untagged.
1774
+ // The unresolvable-dir return.
1775
+ assert.equal(gatherSpend({ dir: { error: "no session directory for this cwd" } }).ok, false);
1776
+ // The all-unreadable return: a dir holding only a transcript that cannot be read.
1777
+ const allBad = mkdtempSync(join(tmpdir(), "spend-"));
1778
+ mkdirSync(join(allBad, "agent-trap.jsonl")); // a directory where a file is expected
1779
+ let bad;
1780
+ withStderr(() => { bad = gatherSpend({ dir: allBad }); }); // it warns; the warning is not what is under test
1781
+ assert.equal(bad.ok, false);
1782
+ assert.match(bad.error, /all 1 transcripts unreadable/);
1783
+ // The success return.
1784
+ assert.equal(gatherSpend({ dir: fixture(TURN) }).ok, true);
1785
+ // And the one return that is deliberately NOT an object: nothing yet.
1786
+ assert.equal(gatherSpend({ dir: mkdtempSync(join(tmpdir(), "spend-")) }), null);
1787
+ });
1788
+
1789
+ // #169: `arg()` is CLI-internal (not exported), so this pins the trailing-flag
1790
+ // refusal at the process boundary. `ledger`/`prev`/`spend-since`/`port`/
1791
+ // `interval` all read via `arg(n) || default` or `?? `, so a trailing flag
1792
+ // previously fell straight through to the default in total silence —
1793
+ // `--spend-since` with nothing after it silently widened the spend panel to
1794
+ // all-time; `--ledger` with nothing after it silently read the wrong file.
1795
+ // Dies before any gh call, so no PATH stub is needed here.
1796
+ test("CLI: trailing --ledger (no value) dies (exit 2) rather than silently falling back to the default ledger", () => {
1797
+ const r = spawnSync(process.execPath, [SCRIPT, "build", "--ledger"], { encoding: "utf8" });
1798
+ assert.equal(r.status, 2);
1799
+ assert.match(r.stderr, /--ledger needs a value/);
1800
+ });
1801
+
1802
+ test("CLI: --ledger=path form dies by name, not silently read as absent", () => {
1803
+ const r = spawnSync(process.execPath, [SCRIPT, "build", "--ledger=/tmp/x"], { encoding: "utf8" });
1804
+ assert.equal(r.status, 2);
1805
+ assert.match(r.stderr, /--ledger needs a space-separated value/);
1806
+ });
1807
+
1808
+ // The other two branches of the same guard, neither of which the tests above
1809
+ // reach: a flag eating the NEXT FLAG as its value (mutating away
1810
+ // `value.startsWith("--")` left board/ci-state/diff-stats 100% green), and an
1811
+ // explicit empty/whitespace value (`value.trim() === ""` was unpinned in all
1812
+ // five scripts that then carried it — board, candidates, ci-state, diff-stats,
1813
+ // pr-overlap — simultaneously). Both die before any gh call.
1814
+ test("CLI: --ledger followed by another flag is rejected, not read as the string \"--prev\"", () => {
1815
+ const r = spawnSync(process.execPath, [SCRIPT, "build", "--ledger", "--prev", "x"], { encoding: "utf8" });
1816
+ assert.equal(r.status, 2);
1817
+ assert.match(r.stderr, /--ledger needs a value/);
1818
+ });
1819
+
1820
+ // #463 fallout, and the one ordering nothing else pins: `--ledger` is read
1821
+ // above stray() and always was, so none of the cases above reaches the new
1822
+ // guard at all. `--prev` is read once, ahead of BOTH branches' stray() calls
1823
+ // (hoisted by #1092 — see main()) — with the read moved back below either
1824
+ // stray() call, this invocation refuses with `unexpected argument '9000'`,
1825
+ // naming --port's innocent value instead of the flag actually given wrong
1826
+ // (measured). Moving the read back below stray() is what this reds on.
1827
+ test("CLI: trailing --prev names --prev, not the innocent value of the flag behind it", () => {
1828
+ const r = spawnSync(process.execPath, [SCRIPT, "build", "--prev", "--port", "9000"], { encoding: "utf8" });
1829
+ assert.equal(r.status, 2);
1830
+ assert.match(r.stderr, /--prev needs a value/);
1831
+ });
1832
+
1833
+ // #1092: unlike the case above, `--prev` was not merely ORDERED wrong on one
1834
+ // subcommand — it was never read on `serve` at all. serve()'s own signature
1835
+ // (`{ ledgerFile, port, interval, open }`) carries no `prev` parameter, and
1836
+ // main()'s `serve` branch called only `stray()`, so a trailing `--prev` on
1837
+ // `serve` never reached ANY guard: measured, pre-fix, `serve --prev` and
1838
+ // `serve --prev=x` both fell straight through to gather()'s first `gh` call
1839
+ // (a real network attempt, not a refusal), and `serve --prev --port 9000`
1840
+ // refused with `unexpected argument '9000'` once stray() got to it — naming
1841
+ // --port's innocent value rather than the flag actually given wrong, the
1842
+ // exact harm the build-side pin above exists for. Hoisting `arg("prev")`
1843
+ // above the dispatch (next to argPort()/has("open")) closes all three: every
1844
+ // case below now dies inside main(), before `serve()` is ever called, so
1845
+ // none of these needs board-cli.test.mjs's gh-stub/PATH rig — same as the
1846
+ // build-side cases above and the --port/--open hoist cases below.
1847
+ test("CLI: serve refuses a trailing --prev (no value), same message as build", () => {
1848
+ const r = spawnSync(process.execPath, [SCRIPT, "serve", "--prev"], { encoding: "utf8" });
1849
+ assert.equal(r.status, 2, r.stderr);
1850
+ assert.match(r.stderr, /--prev needs a value/);
1851
+ });
1852
+
1853
+ test("CLI: serve refuses --prev=x, the same shape --ledger=path is refused", () => {
1854
+ const r = spawnSync(process.execPath, [SCRIPT, "serve", "--prev=x"], { encoding: "utf8" });
1855
+ assert.equal(r.status, 2, r.stderr);
1856
+ assert.match(r.stderr, /--prev needs a space-separated value, not --prev=/);
1857
+ });
1858
+
1859
+ test("CLI: serve refuses --prev --port 9000, naming --prev not --port's innocent value", () => {
1860
+ const r = spawnSync(process.execPath, [SCRIPT, "serve", "--prev", "--port", "9000"], { encoding: "utf8" });
1861
+ assert.equal(r.status, 2, r.stderr);
1862
+ assert.match(r.stderr, /--prev needs a value/);
1863
+ });
1864
+
1865
+ // #1092: the --prev-before-argPort() ordering pinned above (`serve --prev
1866
+ // --port 9000`) only exercises --prev going wrong while --port's value is
1867
+ // well-formed — it never exercises BOTH flags malformed at once, which is
1868
+ // the actual case the hoist comment above `arg("prev")` in main() claims to
1869
+ // handle ("a caller who gets BOTH flags wrong at once ... still hears about
1870
+ // --prev specifically"). With `arg("prev")` read before argPort() in the
1871
+ // hoist (as it is), a trailing --port immediately followed by a trailing
1872
+ // --prev — neither given a value — refuses on --prev, since --prev's read
1873
+ // runs first and sweep() never reaches --port's dangling flag. Swap the
1874
+ // hoist order (argPort() ahead of `arg("prev")`) and this reds: the error
1875
+ // names --port instead (measured).
1876
+ test("CLI: build refuses --port --prev with both flags trailing, naming --prev not --port", () => {
1877
+ const r = spawnSync(process.execPath, [SCRIPT, "build", "--port", "--prev"], { encoding: "utf8" });
1878
+ assert.equal(r.status, 2, r.stderr);
1879
+ assert.match(r.stderr, /--prev needs a value/);
1880
+ });
1881
+
1882
+ test("CLI: --ledger given an empty value dies rather than falling back to the default ledger", () => {
1883
+ const r = spawnSync(process.execPath, [SCRIPT, "build", "--ledger", ""], { encoding: "utf8" });
1884
+ assert.equal(r.status, 2);
1885
+ assert.match(r.stderr, /--ledger needs a value/);
1886
+ });
1887
+
1888
+ // #468: argPort()/has("open") used to run only inside serve(), so build never
1889
+ // evaluated them — `build --port abc` and `build --open=1` were silently
1890
+ // IGNORED at exit 0 rather than refused, the one silent-default shape
1891
+ // ledger/prev/spend-since/interval (pinned above and in board-cli.test.mjs)
1892
+ // did not share. main() now calls both once, ahead of the build/serve
1893
+ // dispatch, so these refuse on build too, with the exact wording serve
1894
+ // already refuses them with. All three die before gather()'s first gh read
1895
+ // (the guard moved above the dispatch, not just above serve()'s own call),
1896
+ // so — like the --ledger/--prev cases above — none of these need the gh-stub
1897
+ // rig board-cli.test.mjs carries for the guards that fire mid-gather().
1898
+ test("CLI: build refuses a trailing --port, same message as serve", () => {
1899
+ const r = spawnSync(process.execPath, [SCRIPT, "build", "--port"], { encoding: "utf8" });
1900
+ assert.equal(r.status, 2, r.stderr);
1901
+ assert.match(r.stderr, /--port needs a value/);
1902
+ });
1903
+
1904
+ test("CLI: build refuses a non-numeric --port, same message as serve", () => {
1905
+ const r = spawnSync(process.execPath, [SCRIPT, "build", "--port", "abc"], { encoding: "utf8" });
1906
+ assert.equal(r.status, 2, r.stderr);
1907
+ assert.match(r.stderr, /--port wants an integer 0-65535, got abc/);
1908
+ });
1909
+
1910
+ test("CLI: build refuses --open=1, same message as serve", () => {
1911
+ const r = spawnSync(process.execPath, [SCRIPT, "build", "--open=1"], { encoding: "utf8" });
1912
+ assert.equal(r.status, 2, r.stderr);
1913
+ assert.match(r.stderr, /--open is a boolean flag, not --open=/);
1914
+ });
1915
+
1916
+ // The ordering half of the same fix, and the one the three cases above cannot
1917
+ // see: they pass a malformed flag ALONE, so nothing distinguishes a guard that
1918
+ // runs ahead of the build branch's stray() from one that runs after it. Add a
1919
+ // stray positional and it does: with the guard moved below that stray() call,
1920
+ // this invocation refused with `unexpected argument 'extra'` (measured),
1921
+ // naming a trailing token instead of the malformed value the caller actually
1922
+ // got wrong. Both orderings still exit 2 — only which real mistake gets named
1923
+ // differs, which is exactly what the --prev case above pins for its own flag.
1924
+ test("CLI: build refuses a malformed --port ahead of a stray token, naming --port not the stray", () => {
1925
+ const r = spawnSync(process.execPath, [SCRIPT, "build", "--port", "abc", "extra"], { encoding: "utf8" });
1926
+ assert.equal(r.status, 2, r.stderr);
1927
+ assert.match(r.stderr, /--port wants an integer 0-65535, got abc/);
1928
+ });
1929
+
1930
+ // #1076: same ordering gap as the --prev/--port cases above, for the two
1931
+ // flags PR #1090 (#468) left standing — argInterval()'s read had two call
1932
+ // sites (serve() directly, and embedded in gather()'s return, which build's
1933
+ // dispatch reaches too), and the --spend-since read sat inside gather();
1934
+ // all three sat below every stray() call on every path that reaches them.
1935
+ // With any of those reads left below the guard, the invocation refused
1936
+ // with `unexpected argument 'x'` (measured), naming the value flag's own
1937
+ // innocent trailing token instead of the flag actually given wrong — true
1938
+ // of build+interval as much as the serve+interval and build+spend-since
1939
+ // cases below cover. Hoisting both into main(), the same place and the
1940
+ // same way #468 hoisted argPort()/has("open"), is what these two red on
1941
+ // if reverted.
1942
+ test("CLI: serve refuses a trailing --interval ahead of a stray token, naming --interval not the stray", () => {
1943
+ const r = spawnSync(process.execPath, [SCRIPT, "serve", "--interval", "--open", "x"], { encoding: "utf8" });
1944
+ assert.equal(r.status, 2, r.stderr);
1945
+ assert.match(r.stderr, /--interval needs a value/);
1946
+ });
1947
+
1948
+ test("CLI: build refuses a trailing --spend-since ahead of a stray token, naming --spend-since not the stray", () => {
1949
+ const r = spawnSync(process.execPath, [SCRIPT, "build", "--spend-since", "--open", "x"], { encoding: "utf8" });
1950
+ assert.equal(r.status, 2, r.stderr);
1951
+ assert.match(r.stderr, /--spend-since needs a value/);
1952
+ });
1953
+
1954
+ // #1583: the same four spellings for --spend-dir, and the same ordering. A
1955
+ // PATH has no range to check, so arg() IS this flag's whole refusal — which
1956
+ // makes the two things this ticket wrote the only things standing between an
1957
+ // operator and a silent wrong answer: the "value" entry in the flag table, and
1958
+ // the read hoisted into main(). Drop it from the table and sweep() calls the
1959
+ // flag unknown; drop the hoisted read and the stray case below blames `x`.
1960
+ test("CLI: every malformed --spend-dir spelling is refused under its own name", () => {
1961
+ const cases = [
1962
+ [["build", "--spend-dir"], /--spend-dir needs a value/], // trailing
1963
+ [["build", "--spend-dir="], /--spend-dir needs a space-separated value, not --spend-dir=/], // = form
1964
+ [["build", "--spend-dir", ""], /--spend-dir needs a value/], // empty value
1965
+ [["build", "--spend-dir", "--prev", "x"], /--spend-dir needs a value/], // eats the next flag, naming --spend-dir not the stray
1966
+ ];
1967
+ for (const [args, message] of cases) {
1968
+ const r = spawnSync(process.execPath, [SCRIPT, ...args], { encoding: "utf8" });
1969
+ assert.equal(r.status, 2, `expected exit 2 for ${args.join(" ")}: ${r.stderr}`);
1970
+ assert.match(r.stderr, message, `for ${args.join(" ")}`);
1971
+ }
1972
+ });
1973
+
1974
+ // The other two malformed spellings arg.mjs refuses, which the hoist closes on
1975
+ // build alongside the three above. Pinned because a NARROWED hoist keeps the
1976
+ // three green while dropping these: measured, `if (process.argv.includes(
1977
+ // "--port")) argPort();` — a plausible "only bother when the flag was given" —
1978
+ // leaves `build --port=9000` at exit 0 with every other case still refusing.
1979
+ test("CLI: build refuses --port=9000, same message as serve", () => {
1980
+ const r = spawnSync(process.execPath, [SCRIPT, "build", "--port=9000"], { encoding: "utf8" });
1981
+ assert.equal(r.status, 2, r.stderr);
1982
+ assert.match(r.stderr, /--port needs a space-separated value, not --port=/);
1983
+ });
1984
+
1985
+ test("CLI: build refuses an empty --port value rather than falling back to the default port", () => {
1986
+ const r = spawnSync(process.execPath, [SCRIPT, "build", "--port", ""], { encoding: "utf8" });
1987
+ assert.equal(r.status, 2, r.stderr);
1988
+ assert.match(r.stderr, /--port needs a value/);
1989
+ });
1990
+
1991
+ // The hoist sits above the `cmd` dispatch, not just above serve()'s own call,
1992
+ // so it also changed the no-subcommand path: `board.mjs --port abc` printed
1993
+ // the usage line before this fix and names the flag after it (measured, both
1994
+ // sides). Sanctioned by #468's Option A ruling — a malformed flag is refused
1995
+ // wherever it is written — and unpinned until now: the same narrowing that
1996
+ // moves the guards into the `build` branch restores the usage line here while
1997
+ // leaving all four `build` cases above green.
1998
+ test("CLI: a malformed --port with no subcommand names the flag, not the usage line", () => {
1999
+ const r = spawnSync(process.execPath, [SCRIPT, "--port", "abc"], { encoding: "utf8" });
2000
+ assert.equal(r.status, 2, r.stderr);
2001
+ assert.match(r.stderr, /--port wants an integer 0-65535, got abc/);
2002
+ });
2003
+
2004
+ // The offline rig every serve spawn below shares. PATH is stripped to an
2005
+ // empty dir so every gh/git/node child fails fast into tryRun's catch: the
2006
+ // tick degrades, `git rev-parse --git-common-dir` answers nothing, and the
2007
+ // instance degrades with it to a cwd-relative `.fleet` on PORT_BASE — which
2008
+ // is what makes 8123 the deterministic derived port for these spawns, and a
2009
+ // fresh mkdtemp cwd what keeps them from sharing a state directory.
2010
+ const serveArgs = (args) => [SCRIPT, "serve", ...args];
2011
+ const serveOpts = () => ({
2012
+ cwd: mkdtempSync(join(tmpdir(), "board-serve-")),
2013
+ env: { ...process.env, PATH: mkdtempSync(join(tmpdir(), "board-nobin-")) },
2014
+ encoding: "utf8",
2015
+ timeout: 20000,
2016
+ });
2017
+
2018
+ // #1660 review: the git-enabled reuse/scan CLI rows below (which need a
2019
+ // real `bin` with git shimmed and a real `repo` cwd, so serveOpts()'s
2020
+ // offline empty-PATH rig doesn't fit) repeated this option literal
2021
+ // verbatim across four call sites, differing only in the timeout.
2022
+ const serveSync = (repo, bin, args, timeout = 20000) =>
2023
+ spawnSync(process.execPath, serveArgs(args), { cwd: repo, env: { ...process.env, PATH: bin }, encoding: "utf8", timeout });
2024
+
2025
+ // A net server that accepts a connection and then says nothing — the holder
2026
+ // no HTTP status describes, and the only one the probe's timer alone can
2027
+ // end. Its sockets are tracked because a socket nobody ever reads from
2028
+ // never notices the peer hanging up: plain `server.close()` would then wait
2029
+ // on it forever and keep this whole test process alive past the last test
2030
+ // (measured — the suite ran to the harness timeout with every test green).
2031
+ function muteHolder() {
2032
+ const conns = [];
2033
+ const server = createServer((s) => conns.push(s));
2034
+ const close = () => {
2035
+ for (const s of conns) s.destroy();
2036
+ return new Promise((res) => server.close(res));
2037
+ };
2038
+ return { server, close };
2039
+ }
2040
+
2041
+ // #1660 review: the row that used to stand here pinned the opposite of what
2042
+ // #1656 closed. This cwd is not a git checkout, so its workspace is null,
2043
+ // and a null workspace can never be confirmed against a handshake no
2044
+ // matter what answers on the other end — there is no identity to scan for.
2045
+ // Stepping past a held port there re-admits the exact dual-cockpit hazard
2046
+ // #1656 fixed: two processes sharing one derived window and one state
2047
+ // directory, neither aware the other exists. A held derived port on the
2048
+ // degrade arm has to stay fatal, exactly as it was before #1585 introduced
2049
+ // scanning at all.
2050
+ //
2051
+ // 8123 just has to be held by SOMEONE — us, or whatever already had it —
2052
+ // so the blocker is a bare net server.
2053
+ test("CLI: a derived port held by anything is fatal on the degrade arm — there is no identity to scan for", async () => {
2054
+ const blocker = createServer();
2055
+ await new Promise((res) => { blocker.once("error", res); blocker.listen(8123, res); });
2056
+ const nobin = mkdtempSync(join(tmpdir(), "board-nobin-"));
2057
+ const cwd = mkdtempSync(join(tmpdir(), "board-serve-"));
2058
+ try {
2059
+ const r = serveSync(cwd, nobin, ["--interval", "3600"]);
2060
+ assert.equal(r.status, 2, `a held derived port on the degrade arm must refuse, not scan past it: ${r.stderr}`);
2061
+ assert.match(r.stderr, /port 8123 in use/, r.stderr);
2062
+ assert.doesNotMatch(r.stderr, /cockpit on http/,
2063
+ `a second server was started with no identity it could ever have matched on: ${r.stderr}`);
2064
+ } finally {
2065
+ blocker.close(() => {});
2066
+ for (const d of [nobin, cwd]) rmSync(d, { recursive: true, force: true });
2067
+ }
2068
+ });
2069
+
2070
+ // #1656 critical (survived review): tick() used to run and write board.json
2071
+ // BEFORE listen() confirmed the bind, so a process that loses this exact
2072
+ // race against another cockpit on the same shared state directory still got
2073
+ // one full write in before dying on EADDRINUSE — overwriting whatever the
2074
+ // live cockpit had just written. Binding first (server.listen()'s success
2075
+ // callback now owns tick()/setInterval()) is what this test pins: the loser
2076
+ // must leave the state directory exactly as untouched as a process that
2077
+ // never ran at all.
2078
+ test("CLI: a port already in use must not write board.json before the process dies", async () => {
2079
+ const blocker = createServer();
2080
+ const port = await new Promise((res) => blocker.listen(0, () => res(blocker.address().port)));
2081
+ const opts = serveOpts();
2082
+ try {
2083
+ const r = spawnSync(process.execPath, serveArgs(["--port", String(port)]), opts);
2084
+ assert.equal(r.status, 2, r.stderr);
2085
+ assert.ok(!existsSync(join(opts.cwd, ".fleet", "board.json")),
2086
+ "the bind loser ticked and wrote board.json before dying on EADDRINUSE");
2087
+ } finally { blocker.close(() => {}); }
2088
+ });
2089
+
2090
+ // #366: `Number(x) || default` treated a non-numeric --port/--interval exactly
2091
+ // like an absent one — silently substituting the default with no refusal.
2092
+ // These pin the refusal itself, before listen() is ever reached.
2093
+ test("CLI: serve refuses a non-numeric --port by name, not silently substituting the default", () => {
2094
+ const r = spawnSync(process.execPath, serveArgs(["--port", "abc"]), serveOpts());
2095
+ assert.equal(r.status, 2, r.stderr);
2096
+ assert.match(r.stderr, /--port wants an integer 0-65535, got abc/);
2097
+ });
2098
+
2099
+ test("CLI: serve refuses an out-of-range or non-integer --port", () => {
2100
+ for (const v of ["-1", "70000", "1.5"]) {
2101
+ const r = spawnSync(process.execPath, serveArgs(["--port", v]), serveOpts());
2102
+ assert.equal(r.status, 2, `expected exit 2 for ${v}: ${r.stderr}`);
2103
+ assert.match(r.stderr, /--port wants an integer 0-65535/, `for ${v}: ${r.stderr}`);
2104
+ }
2105
+ });
2106
+
2107
+ // The named case that must NOT be refused: listen(0) binds an ephemeral port,
2108
+ // a real use, and 0 is falsy — the exact value the old `|| null` idiom lost.
2109
+ // serve() only exits on SIGINT/SIGTERM once bound, so a timeout here is the
2110
+ // expected shape of success; the refusal this guards against dies with
2111
+ // status 2 almost instantly and never reaches listen() at all.
2112
+ //
2113
+ // Accepting 0 is only half of it: the announced URL has to be one the operator
2114
+ // can open. Echoing the REQUESTED port printed http://localhost:0 — reachable
2115
+ // by nothing — while the board sat on the kernel's pick, so pin that the
2116
+ // number announced is the one bound, not the one asked for (#435 review).
2117
+ test("CLI: serve accepts --port 0 (ephemeral bind), announces the port it actually bound, and opens nothing unasked", () => {
2118
+ const r = spawnSync(process.execPath, serveArgs(["--port", "0", "--interval", "3600"]), { ...serveOpts(), timeout: 2000 });
2119
+ assert.notEqual(r.status, 2, r.stderr);
2120
+ assert.doesNotMatch(r.stderr, /--port wants/);
2121
+ const announced = r.stderr.match(/cockpit on http:\/\/localhost:(\d+)/);
2122
+ assert.ok(announced, `no cockpit line: ${r.stderr}`);
2123
+ assert.notEqual(announced[1], "0", `announced the requested port, not the bound one: ${r.stderr}`);
2124
+ // …and the ABSENT half of #364's has() control rides this spawn rather than
2125
+ // paying for a second one byte-identical to it: no --open was passed, so
2126
+ // nothing may try to open. The --open test below carries the present half,
2127
+ // and explains why a launcher that could not run surfaces on stderr at all.
2128
+ assert.doesNotMatch(r.stderr, /could not open a browser/, r.stderr);
2129
+ });
2130
+
2131
+ // #1679: every other argv-read option `serve` takes has both an in-process
2132
+ // override AND a CLI test driving it end to end; --spend-dir had neither
2133
+ // until now — every existing --spend-dir test drove `build` (one gather per
2134
+ // process, no pin) or spendDirPin() directly, never `serve`'s own tick loop.
2135
+ test("CLI: serve --spend-dir reads the named directory's spend into every tick, not just build", () => {
2136
+ const opts = serveOpts();
2137
+ // A real `<ISO>_<uuid>` leaf name: gatherSpend's `explicit` path now
2138
+ // refuses a --spend-dir whose own basename is not an omp session dir
2139
+ // (#1302-style guard), so this fixture must look like one to keep testing
2140
+ // what it says it tests — the named directory's data reaching the panel.
2141
+ const root = mkdtempSync(join(tmpdir(), "spend-named-"));
2142
+ const dir = join(root, "2026-08-25T09-00-00-000Z_abcdef12-3456-7890-abcd-ef1234567890");
2143
+ mkdirSync(dir, { recursive: true });
2144
+ writeFileSync(join(dir, "named.jsonl"), TURN.map((l) => JSON.stringify(l)).join("\n") + "\n");
2145
+ const r = spawnSync(process.execPath, serveArgs(["--port", "0", "--interval", "3600", "--spend-dir", dir]), { ...opts, timeout: 2000 });
2146
+ assert.notEqual(r.status, 2, r.stderr);
2147
+ const body = JSON.parse(readFileSync(join(opts.cwd, ".fleet", "board.json"), "utf8"));
2148
+ assert.equal(body.spend.ok, true, r.stderr);
2149
+ assert.equal(body.spend.totals.cacheWrite, 1000, "the served panel must come from the named directory, not the (absent) heuristic");
2150
+ assert.equal(body.spend.top[0].label, "named");
2151
+ });
2152
+
2153
+ test("CLI: serve refuses a non-numeric or non-positive --interval by name", () => {
2154
+ for (const v of ["abc", "0", "-5"]) {
2155
+ const r = spawnSync(process.execPath, serveArgs(["--interval", v]), serveOpts());
2156
+ assert.equal(r.status, 2, `expected exit 2 for ${v}: ${r.stderr}`);
2157
+ assert.match(r.stderr, new RegExp(`--interval wants seconds > 0 and <= 2147483, got ${v}`), `for ${v}: ${r.stderr}`);
2158
+ }
2159
+ });
2160
+
2161
+ // Both boundaries, both flags — an untested edge is an edge a later mutation
2162
+ // walks straight through: `n > 65535` weakened to `n >= 65535` (rejecting the
2163
+ // legal maximum port) survived the whole suite (#435 review). 65535 may well
2164
+ // be free here and may not, so pin the ABSENCE of the refusal rather than a
2165
+ // successful bind: an occupied port dies with "port 65535 in use", a rejected
2166
+ // one with "--port wants", and only the second is this guard's doing.
2167
+ test("CLI: serve accepts the maximum legal --port 65535 and refuses 65536", () => {
2168
+ const ok = spawnSync(process.execPath, serveArgs(["--port", "65535", "--interval", "3600"]), { ...serveOpts(), timeout: 2000 });
2169
+ assert.doesNotMatch(ok.stderr, /--port wants/, ok.stderr);
2170
+ const over = spawnSync(process.execPath, serveArgs(["--port", "65536"]), serveOpts());
2171
+ assert.equal(over.status, 2, over.stderr);
2172
+ assert.match(over.stderr, /--port wants an integer 0-65535, got 65536/);
2173
+ });
2174
+
2175
+ // The interval ceiling is setInterval's, so pin it where it bites: at the max
2176
+ // the timer must be armed normally, one second past it the flag is refused.
2177
+ // Without the ceiling, 2147484s becomes a 1ms tick and the rebuild loop spins
2178
+ // on gh instead of sleeping ~25 days — announced only by Node's own warning.
2179
+ test("CLI: serve arms the maximum --interval 2147483 without overflowing, and refuses 2147484", () => {
2180
+ const ok = spawnSync(process.execPath, serveArgs(["--port", "0", "--interval", "2147483"]), { ...serveOpts(), timeout: 2000 });
2181
+ assert.doesNotMatch(ok.stderr, /--interval wants/, ok.stderr);
2182
+ assert.doesNotMatch(ok.stderr, /TimeoutOverflowWarning/, ok.stderr);
2183
+ const over = spawnSync(process.execPath, serveArgs(["--port", "0", "--interval", "2147484"]), serveOpts());
2184
+ assert.equal(over.status, 2, over.stderr);
2185
+ assert.match(over.stderr, /--interval wants seconds > 0 and <= 2147483, got 2147484/);
2186
+ });
2187
+
2188
+ // #364: has() used exact argv.includes, so a boolean flag written --open=value
2189
+ // (in any form the value takes) silently read as absent. Boolean-specific
2190
+ // wording, distinct from arg()'s "needs a space-separated value" above: a
2191
+ // boolean has no value to give. Dies before listen(), same as the port/interval
2192
+ // guards above — nothing this reaches ever shells out.
2193
+ for (const v of ["=true", "=false", "="]) {
2194
+ test(`CLI: serve refuses --open${v} as a boolean flag, not silently read as absent`, () => {
2195
+ const r = spawnSync(process.execPath, serveArgs([`--open${v}`]), serveOpts());
2196
+ assert.equal(r.status, 2, r.stderr);
2197
+ assert.match(r.stderr, /--open is a boolean flag, not --open=/);
2198
+ });
2199
+ }
2200
+
2201
+ // Position, not just spelling: `serve` is fixed and every case in the loop
2202
+ // above passes its flag alone, so all three land at exactly process.argv[3] —
2203
+ // and a guard narrowed to that one index passes all three. Measured (#462
2204
+ // review): has() rewritten to `process.argv[3].startsWith(...)` kept this file
2205
+ // green at 34/34 while `serve --port 0 --interval 3600 --open=true` started
2206
+ // the server, dropped the flag in silence and never opened a browser — #364
2207
+ // itself, alive under a green suite. The real invocation always carries
2208
+ // --port/--interval, so pin the flag where an operator actually types it.
2209
+ // The MESSAGE is the load-bearing assertion, not `status`: spawnSync reports
2210
+ // status 2 on a timeout too, so a serve left running would satisfy the code
2211
+ // alone.
2212
+ test("CLI: serve refuses --open=true behind other flags, not only as the first argument", () => {
2213
+ const r = spawnSync(process.execPath, serveArgs(["--port", "0", "--interval", "3600", "--open=true"]), { ...serveOpts(), timeout: 2000 });
2214
+ assert.match(r.stderr, /--open is a boolean flag, not --open=/, r.stderr);
2215
+ assert.equal(r.status, 2, r.stderr);
2216
+ });
2217
+
2218
+ // The control: the new `=` guard must not touch the bare spelling. Observable
2219
+ // effect is the browser launcher firing — PATH is stripped to an empty dir
2220
+ // (serveOpts), so every launcher this platform would try is missing and the
2221
+ // warning naming the URL shows up on stderr rather than a browser opening.
2222
+ // #1714's rows further down put stub launchers on PATH to see which one ran.
2223
+ // The other half of the control — absence still reading as absent — is
2224
+ // asserted on the --port 0 test above, whose spawn is byte-identical to the
2225
+ // one this would otherwise repeat.
2226
+ test("CLI: serve --open (bare) still reads as present, not swallowed by the `=` guard", () => {
2227
+ const opened = spawnSync(process.execPath, serveArgs(["--port", "0", "--interval", "3600", "--open"]), { ...serveOpts(), timeout: 2000 });
2228
+ assert.match(opened.stderr, /could not open a browser .*http:\/\/localhost:\d+\//, opened.stderr);
2229
+ });
2230
+
2231
+ // #463: sweep() only ever refuses a `--`-prefixed token, so a bare stray
2232
+ // alongside a valid subcommand rode through in silence the same way
2233
+ // `board.mjs build junk` did — this pins the `serve` side of that fix.
2234
+ // stray() sits at the top of the `serve` branch, ahead of serve()'s own
2235
+ // port/interval/open reads, so this dies before ever calling listen() —
2236
+ // same reasoning as every guard above it in this file, and why serveOpts()'s
2237
+ // 20s timeout is a backstop here rather than the expected path.
2238
+ test("CLI: serve refuses a stray positional the same way build does", () => {
2239
+ const r = spawnSync(process.execPath, serveArgs(["--port", "0", "junk"]), serveOpts());
2240
+ assert.equal(r.status, 2, r.stderr);
2241
+ assert.match(r.stderr, /unexpected argument 'junk'/);
2242
+ });
2243
+
2244
+ // ---------------------------------------------------------------------------
2245
+ // #1582: cockpit instance resolution. A cockpit instance is identified by its
2246
+ // WORKSPACE — the directory holding the shared git dir, the same
2247
+ // `--git-common-dir` rule ledger.mjs's defaultLedgerPath() already resolves
2248
+ // the run's one ledger with — so two workspaces get two boards on two ports
2249
+ // and one workspace gets the SAME port on every run, making the URL
2250
+ // bookmarkable across runs, reboots and node versions.
2251
+ //
2252
+ // resolveCockpitInstance() takes the git-common-dir string as an ARGUMENT
2253
+ // rather than reading it, which is what turns the worktree case and the
2254
+ // resolution-failed case into plain rows here instead of two fixture
2255
+ // repositories apiece.
2256
+ //
2257
+ // Why these rows and not only a live probe: every serve() spawn above runs
2258
+ // with PATH stripped to an empty dir, so git is unreachable and all of them
2259
+ // take the DEGRADE arm. A green CLI section above is evidence about that arm
2260
+ // and no other — the resolved arm is reached in the rows below, and
2261
+ // end-to-end by the two spawns at the bottom, which put a git shim back on
2262
+ // PATH on purpose.
2263
+ // ---------------------------------------------------------------------------
2264
+
2265
+ for (const [name, args, stateDir, workspace] of [
2266
+ ["an absolute --git-common-dir names the checkout holding it",
2267
+ { cwd: "/w/repo", gitCommonDir: "/w/repo/.git" }, "/w/repo/.fleet", "/w/repo"],
2268
+ // git answers RELATIVE from a checkout's top level, and the cwd it is
2269
+ // relative to is an argument here — a resolve() that reached for
2270
+ // process.cwd() instead would put the board under the test runner.
2271
+ ["a relative --git-common-dir resolves against the passed cwd, not process.cwd()",
2272
+ { cwd: "/w/repo", gitCommonDir: ".git" }, "/w/repo/.fleet", "/w/repo"],
2273
+ // Not a `.trim()` pin, despite the name's old claim: `dirname()` discards
2274
+ // the newline together with the rest of the final path segment it rides
2275
+ // on, wholesale, whether or not `.trim()` ran first — mutation-verified
2276
+ // (#1656 review: removing `.trim()` here leaves every row in this table
2277
+ // green). `.trim()`'s one load-bearing case is a value that is WHOLLY
2278
+ // whitespace, pinned by the degrade rows below instead. Kept as a
2279
+ // realistic-shape check: git really does answer `--git-common-dir` with a
2280
+ // trailing newline, and this is what that answer resolves to.
2281
+ ["a real git answer's trailing newline still resolves to the parent directory",
2282
+ { cwd: "/w/repo", gitCommonDir: "/w/repo/.git\n" }, "/w/repo/.fleet", "/w/repo"],
2283
+ // `--git-common-dir` answers with the MAIN checkout's git dir from inside a
2284
+ // linked worktree — that is the whole reason the rule is this one and not
2285
+ // `--git-dir`, which names the worktree's own admin directory. Two
2286
+ // worktrees therefore share one state directory, matching the ledger's
2287
+ // one-run-one-workspace model rather than giving every member its own board.
2288
+ ["a linked worktree resolves to the main checkout, never its own directory",
2289
+ { cwd: "/w/repo/.worktrees/t", gitCommonDir: "/w/repo/.git" }, "/w/repo/.fleet", "/w/repo"],
2290
+ ]) {
2291
+ test(`resolveCockpitInstance: ${name}`, () => {
2292
+ const r = resolveCockpitInstance(args);
2293
+ assert.equal(r.stateDir, stateDir);
2294
+ assert.equal(r.workspace, workspace);
2295
+ });
2296
+ }
2297
+
2298
+ // The window is written out literally rather than imported from board.mjs:
2299
+ // these two numbers ARE the contract. BASE is the port the cockpit served on
2300
+ // before any of this existed, so a silent change to it breaks every bookmark
2301
+ // the ticket exists to preserve, and a test that read both from the module
2302
+ // under test could not notice either one moving.
2303
+ const PORT_BASE = 8123, PORT_SPAN = 512;
2304
+
2305
+ for (const dir of ["/w/one", "/w/two", "/srv/fleet-plugin", "/Users/x/dev/repo"]) {
2306
+ test(`resolveCockpitInstance: ${dir} derives one stable port inside [${PORT_BASE}, ${PORT_BASE + PORT_SPAN})`, () => {
2307
+ const first = resolveCockpitInstance({ cwd: dir, gitCommonDir: join(dir, ".git") });
2308
+ // Same workspace, different cwd: the port follows the workspace, so a
2309
+ // member running from elsewhere in the tree must land on the same board.
2310
+ const again = resolveCockpitInstance({ cwd: "/somewhere/else", gitCommonDir: join(dir, ".git") });
2311
+ assert.equal(first.port, again.port, "the port must follow the workspace, not the cwd");
2312
+ assert.equal(first.derived, true, "nothing forced this port, so it is a derived one");
2313
+ assert.ok(first.port >= PORT_BASE && first.port < PORT_BASE + PORT_SPAN,
2314
+ `${dir} derived ${first.port}, outside [${PORT_BASE}, ${PORT_BASE + PORT_SPAN}) — the unsigned coercion on the hash is what keeps it in the window`);
2315
+ });
2316
+ }
2317
+
2318
+ // The other half of "two workspaces, two boards": a hash that collapses to a
2319
+ // constant keeps every row above green while putting every workspace on one
2320
+ // port — this test catches that. It does NOT reliably catch a precision-
2321
+ // losing variant (Math.imul replaced by a plain `*`): for these six fixed
2322
+ // paths that variant still lands on six distinct ports, so this row would
2323
+ // pass vacuously against it (mutation-verified, #1656 review). The dedicated
2324
+ // pinned-value test below exists to catch that case. Fixed paths, so both
2325
+ // tests are deterministic: they cannot flake, they can only be wrong.
2326
+ test("resolveCockpitInstance: different workspaces derive different ports", () => {
2327
+ const seen = new Map();
2328
+ for (const dir of ["/w/one", "/w/two", "/w/three", "/w/four", "/w/five", "/w/six"]) {
2329
+ const { port } = resolveCockpitInstance({ cwd: dir, gitCommonDir: join(dir, ".git") });
2330
+ assert.ok(!seen.has(port),
2331
+ `${dir} and ${seen.get(port)} both derived ${port} — a hash that cannot separate two workspaces cannot give them two boards`);
2332
+ seen.set(port, dir);
2333
+ }
2334
+ });
2335
+
2336
+ // workspaceHash() is not exported, so this pins the algorithm indirectly
2337
+ // through resolveCockpitInstance()'s derived port. 8337 was hand-computed by
2338
+ // re-deriving FNV-1a-with-Math.imul for the key "/fixed/workspace" in two
2339
+ // independent scripts (JS and Python, the latter with explicit 32-bit
2340
+ // unsigned-multiply/wrap semantics) and cross-checked against the real
2341
+ // function — it is NOT copied from this file's own module under test. A
2342
+ // Math.imul -> `*` mutation changes this key's hash and port (8337 -> 8355),
2343
+ // so — unlike the uniqueness test above — this one does catch it.
2344
+ test("resolveCockpitInstance: a fixed workspace pins the FNV-1a-with-Math.imul port exactly", () => {
2345
+ const { port } = resolveCockpitInstance({ cwd: "/fixed/workspace", gitCommonDir: join("/fixed/workspace", ".git") });
2346
+ assert.equal(port, 8337,
2347
+ "port drifted off the hand-computed FNV-1a value for this fixed key — the hash algorithm itself changed");
2348
+ });
2349
+
2350
+ // Without the realpath, a route to the workspace through a symlink — a
2351
+ // symlinked home, /var vs /private/var on this very platform — derives a
2352
+ // SECOND port and a second state directory for a workspace already being
2353
+ // served, which is the collision this ticket exists to prevent.
2354
+ test("resolveCockpitInstance: a symlinked route to one workspace derives the canonical form's port", () => {
2355
+ const root = mkdtempSync(join(tmpdir(), "board-ws-link-"));
2356
+ try {
2357
+ const real = join(root, "repo");
2358
+ mkdirSync(join(real, ".git"), { recursive: true });
2359
+ const link = join(root, "link");
2360
+ symlinkSync(real, link);
2361
+ const direct = resolveCockpitInstance({ cwd: real, gitCommonDir: join(real, ".git") });
2362
+ const viaLink = resolveCockpitInstance({ cwd: link, gitCommonDir: join(link, ".git") });
2363
+ assert.equal(viaLink.workspace, direct.workspace, "the symlinked route must canonicalise onto the same workspace key");
2364
+ assert.equal(viaLink.port, direct.port);
2365
+ assert.equal(viaLink.stateDir, direct.stateDir);
2366
+ // …and the key is the CANONICAL path, not merely the two sides agreeing
2367
+ // because neither was canonicalised at all.
2368
+ assert.equal(direct.workspace, realpathSync(real));
2369
+ } finally { rmSync(root, { recursive: true, force: true }); }
2370
+ });
2371
+
2372
+ // The false-positive half of this ticket. Deriving is the new behaviour, and
2373
+ // the way to get it wrong is to derive over the top of a port the caller
2374
+ // chose. 0 is a row on purpose: it is a legal ephemeral bind (#366/#435) and
2375
+ // it is FALSY, so any truthiness test in place of `port != null` silently
2376
+ // replaces it with a derived port and `--port 0` stops meaning anything.
2377
+ // 8123 is a row for the opposite reason — it is the base, so only `derived`
2378
+ // can tell a forced one from a derived one there.
2379
+ for (const port of [0, 8123, 65535]) {
2380
+ test(`resolveCockpitInstance: --port ${port} is returned verbatim and marked not derived`, () => {
2381
+ const r = resolveCockpitInstance({ cwd: "/w/cwd", gitCommonDir: "/w/repo/.git", port });
2382
+ assert.equal(r.port, port);
2383
+ assert.equal(r.derived, false);
2384
+ // Forcing the port forces the port — the state directory still follows
2385
+ // the workspace.
2386
+ assert.equal(r.stateDir, "/w/repo/.fleet");
2387
+ });
2388
+ }
2389
+
2390
+ // An unresolvable shared git dir degrades to a cwd-relative state directory
2391
+ // with a null workspace and says so; a non-git or otherwise unusual checkout
2392
+ // never dies for it. The wording is defaultLedgerPath()'s own — one dialect
2393
+ // for one failure, so an operator who has seen the ledger's line recognises
2394
+ // this one rather than learning a second phrasing of it.
2395
+ for (const [name, gitCommonDir] of [
2396
+ ["git exited non-zero, so the probe handed back nothing", ""],
2397
+ ["no probe ran at all", undefined],
2398
+ ["whitespace is not a path", " \n "],
2399
+ ]) {
2400
+ test(`resolveCockpitInstance: ${name} — degrades to cwd, warns, never throws`, () => {
2401
+ let r;
2402
+ const errs = withStderr(() => { r = resolveCockpitInstance({ cwd: "/w/cwd", gitCommonDir }); });
2403
+ assert.equal(r.workspace, null, "no workspace was established, so none may be claimed");
2404
+ assert.equal(r.stateDir, "/w/cwd/.fleet", "the fallback is cwd-relative — the behaviour this file had before #1582");
2405
+ assert.equal(r.port, PORT_BASE, "with no workspace to hash there is nothing to derive from, so the port is the familiar default");
2406
+ assert.equal(errs.length, 1, "expected one stderr line, got " + JSON.stringify(errs));
2407
+ assert.match(errs[0], /WARNING could not resolve --git-common-dir/,
2408
+ "the ledger's existing fail-loud wording, not a second dialect for the same failure");
2409
+ assert.match(errs[0], /using cwd-relative/);
2410
+ });
2411
+ }
2412
+
2413
+ // The degrade arm has its own copy of the forced/derived decision, so a
2414
+ // mutation that drops it there is invisible to the rows above: a caller who
2415
+ // passed --port outside a git checkout would silently get 8123 instead.
2416
+ test("resolveCockpitInstance: an explicit port survives the degrade path too", () => {
2417
+ let r;
2418
+ const errs = withStderr(() => { r = resolveCockpitInstance({ cwd: "/w/cwd", gitCommonDir: "", port: 4242 }); });
2419
+ assert.equal(r.port, 4242);
2420
+ assert.equal(r.derived, false);
2421
+ assert.equal(errs.length, 1, "the state directory still degraded, so the warning still belongs");
2422
+ });
2423
+
2424
+ // A PATH carrying git and nothing else. The resolved arm needs a real
2425
+ // `git rev-parse`, while gh and node must stay unreachable so these spawns
2426
+ // remain offline and fast — the same intent serveOpts()'s empty PATH has.
2427
+ function gitOnlyPath() {
2428
+ const bin = mkdtempSync(join(tmpdir(), "board-gitbin-"));
2429
+ const real = spawnSync("sh", ["-c", "command -v git"], { encoding: "utf8" });
2430
+ assert.equal(real.status, 0, "test setup: no git on PATH to shim, so the resolved arm cannot be reached");
2431
+ symlinkSync(real.stdout.trim(), join(bin, "git"));
2432
+ return bin;
2433
+ }
2434
+
2435
+ function gitRepo(prefix) {
2436
+ const dir = mkdtempSync(join(tmpdir(), prefix));
2437
+ // GIT_DIR/GIT_WORK_TREE scrubbed off the FIXTURE too: under an ambient one
2438
+ // `git init` exits 0 having re-inited whichever directory the variable
2439
+ // names, leaving this one silently not a repository (ledger.test.mjs hit
2440
+ // exactly that) — and the status check alone cannot see it.
2441
+ const env = gitEnv();
2442
+ const init = spawnSync("git", ["init", "-q"], { cwd: dir, stdio: "ignore", env });
2443
+ assert.equal(init.status, 0, "test setup: git init must succeed");
2444
+ assert.ok(existsSync(join(dir, ".git")), "test setup: git init must have created a repository HERE");
2445
+ return dir;
2446
+ }
2447
+
2448
+ // The behavioural fixture ambient-git-vars-mjs-prose.test.mjs's census
2449
+ // requires of every file it lists in COVERED_MJS, measured for board.mjs
2450
+ // rather than copied from another script's reason: GIT_DIR outranks the
2451
+ // child's cwd, so an ambient one makes `git rev-parse --git-common-dir`
2452
+ // answer for a DIFFERENT repository — and this cockpit would then serve, and
2453
+ // write board.json into, someone else's workspace, at exit 0 and in silence.
2454
+ // gitEnv() on the probe is what prevents it.
2455
+ test("CLI: an ambient GIT_DIR cannot move the cockpit into another repository's workspace", () => {
2456
+ const bin = gitOnlyPath(), mine = gitRepo("board-ws-mine-"), other = gitRepo("board-ws-other-");
2457
+ try {
2458
+ const r = spawnSync(process.execPath, serveArgs(["--port", "0", "--interval", "3600"]), {
2459
+ cwd: mine,
2460
+ env: { ...process.env, PATH: bin, GIT_DIR: join(other, ".git") },
2461
+ encoding: "utf8",
2462
+ timeout: 5000,
2463
+ });
2464
+ // Without this the test passes vacuously: a probe that FAILED also keeps
2465
+ // the board out of `other`, by degrading to the cwd rather than by
2466
+ // scrubbing anything.
2467
+ assert.doesNotMatch(r.stderr, /could not resolve --git-common-dir/,
2468
+ `the probe had to succeed, or this proves nothing about which repo it answered for: ${r.stderr}`);
2469
+ assert.match(r.stderr, /cockpit on http/, r.stderr);
2470
+ assert.ok(existsSync(join(mine, ".fleet", "board.json")),
2471
+ "the board belongs in the caller's own workspace");
2472
+ assert.ok(!existsSync(join(other, ".fleet")),
2473
+ "an ambient GIT_DIR relocated the whole cockpit into the repository it names");
2474
+ } finally { for (const d of [bin, mine, other]) rmSync(d, { recursive: true, force: true }); }
2475
+ });
2476
+
2477
+ const withTimeout = (pr, ms, what) => Promise.race([
2478
+ pr,
2479
+ new Promise((_, rej) => setTimeout(() => rej(new Error(`timed out waiting for ${what}`)), ms).unref()),
2480
+ ]);
2481
+
2482
+ function serveProcess(cwd, bin, args = ["--port", "0", "--interval", "3600"], node = []) {
2483
+ const p = spawn(process.execPath, [...node, ...serveArgs(args)],
2484
+ { cwd, env: { ...process.env, PATH: bin }, stdio: ["ignore", "ignore", "pipe"] });
2485
+ p.stderr.setEncoding("utf8");
2486
+ let buf = "";
2487
+ const url = new Promise((res, rej) => {
2488
+ p.stderr.on("data", (d) => {
2489
+ buf += d;
2490
+ const m = buf.match(/cockpit on (http:\/\/localhost:\d+)/);
2491
+ if (m) res(m[1]);
2492
+ });
2493
+ p.on("exit", (code) => rej(new Error(`serve exited (${code}) before announcing: ${buf}`)));
2494
+ });
2495
+ return { p, url, stderr: () => buf };
2496
+ }
2497
+
2498
+ // #1713: the cockpit now answers HTTP while its first tick is still
2499
+ // computing, so the first payload on this wire is #1660's identity stub —
2500
+ // `{workspace, port}`, no `tickets` — and only the tick behind it is a board.
2501
+ // Before the tick ran asynchronously this process could not answer at all
2502
+ // until it had finished, which is the only reason a bare fetch here used to
2503
+ // land on a built board. `generatedAt` is the discriminant because only
2504
+ // computeBoard() produces it; board-identity.test.mjs polls on the same field
2505
+ // for the same reason.
2506
+ async function untilBuiltBoard(url) {
2507
+ const ms = 20000, deadline = Date.now() + ms;
2508
+ for (;;) {
2509
+ try {
2510
+ const res = await fetch(`${url}/board.json`);
2511
+ if (res.ok) {
2512
+ const body = await res.json();
2513
+ if (typeof body.generatedAt === "number") return body;
2514
+ } else { await res.arrayBuffer(); }
2515
+ } catch { /* not up yet */ }
2516
+ if (Date.now() > deadline) throw new Error(`no built board at ${url} after ${ms}ms`);
2517
+ await new Promise((res) => setTimeout(res, 50));
2518
+ }
2519
+ }
2520
+
2521
+ // The end-to-end claim, and the one no pure row can make: two workspaces
2522
+ // served AT ONCE are two live boards, each writing only its own state
2523
+ // directory — and the one started from a linked worktree writes its MAIN
2524
+ // checkout's, not the worktree's.
2525
+ //
2526
+ // `--port 0` on both, deliberately. What needs two real processes is the
2527
+ // state-directory separation; that two workspaces derive two DIFFERENT ports
2528
+ // is already pinned deterministically in the rows above, and binding the
2529
+ // derived ports here would make the test depend on whether this machine
2530
+ // happens to hold either of them.
2531
+ //
2532
+ // Unlike every other `gitOnlyPath()` consumer, this test also symlinks node
2533
+ // onto the shim PATH (gh stays unreachable): gather()'s ledger read shells
2534
+ // out to a `node ledger.mjs` subprocess, and with node unreachable that read
2535
+ // always fails and every board here would show `tickets: []` regardless of
2536
+ // which ledger.md — or none at all — actually got read, making the ledger
2537
+ // fixture below assert nothing (#1656 review).
2538
+ test("CLI: two workspaces serve two live boards at once, each writing only its own state directory", async () => {
2539
+ const bin = gitOnlyPath(), repoA = gitRepo("board-ws-a-"), repoB = gitRepo("board-ws-b-");
2540
+ symlinkSync(process.execPath, join(bin, "node"));
2541
+ const procs = [];
2542
+ try {
2543
+ const env = gitEnv();
2544
+ const git = (cwd, args) => {
2545
+ const r = spawnSync("git", ["-c", "user.email=t@t", "-c", "user.name=t", ...args], { cwd, stdio: "ignore", env });
2546
+ assert.equal(r.status, 0, `test setup: git ${args.join(" ")} must succeed`);
2547
+ };
2548
+ // `worktree add` needs a commit to branch from.
2549
+ git(repoA, ["commit", "-q", "--allow-empty", "-m", "init"]);
2550
+ const worktree = join(repoA, "wt");
2551
+ git(repoA, ["worktree", "add", "-q", worktree, "-b", "side"]);
2552
+
2553
+ // #1656 critical (survived review): the served state directory moved to
2554
+ // the workspace, but an unfixed default ledger path stayed cwd-relative
2555
+ // — so a cockpit started from this worktree found no ledger there and
2556
+ // silently served an EMPTY board into repoA's shared board.json. A row
2557
+ // written into repoA's OWN `.fleet/ledger.md` (never the worktree's) is
2558
+ // the only way to tell "read the right ledger" apart from "read no
2559
+ // ledger and get an empty board either way": both look like `tickets: []`
2560
+ // without it.
2561
+ mkdirSync(join(repoA, ".fleet"), { recursive: true });
2562
+ writeFileSync(join(repoA, ".fleet", "ledger.md"),
2563
+ "# Fleet run ledger\n\n## Rows\n\n- #42 impl-1 build the thing\n\n## Filed\n\n## Ruled\n\n");
2564
+
2565
+ const a = serveProcess(worktree, bin), b = serveProcess(repoB, bin);
2566
+ procs.push(a.p, b.p);
2567
+ const [urlA, urlB] = await withTimeout(Promise.all([a.url, b.url]), 20000, "both cockpits to announce");
2568
+
2569
+ for (const [label, url] of [["worktree-of-A", urlA], ["B", urlB]]) {
2570
+ const board = await untilBuiltBoard(url);
2571
+ assert.ok(Array.isArray(board.tickets), `${label} served something that is not a board`);
2572
+ }
2573
+ assert.notEqual(urlA, urlB, "two concurrent boards cannot share one URL");
2574
+
2575
+ const boardA = await (await fetch(`${urlA}/board.json`)).json();
2576
+ assert.ok(boardA.tickets.some((t) => t.issue === 42),
2577
+ "the worktree's cockpit must read the MAIN checkout's ledger, not a cwd-relative one that does not exist under the worktree");
2578
+
2579
+ assert.ok(existsSync(join(repoA, ".fleet", "board.json")),
2580
+ "the worktree's cockpit must write its MAIN checkout's state directory");
2581
+ assert.ok(!existsSync(join(worktree, ".fleet")),
2582
+ "the worktree got a state directory of its own — one repo, one board, one ledger");
2583
+ assert.ok(existsSync(join(repoB, ".fleet", "board.json")),
2584
+ "the second workspace must write its own state directory");
2585
+ } finally {
2586
+ for (const p of procs) p.kill("SIGKILL");
2587
+ for (const d of [bin, repoA, repoB]) rmSync(d, { recursive: true, force: true });
2588
+ }
2589
+ });
2590
+
2591
+ // ── #1585: the launch is idempotent ─────────────────────────────────────────
2592
+
2593
+ // The pure half of the scan, reachable with no socket at all.
2594
+ test("cockpitPorts: an explicit port is a list of one — there is nothing to scan", () => {
2595
+ assert.deepEqual(cockpitPorts({ port: 9000, derived: false }), [9000]);
2596
+ // 0 is the row that catches a truthiness test in place of the `derived`
2597
+ // flag: it is a legal ephemeral bind (#366) and it is falsy.
2598
+ assert.deepEqual(cockpitPorts({ port: 0, derived: false }), [0]);
2599
+ });
2600
+
2601
+ test("cockpitPorts: a derived port leads a bounded, contiguous window inside the range", () => {
2602
+ const ports = cockpitPorts({ port: 8200, derived: true });
2603
+ assert.equal(ports[0], 8200, "the scan must start at the stable, bookmarkable port, not one past it");
2604
+ assert.ok(ports.length > 1, "a derived port with no fallback is the failure this ticket exists to remove");
2605
+ // Every attempt can cost a bind plus a probe timeout, so the bound is what
2606
+ // keeps an exhausted range a refusal an operator waits seconds for rather
2607
+ // than minutes.
2608
+ assert.ok(ports.length <= 16, `${ports.length} attempts is not a bounded scan`);
2609
+ assert.deepEqual(ports, ports.map((_, i) => 8200 + i), "the window must be contiguous from the derived port");
2610
+ });
2611
+
2612
+ // The top of the range is exactly where a naive `derived + i` walks out of
2613
+ // the window resolveCockpitInstance() promises — onto ports this scheme
2614
+ // never claimed, where no other workspace's cockpit could ever be found.
2615
+ test("cockpitPorts: the window wraps at the top of the range rather than leaving it", () => {
2616
+ const top = PORT_BASE + PORT_SPAN - 1;
2617
+ const ports = cockpitPorts({ port: top, derived: true });
2618
+ assert.equal(ports[0], top);
2619
+ assert.equal(ports[1], PORT_BASE, "the port after the last one in the range is the first one");
2620
+ for (const p of ports) {
2621
+ assert.ok(p >= PORT_BASE && p < PORT_BASE + PORT_SPAN, `${p} escaped [${PORT_BASE}, ${PORT_BASE + PORT_SPAN})`);
2622
+ }
2623
+ });
2624
+
2625
+ // A holder serving `dir` on a real ephemeral port, through the same
2626
+ // server-creation seam the cockpit itself uses — no second I/O surface, in
2627
+ // the tests either.
2628
+ async function holderOn(dir, port = 0) {
2629
+ const server = createBoardServer(dir);
2630
+ const bound = await new Promise((res) => { server.once("error", () => res(null)); server.listen(port, () => res(server.address().port)); });
2631
+ return { server, port: bound };
2632
+ }
2633
+
2634
+ const boardDir = (payload) => {
2635
+ const dir = mkdtempSync(join(tmpdir(), "board-holder-"));
2636
+ if (payload !== undefined) writeFileSync(join(dir, "board.json"), payload);
2637
+ return dir;
2638
+ };
2639
+
2640
+ // The half that must ACCEPT: a real board payload naming a workspace is the
2641
+ // one answer the probe has to believe, and everything below is a way of not
2642
+ // believing it. A probe that only ever returns null passes every negative
2643
+ // row and turns the reuse path off entirely.
2644
+ test("probeCockpitWorkspace: a live board's payload answers with its workspace", async () => {
2645
+ const dir = boardDir(JSON.stringify({ tickets: [], workspace: "/w/mine" }));
2646
+ const { server, port } = await holderOn(dir);
2647
+ try {
2648
+ assert.equal(await probeCockpitWorkspace(port), "/w/mine");
2649
+ } finally { server.close(() => {}); rmSync(dir, { recursive: true, force: true }); }
2650
+ });
2651
+
2652
+ // Every way of failing to prove "this is my cockpit" is one answer: foreign.
2653
+ // The 404 row is the live one — an empty state directory is what a cockpit
2654
+ // whose first tick failed actually serves — and the rest are what a holder
2655
+ // that is not a cockpit at all returns.
2656
+ for (const [name, payload] of [
2657
+ ["no board.json at all (404)", undefined],
2658
+ ["a body that is not JSON", "<html>not a board</html>"],
2659
+ ["a payload with no workspace field", JSON.stringify({ tickets: [] })],
2660
+ ["a workspace that is not a string", JSON.stringify({ tickets: [], workspace: 42 })],
2661
+ ["an empty workspace", JSON.stringify({ tickets: [], workspace: "" })],
2662
+ ["a bare null payload", "null"],
2663
+ ]) {
2664
+ test(`probeCockpitWorkspace: ${name} reads as foreign`, async () => {
2665
+ const dir = boardDir(payload);
2666
+ const { server, port } = await holderOn(dir);
2667
+ try {
2668
+ assert.equal(await probeCockpitWorkspace(port), null);
2669
+ } finally { server.close(() => {}); rmSync(dir, { recursive: true, force: true }); }
2670
+ });
2671
+ }
2672
+
2673
+ // #1660 review: every foreign row above happens to be a 404, which a
2674
+ // mutation to `res.statusCode >= 400` would also reject — the guard must
2675
+ // require exactly 200, not merely "not a client/server error". A non-200
2676
+ // status carrying an otherwise-valid, matching workspace body is what tells
2677
+ // the two apart: the real guard has to refuse it on status alone, without
2678
+ // ever reading a body that would answer "yes" if it got that far.
2679
+ test("probeCockpitWorkspace: a non-200 status with an otherwise-valid matching body still reads as foreign", async () => {
2680
+ const server = createServer((socket) => {
2681
+ socket.once("data", () => {
2682
+ const body = JSON.stringify({ tickets: [], workspace: "/w/mine" });
2683
+ socket.end(`HTTP/1.1 301 Moved Permanently\r\nContent-Type: application/json\r\nContent-Length: ${Buffer.byteLength(body)}\r\nConnection: close\r\n\r\n${body}`);
2684
+ });
2685
+ });
2686
+ const port = await new Promise((res) => server.listen(0, () => res(server.address().port)));
2687
+ try {
2688
+ assert.equal(await probeCockpitWorkspace(port), null,
2689
+ "a non-200 status must be refused on the status alone, even carrying a real workspace body");
2690
+ } finally { server.close(); }
2691
+ });
2692
+
2693
+ // The case no HTTP status covers: a holder that accepts the connection and
2694
+ // then says nothing. Only the probe's own timer ends this, and the injected
2695
+ // timeout is what proves the timer is the thing that ended it — a probe that
2696
+ // ignored its argument and used the ~1s default would sit here ten times
2697
+ // longer than the bound below.
2698
+ test("probeCockpitWorkspace: a holder that never answers is bounded, and a refused connection is immediate", async () => {
2699
+ const mute = muteHolder();
2700
+ const port = await new Promise((res) => mute.server.listen(0, () => res(mute.server.address().port)));
2701
+ try {
2702
+ const started = Date.now();
2703
+ assert.equal(await probeCockpitWorkspace(port, 100), null);
2704
+ const waited = Date.now() - started;
2705
+ assert.ok(waited < 700, `the probe waited ${waited}ms past its 100ms budget — the launch's bound is this one`);
2706
+ } finally { await mute.close(); }
2707
+ // Same answer by the other road: nothing is listening there any more, so
2708
+ // the connect is refused rather than hung.
2709
+ assert.equal(await probeCockpitWorkspace(port, 100), null);
2710
+ });
2711
+
2712
+ // The first candidate this machine can actually bind — the derived port
2713
+ // itself unless something outside this suite is sitting on it.
2714
+ async function firstFreePort(ports) {
2715
+ for (const p of ports) {
2716
+ const free = await new Promise((res) => {
2717
+ const probe = createServer();
2718
+ probe.once("error", () => res(false));
2719
+ probe.listen(p, () => probe.close(() => res(true)));
2720
+ });
2721
+ if (free) return p;
2722
+ }
2723
+ throw new Error(`test setup: no free port among ${ports.join(", ")}`);
2724
+ }
2725
+
2726
+ async function untilBoardJson(url) {
2727
+ const ms = 15000, deadline = Date.now() + ms;
2728
+ for (;;) {
2729
+ try { if ((await fetch(`${url}/board.json`)).ok) return; } catch { /* not up yet */ }
2730
+ if (Date.now() > deadline) throw new Error(`no readable board at ${url} after ${ms}ms`);
2731
+ await new Promise((res) => setTimeout(res, 50));
2732
+ }
2733
+ }
2734
+
2735
+ // #1714: stub browser launchers. Each appends its own name and argv to one
2736
+ // log and exits with the code it was given, so a row reads which launcher
2737
+ // ran, at what URL and how many times — and no real browser is ever reached.
2738
+ // Written into gitOnlyPath()'s directory, so git still resolves beside them.
2739
+ const ALL_LAUNCHERS = { open: 0, "xdg-open": 0, wslview: 0 };
2740
+ function launcherBin(launchers) {
2741
+ const bin = gitOnlyPath();
2742
+ const log = join(bin, "launched.log");
2743
+ for (const [name, code] of Object.entries(launchers)) {
2744
+ writeFileSync(join(bin, name), `#!/bin/sh\necho "${name} $*" >> '${log}'\nexit ${code}\n`);
2745
+ chmodSync(join(bin, name), 0o755);
2746
+ }
2747
+ return { bin, launched: () => (existsSync(log) ? readFileSync(log, "utf8").split("\n").filter(Boolean) : []) };
2748
+ }
2749
+
2750
+ async function untilLaunched(rig, count) {
2751
+ const deadline = Date.now() + 20000;
2752
+ while (rig.launched().length < count) {
2753
+ if (Date.now() > deadline) throw new Error(`no launcher ran within 20000ms: ${JSON.stringify(rig.launched())}`);
2754
+ await new Promise((res) => setTimeout(res, 50));
2755
+ }
2756
+ }
2757
+
2758
+ // The reuse path end to end, and the claim no unit row can make: a second
2759
+ // launch against a LIVE cockpit for the same workspace starts no server,
2760
+ // says where the board already is, and exits 0. The exit code is the whole
2761
+ // point — the documented launch is `serve --open &`, so a backgrounded
2762
+ // non-zero exit is read by nobody and the operator just waits for a tab.
2763
+ //
2764
+ // The first launch's own landing rides this spawn rather than paying for one
2765
+ // byte-identical to it: nothing is held, so it must take the port its
2766
+ // workspace DERIVES. Every other row here only asserts where a launch did
2767
+ // not land, so a scan that skipped the derived port entirely — or probed
2768
+ // before it tried to bind — would pass all of them and move every
2769
+ // bookmarked URL by one.
2770
+ //
2771
+ // #1714: both launches pass --open, the way run-team's phase 0 relaunches on
2772
+ // every re-shortlist, with every launcher stubbed on PATH. The first bound
2773
+ // the port, so it opens exactly one tab; the second found that cockpit
2774
+ // already running (the held-port arm), so it opens none — before #1714 it
2775
+ // opened the existing board again, one more tab per pass.
2776
+ test("CLI: a second launch for the same workspace reuses the live cockpit, opens nothing, and exits 0", async () => {
2777
+ const rig = launcherBin(ALL_LAUNCHERS), repo = gitRepo("board-ws-reuse-");
2778
+ const instance = resolveCockpitInstance({ cwd: repo, gitCommonDir: join(repo, ".git") });
2779
+ const expected = await firstFreePort(cockpitPorts(instance));
2780
+ const first = serveProcess(repo, rig.bin, ["--interval", "3600", "--open"]);
2781
+ try {
2782
+ const url = await withTimeout(first.url, 20000, "the first cockpit to announce");
2783
+ assert.equal(url, `http://localhost:${expected}`,
2784
+ "a launch with nothing in its way must take the port its workspace derives — that URL is the bookmarkable one");
2785
+ // The handshake reads the payload, so the first tick has to have landed.
2786
+ await untilBoardJson(url);
2787
+ assert.equal((await (await fetch(`${url}/board.json`)).json()).workspace, realpathSync(repo),
2788
+ "the board payload is what the handshake reads — a cockpit that does not name its workspace cannot be recognised");
2789
+ await untilLaunched(rig, 1);
2790
+
2791
+ const second = serveSync(repo, rig.bin, ["--interval", "3600", "--open"]);
2792
+ assert.equal(second.status, 0, `the reuse path must exit 0 — a backgrounded launch reports nothing else: ${second.stderr}`);
2793
+ assert.match(second.stderr, new RegExp(`already running for this workspace on ${url}/`), second.stderr);
2794
+ assert.doesNotMatch(second.stderr, /cockpit on http/, `a second server was started for one workspace: ${second.stderr}`);
2795
+ // Read only once the second launch has exited, so anything it launched
2796
+ // is already in the log: still the first launch's one line, at its URL.
2797
+ const launched = rig.launched();
2798
+ assert.equal(launched.length, 1, `the launch that bound opens one tab and the reuse opens none: ${JSON.stringify(launched)}`);
2799
+ assert.ok(launched[0].endsWith(` ${url}/`), `the one tab is not the served board: ${launched[0]}`);
2800
+ assert.doesNotMatch(second.stderr, /could not open a browser/, second.stderr);
2801
+ } finally { first.p.kill("SIGKILL"); for (const d of [rig.bin, repo]) rmSync(d, { recursive: true, force: true }); }
2802
+ });
2803
+
2804
+ // #1714: the reuse arm the row above cannot reach. That one's cockpit holds
2805
+ // the derived port, so the second launch's bind fails and it handshakes the
2806
+ // holder; here the derived port is FREE and this workspace's cockpit sits
2807
+ // one candidate further along — the shape a departed squatter leaves — so
2808
+ // the launch binds first and finds the match in its post-bind scan. That arm
2809
+ // had its own copy of the open, and has to open nothing just the same. The
2810
+ // stand-in cockpit answers from THIS process, so the launch is spawned
2811
+ // asynchronously: a spawnSync would block the loop it answers on, and the
2812
+ // probe would read it as silent rather than as this workspace's.
2813
+ test("CLI: a launch whose post-bind scan finds this workspace's cockpit further along opens nothing", async () => {
2814
+ const rig = launcherBin(ALL_LAUNCHERS), repo = gitRepo("board-ws-scan-reuse-");
2815
+ const instance = resolveCockpitInstance({ cwd: repo, gitCommonDir: join(repo, ".git") });
2816
+ const ports = cockpitPorts(instance);
2817
+ const free = await firstFreePort(ports);
2818
+ const further = await firstFreePort(ports.slice(ports.indexOf(free) + 1));
2819
+ const dir = boardDir(JSON.stringify({ tickets: [], workspace: instance.workspace }));
2820
+ const { server, port } = await holderOn(dir, further);
2821
+ const p = spawn(process.execPath, serveArgs(["--interval", "3600", "--open"]),
2822
+ { cwd: repo, env: { ...process.env, PATH: rig.bin }, stdio: ["ignore", "ignore", "pipe"] });
2823
+ let stderr = "";
2824
+ p.stderr.setEncoding("utf8");
2825
+ p.stderr.on("data", (d) => { stderr += d; });
2826
+ try {
2827
+ assert.equal(port, further, "test setup: the stand-in cockpit must hold the later candidate");
2828
+ const status = await withTimeout(new Promise((res) => p.on("close", res)), 20000, "the launch to exit");
2829
+ assert.equal(status, 0, `the reuse path must exit 0: ${stderr}`);
2830
+ assert.match(stderr, new RegExp(`already running for this workspace on http://localhost:${further}/`), stderr);
2831
+ assert.doesNotMatch(stderr, /cockpit on http/, stderr);
2832
+ assert.deepEqual(rig.launched(), [], "a launch that found this workspace's cockpit already running opened a tab for it");
2833
+ } finally {
2834
+ p.kill("SIGKILL");
2835
+ server.close(() => {});
2836
+ for (const d of [rig.bin, repo, dir]) rmSync(d, { recursive: true, force: true });
2837
+ }
2838
+ });
2839
+
2840
+ // #1714: which launcher a launch that bound its port runs, per platform (ADR
2841
+ // 0009) — `open` on macOS; elsewhere `xdg-open`, then `wslview` (WSL) only
2842
+ // when `xdg-open` is not on PATH at all, since one that ran and failed is the
2843
+ // right program meeting a real fault. process.platform is forced in the
2844
+ // child through a preload, so every platform's order is exercised on
2845
+ // whichever one runs the suite, and each row's PATH also carries a launcher
2846
+ // the forced platform must NOT reach for. A launch with no working launcher
2847
+ // warns with the URL and keeps serving: it still answers after warning and
2848
+ // exits 0 on the SIGTERM that ends it, exactly like one whose launcher
2849
+ // worked — the status a missing `open` produced before #1714.
2850
+ //
2851
+ // Each row waits on --open's own outcome, not on a clock: read at a fixed
2852
+ // deadline (the 2s spawnSync timeout this used to be), a launch slowed by a
2853
+ // loaded machine had not reached its launcher yet and failed a row the code
2854
+ // passes. openBrowser() warns only once it is done with the launcher list, so
2855
+ // a warning row is complete the moment that line lands. A launcher that
2856
+ // worked announces nothing, so a row expecting one waits for its log line and
2857
+ // then LAUNCHER_SETTLE_MS more: a wrong second launcher, or a warning after
2858
+ // all, would follow the one that worked within a turn of the loop, and this
2859
+ // is the time it gets to show up. That wait can only miss a fault, never
2860
+ // invent one.
2861
+ const LAUNCHER_SETTLE_MS = 1000;
2862
+ const WARNED = /could not open a browser.*\n/;
2863
+ const serveOn = (platform, cwd, bin) => serveProcess(cwd, bin, ["--port", "0", "--interval", "3600", "--open"], [
2864
+ "--import", `data:text/javascript,${encodeURIComponent(`Object.defineProperty(process, "platform", { value: ${JSON.stringify(platform)} });`)}`,
2865
+ ]);
2866
+
2867
+ async function untilWarned(launch) {
2868
+ const deadline = Date.now() + 20000;
2869
+ while (!WARNED.test(launch.stderr())) {
2870
+ if (Date.now() > deadline) throw new Error(`no --open warning within 20000ms: ${launch.stderr()}`);
2871
+ await new Promise((res) => setTimeout(res, 50));
2872
+ }
2873
+ }
2874
+
2875
+ for (const [platform, launchers, ran, warns] of [
2876
+ ["darwin", ALL_LAUNCHERS, ["open"], false],
2877
+ ["linux", ALL_LAUNCHERS, ["xdg-open"], false],
2878
+ ["linux", { open: 0, wslview: 0 }, ["wslview"], false],
2879
+ ["linux", { "xdg-open": 3, wslview: 0 }, ["xdg-open"], true],
2880
+ ["linux", { open: 0 }, [], true],
2881
+ ["darwin", { "xdg-open": 0, wslview: 0 }, [], true],
2882
+ ]) {
2883
+ const onPath = Object.entries(launchers).map(([n, c]) => (c ? `${n} (exit ${c})` : n)).join(", ");
2884
+ test(`CLI: a fresh --open launch on ${platform} with ${onPath} on PATH runs ${ran.join(" ") || "no launcher"}${warns ? " and warns with the URL" : ""}`, async () => {
2885
+ const rig = launcherBin(launchers), cwd = mkdtempSync(join(tmpdir(), "board-open-"));
2886
+ const launch = serveOn(platform, cwd, rig.bin);
2887
+ const exited = new Promise((res) => launch.p.on("exit", (code, signal) => res({ code, signal })));
2888
+ try {
2889
+ const url = await withTimeout(launch.url, 20000, "the cockpit to announce");
2890
+ if (warns) {
2891
+ await untilWarned(launch);
2892
+ assert.match(launch.stderr(), new RegExp(`WARNING --open could not open a browser \\(.*\\) — the cockpit is on ${url}/`), launch.stderr());
2893
+ } else {
2894
+ await untilLaunched(rig, ran.length);
2895
+ await new Promise((res) => setTimeout(res, LAUNCHER_SETTLE_MS));
2896
+ assert.doesNotMatch(launch.stderr(), /could not open a browser/, launch.stderr());
2897
+ }
2898
+ assert.deepEqual(rig.launched(), ran.map((cmd) => `${cmd} ${url}/`), launch.stderr());
2899
+ const serving = await fetch(`${url}/board.json`).then((res) => res.ok, () => false);
2900
+ assert.ok(serving, `the cockpit stopped serving instead of running until signalled: ${launch.stderr()}`);
2901
+ launch.p.kill("SIGTERM");
2902
+ assert.deepEqual(await withTimeout(exited, 20000, "the cockpit to exit on SIGTERM"), { code: 0, signal: null }, launch.stderr());
2903
+ } finally {
2904
+ launch.p.kill("SIGKILL");
2905
+ for (const d of [rig.bin, cwd]) rmSync(d, { recursive: true, force: true });
2906
+ }
2907
+ });
2908
+ }
2909
+
2910
+ // The false-match half. This holder answers, parses, and serves a real board
2911
+ // payload on the exact port this workspace derives — nothing but the
2912
+ // workspace field distinguishes it from the cockpit reused above. A
2913
+ // handshake that asks "did anyone answer" rather than "whose board is this"
2914
+ // adopts it, and this run gets no board of its own at all.
2915
+ test("CLI: a holder reporting a different workspace is not adopted — the launch serves elsewhere", async () => {
2916
+ const bin = gitOnlyPath(), repo = gitRepo("board-ws-foreign-");
2917
+ const { port: derived } = resolveCockpitInstance({ cwd: repo, gitCommonDir: join(repo, ".git") });
2918
+ const dir = boardDir(JSON.stringify({ tickets: [], workspace: "/some/other/workspace" }));
2919
+ const { server } = await holderOn(dir, derived);
2920
+ const launch = serveProcess(repo, bin, ["--interval", "3600"]);
2921
+ try {
2922
+ const url = await withTimeout(launch.url, 20000, "the launch to step over the foreign holder");
2923
+ assert.notEqual(url, `http://localhost:${derived}`, "the launch adopted a board belonging to another workspace");
2924
+ const window = cockpitPorts({ port: derived, derived: true });
2925
+ assert.ok(window.includes(Number(url.split(":")[2])), `${url} is outside the bounded scan window ${window.join(", ")}`);
2926
+ // …and it is really serving its OWN board there, not merely announcing a
2927
+ // port it stepped onto.
2928
+ await untilBoardJson(url);
2929
+ assert.equal((await (await fetch(`${url}/board.json`)).json()).workspace, realpathSync(repo));
2930
+ } finally {
2931
+ launch.p.kill("SIGKILL");
2932
+ server.close(() => {});
2933
+ for (const d of [bin, repo, dir]) rmSync(d, { recursive: true, force: true });
2934
+ }
2935
+ });
2936
+
2937
+ // The only hard failure left on a derived port, and the shape it has to
2938
+ // have. Non-zero, because an exhausted range is a real refusal where reuse
2939
+ // is not — and a message naming every port tried, because an operator told
2940
+ // only "no free port" cannot tell a crowded range from a broken derivation.
2941
+ //
2942
+ // The blockers serve an empty directory, so each one 404s /board.json — one
2943
+ // of the foreign shapes no launch may adopt. They cannot actually answer
2944
+ // during the spawn below, though: spawnSync blocks this runner's event loop,
2945
+ // so every probe runs out its full timeout, retries once (#1660 — a timeout
2946
+ // alone does not prove foreign), and the row costs ~16s (measured, up from
2947
+ // ~8s pre-#1660: PORT_ATTEMPTS candidates times two attempts times
2948
+ // PROBE_TIMEOUT_MS). That is the bound doing its job rather than a hang,
2949
+ // and it is why this row is the only slow one here — the rows that need a
2950
+ // holder to really answer use serveProcess(), which leaves the loop free.
2951
+ test("CLI: an exhausted derived range exits non-zero and names the ports it tried", async () => {
2952
+ const bin = gitOnlyPath(), repo = gitRepo("board-ws-full-");
2953
+ const instance = resolveCockpitInstance({ cwd: repo, gitCommonDir: join(repo, ".git") });
2954
+ const ports = cockpitPorts(instance);
2955
+ const dir = boardDir(undefined);
2956
+ const blockers = [];
2957
+ try {
2958
+ // A port already held by something else is held either way — what this
2959
+ // row needs is the range full, not our own socket on every port in it.
2960
+ for (const p of ports) blockers.push((await holderOn(dir, p)).server);
2961
+ const r = serveSync(repo, bin, ["--interval", "3600"], 30000);
2962
+ assert.equal(r.status, 2, `an exhausted range must refuse, not hang and not succeed: ${r.stderr}`);
2963
+ for (const p of ports) assert.match(r.stderr, new RegExp(`\\b${p}\\b`), `the refusal does not name ${p}: ${r.stderr}`);
2964
+ assert.match(r.stderr, /--port/, "the refusal has to point at the way out of it");
2965
+ assert.doesNotMatch(r.stderr, /cockpit on http/, r.stderr);
2966
+ } finally {
2967
+ for (const s of blockers) s.close(() => {});
2968
+ for (const d of [bin, repo, dir]) rmSync(d, { recursive: true, force: true });
2969
+ }
2970
+ });
2971
+
2972
+ // Neither half of the new behaviour may touch a port the operator named, and
2973
+ // this replaces the narrower row that pinned only the bind error's wording
2974
+ // there (its other assertion, the absence of the "(default)" marker, pins a
2975
+ // string no path can print any more). The holder here is not a stranger: it
2976
+ // serves a payload naming THIS workspace, the exact thing the derived path
2977
+ // reuses at exit 0 above. A handshake not gated on `instance.derived` adopts
2978
+ // it and exits 0, silently serving a board the operator did not ask for on
2979
+ // the port they did.
2980
+ test("CLI: an explicit port neither scans nor handshakes — a bind failure on it is fatal", async () => {
2981
+ const bin = gitOnlyPath(), repo = gitRepo("board-ws-explicit-");
2982
+ const dir = boardDir(JSON.stringify({ tickets: [], workspace: realpathSync(repo) }));
2983
+ const { server, port } = await holderOn(dir);
2984
+ try {
2985
+ const r = serveSync(repo, bin, ["--interval", "3600", "--port", String(port)]);
2986
+ assert.equal(r.status, 2, `a bind failure on a chosen port is a hard error: ${r.stderr}`);
2987
+ assert.match(r.stderr, new RegExp(`port ${port} in use`), r.stderr);
2988
+ assert.doesNotMatch(r.stderr, /already running/, "an explicit port was handshaked and reused");
2989
+ assert.doesNotMatch(r.stderr, /trying the next port/, "an explicit port was scanned off");
2990
+ } finally { server.close(() => {}); for (const d of [bin, repo, dir]) rmSync(d, { recursive: true, force: true }); }
2991
+ });
2992
+
2993
+ // #1093: the CLI's top-level handler printed `e.message`, which is `undefined`
2994
+ // for a rejection that is not an `Error` — so the whole diagnostic was the
2995
+ // literal `board: undefined`. Nothing in this file throws a non-Error today,
2996
+ // which is why this is the unit half of board-cli.test.mjs's fault case: the
2997
+ // text the handler writes has to carry bytes for every value a rejection can
2998
+ // arrive as, including the four that render as nothing under a naive
2999
+ // `String(e)`/`e.message` read.
3000
+ test("faultText renders any rejected value, so no fault prints an empty diagnostic", () => {
3001
+ for (const v of [undefined, null, "", 0, false, { a: 1 }]) {
3002
+ const t = faultText(v);
3003
+ assert.match(t, /\S/, `faultText(${String(v)}) has nothing in it`);
3004
+ assert.notEqual(t, "undefined", "the `board: undefined` diagnostic is exactly what this replaces");
3005
+ }
3006
+ // The rejected value is NAMED, not merely non-empty: a constant string would
3007
+ // satisfy the loop above and tell the reader nothing.
3008
+ assert.match(faultText(undefined), /undefined/);
3009
+ assert.match(faultText({ a: 1 }), /a: 1/);
3010
+ // Why inspect() and not JSON.stringify: a self-referential rejection is a
3011
+ // value like any other, and stringify THROWS on it — inside the fault
3012
+ // handler, which is the one place left that can still report anything.
3013
+ const circular = {};
3014
+ circular.self = circular;
3015
+ assert.match(faultText(circular), /Circular/);
3016
+ // An Error keeps its stack verbatim. That is the whole point of the path:
3017
+ // a message alone is what made a fault indistinguishable from a refusal.
3018
+ const e = new Error("boom");
3019
+ assert.equal(faultText(e), e.stack);
3020
+ assert.match(faultText(e), /\n\s+at /);
3021
+ });
3022
+
3023
+ // #1547: fault() writes a full stack trace in a single writeSync(2, ...) call
3024
+ // — the same unlooped shape die()'s pre-#889 bug had (arg.mjs). board.mjs has
3025
+ // exactly one writeSync call site — this is it, not the largest of four in
3026
+ // this file — but it is one of four across the fleet (arg.mjs's die(),
3027
+ // board.mjs's fault(), ci-state.mjs's emit(), staleness.mjs's verdict()) and
3028
+ // carries the largest single payload of the four: a full stack, not a
3029
+ // one-line refusal. A short write returns the count it actually wrote and
3030
+ // throws nothing at all, so a bare try/catch around one call never sees it
3031
+ // and the diagnostic is silently truncated with no error — the class
3032
+ // ci-state.mjs's emit() had before #885, and the reason #889 gave
3033
+ // die()/verdict() a bounded retry loop.
3034
+ //
3035
+ // A source-shape pin alone cannot tell a retry loop from a bare call that
3036
+ // happens to fit in one write, and the pin below used to stop at the resumed
3037
+ // writeSync call itself — the EAGAIN check, the MAX_EAGAIN_RETRIES cap and
3038
+ // the Atomics.wait backoff that follow were unanchored, so a mutant that
3039
+ // collapses the whole catch block to a bare `break;` — deleting the retry
3040
+ // this PR exists to add — still passed it (measured). The regex below now
3041
+ // anchors through those lines too, and board-cli.test.mjs pairs this with an
3042
+ // EXECUTED companion: a real non-blocking stderr pipe that starts fully
3043
+ // saturated and is never drained, the same rig staleness.test.mjs's verdict()
3044
+ // test and arg.test.mjs's die() test use — but timed, not just bounded, since
3045
+ // a doomed single call and a 200-retry loop against a pipe that never drains
3046
+ // both write nothing and both still reach process.exit() well inside any
3047
+ // generous bound; only the loop spends real time doing it.
3048
+ //
3049
+ // A body that still calls writeSync once and discards the count — `try {
3050
+ // writeSync(2, ...) } catch {}` — satisfies a pin that stops at `try {`, so
3051
+ // this one requires the loop that resumes from writeSync's own return value,
3052
+ // and now the retry/backoff that follows it too. Each fragment is anchored at
3053
+ // a line start and joined with `\s*^\s*`, and no fragment is terminated with
3054
+ // `$`, so a comment line added inside fault() does not redden this and a
3055
+ // trailing comment cannot satisfy it — the anchoring candidates.test.mjs's
3056
+ // die() pin documents in full.
3057
+ test("fault()'s writeSync loop consumes its own return value and retries EAGAIN with a capped backoff, not just a bare call", () => {
3058
+ assert.equal(
3059
+ stripComments(readFileSync(SCRIPT, "utf8")).match(/^\s*function fault\(/gm)?.length,
3060
+ 1,
3061
+ "board.mjs declares fault() more than once, or not at all — the pin below reads the first",
3062
+ );
3063
+ assert.match(
3064
+ stripComments(readFileSync(SCRIPT, "utf8")),
3065
+ /^\s*function fault\(e\) \{\s*^\s*try \{\s*^\s*let buf = Buffer\.from\(`[^`]*`\);\s*^\s*let retries = 0;\s*^\s*while \(buf\.length\) \{\s*^\s*try \{\s*^\s*buf = buf\.subarray\(writeSync\(2, buf\)\);\s*^\s*\} catch \(writeErr\) \{\s*^\s*if \(writeErr\.code !== "EAGAIN" \|\| \+\+retries > MAX_EAGAIN_RETRIES\) break;\s*^\s*Atomics\.wait\(IDLE, 0, 0, 1\);/m,
3066
+ );
3067
+ });
3068
+
3069
+ // board.mjs had no row in the design spec's script-surface table, so neither of
3070
+ // its exit codes was written down anywhere a consumer reads. Derived from the
3071
+ // script rather than restated here: the fault code is read out of board.mjs's
3072
+ // own declaration, so changing it there and leaving the document behind reddens
3073
+ // this — the drift #407 caught the hard way for candidates.mjs's exit 3.
3074
+ test("the design spec's board row names both exit codes the script can produce", () => {
3075
+ const declared = readFileSync(SCRIPT, "utf8").match(/^const FAULT_EXIT = (\d+);$/m);
3076
+ assert.ok(declared, "board.mjs no longer declares FAULT_EXIT — update this test");
3077
+ const spec = readFileSync(
3078
+ fileURLToPath(new URL("../../docs/specs/2026-07-23-fleet-plugin-design.md", import.meta.url)),
3079
+ "utf8",
3080
+ );
3081
+ const row = spec.split("\n").find((l) => l.startsWith("| `board.mjs` |"));
3082
+ assert.ok(row, "the design spec's script-surface table has no `board.mjs` row");
3083
+ for (const code of ["2", declared[1]]) {
3084
+ assert.match(row, new RegExp(`exit ${code}\\b`, "i"), `the board row does not name exit ${code}`);
3085
+ }
3086
+ });