@feigi/fleet-ctl 3.23.36 → 3.23.37

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