@feigi/fleet-ctl 3.39.4 → 3.39.5

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.
@@ -0,0 +1,997 @@
1
+ // The cockpit's raw-input half: everything upstream of computeBoard(). gather()
2
+ // reads the ledger, the `gh` issue/PR/repo/merged reads, per-PR CI and the
3
+ // member-spend transcripts, and returns exactly the shape computeBoard()
4
+ // consumes.
5
+ //
6
+ // Unlike compute-board.mjs this module is NOT pure. gather() performs real I/O
7
+ // — it spawns `gh`, `ledger.mjs` and `ci-state.mjs` and walks the transcript
8
+ // tree — so it is testable only through `PATH` stubs and fixture trees, never
9
+ // by handing it values. Splitting it out of board.mjs does not change leverage:
10
+ // every caller still reaches the board through the one board.mjs interface.
11
+ // The reason for the split is locality — a defect in a ledger, `gh` or
12
+ // transcript read points here, not at the HTTP server.
13
+ //
14
+ // Pipeline state is a pure function of ledger + GitHub. The spend panel adds
15
+ // a THIRD input that is neither — the local member-transcript tree, under
16
+ // ~/.omp/agent/sessions — so the "f(ledger, gh)" property no longer covers
17
+ // the whole model. It is
18
+ // telemetry, kept strictly to the side: it can only ever populate or omit
19
+ // `spend`, never change a ticket's stage.
20
+ //
21
+ // That transcript tree is keyed by PROJECT DIRECTORY, not by session, and one
22
+ // directory can hold several sessions at once. `serve` therefore resolves ONE
23
+ // session's transcript directory and keeps it for its whole life — see
24
+ // spendDirPin() below — rather than re-picking the newest on every tick and
25
+ // alternating between two live runs' numbers in silence.
26
+ //
27
+ // LIMITATION, stated rather than solved: the session it keeps is whichever
28
+ // FIRST writes a transcript at or after the pin's own construction.
29
+ // Before that, a session that was already active when the pin was built —
30
+ // this run's own, mid-EACCES-fault, or a genuinely previous run's — is never
31
+ // latched; the pin keeps re-asking findSubagentsDir() every tick instead,
32
+ // which is what lets a transient fault or a stale session recover instead of
33
+ // freezing the panel for the server's whole life. What is not solved: two
34
+ // sessions that BOTH start writing after the pin exists, in the same project
35
+ // directory, are still indistinguishable — the board is scoped to a
36
+ // workspace and a workspace does not know that — so the first of them
37
+ // to pass the newest-transcript check wins and keeps winning. `--spend-dir
38
+ // <path>` is how an operator names the right one: it overrides the
39
+ // heuristic outright.
40
+
41
+ import { readFileSync, existsSync, readdirSync, statSync } from "node:fs";
42
+ import { computeSpend, attributeTools, mergeTools } from "./compute-spend.mjs";
43
+ import {
44
+ encodeProjectDir, isOmpSessionDirName, ompSessionTranscripts, foldOmpTranscript, ompMemberRecord,
45
+ } from "./member-record.mjs";
46
+ import { NAME, warnOnce, execRead } from "./board-common.mjs";
47
+ import { mergedReadPrs } from "./compute-board.mjs";
48
+ // The heartbeat's liveness mark and the controller record beside it, read here
49
+ // and never written: the heartbeat is the mark's only writer and
50
+ // `ledger.mjs rotate` the record's. stallOwner() reads the process table to
51
+ // name whose stall a stopped beat is.
52
+ import { readState, assessBeat, isStalled, stallOwner } from "./fleet-state.mjs";
53
+ import { fileURLToPath } from "node:url";
54
+ import { dirname, join, basename } from "node:path";
55
+
56
+ const SCRIPT_DIR = dirname(fileURLToPath(import.meta.url));
57
+
58
+ // The "is this a plain JSON object" predicate and its kind word, one
59
+ // copy for the reads in this file that reject a parsed-but-wrong payload
60
+ // WHOLE — gather's `--prev` payload, gather's per-entry `tickets[i]` check,
61
+ // and readMerged()'s `data.repository`. Each carried its own inline
62
+ // copy of both halves before, which is three places for one policy to drift in.
63
+ //
64
+ // TWO functions and not one, because `typeof` alone cannot name the fault the
65
+ // predicate rejects: it answers "object" for `null` and for `[]` alike, and
66
+ // those are exactly two of the three shapes turned away here, so a
67
+ // `typeof`-only diagnostic distinguishes neither from a real object. That is
68
+ // the same three-arm naming review-core.mjs's resolveDimensions keeps, for the
69
+ // same reason.
70
+ //
71
+ // Not every payload-shape check in this file is one of these, and the others
72
+ // are not oversights: mapCi's and tryParse's are both null-only, neither
73
+ // refusing a payload for being an array or a scalar. A settled, deliberately
74
+ // different policy — not more callers waiting to be converted.
75
+ function isJsonObject(v) {
76
+ return typeof v === "object" && v !== null && !Array.isArray(v);
77
+ }
78
+
79
+ function jsonKind(v) {
80
+ return v === null ? "null" : Array.isArray(v) ? "array" : typeof v;
81
+ }
82
+
83
+ // Every external read is wrapped: a failure returns null and the caller keeps a
84
+ // last-known value. Partial board beats a crashed loop or a false alarm.
85
+ async function tryRun(cmd, args) {
86
+ const r = await execRead(cmd, args);
87
+ if (r.error) { console.error(`${NAME}: ${cmd} ${args.join(" ")} failed: ${r.error.message}`); return null; }
88
+ return r.stdout;
89
+ }
90
+
91
+ // Parse tool stdout defensively: a tool can exit 0 yet print malformed or
92
+ // warning-prefixed stdout. Treat that like a failed read (fall back to the
93
+ // caller's empty default), never let it crash the tick.
94
+ //
95
+ // A nullish INPUT and a null PARSED VALUE are two faults, and the first guard
96
+ // does not cover the second: `JSON.parse("null")` succeeds and yields null, so
97
+ // without the second guard a bare `null` payload arrives at the caller as its
98
+ // answer. Strictly `=== null`, never falsiness — `0`, `false` and `""` are all
99
+ // answers a caller can read, and refusing them would substitute a shape
100
+ // judgement this helper is not in a position to make.
101
+ //
102
+ // Null is guarded here and shape is not, because null is the only parse result
103
+ // no caller of this helper can use: every other one boxes and reads, null alone
104
+ // has no properties, whatever shape the caller wanted. Shape is the caller's
105
+ // question and keeps the caller's answer — withNumber below rejects a non-array
106
+ // for the `gh ... list` reads, gather()'s `--prev` read demands
107
+ // an object, and gather()'s ledger branch takes any shape ledger.mjs emits,
108
+ // deliberately, for the reason stated there. A shape policy could not be written
109
+ // in here anyway: `fallback` is `[]` where the open-PR read calls this and null where the
110
+ // ledger read does, so the helper is never told what its caller wanted — only
111
+ // that null is not it.
112
+ //
113
+ // Reported, and never as "parse failed": the parse succeeded, and keeping the
114
+ // state a read reached apart from the state it failed at is what the ledger states are for.
115
+ function tryParse(json, fallback, what) {
116
+ if (json == null) return fallback;
117
+ let parsed;
118
+ try { parsed = JSON.parse(json); }
119
+ catch (e) { console.error(`${NAME}: ${what} parse failed: ${e.message}`); return fallback; }
120
+ if (parsed === null) {
121
+ console.error(`${NAME}: ${what}: payload is JSON null, not a usable answer; falling back`);
122
+ return fallback;
123
+ }
124
+ return parsed;
125
+ }
126
+
127
+ // A row without a usable `number` cannot be placed: compute-board.mjs joins
128
+ // issues/PRs to ledger rows and to each other BY number (Map keys, Set
129
+ // membership, `.find`), so a numberless row does not fail to render on its
130
+ // own — it collides with every other numberless row on the shared `undefined`
131
+ // key. Drop it, loudly. candidates.mjs's row guard is a different shape —
132
+ // comprehensive and hard-failing (die() on the first bad row) — this one is
133
+ // narrower: it only checks `number`, the one field whose absence corrupts
134
+ // OTHER rows, and degrades instead of dying.
135
+ //
136
+ // `rows` itself can be the wrong shape too: `tryParse` only checks that its
137
+ // input is valid JSON, not that it is an array, so a syntactically-valid
138
+ // object or scalar from `gh` would otherwise reach the `for...of` below and
139
+ // throw "rows is not iterable" — an uncaught throw that reaches main()'s
140
+ // build path or the serve tick's catch, exactly the crash-instead-of-degrade
141
+ // failure this guard exists to prevent for individual rows.
142
+ function withNumber(rows, what) {
143
+ if (!Array.isArray(rows)) {
144
+ console.error(`${NAME}: ${what}: expected an array of rows, got ${JSON.stringify(rows)}`);
145
+ return [];
146
+ }
147
+ const kept = [];
148
+ for (const r of rows) {
149
+ if (r && typeof r.number === "number") kept.push(r);
150
+ else console.error(`${NAME}: ${what}: dropping row with no usable number: ${JSON.stringify(r)}`);
151
+ }
152
+ return kept;
153
+ }
154
+
155
+ // gh stops a `list` read at its `--limit` with exit 0 and no warning, so
156
+ // a read that came back exactly that long may have been cut there — "at least
157
+ // this many", never "this many". candidates.mjs's refuseIfCapped() and
158
+ // fleet-tick.mjs's PR_LIMIT/CLAIMED_LIMIT carry the same rule; this board is a
159
+ // display, so it discloses a capped read (computeBoard's `n+` and capNotice)
160
+ // rather than dying on one. Counted on the raw rows, before withNumber() drops
161
+ // any: gh's cap applies to what it returned, not to what this file kept.
162
+ const POOL_LIMIT = 100;
163
+ const OPEN_PR_LIMIT = 100;
164
+ function hitLimit(parsed, limit) {
165
+ return Array.isArray(parsed) && parsed.length >= limit;
166
+ }
167
+
168
+ // Which of `prNums` gh calls MERGED, in ONE `gh api graphql` query —
169
+ // one aliased `pullRequest(number:)` field per PR, on the cwd's repository
170
+ // (gh's own `{owner}`/`{repo}` placeholders, the repo every other read here
171
+ // resolves) — so a PR merged at any age is found, and ten PRs cost what one
172
+ // does. It replaced `gh pr list --state merged --limit 100`, the repo's 100
173
+ // most recent merges: about six days on 2026-09-25, so a row PR merged
174
+ // before that and never seen MERGED rendered REVIEW, turned stale and
175
+ // counted as claimed. Measured 2026-09-26: 400 aliases answer in one call.
176
+ //
177
+ // An empty `prNums` makes no read at all. `state` is checked, so an entry gh
178
+ // does not call MERGED never makes a card MERGED on its own account.
179
+ //
180
+ // A body with an object `data.repository` IS an answer even at exit 1:
181
+ // GitHub resolves every alias it can and nulls the rest — a number that is
182
+ // not a PR comes back null beside a NOT_FOUND error, and gh exits 1 with the
183
+ // whole body on stdout (measured 2026-09-26, gh 2.101.0, which also names
184
+ // the number on stderr). Refusing that body would let one such row — a
185
+ // typo, or a row with no impl token keyed by an issue number — put every other
186
+ // row PR back in REVIEW on every tick. A null alias reads as not merged,
187
+ // which is what a failed read means for that one PR.
188
+ //
189
+ // Real GitHub always answers EVERY requested `p<N>` alias, null or an
190
+ // object — never omits one — so an object naming NONE of `prNums` is not a
191
+ // shape the API produces, only a corrupted or truncated one; `isJsonObject`
192
+ // alone cannot tell that apart from a genuine "checked, nothing merged"
193
+ // answer, so it is checked for too. Anything else is a failed read: `[]`,
194
+ // and computeBoard()'s carry-forward rule takes it from there.
195
+ async function readMerged(prNums) {
196
+ if (!prNums.length) return [];
197
+ const fields = prNums.map((n) => `p${n}:pullRequest(number:${n}){state}`).join(" ");
198
+ const r = await execRead("gh", ["api", "graphql", "-F", "owner={owner}", "-F", "name={repo}",
199
+ "-f", `query=query($owner:String!,$name:String!){repository(owner:$owner,name:$name){${fields}}}`]);
200
+ let repo;
201
+ try { repo = JSON.parse(r.stdout)?.data?.repository; } catch {}
202
+ if (!isJsonObject(repo) || !prNums.some((n) => Object.prototype.hasOwnProperty.call(repo, `p${n}`))) {
203
+ // `how` as runCiState() spells it; never r.error.message, which repeats
204
+ // the whole query — one field per PR — into every failed tick's line.
205
+ const how = r.code ?? (r.signal ? `killed by ${r.signal}` : `exit ${r.status}`);
206
+ console.error(`${NAME}: gh api graphql merged read (${prNums.length} PR${prNums.length === 1 ? "" : "s"}) failed (${how}) with no usable answer; they read as not merged`);
207
+ return [];
208
+ }
209
+ return prNums.filter((n) => repo[`p${n}`]?.state === "MERGED");
210
+ }
211
+
212
+ // labels: gh emits an array of {name,...} objects, but a malformed row can
213
+ // hand back a non-array `labels` (`.map` throws) or an array containing a
214
+ // null/malformed element (`.name` throws) — reproduced live: either crashes
215
+ // gather() entirely, reaching main()'s `die()` on the build path or freezing
216
+ // the board on its last-known value on the serve path. Strictly worse than
217
+ // this ticket's original "shows undefined on the page" bug. Drop-and-continue,
218
+ // like withNumber above: a bad label never takes its row's whole labels array
219
+ // down, and a bad labels field never takes the row down.
220
+ function labelsOf(row) {
221
+ if (!Array.isArray(row.labels)) return [];
222
+ return row.labels
223
+ .map((l) => (l && typeof l.name === "string") ? l.name : null)
224
+ .filter(Boolean);
225
+ }
226
+
227
+ // ci-state.mjs exits 0 for green, 1 for not-green or no-ci, 2 for a hard
228
+ // failure — no-ci is its own verdict and shares exit 1 because this call omits
229
+ // --declare-no-ci, the only thing that would move it to exit 0 — and on
230
+ // exit 1 it has ALREADY printed its verdict JSON to stdout before exiting, so a
231
+ // thrown exit 1 carries a real verdict. Feed that to mapCi: discarding e.stdout,
232
+ // as a plain tryRun would, makes red/still-running CI unreachable — every
233
+ // non-green PR reads as "unknown" and the red-ci flag, the top of the attention
234
+ // strip, never fires.
235
+ //
236
+ // What separates a verdict from a failed read is the EXIT CODE. Emptiness of
237
+ // stdout was only ever a proxy for it, and that proxy no longer holds: a quota
238
+ // refusal now names its cause on stdout on the way out at exit 2, so "non-empty
239
+ // stdout" began reading an outage as a reading. That payload carries no
240
+ // `status`, so mapCi answered "unknown" and gather()'s prevCi carry-forward —
241
+ // which only a null return reaches — was skipped, overwriting a PR's
242
+ // last-known-good CI state during a blip that clears itself. Exit 2 means the
243
+ // question could not be answered, whatever the script printed while saying so.
244
+ //
245
+ // The exit code is not sufficient on its own either, for the symmetric
246
+ // reason: it reports that the child reached its own exit path, never that its
247
+ // payload arrived whole. `e.status !== 2` is also true of a signal kill, where
248
+ // `status` is null, and of a write cut mid-JSON at exit 1 — emit() over in
249
+ // ci-state.mjs abandons a short write it cannot retry, which keeps the exit
250
+ // code intact while losing the tail of the line. Those bytes were returned AS a
251
+ // verdict, mapCi could not parse them, and the non-null return skipped the very
252
+ // carry-forward added for the exit-2 case: that regression re-entering through the gate
253
+ // built to stop it. So both halves have to hold — a non-2 exit AND bytes that
254
+ // parse.
255
+ //
256
+ // The parse is the discriminator rather than "any abnormal termination", the
257
+ // other candidate, because only the parse gets both directions right. It
258
+ // catches the cut-off exit-1 write, which carries status 1 and no signal at all
259
+ // (measured), and it goes on ACCEPTING a complete payload from a child killed
260
+ // after writing it, as well as no-ci — a real exit-1 verdict whose own `status`
261
+ // field is null, so a status-shaped guard tightened far enough to catch a
262
+ // truncation starts refusing it and resurrects a red for a PR with no run
263
+ // behind it. Wholeness is the only question asked here; SHAPE stays mapCi's,
264
+ // which is total over every payload that parses.
265
+ async function runCiState(scriptDir, pr) {
266
+ const r = await execRead("node", [join(scriptDir, "ci-state.mjs"), "--pr", String(pr), "--quiet"]);
267
+ const out = r.stdout;
268
+ if (r.error) {
269
+ // `r.stdout` and not `error.stdout`: what the child managed to write before
270
+ // it died is the salvage this whole block exists for, and execRead's record
271
+ // carries it on every arm — including a spawn failure, where it is "".
272
+ if (r.status === 2 || !out.trim()) {
273
+ console.error(`${NAME}: ci-state --pr ${pr} failed: ${r.error.message}`);
274
+ return null;
275
+ }
276
+ // Its own line, not the one above: "failed" reads as "the child never
277
+ // answered", and an operator looking at a carried-forward CI value needs to
278
+ // know a payload DID arrive and was thrown away, and why.
279
+ //
280
+ // `how` reads the libuv/node `code` first — the three-way ci-state.mjs
281
+ // already uses at its own child reads — because one cause of this shape is
282
+ // OURS: overrunning READ_OPTS.maxBuffer is enforced by node killing the
283
+ // child, and that arrives as code ERR_CHILD_PROCESS_STDIO_MAXBUFFER
284
+ // (measured; the synchronous read this replaced reported the same cap as
285
+ // signal SIGTERM carrying code ENOBUFS). A signal-first `how` renders a cap
286
+ // this file sets as an outside kill, sending the operator after an OOM kill
287
+ // or a stray `kill -TERM`. The signal arm stays ahead of the exit arm
288
+ // behind it: `status` is null on a real signal kill, where "exit null"
289
+ // would name nothing to act on. execRead splits the async error's one
290
+ // `code` field back into these three, so all three arms still read as they
291
+ // did — measured: an exit 3 gives `status` 3 and no `code`, a SIGKILL gives
292
+ // `signal` and neither, an unreachable binary gives `code` ENOENT.
293
+ //
294
+ // Through the warn-once gate, keyed on the PR exactly as mapCi's
295
+ // `ci-parse` gate is and for the same reason: serve() re-gathers on a
296
+ // timer, so a payload truncated by a cause that persists is truncated
297
+ // again on every tick, and an ungated line spends one per PR per tick for
298
+ // as long as the cause lasts. Its own channel, `ci-salvage-nonzero`,
299
+ // distinct from both `ci-parse` and the exit-0 guard's `ci-salvage-exit0`
300
+ // below: for any one payload the three are mutually exclusive — bytes
301
+ // refused here return null and never reach mapCi — so a channel shared
302
+ // between any two of them would buy nothing, and would let whichever arm
303
+ // a PR happened to hit FIRST silence a later, structurally different
304
+ // failure on another arm for the rest of the run — measured: driving the
305
+ // same PR through this arm then the exit-0 guard below printed only the
306
+ // first tick's warning until the channels were split.
307
+ try { JSON.parse(out); }
308
+ catch (pe) {
309
+ const how = r.code ?? (r.signal ? `killed by ${r.signal}` : `exit ${r.status}`);
310
+ warnOnce("ci-salvage-nonzero", pr, `ci-state --pr ${pr} (${how}) left a payload that will not parse (${pe.message}); carrying the previous CI value forward rather than reading this as a verdict`);
311
+ return null;
312
+ }
313
+ return out;
314
+ }
315
+ // Exit 0 was never covered by any of the checks above — they only run
316
+ // once the child read reports a failure, and a child that exits 0 reports
317
+ // none. So the same write cut mid-JSON that the failure block above salvages
318
+ // at exit 1 rode straight through here and into mapCi at exit 0, where an
319
+ // unparseable string maps to "unknown" and gather()'s carry-forward — which
320
+ // only a null return reaches — was skipped, discarding the PR's last-known
321
+ // CI value exactly as the exit-2 case did before it was fixed. Same parse
322
+ // check, same null return as the failure block above — but its OWN channel,
323
+ // `ci-salvage-exit0`, not that block's `ci-salvage-nonzero`: a
324
+ // zero-exit child does not get a looser contract than a non-zero one, and
325
+ // the two arms are structurally different failures that must not silence
326
+ // each other (see the channel-split comment above).
327
+ //
328
+ // Emptiness is checked before the parse, and gets its own wording: an empty
329
+ // `out` is not a corrupted payload, it is no payload at all — "left a
330
+ // payload that will not parse" is a true diagnosis of truncated JSON and a
331
+ // false one of a child that printed nothing, the same distinction the
332
+ // empty/status-2 branch above draws for a non-zero exit.
333
+ try { JSON.parse(out); }
334
+ catch (pe) {
335
+ const msg = out.trim()
336
+ ? `ci-state --pr ${pr} (exit 0) left a payload that will not parse (${pe.message}); carrying the previous CI value forward rather than reading this as a verdict`
337
+ : `ci-state --pr ${pr} (exit 0) never answered; carrying the previous CI value forward rather than reading this as a verdict`;
338
+ warnOnce("ci-salvage-exit0", pr, msg);
339
+ return null;
340
+ }
341
+ return out;
342
+ }
343
+
344
+ // The `ci-parse` gate is keyed on the PR, not on the payload: `serve` rebuilds
345
+ // every ~15s and calls mapCi once per PR per tick, so a payload that is broken
346
+ // is broken on every tick, and a payload-keyed gate would flood anyway the
347
+ // moment the garbage varies between ticks. A single global flag is the other
348
+ // wrong answer — it would let the first broken PR mask every later one for the
349
+ // rest of the run, which is the silence this gate exists to end.
350
+
351
+ // ci-state's verdict already excludes behind-count staleness. Map it, and treat
352
+ // anything not cleanly green-or-completed-red as unknown — never a false red.
353
+ //
354
+ // `pr` is carried for the warn below and nothing else: an unparseable payload
355
+ // has no field to identify itself by, and "some PR's CI payload was garbage" is
356
+ // not actionable. The caller has the number in hand.
357
+ export function mapCi(ciJson, pr) {
358
+ // A NULL payload, which is a failed read runCiState() has already reported
359
+ // on stderr. Warning again here would report one failure twice. Null
360
+ // strictly, not falsiness: an EMPTY payload is not that case. Since
361
+ // runCiState() parse-checks its exit-0 return too, so its own callers never
362
+ // hand this an empty string any more — but mapCi() is exported and total
363
+ // over any caller, not just this file's, so a `!ciJson` guard that swallowed
364
+ // "" as though it had been reported would still be wrong. It falls through
365
+ // to the parse below instead, which is where it earns its line.
366
+ if (ciJson == null) return "unknown";
367
+ let d;
368
+ // A payload that will not parse is a THIRD state, and the return value cannot
369
+ // carry it: "unknown" is what the regression gate pins, since a false red is
370
+ // worse than no verdict. So the distinction leaves through stderr or not at
371
+ // all. That was closed for runCiState()'s catch block (a payload that will
372
+ // not parse there is a failed read, reaching gather()'s carry-forward);
373
+ // and for the exit-0 arm the same way (see runCiState() above),
374
+ // so a write cut mid-JSON no longer reaches mapCi from gather() on EITHER
375
+ // arm — a lost write now reads as a failed read there too, and that PR's
376
+ // last-known CI value stands instead of reverting to "unknown". This catch
377
+ // stays live regardless: mapCi() is exported and total over any string
378
+ // handed to it, parseable or not, and its own tests drive it directly
379
+ // without going through runCiState() at all.
380
+ try { d = JSON.parse(ciJson); }
381
+ catch (e) {
382
+ warnOnce("ci-parse", pr, `PR ${pr} ci-state payload is not JSON (${e.message}); reading its CI as unknown, so its red-ci flag stays down`);
383
+ return "unknown";
384
+ }
385
+ // JSON.parse("null") succeeds and yields d === null. Nullishness, not
386
+ // object-ness, is the discriminator: `[]` and `{}` are typeof "object" just
387
+ // as null is, but null alone has no properties to read, so the status gate
388
+ // throws a TypeError on it where every other parsed payload boxes and reads
389
+ // its status as undefined. Hence a guard with its own return, rather than a
390
+ // payload that reaches the status gate and answers "unknown" there. Silent,
391
+ // not warned: the status gate already answers every parseable payload it
392
+ // cannot read a status from without a line, and a bare "null" is no more
393
+ // corrupt than those.
394
+ if (d === null) return "unknown";
395
+ if (d.status !== "completed") return "unknown"; // still running, or no run yet (status null)
396
+ if (d.verdict === "green") return "green";
397
+ if (d.verdict === "not-green") return "red";
398
+ return "unknown";
399
+ }
400
+
401
+ // Where this session's member transcripts live:
402
+ // ~/.omp/agent/sessions/<encoded-cwd>/<ISO>_<uuid>/
403
+ //
404
+ // The session uuid is not knowable from here, so take the most recently
405
+ // active one. Rank on the newest TRANSCRIPT mtime, not on the session
406
+ // directory's own: a directory's mtime moves when an entry is created or
407
+ // removed, never when a file inside it is appended to. Ranking on the
408
+ // directory therefore tracked the last agent SPAWN rather than the last
409
+ // agent activity — and since the cockpit launches in run-team phase 0,
410
+ // before the first agent spawns, the live session has no transcript yet and
411
+ // a PREVIOUS session won. The board would render a prior run's spend as
412
+ // this run's, then silently switch when the first agent landed. That is the
413
+ // one failure mode here that produces confidently wrong numbers rather than
414
+ // no numbers.
415
+ //
416
+ // Returns { error } when there is no project dir for this cwd — a bug that
417
+ // never fixes itself — and null when one resolves but holds no sessions
418
+ // yet, which is normal at run start. Collapsing those two into one bare
419
+ // null is what hid the encoding bug above. A listing that THROWS is
420
+ // { error } too.
421
+ export function findSubagentsDir(home = process.env.HOME, cwd = process.cwd()) {
422
+ try {
423
+ const tree = sessionDirs(home, cwd);
424
+ if (tree.dirs === null) {
425
+ return { error: `no transcript dir for cwd ${cwd} (looked in ${tree.root})` };
426
+ }
427
+ const cands = tree.dirs
428
+ .map((d) => ({ d, m: newestTranscriptMs(d) }))
429
+ .sort((a, b) => b.m - a.m);
430
+ return cands.length ? cands[0].d : null;
431
+ } catch (e) { return { error: `transcript lookup failed: ${e.message}` }; }
432
+ }
433
+
434
+ // The candidate session directories for this cwd. `dirs: null` means there
435
+ // is no project dir here at all; `[]` means there is one holding no session
436
+ // yet. `root` is where it looked, for the error above.
437
+ //
438
+ // `encodeProjectDir` realpath-resolves a cwd outside $HOME, which throws
439
+ // ENOENT when that cwd does not exist. No omp session can be keyed on such a
440
+ // cwd, so THAT is this tree's absence — not a lookup fault. Any OTHER error
441
+ // (EACCES on an ancestor directory, say) is a real fault, not an absence,
442
+ // and must not be relabelled as one: swallowing it here would crash
443
+ // silently with no signal anything went wrong. It is rethrown, uncaught,
444
+ // into findSubagentsDir's own catch — the same fate a listing failure below
445
+ // already gets, deliberately.
446
+ function sessionDirs(home, cwd) {
447
+ const sessions = join(home, ".omp", "agent", "sessions");
448
+ let root;
449
+ try {
450
+ root = join(sessions, encodeProjectDir(cwd, { home }));
451
+ } catch (e) {
452
+ if (e.code !== "ENOENT") throw e;
453
+ return { root: sessions, dirs: null };
454
+ }
455
+ if (!existsSync(root)) return { root, dirs: null };
456
+ const dirs = readdirSync(root, { withFileTypes: true })
457
+ .filter((e) => e.isDirectory() && isOmpSessionDirName(e.name))
458
+ .map((e) => join(root, e.name));
459
+ return { root, dirs };
460
+ }
461
+
462
+ // Newest *.jsonl mtime anywhere under a session's transcript dir, 0 if it
463
+ // holds none. Recursive: a nested member (a dispatcher's own further
464
+ // fan-out, one directory level down — the same walk ompSessionTranscripts
465
+ // does to book their spend) can be the only fresh activity in an otherwise
466
+ // idle-looking session, and a scan bounded to the top level would score
467
+ // that session 0 and lose it to a genuinely stale sibling.
468
+ //
469
+ // A dir whose transcripts are all unreadable loses to one that is readable,
470
+ // which is the behaviour we want when picking "the live session".
471
+ //
472
+ // The scan is wrapped for the same reason the per-file stat below is. This runs
473
+ // once per CANDIDATE, so an uncaught throw here does not just lose one dir — it
474
+ // escapes findSubagentsDir's try and turns the whole lookup into { error },
475
+ // blacking out every readable session over one bad sibling. Scoring 0 is what
476
+ // the comment above already promises: a dir we cannot read simply loses.
477
+ function newestTranscriptMs(dir) {
478
+ let names;
479
+ try { names = readdirSync(dir, { recursive: true }); } catch { return 0; }
480
+ let newest = 0;
481
+ for (const f of names) {
482
+ if (!f.endsWith(".jsonl")) continue;
483
+ try { newest = Math.max(newest, statSync(join(dir, f)).mtimeMs); } catch { /* raced away */ }
484
+ }
485
+ return newest;
486
+ }
487
+
488
+ // The transcript directory a `serve` process is bound to, resolved
489
+ // once it can be trusted and reused by every tick after it. findSubagentsDir()
490
+ // above ranks sessions by newest transcript mtime and gather() reached it
491
+ // through gatherSpend() on EVERY tick (~15s by default), so two sessions live
492
+ // under one project directory took turns winning: the panel alternated
493
+ // between two runs' numbers with nothing on the page or on stderr to say it
494
+ // had switched.
495
+ //
496
+ // The pin holds the first answer that COULD BE THIS RUN'S, not the first
497
+ // non-null answer and not the first call. findSubagentsDir() has
498
+ // three returns and none of them is safe to latch on sight: a directory
499
+ // resolved at pin-construction time can be a PREVIOUS run's session — newer
500
+ // than nothing else that exists yet, so it wins the ranking, but not this
501
+ // run's — and `{ error }` can be a transient fault (EACCES on a directory
502
+ // mid-permission-change, EMFILE, EIO) recovering on the very next tick just
503
+ // as easily as it can be the truly unresolvable "bug that never fixes
504
+ // itself" the ticket originally reasoned about. Latching either one turns
505
+ // the self-correcting degradation this file's header describes into a
506
+ // permanent one: measured, a chmod'd-then-restored session tree left
507
+ // the OLD `??=` pin stuck on `{ error }` forever while the unpinned lookup
508
+ // recovered on its very next tick, and a prior run's session dir
509
+ // present at launch left the old pin on yesterday's numbers for the whole of
510
+ // today's run, even once today's first agent had written its own transcript.
511
+ //
512
+ // So `launchMs`, captured once at construction, is the boundary: `null` (no
513
+ // session anywhere yet) and `{ error }` (unresolvable OR transiently
514
+ // unreadable — indistinguishable from here, so neither is trusted) both keep
515
+ // re-asking, same one scan per tick the `null` case always cost. A resolved
516
+ // directory whose own newest transcript predates `launchMs` is treated the
517
+ // same way — returned as this tick's best-effort answer, so the panel still
518
+ // renders it, but not cached — because a transcript that stopped moving
519
+ // before this pin existed cannot be evidence of THIS run's activity. Only a
520
+ // directory whose newest transcript is at or after `launchMs` latches, which
521
+ // is the one fact available here that says "something is writing to this
522
+ // session on my watch", never a previous run's signature.
523
+ //
524
+ // An explicit directory skips the heuristic entirely — never resolved, never
525
+ // re-picked, and findSubagentsDir() is never called at all, so a tree it could
526
+ // not read cannot degrade a panel the operator has already named the source
527
+ // for. `home`/`cwd` are captured HERE rather than read per call for the same
528
+ // reason the resolution is: a pin that could answer for a different workspace
529
+ // later is not a pin.
530
+ //
531
+ // The limitation this leaves is stated at the top of this file: two sessions
532
+ // that both start writing after the pin exists are still indistinguishable.
533
+ // --spend-dir is the way out.
534
+ export function spendDirPin(explicit, home = process.env.HOME, cwd = process.cwd()) {
535
+ if (explicit != null) return () => explicit;
536
+ const launchMs = Date.now();
537
+ let pinned = null;
538
+ return () => {
539
+ if (pinned !== null) return pinned;
540
+ const answer = findSubagentsDir(home, cwd);
541
+ if (typeof answer !== "string") return answer; // null or { error }: neither is a trustworthy answer to latch
542
+ if (newestTranscriptMs(answer) < launchMs) return answer; // predates this pin — could be a previous run's
543
+ return (pinned = answer);
544
+ };
545
+ }
546
+
547
+ // The `no-spend-dir` gate warns at most once per process PER DISTINCT ERROR.
548
+ // `dir.error` is not constant — findSubagentsDir words an unresolvable project
549
+ // dir differently from a lookup that threw — so it is keyed on the message
550
+ // itself, not the empty string this gate used to key on: an empty key
551
+ // collapsed both wordings onto the one `no-spend-dir\0` slot, so whichever
552
+ // fault landed first for a process consumed the slot and a later, genuinely
553
+ // different fault never reached stderr again for the rest of the run. Keying
554
+ // on `dir.error` fixes that without losing the steady-state behaviour: `cwd`
555
+ // and `HOME` are fixed for the life of `serve`, so a repeating identical fault
556
+ // still costs one line, not one per tick. Either way this gate only ever
557
+ // controlled the repeated stderr LINE — a fault that differs still reaches the
558
+ // browser on the tick it happens, through the `{ error }` gatherSpend returns
559
+ // for it, which board.html renders as the panel's text. The board gathers
560
+ // every ~15s and a line repeating at that rate just trains the eye to ignore
561
+ // it.
562
+ //
563
+ // The `skips` gate is the same rule, per transcript: a file that is broken is
564
+ // broken every tick, and at the default 15s interval three of them are 720 lines
565
+ // an hour. Keyed on the FULL PATH, not the bare filename — gatherSpend
566
+ // re-resolves its dir on every tick, so a bare-filename key would silence a
567
+ // genuinely different broken file living under a second session directory. The
568
+ // count still reaches the browser every tick via `skipped`, which is the route
569
+ // that matters here.
570
+
571
+ // Scope is the SESSION directory, which is the closest thing to a run
572
+ // boundary that actually exists on disk — one session, one folder,
573
+ // identified by its own NAME: `<ISO>_<uuid>` (member-record.mjs's
574
+ // isOmpSessionDirName, the rule its own readers dispatch on).
575
+ //
576
+ // `sinceMs` is opt-in and defaults to no filter. An earlier attempt defaulted it
577
+ // to the ledger's mtime as a "run start" marker; that is wrong and silently
578
+ // reported zero, because the controller rewrites ledger rows continuously, so the
579
+ // mtime is always ~now and every transcript sorts as older than it. Kept as an
580
+ // explicit option for the one case the session scope cannot cover: a single
581
+ // session that spans two fleet runs, where the caller knows the boundary and the
582
+ // board does not.
583
+ //
584
+ // Three returns, deliberately distinct — collapsing them into one bare null is
585
+ // what let the path-encoding bug live: `{ ok: false, error }` is a bug the
586
+ // operator must act on and the UI shows it; `null` is the normal "nothing yet"
587
+ // and the UI hides the panel; `{ ok: true, ... }` is data.
588
+ //
589
+ // `ok` is an explicit TAG, and it is what the page switches on — never the
590
+ // presence or the truthiness of any other field. Reading the error case off
591
+ // `error`'s truthiness was a bug: `e.message` is "" for an error thrown
592
+ // without one and `undefined` for a thrown non-Error, so two shapes the catch
593
+ // below can emit matched neither the error branch nor a success shape, and the
594
+ // panel HID — a fault rendered as an idle run, the one conflation this panel
595
+ // exists to remove. A presence check would have fixed the "" case and still
596
+ // mis-routed the `undefined` one, and either is a refactor away from a
597
+ // truthiness check returning, because nothing in the data says which field is
598
+ // the tag. This follows `ledger.mjs`'s `tracker`: a boolean checked before any
599
+ // success-only field is read.
600
+ export function gatherSpend({ dir = findSubagentsDir(), sinceMs = null, topN = 8, explicit = false } = {}) {
601
+ try {
602
+ // A caller-supplied `null` is a RESOLUTION from one that owns a pin
603
+ // (spendDirPin() above) — the project directory is there and holds no
604
+ // session yet — and must not run the heuristic a second time; only an
605
+ // omitted `dir` (every gatherSpend test driver, and `build`, which is one
606
+ // gather per process and so needs no pin) defaults to it. A default
607
+ // parameter fires on `undefined` alone, never `null`, which is exactly
608
+ // that distinction — the hand-rolled `if (dir === undefined) dir =
609
+ // findSubagentsDir();` this used to spell out is redundant with it.
610
+ //
611
+ // `explicit` is true only when `dir` came from the operator's
612
+ // own --spend-dir, never from the heuristic or an unresolved pin — see
613
+ // its one use below, at the empty-directory branch.
614
+ const dirError = dir?.error;
615
+ if (dirError) {
616
+ warnOnce("no-spend-dir", dirError, dirError);
617
+ return { ok: false, error: dirError };
618
+ }
619
+ if (!dir) return null; // resolved, but this session has spawned no agents yet
620
+ // Only for an EXPLICIT --spend-dir — the heuristic's own
621
+ // findSubagentsDir() already dispatches on isOmpSessionDirName, so a
622
+ // resolved-but-non-heuristic `dir` here only ever arrives from the
623
+ // operator naming a directory directly. Without this check the
624
+ // mis-levelled path this same function's comments already name (the
625
+ // encoded-cwd project dir instead of its own <ISO>_<uuid> child) walked
626
+ // straight into readOmpSpend below, which recurses over every nested
627
+ // .jsonl with no name check of its own, and booked every session's
628
+ // transcripts — including the controller's own main-session one — as
629
+ // "agents" instead of refusing.
630
+ if (explicit && !isOmpSessionDirName(basename(dir))) {
631
+ const error = `${dir} is not an omp <ISO>_<uuid> session directory`;
632
+ warnOnce("bad-spend-dir", dir, `--spend-dir ${error}`);
633
+ return { ok: false, error };
634
+ }
635
+
636
+ const { agents, toolTables, skipped, damaged } = readOmpSpend(dir, sinceMs);
637
+ if (!agents.length) {
638
+ // `damaged` belongs here beside `skipped`. An omp transcript with
639
+ // no parseable assistant-with-usage line folds to no model, so
640
+ // readOmpSpend drops it without a throw — `skipped` stays 0 — and its
641
+ // non-last parse failures are the only trace that the directory held a
642
+ // transcript at all. Reading `skipped` alone sent that down the empty
643
+ // path below: a hidden panel, or an explicit override told the directory
644
+ // "holds no agent transcripts". A torn LAST line never counts as damaged,
645
+ // so a live write's partial first line still takes the empty path.
646
+ // A wholly-corrupt transcript with a readable "not executed" tool
647
+ // result but no assistant-with-usage line still drops here rather
648
+ // than booking at zero spend.
649
+ //
650
+ // `damaged` counts LINES, `skipped` whole transcripts, so each keeps its
651
+ // own clause — the lines one in board.html's damagedPhrase wording. "all
652
+ // N transcripts unreadable" stays for `skipped` alone: beside damaged
653
+ // lines it would count only the whole files and read as the entire loss.
654
+ if (damaged) {
655
+ const lost = [`${damaged} damaged transcript line${damaged === 1 ? "" : "s"}`];
656
+ if (skipped) lost.unshift(`${skipped} transcript${skipped === 1 ? "" : "s"} unreadable`);
657
+ return { ok: false, error: `no agent turn readable: ${lost.join("; ")}` };
658
+ }
659
+ if (skipped) return { ok: false, error: `all ${skipped} transcripts unreadable` };
660
+ // Only for an EXPLICIT override — never the heuristic's own
661
+ // "resolved, no session yet" `null` case two arms up, which is the
662
+ // normal state at launch and must stay silent. An operator who named
663
+ // this exact directory has a panel that just went quiet with nothing
664
+ // saying whether that is the normal "not written yet" wait or a typo'd
665
+ // / mis-levelled path (e.g. the encoded-cwd directory instead of its
666
+ // own `<ISO>_<uuid>` child) that will never resolve.
667
+ if (explicit) warnOnce("empty-spend-dir", dir, `--spend-dir ${dir} exists but holds no agent transcripts`);
668
+ return null;
669
+ }
670
+ const spend = computeSpend({ agents, topN });
671
+ const tools = mergeTools(toolTables);
672
+ // What fraction of cache_creation the tool table actually explains. It is
673
+ // never 100%: only a turn that FOLLOWS a tool result can be attributed to a
674
+ // tool, and an agent's first turn — usually its largest single write, the
675
+ // system prompt and context — follows nothing. Surfacing the coverage keeps
676
+ // the two columns honest about being different bases; without it the tool
677
+ // percentages silently read as shares of the headline number, which they
678
+ // are not.
679
+ const attributed = tools.reduce((n, t) => n + t.cacheWrite, 0);
680
+ const attributedPct = spend.totals.cacheWrite > 0 ? (attributed / spend.totals.cacheWrite) * 100 : 0;
681
+ // `ok` last, so a future field named `ok` on computeSpend's return cannot
682
+ // silently untag a success (a later spread key always wins over an earlier one).
683
+ return { ...spend, tools, attributedPct, skipped, damaged, since: sinceMs, ok: true };
684
+ } catch (e) {
685
+ // A real bug, not an empty run — say so rather than hiding the panel, which
686
+ // is what turned the last type surprise in here into "no panel appeared".
687
+ // `e.message` is carried as-is, including the "" and `undefined` a
688
+ // message-less throw would give it: the tag above is what routes this to the
689
+ // error panel, so an unhelpful message costs wording, never the panel.
690
+ // An explicit --spend-dir naming a directory that does not exist
691
+ // YET (the legitimate, tested case) throws ENOENT here on every tick
692
+ // until it appears, and this catch used to print unconditionally — one
693
+ // line per ~15s tick, forever. Routed through warnOnce, keyed on the
694
+ // message the same way the `{ error }` arm above it already is, so a
695
+ // repeating fault costs one stderr line, not one per tick.
696
+ warnOnce("spend-read-failed", e.message, `spend read failed: ${e.message}`);
697
+ return { ok: false, error: e.message };
698
+ }
699
+ }
700
+
701
+ // omp's side: one agent per member transcript anywhere under the
702
+ // session dir — a nested member's too, at its own spawnDepth — read by
703
+ // member-record.mjs's own omp reader over the walk readOmpSession uses:
704
+ // foldOmpTranscript once per file, then ompMemberRecord on that fold, never
705
+ // a second parse of omp's line shape. So each row's totals, model and role
706
+ // are exactly the member record's: role from `session_init`'s agent
707
+ // definition, task and AgentId, label the AgentId itself (the path-relative
708
+ // stem, `review-pr-12/Security` for a nested one). The same fold's `entries`
709
+ // are the tool stream, so the tool table goes through attributeTools.
710
+ //
711
+ // Per-transcript tolerance is this file's, not readOmpSession's: readOmpSession
712
+ // (used by the bulk scrape) lets a wrong-shape refusal propagate, and here
713
+ // both — an unreadable file and a wrong-shape refusal — are one transcript's
714
+ // fault, so readOmpSpend, this file's own reader, instead catches both per-
715
+ // transcript, landing them in `skipped` with a stderr line. A transcript
716
+ // ompMemberRecord answers null for (no assistant turn yet — a member
717
+ // dispatched this second) has spent nothing, so it is neither booked nor
718
+ // skipped.
719
+ //
720
+ // `damaged` is real — the tool-attribution stream is a join
721
+ // across lines (a toolCall's id names its tool, a pending result batch bills
722
+ // the next turn), so a dropped MIDDLE line can silently shift spend onto a
723
+ // neighbouring tool instead of just costing its own turn's totals — the
724
+ // hazard foldOmpTranscript's `malformedNonLastLines` counts. This reader
725
+ // sums it across
726
+ // the transcript regardless of whether the file ends up booked as an agent,
727
+ // so a transcript that is corrupt where its assistant-with-usage line should
728
+ // be still surfaces here instead of falling through `if (!m) continue` unseen.
729
+ function readOmpSpend(dir, sinceMs) {
730
+ const agents = [];
731
+ const toolTables = [];
732
+ let skipped = 0;
733
+ let damaged = 0;
734
+ for (const { file, agent, spawnDepth } of ompSessionTranscripts(dir)) {
735
+ try {
736
+ if (sinceMs != null && statSync(file).mtimeMs < sinceMs) continue;
737
+ const folded = foldOmpTranscript(readFileSync(file, "utf8"), file);
738
+ damaged += folded.malformedNonLastLines;
739
+ const m = ompMemberRecord(folded, agent, spawnDepth);
740
+ if (!m) continue;
741
+ // Both halves before either is recorded, so `skipped++` below always
742
+ // means "this transcript contributed nothing".
743
+ const tools = attributeTools(folded.entries);
744
+ agents.push({
745
+ label: m.member, role: m.role, model: m.model,
746
+ cacheWrite: m.tokens_cache_create, output: m.tokens_out, cacheRead: m.tokens_cache_read,
747
+ });
748
+ toolTables.push(tools);
749
+ } catch (e) {
750
+ skipped++;
751
+ // The prefix already names `file`; Node's errno text (`..., open|stat
752
+ // '<file>'`) and member-record's shape refusal (`...: <file>`) end in
753
+ // it too, so that tail is dropped. Any other wording prints whole.
754
+ let why = String(e.message);
755
+ for (const tail of [` '${file}'`, `: ${file}`]) {
756
+ if (why.endsWith(tail)) { why = why.slice(0, -tail.length); break; }
757
+ }
758
+ warnOnce("skips", file, `skipping ${file}: ${why}`);
759
+ }
760
+ }
761
+ return { agents, toolTables, skipped, damaged };
762
+ }
763
+
764
+ // `workspace`/`port` are the caller's answers, never read in here:
765
+ // resolveCockpitInstance() already decided both, and a second derivation in
766
+ // this function could disagree with the one the server actually bound. They
767
+ // join the payload HERE, alongside the repo fields above, because this is the
768
+ // boundary where every impure input meets the pure model — computeBoard() only
769
+ // echoes them. Defaulted to null, which is also the degrade arm's workspace
770
+ // and the value the launch handshake refuses to match on, so a caller with no
771
+ // instance to name (every gather() test driver) says so rather than omitting
772
+ // the fields.
773
+ //
774
+ // `spendDir` is the caller's transcript directory and is the one
775
+ // parameter here whose ABSENCE is not a default to fill in: the tick loop hands
776
+ // the same pin's answer to every tick, and its three shapes — a directory, `null`
777
+ // for "resolved, no session yet", `{ error }` for unresolvable — all have to
778
+ // reach gatherSpend() as themselves. `build` is one gather per process, so it
779
+ // needs the --spend-dir override but never a pin, and passes the override or
780
+ // nothing; with neither the pin nor the flag, gatherSpend() resolves for itself.
781
+ //
782
+ // `spendDirExplicit` is passed separately from `spendDir` itself: the tick
783
+ // loop always passes a resolved `spendDir` (the pin's answer), never leaving it
784
+ // to default, so `spendDir`'s own presence cannot say whether an operator named
785
+ // it. Whether --spend-dir was given is a fact about argv, unrelated to which of
786
+ // gatherSpend's three shapes the pin currently holds. It, `spendSince` and
787
+ // `interval` are argv's answers, resolved by the caller: nothing in here reads
788
+ // argv.
789
+ // Async, because every child read below is. The event loop this frees
790
+ // belongs to serve()'s HTTP server, which shares this process — see execRead's
791
+ // note in board-common.mjs for what the synchronous version cost. `build` awaits it and is
792
+ // otherwise unchanged: one gather per process, nothing else waiting on it.
793
+ export async function gather({ ledgerFile, prevFile, stateFile = null, scriptDir = SCRIPT_DIR, interval, workspace = null, port = null, spendDir, spendDirExplicit = false, spendSince = null }) {
794
+ // The one read that must not crash the gather: a corrupt/partial board.json
795
+ // (the fallback safety net itself) is ignored, not fatal. That holds for a
796
+ // SHAPE fault as much as a parse fault — the guard below rejects the
797
+ // payload here so both leave through the one catch, which names the file the
798
+ // operator passed. A wrong-typed `tickets` left to reach the prevCi map
799
+ // instead throws `.filter is not a function` out of gather(), which made a
800
+ // corrupt prev board fatal after all and blamed an "intermediate value".
801
+ //
802
+ // Validated HERE and not per-read, deliberately: this payload has three more
803
+ // readers (`prev?.repo`/`prev?.repoUrl` below, and compute-board.mjs's dwell
804
+ // tracking, which consumes the whole `prev` this returns), and the prevCi
805
+ // expression's `|| []` is the demonstration — it defends against an ABSENT
806
+ // `tickets`, never a present one of the wrong type. This guard covers that one
807
+ // shape — `prev` is an object, `tickets` is an array of objects — not every
808
+ // field those three readers go on to trust: a wrong-typed `repo`, `repoUrl`, or
809
+ // `sinceEnteredStage` still reaches them unchanged. Those `?.`/`|| []` defaults
810
+ // stay as the belt to these braces.
811
+ let prev = null;
812
+ if (prevFile && existsSync(prevFile)) {
813
+ try {
814
+ // JSON.parse SUCCEEDS on `null`, a bare number, a string and an array,
815
+ // none of which is a board; `null` in particular is absent, not an
816
+ // object, and `typeof null` alone would let it through. Same check and
817
+ // same wording as readMerged()'s `data.repository` read, which is this
818
+ // repo's precedent for rejecting a parsed-but-wrong payload at its own
819
+ // read — literally the same, both calling the shared predicate.
820
+ const p = JSON.parse(readFileSync(prevFile, "utf8"));
821
+ if (!isJsonObject(p)) throw new TypeError(`expected a JSON object, got ${jsonKind(p)}`);
822
+ // Nullish `tickets` is ABSENT and stays usable: `|| []` reads it as the
823
+ // empty carry-forward, which is what a board with no PRs on it says.
824
+ // Only a present-and-wrong-typed one is a fault.
825
+ if (p.tickets != null) {
826
+ if (!Array.isArray(p.tickets))
827
+ throw new TypeError(`expected tickets to be an array, got ${typeof p.tickets}`);
828
+ // Per ENTRY too, and not because a `[null]` is exotic: `Array.isArray`
829
+ // is satisfied by an array of anything, and the very next thing the
830
+ // prevCi map does is read `t.pr` off each element. The whole payload
831
+ // goes, not the bad entry — a board with one unreadable ticket is not a board
832
+ // whose others can be trusted to carry CI state forward, and filtering here
833
+ // (drop the bad entry, keep the rest) would make this a new, fourth policy for
834
+ // one payload class in this file — mapCi's null-only guard and tryParse's
835
+ // unguarded read are the other two — rather than the reject-whole-payload
836
+ // policy this guard already shares with readMerged()'s own read.
837
+ const bad = p.tickets.findIndex((t) => !isJsonObject(t));
838
+ if (bad !== -1)
839
+ throw new TypeError(`expected tickets[${bad}] to be a JSON object, got ${jsonKind(p.tickets[bad])}`);
840
+ }
841
+ prev = p;
842
+ }
843
+ catch (e) { console.error(`${NAME}: ignoring unreadable prev board ${prevFile}: ${e.message}`); }
844
+ }
845
+
846
+ // `--require-file` turns an absent ledger into a refusal at exit 2 rather
847
+ // than the empty payload a real empty ledger returns. Without it the
848
+ // two are byte-identical on stdout, and tryParse's fallback is that same
849
+ // empty shape besides — so an unread ledger, one read empty, and a read whose
850
+ // answer would not parse were three states with one rendering, on the one
851
+ // subcommand this cockpit consumes.
852
+ //
853
+ // The three stay three here because each is a different observation, not a
854
+ // different value of one: null from tryRun is a read that did not happen (the
855
+ // refusal, or an unreachable node), null from tryParse is a read whose answer
856
+ // was unusable, and anything else is the ledger. `tryParse`'s fallback is
857
+ // null rather than the empty shape for exactly that reason — the empty shape
858
+ // is a real answer and must not double as the failure.
859
+ const ledgerJson = await tryRun("node", [join(scriptDir, "ledger.mjs"), "--file", ledgerFile, "--require-file", "read"]);
860
+ // "read" means ledgerJson parsed as JSON, not that it conforms to the
861
+ // {rows,filed,ruled} shape — tryParse only checks syntax, so a
862
+ // syntactically-valid-but-wrong-shape payload from ledger.mjs would still
863
+ // be labelled "read" here. ledger.mjs is this repo's own, already-tested
864
+ // producer of this JSON, so that gap is accepted rather than guarded.
865
+ const parsedLedger = tryParse(ledgerJson, null, "ledger read");
866
+ // Strictly `!== null`, never falsiness — a ledger payload that parses to
867
+ // `0`, `false` or `""` is a real answer tryParse already forwarded (see
868
+ // tryParse's own comment above), and treating it as falsy here would
869
+ // silently discard it into `unparsed`, the exact bug class tryParse's
870
+ // guard exists to prevent, one caller downstream of the fix.
871
+ const ledger = parsedLedger !== null
872
+ ? { ...parsedLedger, state: "read" }
873
+ : { rows: [], filed: [], ruled: [], state: ledgerJson == null ? "unread" : "unparsed" };
874
+
875
+ const issuesJson = await tryRun("gh", ["issue", "list", "--label", "ready-for-agent",
876
+ "--state", "open", "--limit", String(POOL_LIMIT), "--json", "number,title,labels"]);
877
+ // title: falls back to the same `#<number>` placeholder titleFor() already
878
+ // uses for an issue it cannot find at all (compute-board.mjs). An unrowed
879
+ // issue becomes a POOL card straight from this array — compute-board.mjs's
880
+ // POOL loop reads `iss.title` RAW, never through titleFor()'s fallback
881
+ // chain — so this row genuinely needs a guaranteed string: an issue found
882
+ // but unable to describe itself reads as its number rather than literal
883
+ // `undefined` on the operator's page.
884
+ //
885
+ // Its null fallback, not the open-PR read's `[]` below, is deliberate:
886
+ // this read is the pool's ONLY source, and
887
+ // compute-board.mjs's stall() needs to tell a genuinely empty pool from a
888
+ // `gh` outage the same way it already tells an empty ledger from an unread
889
+ // one — a `[]` fallback collapses both to the identical shape before a
890
+ // caller here could split them back apart.
891
+ const issuesParsed = tryParse(issuesJson, null, "gh issue list");
892
+ const poolOk = issuesParsed !== null;
893
+ const poolCapped = hitLimit(issuesParsed, POOL_LIMIT);
894
+ const issues = withNumber(poolOk ? issuesParsed : [], "gh issue list").map((i) => ({
895
+ number: i.number,
896
+ title: typeof i.title === "string" ? i.title : `#${i.number}`,
897
+ labels: labelsOf(i),
898
+ }));
899
+
900
+ const prsJson = await tryRun("gh", ["pr", "list", "--state", "open", "--limit", String(OPEN_PR_LIMIT),
901
+ "--json", "number,state,labels,title,headRefOid"]);
902
+ // No default for `title` or `state` here, unlike the issue row above — raw
903
+ // passthrough, deliberately. `title`: compute-board.mjs's titleFor() already
904
+ // falls through a falsy `pr.title` to the real issue title (`if (pr &&
905
+ // pr.title) return pr.title;`); nothing else reads a PR row's `title` field
906
+ // raw, so defaulting it to `#<number>` made it unconditionally truthy and
907
+ // SILENTLY DISABLED that fallback — a titleless PR row showed the PR number
908
+ // instead of the real issue title, worse than doing nothing. `state`: its
909
+ // only consumer is `pr.state === "OPEN"` (compute-board.mjs), already false
910
+ // for `undefined` exactly as it was for the old "UNKNOWN" sentinel, so the
911
+ // default was inert — pure indirection with no behaviour to show for it.
912
+ const prsParsed = tryParse(prsJson, [], "gh pr list");
913
+ const prsCapped = hitLimit(prsParsed, OPEN_PR_LIMIT);
914
+ const prs = withNumber(prsParsed, "gh pr list").map((p) => ({
915
+ number: p.number,
916
+ state: p.state,
917
+ title: p.title,
918
+ labels: labelsOf(p),
919
+ // compute-board.mjs's reviewBacklog needs it to tell a
920
+ // past-pin halt already answered by the automatic re-review apart from
921
+ // one still owed a fresh one — the same field fleet-tick.mjs's
922
+ // openPrs() already requires.
923
+ headRefOid: p.headRefOid,
924
+ }));
925
+
926
+ // MERGED is gh's answer, not a ledger token — no rule writes `MERGED
927
+ // <sha>`, and the open list above drops a PR the moment it merges. It is
928
+ // asked only about mergedReadPrs()'s set — row PRs absent from the open
929
+ // list, with no token, not carried forward — in one batched read
930
+ // that answers whatever their merge age; see readMerged(). A failed read
931
+ // is `[]`, and the carry-forward in computeBoard() covers exactly the
932
+ // PRs this set leaves out, so a failure costs only a PR never yet seen
933
+ // MERGED, which reads REVIEW.
934
+ const merged = await readMerged(mergedReadPrs({ ledger, prs, prev }));
935
+
936
+ // CI per open PR. On failure, carry the previous board's value for that PR.
937
+ const prevCi = new Map((prev?.tickets || []).filter((t) => t.pr != null).map((t) => [t.pr, t.ci]));
938
+ const ci = {};
939
+ // Awaited one at a time rather than raced with Promise.all, and that is a
940
+ // decision rather than an oversight: this loop spawns one `node
941
+ // ci-state.mjs` per open PR and each of those hits the GitHub API, so a fan
942
+ // of 40 at once is a rate-limit and a load spike where a queue of 40 is
943
+ // neither. Nothing here waits on the loop any more — the server answers
944
+ // throughout it — so the only thing concurrency would buy is a
945
+ // shorter tick, against an interval measured in seconds. The warn-once
946
+ // lines below also stay in PR order this way.
947
+ for (const p of prs) {
948
+ const out = await runCiState(scriptDir, p.number);
949
+ ci[p.number] = out === null ? (prevCi.get(p.number) ?? "unknown") : mapCi(out, p.number);
950
+ }
951
+
952
+ // Repo identity + web URL for PR links — the url carries the host, so links
953
+ // resolve on GitHub Enterprise, not just github.com. From the fleet's cwd, so
954
+ // the board stays repo-agnostic. On failure, carry the previous board's values.
955
+ const repoJson = await tryRun("gh", ["repo", "view", "--json", "nameWithOwner,url"]);
956
+ let repo = prev?.repo ?? null;
957
+ let repoUrl = prev?.repoUrl ?? null;
958
+ if (repoJson) {
959
+ try { const d = JSON.parse(repoJson); repo = d.nameWithOwner ?? repo; repoUrl = d.url ?? repoUrl; }
960
+ catch (e) { console.error(`${NAME}: gh repo view parse failed: ${e.message}`); }
961
+ }
962
+
963
+ // The guard's own rationale (fail loud, gate on presence and on range,
964
+ // not just finiteness) lives at argSpendSince()'s definition in board.mjs,
965
+ // whose main() runs it and hands the answer in as `spendSince`.
966
+ const spend = gatherSpend({ dir: spendDir, sinceMs: spendSince, explicit: spendDirExplicit });
967
+ // The heartbeat's mark, raw. readState() never throws — an absent
968
+ // file is the ordinary state of a run whose heartbeat has not beaten yet,
969
+ // and an unreadable or corrupt one announces itself on stderr and degrades
970
+ // to no mark, which computeBoard() renders as no panel rather than as a
971
+ // death it cannot substantiate. So no try/catch here and no `tryRun` shape:
972
+ // the degrade lives in the module that owns the file.
973
+ //
974
+ // `null` when no caller named a state file, and DISTINCT from a file that
975
+ // is simply absent: both omit the surface today, but only the second is a
976
+ // reading. Defaulted rather than resolved here for gather()'s own reason —
977
+ // every caller in this file passes the instance's answer, and a second
978
+ // resolution could name a different workspace's beat.
979
+ // `ticked`, `acted` and `controller` ride beside `beat`, same file same
980
+ // read, and under the same "no try/catch, no tryRun shape" rule just above:
981
+ // a run is judged from all of its own marks, and the record's `at` is what
982
+ // tells this run's marks from the previous run's (fleet-state.mjs's
983
+ // assessBeat has the rule).
984
+ const priorState = stateFile ? readState(stateFile, NAME) : null;
985
+ const beat = priorState?.beat ?? null;
986
+ const ticked = priorState?.ticked ?? null;
987
+ const acted = priorState?.acted ?? null;
988
+ const controller = priorState?.controller ?? null;
989
+ // Whose stall it is, off the controller record in the same file — judged
990
+ // here because it reads the process table, and only when the mark is
991
+ // stalled, so a healthy board reads none. computeBoard() words it.
992
+ const now = Date.now();
993
+ const stallOwnerOf = isStalled(assessBeat({ beat, ticked, acted, controller, now })) ? stallOwner(priorState, NAME) : null;
994
+ return { ledger, issues, prs, merged, ci, prev, repo, repoUrl, workspace, port, spend, beat, ticked, acted, controller, stallOwner: stallOwnerOf, poolOk,
995
+ poolCapped, prsCapped,
996
+ now, interval };
997
+ }