@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.
- package/package.json +1 -1
- package/scripts/arg.mjs +1 -1
- package/scripts/board-common.mjs +3 -3
- package/scripts/board-gather.mjs +997 -0
- package/scripts/board-server.mjs +611 -0
- package/scripts/board.mjs +28 -1598
- package/scripts/ci-state.mjs +2 -2
- package/scripts/ledger.mjs +2 -2
- package/skills/run-team/SKILL.md +3 -4
package/scripts/board.mjs
CHANGED
|
@@ -1,64 +1,32 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
// The cockpit's
|
|
3
|
-
//
|
|
4
|
-
//
|
|
5
|
-
//
|
|
6
|
-
//
|
|
7
|
-
//
|
|
8
|
-
//
|
|
9
|
-
//
|
|
10
|
-
//
|
|
11
|
-
//
|
|
12
|
-
//
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
// directory can hold several sessions at once. `serve` therefore resolves ONE
|
|
16
|
-
// session's transcript directory and keeps it for its whole life — see
|
|
17
|
-
// spendDirPin() below — rather than re-picking the newest on every tick and
|
|
18
|
-
// alternating between two live runs' numbers in silence.
|
|
19
|
-
//
|
|
20
|
-
// LIMITATION, stated rather than solved: the session it keeps is whichever
|
|
21
|
-
// FIRST writes a transcript at or after the pin's own construction.
|
|
22
|
-
// Before that, a session that was already active when the pin was built —
|
|
23
|
-
// this run's own, mid-EACCES-fault, or a genuinely previous run's — is never
|
|
24
|
-
// latched; the pin keeps re-asking findSubagentsDir() every tick instead,
|
|
25
|
-
// which is what lets a transient fault or a stale session recover instead of
|
|
26
|
-
// freezing the panel for the server's whole life. What is not solved: two
|
|
27
|
-
// sessions that BOTH start writing after the pin exists, in the same project
|
|
28
|
-
// directory, are still indistinguishable — the board is scoped to a
|
|
29
|
-
// workspace and a workspace does not know that — so the first of them
|
|
30
|
-
// to pass the newest-transcript check wins and keeps winning. `--spend-dir
|
|
31
|
-
// <path>` is how an operator names the right one: it overrides the
|
|
32
|
-
// heuristic outright.
|
|
33
|
-
|
|
34
|
-
import { readFileSync, writeFileSync, renameSync, existsSync, readdirSync, statSync, writeSync } from "node:fs";
|
|
35
|
-
import { classifyRole, computeSpend, attributeTools, mergeTools } from "./compute-spend.mjs";
|
|
36
|
-
import {
|
|
37
|
-
encodeProjectDir, isOmpSessionDirName, ompSessionTranscripts, foldOmpTranscript, ompMemberRecord,
|
|
38
|
-
} from "./member-record.mjs";
|
|
2
|
+
// The cockpit's entry point, and only its composition. `build` has gather()
|
|
3
|
+
// (board-gather.mjs) read the raw inputs, hands them to the pure computeBoard()
|
|
4
|
+
// and prints the board model as JSON to stdout. `serve` has serve()
|
|
5
|
+
// (board-server.mjs) own the listener and the cockpit's identity, and runs the
|
|
6
|
+
// tick loop that this file hands it: gather() -> computeBoard() -> an atomic
|
|
7
|
+
// write of .fleet/board.json.
|
|
8
|
+
// The board never depends on the controller feeding it.
|
|
9
|
+
//
|
|
10
|
+
// What stays here is what neither half owns: argv parsing, the build/serve
|
|
11
|
+
// dispatch, the tick loop with its overlap guard and spend pin, and the fault
|
|
12
|
+
// path.
|
|
13
|
+
|
|
14
|
+
import { writeFileSync, renameSync, writeSync } from "node:fs";
|
|
39
15
|
import { defineFlags } from "./arg.mjs";
|
|
40
|
-
import { NAME, die, warnOnce
|
|
41
|
-
import {
|
|
42
|
-
import {
|
|
43
|
-
// The heartbeat's liveness mark,
|
|
44
|
-
//
|
|
45
|
-
//
|
|
46
|
-
//
|
|
47
|
-
//
|
|
48
|
-
//
|
|
49
|
-
|
|
50
|
-
// It also reads the controller record beside the mark, and the process table
|
|
51
|
-
// through stallOwner(), to name whose stall a stopped beat is; the record's
|
|
52
|
-
// writer is `ledger.mjs rotate`, and the cockpit never writes it either.
|
|
53
|
-
import { readState, stateFileIn, assessBeat, isStalled, stallOwner } from "./fleet-state.mjs";
|
|
54
|
-
import { fileURLToPath } from "node:url";
|
|
16
|
+
import { NAME, die, warnOnce } from "./board-common.mjs";
|
|
17
|
+
import { gather, spendDirPin } from "./board-gather.mjs";
|
|
18
|
+
import { serve, resolveCockpitInstance, cockpitWorkspace } from "./board-server.mjs";
|
|
19
|
+
// The heartbeat's liveness mark path, taken from the module that owns the
|
|
20
|
+
// filename rather than spelling `heartbeat.json` a second time. The PATH
|
|
21
|
+
// still comes from resolveCockpitInstance() (board-server.mjs), not from
|
|
22
|
+
// statePath(): the workspace is already resolved once per launch there, with
|
|
23
|
+
// the `canonicalise` opt-in only that caller takes, and a second resolution
|
|
24
|
+
// could answer differently.
|
|
25
|
+
import { stateFileIn } from "./fleet-state.mjs";
|
|
55
26
|
import { isCLI } from "./is-cli.mjs";
|
|
56
|
-
import {
|
|
57
|
-
import { createServer, request as httpRequest } from "node:http";
|
|
58
|
-
import { connect } from "node:net";
|
|
27
|
+
import { join } from "node:path";
|
|
59
28
|
import { inspect } from "node:util";
|
|
60
29
|
|
|
61
|
-
const SCRIPT_DIR = dirname(fileURLToPath(import.meta.url));
|
|
62
30
|
// arg()/has() shared with the other fleet scripts — see arg.mjs for
|
|
63
31
|
// the fail-open and pipe-safety rationale.
|
|
64
32
|
const { arg, has, sweep, stray } = defineFlags(die, {
|
|
@@ -95,30 +63,6 @@ const { arg, has, sweep, stray } = defineFlags(die, {
|
|
|
95
63
|
// `prev` — `prev` was read on `build` alone, and serve() never read it at
|
|
96
64
|
// all. Hoisted in main() below, next to the --port/--open reads.
|
|
97
65
|
|
|
98
|
-
// The "is this a plain JSON object" predicate and its kind word, one
|
|
99
|
-
// copy for the reads in this file that reject a parsed-but-wrong payload
|
|
100
|
-
// WHOLE — gather's `--prev` payload, gather's per-entry `tickets[i]` check,
|
|
101
|
-
// and readMerged()'s `data.repository`. Each carried its own inline
|
|
102
|
-
// copy of both halves before, which is three places for one policy to drift in.
|
|
103
|
-
//
|
|
104
|
-
// TWO functions and not one, because `typeof` alone cannot name the fault the
|
|
105
|
-
// predicate rejects: it answers "object" for `null` and for `[]` alike, and
|
|
106
|
-
// those are exactly two of the three shapes turned away here, so a
|
|
107
|
-
// `typeof`-only diagnostic distinguishes neither from a real object. That is
|
|
108
|
-
// the same three-arm naming review-core.mjs's resolveDimensions keeps, for the
|
|
109
|
-
// same reason.
|
|
110
|
-
//
|
|
111
|
-
// Not every payload-shape check in this file is one of these, and the others
|
|
112
|
-
// are not oversights: mapCi's and tryParse's are both null-only, neither
|
|
113
|
-
// refusing a payload for being an array or a scalar. A settled, deliberately
|
|
114
|
-
// different policy — not more callers waiting to be converted.
|
|
115
|
-
function isJsonObject(v) {
|
|
116
|
-
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
117
|
-
}
|
|
118
|
-
|
|
119
|
-
function jsonKind(v) {
|
|
120
|
-
return v === null ? "null" : Array.isArray(v) ? "array" : typeof v;
|
|
121
|
-
}
|
|
122
66
|
|
|
123
67
|
// `Number(x) || default` treated a garbage --port/--interval exactly
|
|
124
68
|
// like an absent one — "abc" is NaN, NaN is falsy, so it silently became the
|
|
@@ -182,8 +126,8 @@ function argSpendSince() {
|
|
|
182
126
|
return sinceMs;
|
|
183
127
|
}
|
|
184
128
|
|
|
185
|
-
// The operator's override for the session heuristic (findSubagentsDir()
|
|
186
|
-
//
|
|
129
|
+
// The operator's override for the session heuristic (findSubagentsDir() in
|
|
130
|
+
// board-gather.mjs). A PATH, so there is no range or magnitude to check the way
|
|
187
131
|
// --spend-since and --interval have one — every malformed SHAPE this flag can
|
|
188
132
|
// take is already arg()'s: a trailing `--spend-dir`, an empty or whitespace
|
|
189
133
|
// value, a following flag eaten as the value, and the `--spend-dir=` form.
|
|
@@ -204,956 +148,13 @@ function argSpendSince() {
|
|
|
204
148
|
// renders zeroes and never dies.
|
|
205
149
|
//
|
|
206
150
|
// `undefined` for an absent flag, not the `null` argPort()/argInterval()/
|
|
207
|
-
// argSpendSince() return: `null` is a transcript-directory RESOLUTION
|
|
208
|
-
//
|
|
151
|
+
// argSpendSince() return: `null` is a transcript-directory RESOLUTION
|
|
152
|
+
// ("resolved, no session yet" — findSubagentsDir() in board-gather.mjs), and the
|
|
209
153
|
// absence of an override must not read as one.
|
|
210
154
|
function argSpendDir() {
|
|
211
155
|
return arg("spend-dir") ?? undefined;
|
|
212
156
|
}
|
|
213
157
|
|
|
214
|
-
// Every external read is wrapped: a failure returns null and the caller keeps a
|
|
215
|
-
// last-known value. Partial board beats a crashed loop or a false alarm.
|
|
216
|
-
async function tryRun(cmd, args) {
|
|
217
|
-
const r = await execRead(cmd, args);
|
|
218
|
-
if (r.error) { console.error(`${NAME}: ${cmd} ${args.join(" ")} failed: ${r.error.message}`); return null; }
|
|
219
|
-
return r.stdout;
|
|
220
|
-
}
|
|
221
|
-
|
|
222
|
-
// `serve --open`'s browser launcher, one per supported platform.
|
|
223
|
-
// macOS ships `open`. Linux has no single program, but `xdg-open` is
|
|
224
|
-
// the freedesktop one every mainstream desktop provides; WSL usually lacks it
|
|
225
|
-
// and has `wslview` (wslu) instead, which hands the URL to the Windows default
|
|
226
|
-
// browser. Only a launcher that is NOT ON PATH passes the URL down the list:
|
|
227
|
-
// one that ran and failed is the right program meeting a real fault, and the
|
|
228
|
-
// next one would not fix that.
|
|
229
|
-
//
|
|
230
|
-
// Never throws and never exits. A tab that did not open is a warning naming
|
|
231
|
-
// the URL — the cockpit is up and serving either way, and the operator can
|
|
232
|
-
// open it by hand — so a missing launcher changes nothing about the exit code.
|
|
233
|
-
async function openBrowser(url) {
|
|
234
|
-
const tried = [];
|
|
235
|
-
for (const cmd of process.platform === "darwin" ? ["open"] : ["xdg-open", "wslview"]) {
|
|
236
|
-
const r = await execRead(cmd, [url]);
|
|
237
|
-
if (!r.error) return;
|
|
238
|
-
if (r.code === "ENOENT") { tried.push(`${cmd} not found`); continue; }
|
|
239
|
-
tried.push(r.status != null ? `${cmd} exited ${r.status}` : `${cmd} failed: ${r.error.message.split("\n")[0]}`);
|
|
240
|
-
break;
|
|
241
|
-
}
|
|
242
|
-
console.error(`${NAME}: WARNING --open could not open a browser (${tried.join(", ")}) — the cockpit is on ${url}`);
|
|
243
|
-
}
|
|
244
|
-
|
|
245
|
-
// Parse tool stdout defensively: a tool can exit 0 yet print malformed or
|
|
246
|
-
// warning-prefixed stdout. Treat that like a failed read (fall back to the
|
|
247
|
-
// caller's empty default), never let it crash the tick.
|
|
248
|
-
//
|
|
249
|
-
// A nullish INPUT and a null PARSED VALUE are two faults, and the first guard
|
|
250
|
-
// does not cover the second: `JSON.parse("null")` succeeds and yields null, so
|
|
251
|
-
// without the second guard a bare `null` payload arrives at the caller as its
|
|
252
|
-
// answer. Strictly `=== null`, never falsiness — `0`, `false` and `""` are all
|
|
253
|
-
// answers a caller can read, and refusing them would substitute a shape
|
|
254
|
-
// judgement this helper is not in a position to make.
|
|
255
|
-
//
|
|
256
|
-
// Null is guarded here and shape is not, because null is the only parse result
|
|
257
|
-
// no caller of this helper can use: every other one boxes and reads, null alone
|
|
258
|
-
// has no properties, whatever shape the caller wanted. Shape is the caller's
|
|
259
|
-
// question and keeps the caller's answer — withNumber below rejects a non-array
|
|
260
|
-
// for the `gh ... list` reads, gather()'s `--prev` read demands
|
|
261
|
-
// an object, and gather()'s ledger branch takes any shape ledger.mjs emits,
|
|
262
|
-
// deliberately, for the reason stated there. A shape policy could not be written
|
|
263
|
-
// in here anyway: `fallback` is `[]` where the open-PR read calls this and null where the
|
|
264
|
-
// ledger read does, so the helper is never told what its caller wanted — only
|
|
265
|
-
// that null is not it.
|
|
266
|
-
//
|
|
267
|
-
// Reported, and never as "parse failed": the parse succeeded, and keeping the
|
|
268
|
-
// state a read reached apart from the state it failed at is what the ledger states are for.
|
|
269
|
-
function tryParse(json, fallback, what) {
|
|
270
|
-
if (json == null) return fallback;
|
|
271
|
-
let parsed;
|
|
272
|
-
try { parsed = JSON.parse(json); }
|
|
273
|
-
catch (e) { console.error(`${NAME}: ${what} parse failed: ${e.message}`); return fallback; }
|
|
274
|
-
if (parsed === null) {
|
|
275
|
-
console.error(`${NAME}: ${what}: payload is JSON null, not a usable answer; falling back`);
|
|
276
|
-
return fallback;
|
|
277
|
-
}
|
|
278
|
-
return parsed;
|
|
279
|
-
}
|
|
280
|
-
|
|
281
|
-
// A row without a usable `number` cannot be placed: compute-board.mjs joins
|
|
282
|
-
// issues/PRs to ledger rows and to each other BY number (Map keys, Set
|
|
283
|
-
// membership, `.find`), so a numberless row does not fail to render on its
|
|
284
|
-
// own — it collides with every other numberless row on the shared `undefined`
|
|
285
|
-
// key. Drop it, loudly. candidates.mjs's row guard is a different shape —
|
|
286
|
-
// comprehensive and hard-failing (die() on the first bad row) — this one is
|
|
287
|
-
// narrower: it only checks `number`, the one field whose absence corrupts
|
|
288
|
-
// OTHER rows, and degrades instead of dying.
|
|
289
|
-
//
|
|
290
|
-
// `rows` itself can be the wrong shape too: `tryParse` only checks that its
|
|
291
|
-
// input is valid JSON, not that it is an array, so a syntactically-valid
|
|
292
|
-
// object or scalar from `gh` would otherwise reach the `for...of` below and
|
|
293
|
-
// throw "rows is not iterable" — an uncaught throw that reaches main()'s
|
|
294
|
-
// build path or the serve tick's catch, exactly the crash-instead-of-degrade
|
|
295
|
-
// failure this guard exists to prevent for individual rows.
|
|
296
|
-
function withNumber(rows, what) {
|
|
297
|
-
if (!Array.isArray(rows)) {
|
|
298
|
-
console.error(`${NAME}: ${what}: expected an array of rows, got ${JSON.stringify(rows)}`);
|
|
299
|
-
return [];
|
|
300
|
-
}
|
|
301
|
-
const kept = [];
|
|
302
|
-
for (const r of rows) {
|
|
303
|
-
if (r && typeof r.number === "number") kept.push(r);
|
|
304
|
-
else console.error(`${NAME}: ${what}: dropping row with no usable number: ${JSON.stringify(r)}`);
|
|
305
|
-
}
|
|
306
|
-
return kept;
|
|
307
|
-
}
|
|
308
|
-
|
|
309
|
-
// gh stops a `list` read at its `--limit` with exit 0 and no warning, so
|
|
310
|
-
// a read that came back exactly that long may have been cut there — "at least
|
|
311
|
-
// this many", never "this many". candidates.mjs's refuseIfCapped() and
|
|
312
|
-
// fleet-tick.mjs's PR_LIMIT/CLAIMED_LIMIT carry the same rule; this board is a
|
|
313
|
-
// display, so it discloses a capped read (computeBoard's `n+` and capNotice)
|
|
314
|
-
// rather than dying on one. Counted on the raw rows, before withNumber() drops
|
|
315
|
-
// any: gh's cap applies to what it returned, not to what this file kept.
|
|
316
|
-
const POOL_LIMIT = 100;
|
|
317
|
-
const OPEN_PR_LIMIT = 100;
|
|
318
|
-
function hitLimit(parsed, limit) {
|
|
319
|
-
return Array.isArray(parsed) && parsed.length >= limit;
|
|
320
|
-
}
|
|
321
|
-
|
|
322
|
-
// Which of `prNums` gh calls MERGED, in ONE `gh api graphql` query —
|
|
323
|
-
// one aliased `pullRequest(number:)` field per PR, on the cwd's repository
|
|
324
|
-
// (gh's own `{owner}`/`{repo}` placeholders, the repo every other read here
|
|
325
|
-
// resolves) — so a PR merged at any age is found, and ten PRs cost what one
|
|
326
|
-
// does. It replaced `gh pr list --state merged --limit 100`, the repo's 100
|
|
327
|
-
// most recent merges: about six days on 2026-09-25, so a row PR merged
|
|
328
|
-
// before that and never seen MERGED rendered REVIEW, turned stale and
|
|
329
|
-
// counted as claimed. Measured 2026-09-26: 400 aliases answer in one call.
|
|
330
|
-
//
|
|
331
|
-
// An empty `prNums` makes no read at all. `state` is checked, so an entry gh
|
|
332
|
-
// does not call MERGED never makes a card MERGED on its own account.
|
|
333
|
-
//
|
|
334
|
-
// A body with an object `data.repository` IS an answer even at exit 1:
|
|
335
|
-
// GitHub resolves every alias it can and nulls the rest — a number that is
|
|
336
|
-
// not a PR comes back null beside a NOT_FOUND error, and gh exits 1 with the
|
|
337
|
-
// whole body on stdout (measured 2026-09-26, gh 2.101.0, which also names
|
|
338
|
-
// the number on stderr). Refusing that body would let one such row — a
|
|
339
|
-
// typo, or a row with no impl token keyed by an issue number — put every other
|
|
340
|
-
// row PR back in REVIEW on every tick. A null alias reads as not merged,
|
|
341
|
-
// which is what a failed read means for that one PR.
|
|
342
|
-
//
|
|
343
|
-
// Real GitHub always answers EVERY requested `p<N>` alias, null or an
|
|
344
|
-
// object — never omits one — so an object naming NONE of `prNums` is not a
|
|
345
|
-
// shape the API produces, only a corrupted or truncated one; `isJsonObject`
|
|
346
|
-
// alone cannot tell that apart from a genuine "checked, nothing merged"
|
|
347
|
-
// answer, so it is checked for too. Anything else is a failed read: `[]`,
|
|
348
|
-
// and computeBoard()'s carry-forward rule takes it from there.
|
|
349
|
-
async function readMerged(prNums) {
|
|
350
|
-
if (!prNums.length) return [];
|
|
351
|
-
const fields = prNums.map((n) => `p${n}:pullRequest(number:${n}){state}`).join(" ");
|
|
352
|
-
const r = await execRead("gh", ["api", "graphql", "-F", "owner={owner}", "-F", "name={repo}",
|
|
353
|
-
"-f", `query=query($owner:String!,$name:String!){repository(owner:$owner,name:$name){${fields}}}`]);
|
|
354
|
-
let repo;
|
|
355
|
-
try { repo = JSON.parse(r.stdout)?.data?.repository; } catch {}
|
|
356
|
-
if (!isJsonObject(repo) || !prNums.some((n) => Object.prototype.hasOwnProperty.call(repo, `p${n}`))) {
|
|
357
|
-
// `how` as runCiState() spells it; never r.error.message, which repeats
|
|
358
|
-
// the whole query — one field per PR — into every failed tick's line.
|
|
359
|
-
const how = r.code ?? (r.signal ? `killed by ${r.signal}` : `exit ${r.status}`);
|
|
360
|
-
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`);
|
|
361
|
-
return [];
|
|
362
|
-
}
|
|
363
|
-
return prNums.filter((n) => repo[`p${n}`]?.state === "MERGED");
|
|
364
|
-
}
|
|
365
|
-
|
|
366
|
-
// labels: gh emits an array of {name,...} objects, but a malformed row can
|
|
367
|
-
// hand back a non-array `labels` (`.map` throws) or an array containing a
|
|
368
|
-
// null/malformed element (`.name` throws) — reproduced live: either crashes
|
|
369
|
-
// gather() entirely, reaching main()'s `die()` on the build path or freezing
|
|
370
|
-
// the board on its last-known value on the serve path. Strictly worse than
|
|
371
|
-
// this ticket's original "shows undefined on the page" bug. Drop-and-continue,
|
|
372
|
-
// like withNumber above: a bad label never takes its row's whole labels array
|
|
373
|
-
// down, and a bad labels field never takes the row down.
|
|
374
|
-
function labelsOf(row) {
|
|
375
|
-
if (!Array.isArray(row.labels)) return [];
|
|
376
|
-
return row.labels
|
|
377
|
-
.map((l) => (l && typeof l.name === "string") ? l.name : null)
|
|
378
|
-
.filter(Boolean);
|
|
379
|
-
}
|
|
380
|
-
|
|
381
|
-
// ci-state.mjs exits 0 for green, 1 for not-green or no-ci, 2 for a hard
|
|
382
|
-
// failure — no-ci is its own verdict and shares exit 1 because this call omits
|
|
383
|
-
// --declare-no-ci, the only thing that would move it to exit 0 — and on
|
|
384
|
-
// exit 1 it has ALREADY printed its verdict JSON to stdout before exiting, so a
|
|
385
|
-
// thrown exit 1 carries a real verdict. Feed that to mapCi: discarding e.stdout,
|
|
386
|
-
// as a plain tryRun would, makes red/still-running CI unreachable — every
|
|
387
|
-
// non-green PR reads as "unknown" and the red-ci flag, the top of the attention
|
|
388
|
-
// strip, never fires.
|
|
389
|
-
//
|
|
390
|
-
// What separates a verdict from a failed read is the EXIT CODE. Emptiness of
|
|
391
|
-
// stdout was only ever a proxy for it, and that proxy no longer holds: a quota
|
|
392
|
-
// refusal now names its cause on stdout on the way out at exit 2, so "non-empty
|
|
393
|
-
// stdout" began reading an outage as a reading. That payload carries no
|
|
394
|
-
// `status`, so mapCi answered "unknown" and gather()'s prevCi carry-forward —
|
|
395
|
-
// which only a null return reaches — was skipped, overwriting a PR's
|
|
396
|
-
// last-known-good CI state during a blip that clears itself. Exit 2 means the
|
|
397
|
-
// question could not be answered, whatever the script printed while saying so.
|
|
398
|
-
//
|
|
399
|
-
// The exit code is not sufficient on its own either, for the symmetric
|
|
400
|
-
// reason: it reports that the child reached its own exit path, never that its
|
|
401
|
-
// payload arrived whole. `e.status !== 2` is also true of a signal kill, where
|
|
402
|
-
// `status` is null, and of a write cut mid-JSON at exit 1 — emit() over in
|
|
403
|
-
// ci-state.mjs abandons a short write it cannot retry, which keeps the exit
|
|
404
|
-
// code intact while losing the tail of the line. Those bytes were returned AS a
|
|
405
|
-
// verdict, mapCi could not parse them, and the non-null return skipped the very
|
|
406
|
-
// carry-forward added for the exit-2 case: that regression re-entering through the gate
|
|
407
|
-
// built to stop it. So both halves have to hold — a non-2 exit AND bytes that
|
|
408
|
-
// parse.
|
|
409
|
-
//
|
|
410
|
-
// The parse is the discriminator rather than "any abnormal termination", the
|
|
411
|
-
// other candidate, because only the parse gets both directions right. It
|
|
412
|
-
// catches the cut-off exit-1 write, which carries status 1 and no signal at all
|
|
413
|
-
// (measured), and it goes on ACCEPTING a complete payload from a child killed
|
|
414
|
-
// after writing it, as well as no-ci — a real exit-1 verdict whose own `status`
|
|
415
|
-
// field is null, so a status-shaped guard tightened far enough to catch a
|
|
416
|
-
// truncation starts refusing it and resurrects a red for a PR with no run
|
|
417
|
-
// behind it. Wholeness is the only question asked here; SHAPE stays mapCi's,
|
|
418
|
-
// which is total over every payload that parses.
|
|
419
|
-
async function runCiState(scriptDir, pr) {
|
|
420
|
-
const r = await execRead("node", [join(scriptDir, "ci-state.mjs"), "--pr", String(pr), "--quiet"]);
|
|
421
|
-
const out = r.stdout;
|
|
422
|
-
if (r.error) {
|
|
423
|
-
// `r.stdout` and not `error.stdout`: what the child managed to write before
|
|
424
|
-
// it died is the salvage this whole block exists for, and execRead's record
|
|
425
|
-
// carries it on every arm — including a spawn failure, where it is "".
|
|
426
|
-
if (r.status === 2 || !out.trim()) {
|
|
427
|
-
console.error(`${NAME}: ci-state --pr ${pr} failed: ${r.error.message}`);
|
|
428
|
-
return null;
|
|
429
|
-
}
|
|
430
|
-
// Its own line, not the one above: "failed" reads as "the child never
|
|
431
|
-
// answered", and an operator looking at a carried-forward CI value needs to
|
|
432
|
-
// know a payload DID arrive and was thrown away, and why.
|
|
433
|
-
//
|
|
434
|
-
// `how` reads the libuv/node `code` first — the three-way ci-state.mjs
|
|
435
|
-
// already uses at its own child reads — because one cause of this shape is
|
|
436
|
-
// OURS: overrunning READ_OPTS.maxBuffer is enforced by node killing the
|
|
437
|
-
// child, and that arrives as code ERR_CHILD_PROCESS_STDIO_MAXBUFFER
|
|
438
|
-
// (measured; the synchronous read this replaced reported the same cap as
|
|
439
|
-
// signal SIGTERM carrying code ENOBUFS). A signal-first `how` renders a cap
|
|
440
|
-
// this file sets as an outside kill, sending the operator after an OOM kill
|
|
441
|
-
// or a stray `kill -TERM`. The signal arm stays ahead of the exit arm
|
|
442
|
-
// behind it: `status` is null on a real signal kill, where "exit null"
|
|
443
|
-
// would name nothing to act on. execRead splits the async error's one
|
|
444
|
-
// `code` field back into these three, so all three arms still read as they
|
|
445
|
-
// did — measured: an exit 3 gives `status` 3 and no `code`, a SIGKILL gives
|
|
446
|
-
// `signal` and neither, an unreachable binary gives `code` ENOENT.
|
|
447
|
-
//
|
|
448
|
-
// Through the warn-once gate, keyed on the PR exactly as mapCi's
|
|
449
|
-
// `ci-parse` gate is and for the same reason: serve() re-gathers on a
|
|
450
|
-
// timer, so a payload truncated by a cause that persists is truncated
|
|
451
|
-
// again on every tick, and an ungated line spends one per PR per tick for
|
|
452
|
-
// as long as the cause lasts. Its own channel, `ci-salvage-nonzero`,
|
|
453
|
-
// distinct from both `ci-parse` and the exit-0 guard's `ci-salvage-exit0`
|
|
454
|
-
// below: for any one payload the three are mutually exclusive — bytes
|
|
455
|
-
// refused here return null and never reach mapCi — so a channel shared
|
|
456
|
-
// between any two of them would buy nothing, and would let whichever arm
|
|
457
|
-
// a PR happened to hit FIRST silence a later, structurally different
|
|
458
|
-
// failure on another arm for the rest of the run — measured: driving the
|
|
459
|
-
// same PR through this arm then the exit-0 guard below printed only the
|
|
460
|
-
// first tick's warning until the channels were split.
|
|
461
|
-
try { JSON.parse(out); }
|
|
462
|
-
catch (pe) {
|
|
463
|
-
const how = r.code ?? (r.signal ? `killed by ${r.signal}` : `exit ${r.status}`);
|
|
464
|
-
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`);
|
|
465
|
-
return null;
|
|
466
|
-
}
|
|
467
|
-
return out;
|
|
468
|
-
}
|
|
469
|
-
// Exit 0 was never covered by any of the checks above — they only run
|
|
470
|
-
// once the child read reports a failure, and a child that exits 0 reports
|
|
471
|
-
// none. So the same write cut mid-JSON that the failure block above salvages
|
|
472
|
-
// at exit 1 rode straight through here and into mapCi at exit 0, where an
|
|
473
|
-
// unparseable string maps to "unknown" and gather()'s carry-forward — which
|
|
474
|
-
// only a null return reaches — was skipped, discarding the PR's last-known
|
|
475
|
-
// CI value exactly as the exit-2 case did before it was fixed. Same parse
|
|
476
|
-
// check, same null return as the failure block above — but its OWN channel,
|
|
477
|
-
// `ci-salvage-exit0`, not that block's `ci-salvage-nonzero`: a
|
|
478
|
-
// zero-exit child does not get a looser contract than a non-zero one, and
|
|
479
|
-
// the two arms are structurally different failures that must not silence
|
|
480
|
-
// each other (see the channel-split comment above).
|
|
481
|
-
//
|
|
482
|
-
// Emptiness is checked before the parse, and gets its own wording: an empty
|
|
483
|
-
// `out` is not a corrupted payload, it is no payload at all — "left a
|
|
484
|
-
// payload that will not parse" is a true diagnosis of truncated JSON and a
|
|
485
|
-
// false one of a child that printed nothing, the same distinction the
|
|
486
|
-
// empty/status-2 branch above draws for a non-zero exit.
|
|
487
|
-
try { JSON.parse(out); }
|
|
488
|
-
catch (pe) {
|
|
489
|
-
const msg = out.trim()
|
|
490
|
-
? `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`
|
|
491
|
-
: `ci-state --pr ${pr} (exit 0) never answered; carrying the previous CI value forward rather than reading this as a verdict`;
|
|
492
|
-
warnOnce("ci-salvage-exit0", pr, msg);
|
|
493
|
-
return null;
|
|
494
|
-
}
|
|
495
|
-
return out;
|
|
496
|
-
}
|
|
497
|
-
|
|
498
|
-
// The `ci-parse` gate is keyed on the PR, not on the payload: `serve` rebuilds
|
|
499
|
-
// every ~15s and calls mapCi once per PR per tick, so a payload that is broken
|
|
500
|
-
// is broken on every tick, and a payload-keyed gate would flood anyway the
|
|
501
|
-
// moment the garbage varies between ticks. A single global flag is the other
|
|
502
|
-
// wrong answer — it would let the first broken PR mask every later one for the
|
|
503
|
-
// rest of the run, which is the silence this gate exists to end.
|
|
504
|
-
|
|
505
|
-
// ci-state's verdict already excludes behind-count staleness. Map it, and treat
|
|
506
|
-
// anything not cleanly green-or-completed-red as unknown — never a false red.
|
|
507
|
-
//
|
|
508
|
-
// `pr` is carried for the warn below and nothing else: an unparseable payload
|
|
509
|
-
// has no field to identify itself by, and "some PR's CI payload was garbage" is
|
|
510
|
-
// not actionable. The caller has the number in hand.
|
|
511
|
-
export function mapCi(ciJson, pr) {
|
|
512
|
-
// A NULL payload, which is a failed read runCiState() has already reported
|
|
513
|
-
// on stderr. Warning again here would report one failure twice. Null
|
|
514
|
-
// strictly, not falsiness: an EMPTY payload is not that case. Since
|
|
515
|
-
// runCiState() parse-checks its exit-0 return too, so its own callers never
|
|
516
|
-
// hand this an empty string any more — but mapCi() is exported and total
|
|
517
|
-
// over any caller, not just this file's, so a `!ciJson` guard that swallowed
|
|
518
|
-
// "" as though it had been reported would still be wrong. It falls through
|
|
519
|
-
// to the parse below instead, which is where it earns its line.
|
|
520
|
-
if (ciJson == null) return "unknown";
|
|
521
|
-
let d;
|
|
522
|
-
// A payload that will not parse is a THIRD state, and the return value cannot
|
|
523
|
-
// carry it: "unknown" is what the regression gate pins, since a false red is
|
|
524
|
-
// worse than no verdict. So the distinction leaves through stderr or not at
|
|
525
|
-
// all. That was closed for runCiState()'s catch block (a payload that will
|
|
526
|
-
// not parse there is a failed read, reaching gather()'s carry-forward);
|
|
527
|
-
// and for the exit-0 arm the same way (see runCiState() above),
|
|
528
|
-
// so a write cut mid-JSON no longer reaches mapCi from gather() on EITHER
|
|
529
|
-
// arm — a lost write now reads as a failed read there too, and that PR's
|
|
530
|
-
// last-known CI value stands instead of reverting to "unknown". This catch
|
|
531
|
-
// stays live regardless: mapCi() is exported and total over any string
|
|
532
|
-
// handed to it, parseable or not, and its own tests drive it directly
|
|
533
|
-
// without going through runCiState() at all.
|
|
534
|
-
try { d = JSON.parse(ciJson); }
|
|
535
|
-
catch (e) {
|
|
536
|
-
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`);
|
|
537
|
-
return "unknown";
|
|
538
|
-
}
|
|
539
|
-
// JSON.parse("null") succeeds and yields d === null. Nullishness, not
|
|
540
|
-
// object-ness, is the discriminator: `[]` and `{}` are typeof "object" just
|
|
541
|
-
// as null is, but null alone has no properties to read, so the status gate
|
|
542
|
-
// throws a TypeError on it where every other parsed payload boxes and reads
|
|
543
|
-
// its status as undefined. Hence a guard with its own return, rather than a
|
|
544
|
-
// payload that reaches the status gate and answers "unknown" there. Silent,
|
|
545
|
-
// not warned: the status gate already answers every parseable payload it
|
|
546
|
-
// cannot read a status from without a line, and a bare "null" is no more
|
|
547
|
-
// corrupt than those.
|
|
548
|
-
if (d === null) return "unknown";
|
|
549
|
-
if (d.status !== "completed") return "unknown"; // still running, or no run yet (status null)
|
|
550
|
-
if (d.verdict === "green") return "green";
|
|
551
|
-
if (d.verdict === "not-green") return "red";
|
|
552
|
-
return "unknown";
|
|
553
|
-
}
|
|
554
|
-
|
|
555
|
-
// Where this session's member transcripts live:
|
|
556
|
-
// ~/.omp/agent/sessions/<encoded-cwd>/<ISO>_<uuid>/
|
|
557
|
-
// The encoder lives in member-record.mjs, shared with
|
|
558
|
-
// member-outcomes.mjs; it is re-exported here under its original name so
|
|
559
|
-
// nothing importing `encodeProjectDir` from this file needs to change.
|
|
560
|
-
export { encodeProjectDir };
|
|
561
|
-
|
|
562
|
-
// The session uuid is not knowable from here, so take the most recently
|
|
563
|
-
// active one. Rank on the newest TRANSCRIPT mtime, not on the session
|
|
564
|
-
// directory's own: a directory's mtime moves when an entry is created or
|
|
565
|
-
// removed, never when a file inside it is appended to. Ranking on the
|
|
566
|
-
// directory therefore tracked the last agent SPAWN rather than the last
|
|
567
|
-
// agent activity — and since the cockpit launches in run-team phase 0,
|
|
568
|
-
// before the first agent spawns, the live session has no transcript yet and
|
|
569
|
-
// a PREVIOUS session won. The board would render a prior run's spend as
|
|
570
|
-
// this run's, then silently switch when the first agent landed. That is the
|
|
571
|
-
// one failure mode here that produces confidently wrong numbers rather than
|
|
572
|
-
// no numbers.
|
|
573
|
-
//
|
|
574
|
-
// Returns { error } when there is no project dir for this cwd — a bug that
|
|
575
|
-
// never fixes itself — and null when one resolves but holds no sessions
|
|
576
|
-
// yet, which is normal at run start. Collapsing those two into one bare
|
|
577
|
-
// null is what hid the encoding bug above. A listing that THROWS is
|
|
578
|
-
// { error } too.
|
|
579
|
-
export function findSubagentsDir(home = process.env.HOME, cwd = process.cwd()) {
|
|
580
|
-
try {
|
|
581
|
-
const tree = sessionDirs(home, cwd);
|
|
582
|
-
if (tree.dirs === null) {
|
|
583
|
-
return { error: `no transcript dir for cwd ${cwd} (looked in ${tree.root})` };
|
|
584
|
-
}
|
|
585
|
-
const cands = tree.dirs
|
|
586
|
-
.map((d) => ({ d, m: newestTranscriptMs(d) }))
|
|
587
|
-
.sort((a, b) => b.m - a.m);
|
|
588
|
-
return cands.length ? cands[0].d : null;
|
|
589
|
-
} catch (e) { return { error: `transcript lookup failed: ${e.message}` }; }
|
|
590
|
-
}
|
|
591
|
-
|
|
592
|
-
// The candidate session directories for this cwd. `dirs: null` means there
|
|
593
|
-
// is no project dir here at all; `[]` means there is one holding no session
|
|
594
|
-
// yet. `root` is where it looked, for the error above.
|
|
595
|
-
//
|
|
596
|
-
// `encodeProjectDir` realpath-resolves a cwd outside $HOME, which throws
|
|
597
|
-
// ENOENT when that cwd does not exist. No omp session can be keyed on such a
|
|
598
|
-
// cwd, so THAT is this tree's absence — not a lookup fault. Any OTHER error
|
|
599
|
-
// (EACCES on an ancestor directory, say) is a real fault, not an absence,
|
|
600
|
-
// and must not be relabelled as one: swallowing it here would crash
|
|
601
|
-
// silently with no signal anything went wrong. It is rethrown, uncaught,
|
|
602
|
-
// into findSubagentsDir's own catch — the same fate a listing failure below
|
|
603
|
-
// already gets, deliberately.
|
|
604
|
-
function sessionDirs(home, cwd) {
|
|
605
|
-
const sessions = join(home, ".omp", "agent", "sessions");
|
|
606
|
-
let root;
|
|
607
|
-
try {
|
|
608
|
-
root = join(sessions, encodeProjectDir(cwd, { home }));
|
|
609
|
-
} catch (e) {
|
|
610
|
-
if (e.code !== "ENOENT") throw e;
|
|
611
|
-
return { root: sessions, dirs: null };
|
|
612
|
-
}
|
|
613
|
-
if (!existsSync(root)) return { root, dirs: null };
|
|
614
|
-
const dirs = readdirSync(root, { withFileTypes: true })
|
|
615
|
-
.filter((e) => e.isDirectory() && isOmpSessionDirName(e.name))
|
|
616
|
-
.map((e) => join(root, e.name));
|
|
617
|
-
return { root, dirs };
|
|
618
|
-
}
|
|
619
|
-
|
|
620
|
-
// Newest *.jsonl mtime anywhere under a session's transcript dir, 0 if it
|
|
621
|
-
// holds none. Recursive: a nested member (a dispatcher's own further
|
|
622
|
-
// fan-out, one directory level down — the same walk ompSessionTranscripts
|
|
623
|
-
// does to book their spend) can be the only fresh activity in an otherwise
|
|
624
|
-
// idle-looking session, and a scan bounded to the top level would score
|
|
625
|
-
// that session 0 and lose it to a genuinely stale sibling.
|
|
626
|
-
//
|
|
627
|
-
// A dir whose transcripts are all unreadable loses to one that is readable,
|
|
628
|
-
// which is the behaviour we want when picking "the live session".
|
|
629
|
-
//
|
|
630
|
-
// The scan is wrapped for the same reason the per-file stat below is. This runs
|
|
631
|
-
// once per CANDIDATE, so an uncaught throw here does not just lose one dir — it
|
|
632
|
-
// escapes findSubagentsDir's try and turns the whole lookup into { error },
|
|
633
|
-
// blacking out every readable session over one bad sibling. Scoring 0 is what
|
|
634
|
-
// the comment above already promises: a dir we cannot read simply loses.
|
|
635
|
-
function newestTranscriptMs(dir) {
|
|
636
|
-
let names;
|
|
637
|
-
try { names = readdirSync(dir, { recursive: true }); } catch { return 0; }
|
|
638
|
-
let newest = 0;
|
|
639
|
-
for (const f of names) {
|
|
640
|
-
if (!f.endsWith(".jsonl")) continue;
|
|
641
|
-
try { newest = Math.max(newest, statSync(join(dir, f)).mtimeMs); } catch { /* raced away */ }
|
|
642
|
-
}
|
|
643
|
-
return newest;
|
|
644
|
-
}
|
|
645
|
-
|
|
646
|
-
// The transcript directory a `serve` process is bound to, resolved
|
|
647
|
-
// once it can be trusted and reused by every tick after it. findSubagentsDir()
|
|
648
|
-
// above ranks sessions by newest transcript mtime and gather() reached it
|
|
649
|
-
// through gatherSpend() on EVERY tick (~15s by default), so two sessions live
|
|
650
|
-
// under one project directory took turns winning: the panel alternated
|
|
651
|
-
// between two runs' numbers with nothing on the page or on stderr to say it
|
|
652
|
-
// had switched.
|
|
653
|
-
//
|
|
654
|
-
// The pin holds the first answer that COULD BE THIS RUN'S, not the first
|
|
655
|
-
// non-null answer and not the first call. findSubagentsDir() has
|
|
656
|
-
// three returns and none of them is safe to latch on sight: a directory
|
|
657
|
-
// resolved at pin-construction time can be a PREVIOUS run's session — newer
|
|
658
|
-
// than nothing else that exists yet, so it wins the ranking, but not this
|
|
659
|
-
// run's — and `{ error }` can be a transient fault (EACCES on a directory
|
|
660
|
-
// mid-permission-change, EMFILE, EIO) recovering on the very next tick just
|
|
661
|
-
// as easily as it can be the truly unresolvable "bug that never fixes
|
|
662
|
-
// itself" the ticket originally reasoned about. Latching either one turns
|
|
663
|
-
// the self-correcting degradation this file's header describes into a
|
|
664
|
-
// permanent one: measured, a chmod'd-then-restored session tree left
|
|
665
|
-
// the OLD `??=` pin stuck on `{ error }` forever while the unpinned lookup
|
|
666
|
-
// recovered on its very next tick, and a prior run's session dir
|
|
667
|
-
// present at launch left the old pin on yesterday's numbers for the whole of
|
|
668
|
-
// today's run, even once today's first agent had written its own transcript.
|
|
669
|
-
//
|
|
670
|
-
// So `launchMs`, captured once at construction, is the boundary: `null` (no
|
|
671
|
-
// session anywhere yet) and `{ error }` (unresolvable OR transiently
|
|
672
|
-
// unreadable — indistinguishable from here, so neither is trusted) both keep
|
|
673
|
-
// re-asking, same one scan per tick the `null` case always cost. A resolved
|
|
674
|
-
// directory whose own newest transcript predates `launchMs` is treated the
|
|
675
|
-
// same way — returned as this tick's best-effort answer, so the panel still
|
|
676
|
-
// renders it, but not cached — because a transcript that stopped moving
|
|
677
|
-
// before this pin existed cannot be evidence of THIS run's activity. Only a
|
|
678
|
-
// directory whose newest transcript is at or after `launchMs` latches, which
|
|
679
|
-
// is the one fact available here that says "something is writing to this
|
|
680
|
-
// session on my watch", never a previous run's signature.
|
|
681
|
-
//
|
|
682
|
-
// An explicit directory skips the heuristic entirely — never resolved, never
|
|
683
|
-
// re-picked, and findSubagentsDir() is never called at all, so a tree it could
|
|
684
|
-
// not read cannot degrade a panel the operator has already named the source
|
|
685
|
-
// for. `home`/`cwd` are captured HERE rather than read per call for the same
|
|
686
|
-
// reason the resolution is: a pin that could answer for a different workspace
|
|
687
|
-
// later is not a pin.
|
|
688
|
-
//
|
|
689
|
-
// The limitation this leaves is stated at the top of this file: two sessions
|
|
690
|
-
// that both start writing after the pin exists are still indistinguishable.
|
|
691
|
-
// --spend-dir is the way out.
|
|
692
|
-
export function spendDirPin(explicit, home = process.env.HOME, cwd = process.cwd()) {
|
|
693
|
-
if (explicit != null) return () => explicit;
|
|
694
|
-
const launchMs = Date.now();
|
|
695
|
-
let pinned = null;
|
|
696
|
-
return () => {
|
|
697
|
-
if (pinned !== null) return pinned;
|
|
698
|
-
const answer = findSubagentsDir(home, cwd);
|
|
699
|
-
if (typeof answer !== "string") return answer; // null or { error }: neither is a trustworthy answer to latch
|
|
700
|
-
if (newestTranscriptMs(answer) < launchMs) return answer; // predates this pin — could be a previous run's
|
|
701
|
-
return (pinned = answer);
|
|
702
|
-
};
|
|
703
|
-
}
|
|
704
|
-
|
|
705
|
-
// The `no-spend-dir` gate warns at most once per process PER DISTINCT ERROR.
|
|
706
|
-
// `dir.error` is not constant — findSubagentsDir words an unresolvable project
|
|
707
|
-
// dir differently from a lookup that threw — so it is keyed on the message
|
|
708
|
-
// itself, not the empty string this gate used to key on: an empty key
|
|
709
|
-
// collapsed both wordings onto the one `no-spend-dir\0` slot, so whichever
|
|
710
|
-
// fault landed first for a process consumed the slot and a later, genuinely
|
|
711
|
-
// different fault never reached stderr again for the rest of the run. Keying
|
|
712
|
-
// on `dir.error` fixes that without losing the steady-state behaviour: `cwd`
|
|
713
|
-
// and `HOME` are fixed for the life of `serve`, so a repeating identical fault
|
|
714
|
-
// still costs one line, not one per tick. Either way this gate only ever
|
|
715
|
-
// controlled the repeated stderr LINE — a fault that differs still reaches the
|
|
716
|
-
// browser on the tick it happens, through the `{ error }` gatherSpend returns
|
|
717
|
-
// for it, which board.html renders as the panel's text. The board gathers
|
|
718
|
-
// every ~15s and a line repeating at that rate just trains the eye to ignore
|
|
719
|
-
// it.
|
|
720
|
-
//
|
|
721
|
-
// The `skips` gate is the same rule, per transcript: a file that is broken is
|
|
722
|
-
// broken every tick, and at the default 15s interval three of them are 720 lines
|
|
723
|
-
// an hour. Keyed on the FULL PATH, not the bare filename — gatherSpend
|
|
724
|
-
// re-resolves its dir on every tick, so a bare-filename key would silence a
|
|
725
|
-
// genuinely different broken file living under a second session directory. The
|
|
726
|
-
// count still reaches the browser every tick via `skipped`, which is the route
|
|
727
|
-
// that matters here.
|
|
728
|
-
|
|
729
|
-
// Scope is the SESSION directory, which is the closest thing to a run
|
|
730
|
-
// boundary that actually exists on disk — one session, one folder,
|
|
731
|
-
// identified by its own NAME: `<ISO>_<uuid>` (member-record.mjs's
|
|
732
|
-
// isOmpSessionDirName, the rule its own readers dispatch on).
|
|
733
|
-
//
|
|
734
|
-
// `sinceMs` is opt-in and defaults to no filter. An earlier attempt defaulted it
|
|
735
|
-
// to the ledger's mtime as a "run start" marker; that is wrong and silently
|
|
736
|
-
// reported zero, because the controller rewrites ledger rows continuously, so the
|
|
737
|
-
// mtime is always ~now and every transcript sorts as older than it. Kept as an
|
|
738
|
-
// explicit option for the one case the session scope cannot cover: a single
|
|
739
|
-
// session that spans two fleet runs, where the caller knows the boundary and the
|
|
740
|
-
// board does not.
|
|
741
|
-
//
|
|
742
|
-
// Three returns, deliberately distinct — collapsing them into one bare null is
|
|
743
|
-
// what let the path-encoding bug live: `{ ok: false, error }` is a bug the
|
|
744
|
-
// operator must act on and the UI shows it; `null` is the normal "nothing yet"
|
|
745
|
-
// and the UI hides the panel; `{ ok: true, ... }` is data.
|
|
746
|
-
//
|
|
747
|
-
// `ok` is an explicit TAG, and it is what the page switches on — never the
|
|
748
|
-
// presence or the truthiness of any other field. Reading the error case off
|
|
749
|
-
// `error`'s truthiness was a bug: `e.message` is "" for an error thrown
|
|
750
|
-
// without one and `undefined` for a thrown non-Error, so two shapes the catch
|
|
751
|
-
// below can emit matched neither the error branch nor a success shape, and the
|
|
752
|
-
// panel HID — a fault rendered as an idle run, the one conflation this panel
|
|
753
|
-
// exists to remove. A presence check would have fixed the "" case and still
|
|
754
|
-
// mis-routed the `undefined` one, and either is a refactor away from a
|
|
755
|
-
// truthiness check returning, because nothing in the data says which field is
|
|
756
|
-
// the tag. This follows `ledger.mjs`'s `tracker`: a boolean checked before any
|
|
757
|
-
// success-only field is read.
|
|
758
|
-
export function gatherSpend({ dir = findSubagentsDir(), sinceMs = null, topN = 8, explicit = false } = {}) {
|
|
759
|
-
try {
|
|
760
|
-
// A caller-supplied `null` is a RESOLUTION from one that owns a pin
|
|
761
|
-
// (spendDirPin() above) — the project directory is there and holds no
|
|
762
|
-
// session yet — and must not run the heuristic a second time; only an
|
|
763
|
-
// omitted `dir` (every gatherSpend test driver, and `build`, which is one
|
|
764
|
-
// gather per process and so needs no pin) defaults to it. A default
|
|
765
|
-
// parameter fires on `undefined` alone, never `null`, which is exactly
|
|
766
|
-
// that distinction — the hand-rolled `if (dir === undefined) dir =
|
|
767
|
-
// findSubagentsDir();` this used to spell out is redundant with it.
|
|
768
|
-
//
|
|
769
|
-
// `explicit` is true only when `dir` came from the operator's
|
|
770
|
-
// own --spend-dir, never from the heuristic or an unresolved pin — see
|
|
771
|
-
// its one use below, at the empty-directory branch.
|
|
772
|
-
const dirError = dir?.error;
|
|
773
|
-
if (dirError) {
|
|
774
|
-
warnOnce("no-spend-dir", dirError, dirError);
|
|
775
|
-
return { ok: false, error: dirError };
|
|
776
|
-
}
|
|
777
|
-
if (!dir) return null; // resolved, but this session has spawned no agents yet
|
|
778
|
-
// Only for an EXPLICIT --spend-dir — the heuristic's own
|
|
779
|
-
// findSubagentsDir() already dispatches on isOmpSessionDirName, so a
|
|
780
|
-
// resolved-but-non-heuristic `dir` here only ever arrives from the
|
|
781
|
-
// operator naming a directory directly. Without this check the
|
|
782
|
-
// mis-levelled path this same function's comments already name (the
|
|
783
|
-
// encoded-cwd project dir instead of its own <ISO>_<uuid> child) walked
|
|
784
|
-
// straight into readOmpSpend below, which recurses over every nested
|
|
785
|
-
// .jsonl with no name check of its own, and booked every session's
|
|
786
|
-
// transcripts — including the controller's own main-session one — as
|
|
787
|
-
// "agents" instead of refusing.
|
|
788
|
-
if (explicit && !isOmpSessionDirName(basename(dir))) {
|
|
789
|
-
const error = `${dir} is not an omp <ISO>_<uuid> session directory`;
|
|
790
|
-
warnOnce("bad-spend-dir", dir, `--spend-dir ${error}`);
|
|
791
|
-
return { ok: false, error };
|
|
792
|
-
}
|
|
793
|
-
|
|
794
|
-
const { agents, toolTables, skipped, damaged } = readOmpSpend(dir, sinceMs);
|
|
795
|
-
if (!agents.length) {
|
|
796
|
-
// `damaged` belongs here beside `skipped`. An omp transcript with
|
|
797
|
-
// no parseable assistant-with-usage line folds to no model, so
|
|
798
|
-
// readOmpSpend drops it without a throw — `skipped` stays 0 — and its
|
|
799
|
-
// non-last parse failures are the only trace that the directory held a
|
|
800
|
-
// transcript at all. Reading `skipped` alone sent that down the empty
|
|
801
|
-
// path below: a hidden panel, or an explicit override told the directory
|
|
802
|
-
// "holds no agent transcripts". A torn LAST line never counts as damaged,
|
|
803
|
-
// so a live write's partial first line still takes the empty path.
|
|
804
|
-
// A wholly-corrupt transcript with a readable "not executed" tool
|
|
805
|
-
// result but no assistant-with-usage line still drops here rather
|
|
806
|
-
// than booking at zero spend.
|
|
807
|
-
//
|
|
808
|
-
// `damaged` counts LINES, `skipped` whole transcripts, so each keeps its
|
|
809
|
-
// own clause — the lines one in board.html's damagedPhrase wording. "all
|
|
810
|
-
// N transcripts unreadable" stays for `skipped` alone: beside damaged
|
|
811
|
-
// lines it would count only the whole files and read as the entire loss.
|
|
812
|
-
if (damaged) {
|
|
813
|
-
const lost = [`${damaged} damaged transcript line${damaged === 1 ? "" : "s"}`];
|
|
814
|
-
if (skipped) lost.unshift(`${skipped} transcript${skipped === 1 ? "" : "s"} unreadable`);
|
|
815
|
-
return { ok: false, error: `no agent turn readable: ${lost.join("; ")}` };
|
|
816
|
-
}
|
|
817
|
-
if (skipped) return { ok: false, error: `all ${skipped} transcripts unreadable` };
|
|
818
|
-
// Only for an EXPLICIT override — never the heuristic's own
|
|
819
|
-
// "resolved, no session yet" `null` case two arms up, which is the
|
|
820
|
-
// normal state at launch and must stay silent. An operator who named
|
|
821
|
-
// this exact directory has a panel that just went quiet with nothing
|
|
822
|
-
// saying whether that is the normal "not written yet" wait or a typo'd
|
|
823
|
-
// / mis-levelled path (e.g. the encoded-cwd directory instead of its
|
|
824
|
-
// own `<ISO>_<uuid>` child) that will never resolve.
|
|
825
|
-
if (explicit) warnOnce("empty-spend-dir", dir, `--spend-dir ${dir} exists but holds no agent transcripts`);
|
|
826
|
-
return null;
|
|
827
|
-
}
|
|
828
|
-
const spend = computeSpend({ agents, topN });
|
|
829
|
-
const tools = mergeTools(toolTables);
|
|
830
|
-
// What fraction of cache_creation the tool table actually explains. It is
|
|
831
|
-
// never 100%: only a turn that FOLLOWS a tool result can be attributed to a
|
|
832
|
-
// tool, and an agent's first turn — usually its largest single write, the
|
|
833
|
-
// system prompt and context — follows nothing. Surfacing the coverage keeps
|
|
834
|
-
// the two columns honest about being different bases; without it the tool
|
|
835
|
-
// percentages silently read as shares of the headline number, which they
|
|
836
|
-
// are not.
|
|
837
|
-
const attributed = tools.reduce((n, t) => n + t.cacheWrite, 0);
|
|
838
|
-
const attributedPct = spend.totals.cacheWrite > 0 ? (attributed / spend.totals.cacheWrite) * 100 : 0;
|
|
839
|
-
// `ok` last, so a future field named `ok` on computeSpend's return cannot
|
|
840
|
-
// silently untag a success (a later spread key always wins over an earlier one).
|
|
841
|
-
return { ...spend, tools, attributedPct, skipped, damaged, since: sinceMs, ok: true };
|
|
842
|
-
} catch (e) {
|
|
843
|
-
// A real bug, not an empty run — say so rather than hiding the panel, which
|
|
844
|
-
// is what turned the last type surprise in here into "no panel appeared".
|
|
845
|
-
// `e.message` is carried as-is, including the "" and `undefined` a
|
|
846
|
-
// message-less throw would give it: the tag above is what routes this to the
|
|
847
|
-
// error panel, so an unhelpful message costs wording, never the panel.
|
|
848
|
-
// An explicit --spend-dir naming a directory that does not exist
|
|
849
|
-
// YET (the legitimate, tested case) throws ENOENT here on every tick
|
|
850
|
-
// until it appears, and this catch used to print unconditionally — one
|
|
851
|
-
// line per ~15s tick, forever. Routed through warnOnce, keyed on the
|
|
852
|
-
// message the same way the `{ error }` arm above it already is, so a
|
|
853
|
-
// repeating fault costs one stderr line, not one per tick.
|
|
854
|
-
warnOnce("spend-read-failed", e.message, `spend read failed: ${e.message}`);
|
|
855
|
-
return { ok: false, error: e.message };
|
|
856
|
-
}
|
|
857
|
-
}
|
|
858
|
-
|
|
859
|
-
// omp's side: one agent per member transcript anywhere under the
|
|
860
|
-
// session dir — a nested member's too, at its own spawnDepth — read by
|
|
861
|
-
// member-record.mjs's own omp reader over the walk readOmpSession uses:
|
|
862
|
-
// foldOmpTranscript once per file, then ompMemberRecord on that fold, never
|
|
863
|
-
// a second parse of omp's line shape. So each row's totals, model and role
|
|
864
|
-
// are exactly the member record's: role from `session_init`'s agent
|
|
865
|
-
// definition, task and AgentId, label the AgentId itself (the path-relative
|
|
866
|
-
// stem, `review-pr-12/Security` for a nested one). The same fold's `entries`
|
|
867
|
-
// are the tool stream, so the tool table goes through attributeTools.
|
|
868
|
-
//
|
|
869
|
-
// Per-transcript tolerance is this file's, not readOmpSession's: readOmpSession
|
|
870
|
-
// (used by the bulk scrape) lets a wrong-shape refusal propagate, and here
|
|
871
|
-
// both — an unreadable file and a wrong-shape refusal — are one transcript's
|
|
872
|
-
// fault, so readOmpSpend, this file's own reader, instead catches both per-
|
|
873
|
-
// transcript, landing them in `skipped` with a stderr line. A transcript
|
|
874
|
-
// ompMemberRecord answers null for (no assistant turn yet — a member
|
|
875
|
-
// dispatched this second) has spent nothing, so it is neither booked nor
|
|
876
|
-
// skipped.
|
|
877
|
-
//
|
|
878
|
-
// `damaged` is real — the tool-attribution stream is a join
|
|
879
|
-
// across lines (a toolCall's id names its tool, a pending result batch bills
|
|
880
|
-
// the next turn), so a dropped MIDDLE line can silently shift spend onto a
|
|
881
|
-
// neighbouring tool instead of just costing its own turn's totals — the
|
|
882
|
-
// hazard foldOmpTranscript's `malformedNonLastLines` counts. This reader
|
|
883
|
-
// sums it across
|
|
884
|
-
// the transcript regardless of whether the file ends up booked as an agent,
|
|
885
|
-
// so a transcript that is corrupt where its assistant-with-usage line should
|
|
886
|
-
// be still surfaces here instead of falling through `if (!m) continue` unseen.
|
|
887
|
-
function readOmpSpend(dir, sinceMs) {
|
|
888
|
-
const agents = [];
|
|
889
|
-
const toolTables = [];
|
|
890
|
-
let skipped = 0;
|
|
891
|
-
let damaged = 0;
|
|
892
|
-
for (const { file, agent, spawnDepth } of ompSessionTranscripts(dir)) {
|
|
893
|
-
try {
|
|
894
|
-
if (sinceMs != null && statSync(file).mtimeMs < sinceMs) continue;
|
|
895
|
-
const folded = foldOmpTranscript(readFileSync(file, "utf8"), file);
|
|
896
|
-
damaged += folded.malformedNonLastLines;
|
|
897
|
-
const m = ompMemberRecord(folded, agent, spawnDepth);
|
|
898
|
-
if (!m) continue;
|
|
899
|
-
// Both halves before either is recorded, so `skipped++` below always
|
|
900
|
-
// means "this transcript contributed nothing".
|
|
901
|
-
const tools = attributeTools(folded.entries);
|
|
902
|
-
agents.push({
|
|
903
|
-
label: m.member, role: m.role, model: m.model,
|
|
904
|
-
cacheWrite: m.tokens_cache_create, output: m.tokens_out, cacheRead: m.tokens_cache_read,
|
|
905
|
-
});
|
|
906
|
-
toolTables.push(tools);
|
|
907
|
-
} catch (e) {
|
|
908
|
-
skipped++;
|
|
909
|
-
// The prefix already names `file`; Node's errno text (`..., open|stat
|
|
910
|
-
// '<file>'`) and member-record's shape refusal (`...: <file>`) end in
|
|
911
|
-
// it too, so that tail is dropped. Any other wording prints whole.
|
|
912
|
-
let why = String(e.message);
|
|
913
|
-
for (const tail of [` '${file}'`, `: ${file}`]) {
|
|
914
|
-
if (why.endsWith(tail)) { why = why.slice(0, -tail.length); break; }
|
|
915
|
-
}
|
|
916
|
-
warnOnce("skips", file, `skipping ${file}: ${why}`);
|
|
917
|
-
}
|
|
918
|
-
}
|
|
919
|
-
return { agents, toolTables, skipped, damaged };
|
|
920
|
-
}
|
|
921
|
-
|
|
922
|
-
// `workspace`/`port` are the caller's answers, never read in here:
|
|
923
|
-
// resolveCockpitInstance() already decided both, and a second derivation in
|
|
924
|
-
// this function could disagree with the one the server actually bound. They
|
|
925
|
-
// join the payload HERE, alongside the repo fields above, because this is the
|
|
926
|
-
// boundary where every impure input meets the pure model — computeBoard() only
|
|
927
|
-
// echoes them. Defaulted to null, which is also the degrade arm's workspace
|
|
928
|
-
// and the value the launch handshake refuses to match on, so a caller with no
|
|
929
|
-
// instance to name (every gather() test driver) says so rather than omitting
|
|
930
|
-
// the fields.
|
|
931
|
-
//
|
|
932
|
-
// `spendDir` is the caller's transcript directory and is the one
|
|
933
|
-
// parameter here whose ABSENCE is not a default to fill in: the tick loop hands
|
|
934
|
-
// the same pin's answer to every tick, and its three shapes — a directory, `null`
|
|
935
|
-
// for "resolved, no session yet", `{ error }` for unresolvable — all have to
|
|
936
|
-
// reach gatherSpend() as themselves. `build` is one gather per process, so it
|
|
937
|
-
// needs the --spend-dir override but never a pin, and passes the override or
|
|
938
|
-
// nothing; with neither the pin nor the flag, gatherSpend() resolves for itself.
|
|
939
|
-
//
|
|
940
|
-
// `spendDirExplicit` is passed separately from `spendDir` itself: the tick
|
|
941
|
-
// loop always passes a resolved `spendDir` (the pin's answer), never leaving it
|
|
942
|
-
// to default, so `spendDir`'s own presence cannot say whether an operator named
|
|
943
|
-
// it. Whether --spend-dir was given is a fact about argv, unrelated to which of
|
|
944
|
-
// gatherSpend's three shapes the pin currently holds. It, `spendSince` and
|
|
945
|
-
// `interval` are argv's answers, resolved by the caller: nothing in here reads
|
|
946
|
-
// argv.
|
|
947
|
-
// Async, because every child read below is. The event loop this frees
|
|
948
|
-
// belongs to serve()'s HTTP server, which shares this process — see execRead's
|
|
949
|
-
// note in board-common.mjs for what the synchronous version cost. `build` awaits it and is
|
|
950
|
-
// otherwise unchanged: one gather per process, nothing else waiting on it.
|
|
951
|
-
export async function gather({ ledgerFile, prevFile, stateFile = null, scriptDir = SCRIPT_DIR, interval, workspace = null, port = null, spendDir, spendDirExplicit = false, spendSince = null }) {
|
|
952
|
-
// The one read that must not crash the gather: a corrupt/partial board.json
|
|
953
|
-
// (the fallback safety net itself) is ignored, not fatal. That holds for a
|
|
954
|
-
// SHAPE fault as much as a parse fault — the guard below rejects the
|
|
955
|
-
// payload here so both leave through the one catch, which names the file the
|
|
956
|
-
// operator passed. A wrong-typed `tickets` left to reach the prevCi map
|
|
957
|
-
// instead throws `.filter is not a function` out of gather(), which made a
|
|
958
|
-
// corrupt prev board fatal after all and blamed an "intermediate value".
|
|
959
|
-
//
|
|
960
|
-
// Validated HERE and not per-read, deliberately: this payload has three more
|
|
961
|
-
// readers (`prev?.repo`/`prev?.repoUrl` below, and compute-board.mjs's dwell
|
|
962
|
-
// tracking, which consumes the whole `prev` this returns), and the prevCi
|
|
963
|
-
// expression's `|| []` is the demonstration — it defends against an ABSENT
|
|
964
|
-
// `tickets`, never a present one of the wrong type. This guard covers that one
|
|
965
|
-
// shape — `prev` is an object, `tickets` is an array of objects — not every
|
|
966
|
-
// field those three readers go on to trust: a wrong-typed `repo`, `repoUrl`, or
|
|
967
|
-
// `sinceEnteredStage` still reaches them unchanged. Those `?.`/`|| []` defaults
|
|
968
|
-
// stay as the belt to these braces.
|
|
969
|
-
let prev = null;
|
|
970
|
-
if (prevFile && existsSync(prevFile)) {
|
|
971
|
-
try {
|
|
972
|
-
// JSON.parse SUCCEEDS on `null`, a bare number, a string and an array,
|
|
973
|
-
// none of which is a board; `null` in particular is absent, not an
|
|
974
|
-
// object, and `typeof null` alone would let it through. Same check and
|
|
975
|
-
// same wording as readMerged()'s `data.repository` read, which is this
|
|
976
|
-
// repo's precedent for rejecting a parsed-but-wrong payload at its own
|
|
977
|
-
// read — literally the same, both calling the shared predicate.
|
|
978
|
-
const p = JSON.parse(readFileSync(prevFile, "utf8"));
|
|
979
|
-
if (!isJsonObject(p)) throw new TypeError(`expected a JSON object, got ${jsonKind(p)}`);
|
|
980
|
-
// Nullish `tickets` is ABSENT and stays usable: `|| []` reads it as the
|
|
981
|
-
// empty carry-forward, which is what a board with no PRs on it says.
|
|
982
|
-
// Only a present-and-wrong-typed one is a fault.
|
|
983
|
-
if (p.tickets != null) {
|
|
984
|
-
if (!Array.isArray(p.tickets))
|
|
985
|
-
throw new TypeError(`expected tickets to be an array, got ${typeof p.tickets}`);
|
|
986
|
-
// Per ENTRY too, and not because a `[null]` is exotic: `Array.isArray`
|
|
987
|
-
// is satisfied by an array of anything, and the very next thing the
|
|
988
|
-
// prevCi map does is read `t.pr` off each element. The whole payload
|
|
989
|
-
// goes, not the bad entry — a board with one unreadable ticket is not a board
|
|
990
|
-
// whose others can be trusted to carry CI state forward, and filtering here
|
|
991
|
-
// (drop the bad entry, keep the rest) would make this a new, fourth policy for
|
|
992
|
-
// one payload class in this file — mapCi's null-only guard and tryParse's
|
|
993
|
-
// unguarded read are the other two — rather than the reject-whole-payload
|
|
994
|
-
// policy this guard already shares with readMerged()'s own read.
|
|
995
|
-
const bad = p.tickets.findIndex((t) => !isJsonObject(t));
|
|
996
|
-
if (bad !== -1)
|
|
997
|
-
throw new TypeError(`expected tickets[${bad}] to be a JSON object, got ${jsonKind(p.tickets[bad])}`);
|
|
998
|
-
}
|
|
999
|
-
prev = p;
|
|
1000
|
-
}
|
|
1001
|
-
catch (e) { console.error(`${NAME}: ignoring unreadable prev board ${prevFile}: ${e.message}`); }
|
|
1002
|
-
}
|
|
1003
|
-
|
|
1004
|
-
// `--require-file` turns an absent ledger into a refusal at exit 2 rather
|
|
1005
|
-
// than the empty payload a real empty ledger returns. Without it the
|
|
1006
|
-
// two are byte-identical on stdout, and tryParse's fallback is that same
|
|
1007
|
-
// empty shape besides — so an unread ledger, one read empty, and a read whose
|
|
1008
|
-
// answer would not parse were three states with one rendering, on the one
|
|
1009
|
-
// subcommand this cockpit consumes.
|
|
1010
|
-
//
|
|
1011
|
-
// The three stay three here because each is a different observation, not a
|
|
1012
|
-
// different value of one: null from tryRun is a read that did not happen (the
|
|
1013
|
-
// refusal, or an unreachable node), null from tryParse is a read whose answer
|
|
1014
|
-
// was unusable, and anything else is the ledger. `tryParse`'s fallback is
|
|
1015
|
-
// null rather than the empty shape for exactly that reason — the empty shape
|
|
1016
|
-
// is a real answer and must not double as the failure.
|
|
1017
|
-
const ledgerJson = await tryRun("node", [join(scriptDir, "ledger.mjs"), "--file", ledgerFile, "--require-file", "read"]);
|
|
1018
|
-
// "read" means ledgerJson parsed as JSON, not that it conforms to the
|
|
1019
|
-
// {rows,filed,ruled} shape — tryParse only checks syntax, so a
|
|
1020
|
-
// syntactically-valid-but-wrong-shape payload from ledger.mjs would still
|
|
1021
|
-
// be labelled "read" here. ledger.mjs is this repo's own, already-tested
|
|
1022
|
-
// producer of this JSON, so that gap is accepted rather than guarded.
|
|
1023
|
-
const parsedLedger = tryParse(ledgerJson, null, "ledger read");
|
|
1024
|
-
// Strictly `!== null`, never falsiness — a ledger payload that parses to
|
|
1025
|
-
// `0`, `false` or `""` is a real answer tryParse already forwarded (see
|
|
1026
|
-
// tryParse's own comment above), and treating it as falsy here would
|
|
1027
|
-
// silently discard it into `unparsed`, the exact bug class tryParse's
|
|
1028
|
-
// guard exists to prevent, one caller downstream of the fix.
|
|
1029
|
-
const ledger = parsedLedger !== null
|
|
1030
|
-
? { ...parsedLedger, state: "read" }
|
|
1031
|
-
: { rows: [], filed: [], ruled: [], state: ledgerJson == null ? "unread" : "unparsed" };
|
|
1032
|
-
|
|
1033
|
-
const issuesJson = await tryRun("gh", ["issue", "list", "--label", "ready-for-agent",
|
|
1034
|
-
"--state", "open", "--limit", String(POOL_LIMIT), "--json", "number,title,labels"]);
|
|
1035
|
-
// title: falls back to the same `#<number>` placeholder titleFor() already
|
|
1036
|
-
// uses for an issue it cannot find at all (compute-board.mjs). An unrowed
|
|
1037
|
-
// issue becomes a POOL card straight from this array — compute-board.mjs's
|
|
1038
|
-
// POOL loop reads `iss.title` RAW, never through titleFor()'s fallback
|
|
1039
|
-
// chain — so this row genuinely needs a guaranteed string: an issue found
|
|
1040
|
-
// but unable to describe itself reads as its number rather than literal
|
|
1041
|
-
// `undefined` on the operator's page.
|
|
1042
|
-
//
|
|
1043
|
-
// Its null fallback, not the open-PR read's `[]` below, is deliberate:
|
|
1044
|
-
// this read is the pool's ONLY source, and
|
|
1045
|
-
// compute-board.mjs's stall() needs to tell a genuinely empty pool from a
|
|
1046
|
-
// `gh` outage the same way it already tells an empty ledger from an unread
|
|
1047
|
-
// one — a `[]` fallback collapses both to the identical shape before a
|
|
1048
|
-
// caller here could split them back apart.
|
|
1049
|
-
const issuesParsed = tryParse(issuesJson, null, "gh issue list");
|
|
1050
|
-
const poolOk = issuesParsed !== null;
|
|
1051
|
-
const poolCapped = hitLimit(issuesParsed, POOL_LIMIT);
|
|
1052
|
-
const issues = withNumber(poolOk ? issuesParsed : [], "gh issue list").map((i) => ({
|
|
1053
|
-
number: i.number,
|
|
1054
|
-
title: typeof i.title === "string" ? i.title : `#${i.number}`,
|
|
1055
|
-
labels: labelsOf(i),
|
|
1056
|
-
}));
|
|
1057
|
-
|
|
1058
|
-
const prsJson = await tryRun("gh", ["pr", "list", "--state", "open", "--limit", String(OPEN_PR_LIMIT),
|
|
1059
|
-
"--json", "number,state,labels,title,headRefOid"]);
|
|
1060
|
-
// No default for `title` or `state` here, unlike the issue row above — raw
|
|
1061
|
-
// passthrough, deliberately. `title`: compute-board.mjs's titleFor() already
|
|
1062
|
-
// falls through a falsy `pr.title` to the real issue title (`if (pr &&
|
|
1063
|
-
// pr.title) return pr.title;`); nothing else reads a PR row's `title` field
|
|
1064
|
-
// raw, so defaulting it to `#<number>` made it unconditionally truthy and
|
|
1065
|
-
// SILENTLY DISABLED that fallback — a titleless PR row showed the PR number
|
|
1066
|
-
// instead of the real issue title, worse than doing nothing. `state`: its
|
|
1067
|
-
// only consumer is `pr.state === "OPEN"` (compute-board.mjs), already false
|
|
1068
|
-
// for `undefined` exactly as it was for the old "UNKNOWN" sentinel, so the
|
|
1069
|
-
// default was inert — pure indirection with no behaviour to show for it.
|
|
1070
|
-
const prsParsed = tryParse(prsJson, [], "gh pr list");
|
|
1071
|
-
const prsCapped = hitLimit(prsParsed, OPEN_PR_LIMIT);
|
|
1072
|
-
const prs = withNumber(prsParsed, "gh pr list").map((p) => ({
|
|
1073
|
-
number: p.number,
|
|
1074
|
-
state: p.state,
|
|
1075
|
-
title: p.title,
|
|
1076
|
-
labels: labelsOf(p),
|
|
1077
|
-
// compute-board.mjs's reviewBacklog needs it to tell a
|
|
1078
|
-
// past-pin halt already answered by the automatic re-review apart from
|
|
1079
|
-
// one still owed a fresh one — the same field fleet-tick.mjs's
|
|
1080
|
-
// openPrs() already requires.
|
|
1081
|
-
headRefOid: p.headRefOid,
|
|
1082
|
-
}));
|
|
1083
|
-
|
|
1084
|
-
// MERGED is gh's answer, not a ledger token — no rule writes `MERGED
|
|
1085
|
-
// <sha>`, and the open list above drops a PR the moment it merges. It is
|
|
1086
|
-
// asked only about mergedReadPrs()'s set — row PRs absent from the open
|
|
1087
|
-
// list, with no token, not carried forward — in one batched read
|
|
1088
|
-
// that answers whatever their merge age; see readMerged(). A failed read
|
|
1089
|
-
// is `[]`, and the carry-forward in computeBoard() covers exactly the
|
|
1090
|
-
// PRs this set leaves out, so a failure costs only a PR never yet seen
|
|
1091
|
-
// MERGED, which reads REVIEW.
|
|
1092
|
-
const merged = await readMerged(mergedReadPrs({ ledger, prs, prev }));
|
|
1093
|
-
|
|
1094
|
-
// CI per open PR. On failure, carry the previous board's value for that PR.
|
|
1095
|
-
const prevCi = new Map((prev?.tickets || []).filter((t) => t.pr != null).map((t) => [t.pr, t.ci]));
|
|
1096
|
-
const ci = {};
|
|
1097
|
-
// Awaited one at a time rather than raced with Promise.all, and that is a
|
|
1098
|
-
// decision rather than an oversight: this loop spawns one `node
|
|
1099
|
-
// ci-state.mjs` per open PR and each of those hits the GitHub API, so a fan
|
|
1100
|
-
// of 40 at once is a rate-limit and a load spike where a queue of 40 is
|
|
1101
|
-
// neither. Nothing here waits on the loop any more — the server answers
|
|
1102
|
-
// throughout it — so the only thing concurrency would buy is a
|
|
1103
|
-
// shorter tick, against an interval measured in seconds. The warn-once
|
|
1104
|
-
// lines below also stay in PR order this way.
|
|
1105
|
-
for (const p of prs) {
|
|
1106
|
-
const out = await runCiState(scriptDir, p.number);
|
|
1107
|
-
ci[p.number] = out === null ? (prevCi.get(p.number) ?? "unknown") : mapCi(out, p.number);
|
|
1108
|
-
}
|
|
1109
|
-
|
|
1110
|
-
// Repo identity + web URL for PR links — the url carries the host, so links
|
|
1111
|
-
// resolve on GitHub Enterprise, not just github.com. From the fleet's cwd, so
|
|
1112
|
-
// the board stays repo-agnostic. On failure, carry the previous board's values.
|
|
1113
|
-
const repoJson = await tryRun("gh", ["repo", "view", "--json", "nameWithOwner,url"]);
|
|
1114
|
-
let repo = prev?.repo ?? null;
|
|
1115
|
-
let repoUrl = prev?.repoUrl ?? null;
|
|
1116
|
-
if (repoJson) {
|
|
1117
|
-
try { const d = JSON.parse(repoJson); repo = d.nameWithOwner ?? repo; repoUrl = d.url ?? repoUrl; }
|
|
1118
|
-
catch (e) { console.error(`${NAME}: gh repo view parse failed: ${e.message}`); }
|
|
1119
|
-
}
|
|
1120
|
-
|
|
1121
|
-
// The guard's own rationale (fail loud, gate on presence and on range,
|
|
1122
|
-
// not just finiteness) lives at the --spend-since reader's definition above;
|
|
1123
|
-
// main() runs it and hands the answer in as `spendSince`.
|
|
1124
|
-
const spend = gatherSpend({ dir: spendDir, sinceMs: spendSince, explicit: spendDirExplicit });
|
|
1125
|
-
// The heartbeat's mark, raw. readState() never throws — an absent
|
|
1126
|
-
// file is the ordinary state of a run whose heartbeat has not beaten yet,
|
|
1127
|
-
// and an unreadable or corrupt one announces itself on stderr and degrades
|
|
1128
|
-
// to no mark, which computeBoard() renders as no panel rather than as a
|
|
1129
|
-
// death it cannot substantiate. So no try/catch here and no `tryRun` shape:
|
|
1130
|
-
// the degrade lives in the module that owns the file.
|
|
1131
|
-
//
|
|
1132
|
-
// `null` when no caller named a state file, and DISTINCT from a file that
|
|
1133
|
-
// is simply absent: both omit the surface today, but only the second is a
|
|
1134
|
-
// reading. Defaulted rather than resolved here for gather()'s own reason —
|
|
1135
|
-
// every caller in this file passes the instance's answer, and a second
|
|
1136
|
-
// resolution could name a different workspace's beat.
|
|
1137
|
-
// `ticked`, `acted` and `controller` ride beside `beat`, same file same
|
|
1138
|
-
// read, and under the same "no try/catch, no tryRun shape" rule just above:
|
|
1139
|
-
// a run is judged from all of its own marks, and the record's `at` is what
|
|
1140
|
-
// tells this run's marks from the previous run's (fleet-state.mjs's
|
|
1141
|
-
// assessBeat has the rule).
|
|
1142
|
-
const priorState = stateFile ? readState(stateFile, NAME) : null;
|
|
1143
|
-
const beat = priorState?.beat ?? null;
|
|
1144
|
-
const ticked = priorState?.ticked ?? null;
|
|
1145
|
-
const acted = priorState?.acted ?? null;
|
|
1146
|
-
const controller = priorState?.controller ?? null;
|
|
1147
|
-
// Whose stall it is, off the controller record in the same file — judged
|
|
1148
|
-
// here because it reads the process table, and only when the mark is
|
|
1149
|
-
// stalled, so a healthy board reads none. computeBoard() words it.
|
|
1150
|
-
const now = Date.now();
|
|
1151
|
-
const stallOwnerOf = isStalled(assessBeat({ beat, ticked, acted, controller, now })) ? stallOwner(priorState, NAME) : null;
|
|
1152
|
-
return { ledger, issues, prs, merged, ci, prev, repo, repoUrl, workspace, port, spend, beat, ticked, acted, controller, stallOwner: stallOwnerOf, poolOk,
|
|
1153
|
-
poolCapped, prsCapped,
|
|
1154
|
-
now, interval };
|
|
1155
|
-
}
|
|
1156
|
-
|
|
1157
158
|
async function main() {
|
|
1158
159
|
// A misspelled flag was never looked for, so `serve --prot 9000`
|
|
1159
160
|
// served on the default 8123 in silence. In main(), not at module scope:
|
|
@@ -1392,577 +393,6 @@ async function boardTick({ ledgerFile, interval, spendDir, spendSince }) {
|
|
|
1392
393
|
};
|
|
1393
394
|
}
|
|
1394
395
|
|
|
1395
|
-
import { copyFileSync, mkdirSync } from "node:fs";
|
|
1396
|
-
|
|
1397
|
-
// The names a browser on this machine can legitimately put in `Host` to reach
|
|
1398
|
-
// a loopback-only cockpit. DNS rebinding points an attacker-chosen name at
|
|
1399
|
-
// 127.0.0.1, and the browser then sends THAT name as `Host`, so the hostname —
|
|
1400
|
-
// not the peer address, which is loopback either way — is what separates the
|
|
1401
|
-
// operator's own tab from a rebound page. The port is deliberately not
|
|
1402
|
-
// compared: an `ssh -L` forward reaches the cockpit under a different local
|
|
1403
|
-
// port, and the port tells a rebound page nothing it could not scan for.
|
|
1404
|
-
const COCKPIT_HOSTNAMES = new Set(["127.0.0.1", "localhost", "[::1]"]);
|
|
1405
|
-
// A bracketed IPv6 literal or a bare name, then an optional `:port` — anything
|
|
1406
|
-
// else (userinfo, a second colon outside brackets, a path) is not a Host value.
|
|
1407
|
-
const HOST_HEADER = /^(\[[^\]]+\]|[^:[\]]+)(?::\d*)?$/;
|
|
1408
|
-
function isCockpitHost(host) {
|
|
1409
|
-
const m = HOST_HEADER.exec(host ?? "");
|
|
1410
|
-
return m !== null && COCKPIT_HOSTNAMES.has(m[1].toLowerCase());
|
|
1411
|
-
}
|
|
1412
|
-
|
|
1413
|
-
// A refused Host is the operator's only clue to why the tab shows a 403 — an
|
|
1414
|
-
// unlisted spelling of loopback, or a rebound page probing the port — so the
|
|
1415
|
-
// refusal goes to stderr, once per distinct Host. The value is the client's,
|
|
1416
|
-
// so it is rendered as a JSON string (quotes, backslashes and C0 controls
|
|
1417
|
-
// escaped), with DEL, the C1 controls and the U+2028/U+2029 line separators,
|
|
1418
|
-
// which JSON leaves bare, escaped too, and cut to a bounded length: it cannot
|
|
1419
|
-
// split or forge a log line. A rebound page can
|
|
1420
|
-
// send unlimited distinct Hosts, so each server logs at most
|
|
1421
|
-
// REFUSED_HOST_LOG_CAP of them, then one notice, then nothing new.
|
|
1422
|
-
const REFUSED_HOST_LOG_CAP = 16;
|
|
1423
|
-
const REFUSED_HOST_SHOWN = 100;
|
|
1424
|
-
const COCKPIT_HOST_LIST = [...COCKPIT_HOSTNAMES].join(", ");
|
|
1425
|
-
export function renderRefusedHost(host) {
|
|
1426
|
-
if (host === undefined) return "a request with no Host header";
|
|
1427
|
-
const json = JSON.stringify(host.slice(0, REFUSED_HOST_SHOWN))
|
|
1428
|
-
.replace(/[\u007f-\u009f\u2028\u2029]/g, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, "0")}`);
|
|
1429
|
-
return `Host ${json}${host.length > REFUSED_HOST_SHOWN ? `… (${host.length} chars)` : ""}`;
|
|
1430
|
-
}
|
|
1431
|
-
|
|
1432
|
-
export function createBoardServer(dir) {
|
|
1433
|
-
let refusedHostsLogged = 0;
|
|
1434
|
-
function logRefusedHost(host) {
|
|
1435
|
-
if (refusedHostsLogged > REFUSED_HOST_LOG_CAP) return;
|
|
1436
|
-
if (refusedHostsLogged === REFUSED_HOST_LOG_CAP) {
|
|
1437
|
-
refusedHostsLogged++;
|
|
1438
|
-
console.error(`${NAME}: ${REFUSED_HOST_LOG_CAP} distinct Hosts refused; further refused Hosts are not logged`);
|
|
1439
|
-
return;
|
|
1440
|
-
}
|
|
1441
|
-
const shown = renderRefusedHost(host);
|
|
1442
|
-
if (warnOnce("host-refused", shown, `refused ${shown} — not a loopback name (${COCKPIT_HOST_LIST}); answered 403`)) refusedHostsLogged++;
|
|
1443
|
-
}
|
|
1444
|
-
return createServer((req, res) => {
|
|
1445
|
-
// Checked before routing, so an unknown path on a foreign Host is as
|
|
1446
|
-
// opaque as a known one: 403, never a 404 that tells a rebound page which
|
|
1447
|
-
// paths exist.
|
|
1448
|
-
if (!isCockpitHost(req.headers.host)) {
|
|
1449
|
-
logRefusedHost(req.headers.host);
|
|
1450
|
-
res.writeHead(403); res.end("forbidden"); return;
|
|
1451
|
-
}
|
|
1452
|
-
const url = (req.url || "/").split("?")[0];
|
|
1453
|
-
const path = url === "/" || url === "/board.html" ? join(dir, "board.html")
|
|
1454
|
-
: url === "/board.json" ? join(dir, "board.json") : null;
|
|
1455
|
-
if (!path || !existsSync(path)) { res.writeHead(404); res.end("not found"); return; }
|
|
1456
|
-
const type = path.endsWith(".json") ? "application/json" : "text/html; charset=utf-8";
|
|
1457
|
-
res.writeHead(200, { "content-type": type, "cache-control": "no-store" });
|
|
1458
|
-
res.end(readFileSync(path));
|
|
1459
|
-
});
|
|
1460
|
-
}
|
|
1461
|
-
|
|
1462
|
-
// A cockpit instance is identified by its WORKSPACE — the directory holding
|
|
1463
|
-
// the shared git dir — not by the process's cwd and not by the machine. Two
|
|
1464
|
-
// workspaces therefore get two boards on two ports, both live and neither
|
|
1465
|
-
// aware of the other, and one workspace derives the SAME port on every run,
|
|
1466
|
-
// so that URL survives runs, reboots and node versions.
|
|
1467
|
-
//
|
|
1468
|
-
// BASE is the port this file hardcoded before any of this existed;
|
|
1469
|
-
// resolveCockpitInstance()'s degrade arm, with no workspace to hash, still
|
|
1470
|
-
// defaults to it. SPAN = 512 was kept deliberately: a
|
|
1471
|
-
// collision between two DIFFERENT workspaces is not priced into the width but
|
|
1472
|
-
// carried by serve()'s launch loop, which probes whoever holds the derived
|
|
1473
|
-
// port, reuses that cockpit when it is this workspace's own, and otherwise
|
|
1474
|
-
// scans on through cockpitPorts()'s PORT_ATTEMPTS candidates. The accepted
|
|
1475
|
-
// cost is launch order: whichever colliding workspace starts second binds a
|
|
1476
|
-
// port other than the one its hash derives.
|
|
1477
|
-
const PORT_BASE = 8123;
|
|
1478
|
-
const PORT_SPAN = 512;
|
|
1479
|
-
|
|
1480
|
-
// FNV-1a, 32-bit, written out inline. Three properties this needs that no
|
|
1481
|
-
// crypto digest and no Math.random has together: stable across node versions
|
|
1482
|
-
// and across machines (nothing in here reads the engine, the host or the
|
|
1483
|
-
// clock), dependency-free, and cheap enough to run on every start. Math.imul
|
|
1484
|
-
// is the whole reason it is spelled this way — a plain `h * 0x01000193`
|
|
1485
|
-
// leaves exact integer range after two rounds and silently stops being FNV.
|
|
1486
|
-
// `>>> 0` is load-bearing, not decoration: without it `h` stays SIGNED, so
|
|
1487
|
-
// `h % PORT_SPAN` can come back negative and the derived port lands BELOW
|
|
1488
|
-
// base, outside the window this function's own contract promises.
|
|
1489
|
-
function workspaceHash(key) {
|
|
1490
|
-
let h = 0x811c9dc5;
|
|
1491
|
-
for (let i = 0; i < key.length; i++) {
|
|
1492
|
-
h ^= key.charCodeAt(i);
|
|
1493
|
-
h = Math.imul(h, 0x01000193);
|
|
1494
|
-
}
|
|
1495
|
-
return h >>> 0;
|
|
1496
|
-
}
|
|
1497
|
-
|
|
1498
|
-
// The one spelling of "this value is a workspace identity", read by every
|
|
1499
|
-
// side of the cockpit handshake. The invariant is that null and the
|
|
1500
|
-
// empty string are never an identity to match on, and it used to be carried
|
|
1501
|
-
// by two independently-written guards — resolveCockpitInstance()'s
|
|
1502
|
-
// `workspace === null` below and probeCockpitWorkspace()'s
|
|
1503
|
-
// `typeof w === "string" && w !== ""` — correct only because both were
|
|
1504
|
-
// written consistently, not because anything stopped one from moving without
|
|
1505
|
-
// the other. What a drift buys is silent and cross-workspace: let the
|
|
1506
|
-
// construction side call the empty string an identity while the parsing side
|
|
1507
|
-
// still accepts it, and two cockpits in two different workspaces, neither
|
|
1508
|
-
// with an identity established, match each other's board and one reuses the
|
|
1509
|
-
// other — a hand-off nothing else in this file would refuse, since the
|
|
1510
|
-
// degrade arm's "no identity to match on" is the only thing keeping a held
|
|
1511
|
-
// port fatal there.
|
|
1512
|
-
//
|
|
1513
|
-
// A non-empty string, and nothing more: no trim(). A wholly-whitespace
|
|
1514
|
-
// answer to `--git-common-dir` is already refused one layer down, by
|
|
1515
|
-
// git-env.mjs's workspaceDirFromGitCommonDir() inside fleet-dir.mjs's
|
|
1516
|
-
// fleetFile(), so no identity reaching either call site can be whitespace —
|
|
1517
|
-
// the construction side gets the workspace fleetFile() resolved and the
|
|
1518
|
-
// parsing side gets a payload some process wrote from it. A second whitespace
|
|
1519
|
-
// rule here would be one more guard of exactly the kind this predicate exists
|
|
1520
|
-
// to stop writing.
|
|
1521
|
-
//
|
|
1522
|
-
// Not exported, for workspaceHash()'s reason above it: nothing outside this
|
|
1523
|
-
// file asks the question, and every widening of it is already pinned from
|
|
1524
|
-
// outside through the two call sites — mutation-verified for this extraction
|
|
1525
|
-
// and each mutant was killed by a test that already existed in the board tests:
|
|
1526
|
-
// `v != null && v !== ""` by the probe's not-a-string row, `typeof v ===
|
|
1527
|
-
// "string"` by its empty-workspace row, a degrade arm publishing `""` by
|
|
1528
|
-
// resolveCockpitInstance's three degrade rows, and dropping it from
|
|
1529
|
-
// serve()'s `scannable` by the CLI's held-port-on-the-degrade-arm row. So no
|
|
1530
|
-
// test is added here: sharing the predicate is what makes the construction
|
|
1531
|
-
// side's rows constrain the parsing side and back, which is a STRONGER suite
|
|
1532
|
-
// than before, not one with a hole a new row could fill.
|
|
1533
|
-
function isWorkspaceId(v) {
|
|
1534
|
-
return typeof v === "string" && v !== "";
|
|
1535
|
-
}
|
|
1536
|
-
|
|
1537
|
-
/**
|
|
1538
|
-
* The cockpit's instance seam, and the only one. Given a cwd, the workspace
|
|
1539
|
-
* this cockpit belongs to — INJECTED, already resolved, or null when it could
|
|
1540
|
-
* not be — and an explicitly requested port if there was one, decide which
|
|
1541
|
-
* state directory this cockpit serves and which port it binds.
|
|
1542
|
-
*
|
|
1543
|
-
* Pure: it listens to nothing, spawns nothing, reads nothing and writes
|
|
1544
|
-
* nothing, so every branch below is reachable from a test with no git repo
|
|
1545
|
-
* and no socket.
|
|
1546
|
-
*
|
|
1547
|
-
* The workspace comes from fleet-dir.mjs's fleetFile(), the same locator the
|
|
1548
|
-
* run's ledger and heartbeat are resolved with — so the board, the ledger and
|
|
1549
|
-
* the heartbeat cannot disagree about which run they belong to — asked with
|
|
1550
|
-
* the `canonicalise` opt-in only this caller takes: a symlinked route to one
|
|
1551
|
-
* workspace must derive that workspace's port instead of a second, private
|
|
1552
|
-
* one.
|
|
1553
|
-
*
|
|
1554
|
-
* `why` is fleetFile()'s message when it could not answer — it names what
|
|
1555
|
-
* failed, and the degrade warning below carries it, as the ledger's does.
|
|
1556
|
-
* Absent, the warning names the failure without a reason.
|
|
1557
|
-
*/
|
|
1558
|
-
export function resolveCockpitInstance({ cwd = process.cwd(), workspace, why, port } = {}) {
|
|
1559
|
-
// `port != null`, never truthiness: --port 0 is a real request (an
|
|
1560
|
-
// ephemeral bind) and reading it as "absent" would derive a port
|
|
1561
|
-
// straight over the top of one the caller explicitly asked for.
|
|
1562
|
-
const forced = port != null;
|
|
1563
|
-
// Asked as `!isWorkspaceId(...)` rather than `=== null`: the question this
|
|
1564
|
-
// arm answers is "was an identity established", and what counts as one is
|
|
1565
|
-
// the predicate above — the same one the probe parses with, so the two
|
|
1566
|
-
// sides cannot answer it differently.
|
|
1567
|
-
if (!isWorkspaceId(workspace)) {
|
|
1568
|
-
// Degrade, never die: a non-git or otherwise unusual checkout still gets
|
|
1569
|
-
// a board. The wording is the ledger's rather than a second dialect for
|
|
1570
|
-
// the same failure, trailing parenthetical included — that parenthetical
|
|
1571
|
-
// names what is degraded HERE, which is not what is degraded there.
|
|
1572
|
-
console.error(`${NAME}: WARNING ${why || "could not resolve --git-common-dir"}; using cwd-relative .fleet (a second cockpit in another workspace may collide on this port and this state directory)`);
|
|
1573
|
-
// Absolute, like the resolved arm, but anchored on the cwd — which is
|
|
1574
|
-
// what "cwd-relative" resolves to and what this script's fs calls did
|
|
1575
|
-
// with the bare `.fleet` they used before. No workspace was established,
|
|
1576
|
-
// so there is no key to hash and the port is BASE: today's default,
|
|
1577
|
-
// unchanged, for the case that used to be the only case.
|
|
1578
|
-
return { stateDir: join(cwd, ".fleet"), workspace: null, port: forced ? port : PORT_BASE, derived: !forced };
|
|
1579
|
-
}
|
|
1580
|
-
return {
|
|
1581
|
-
stateDir: join(workspace, ".fleet"),
|
|
1582
|
-
workspace,
|
|
1583
|
-
port: forced ? port : PORT_BASE + (workspaceHash(workspace) % PORT_SPAN),
|
|
1584
|
-
derived: !forced,
|
|
1585
|
-
};
|
|
1586
|
-
}
|
|
1587
|
-
|
|
1588
|
-
// The impure half, deliberately outside the seam above: the `{ workspace }`
|
|
1589
|
-
// fleetFile() resolves from `cwd`, or `{ workspace: null, why }` when it
|
|
1590
|
-
// cannot — which takes the degrade arm above, so a non-git checkout, a stalled
|
|
1591
|
-
// git and git missing entirely all still get a board, with the reason on its
|
|
1592
|
-
// warning. Spread into resolveCockpitInstance()'s arguments.
|
|
1593
|
-
function cockpitWorkspace(cwd) {
|
|
1594
|
-
try {
|
|
1595
|
-
return { workspace: dirname(fleetFile(null, { cwd, canonicalise: true })) };
|
|
1596
|
-
} catch (e) {
|
|
1597
|
-
if (!(e instanceof FleetDirUnresolvable)) throw e;
|
|
1598
|
-
return { workspace: null, why: e.message };
|
|
1599
|
-
}
|
|
1600
|
-
}
|
|
1601
|
-
|
|
1602
|
-
// How many ports one launch may try before it gives up, and the whole cost
|
|
1603
|
-
// of the scan: the worst case is ATTEMPTS × (a bind plus a probe), so a
|
|
1604
|
-
// workspace whose derived port sits in a crowded corner of the range still
|
|
1605
|
-
// fails in seconds rather than walking all 512. It also bounds how far a
|
|
1606
|
-
// cockpit can land from the stable URL its workspace derives — a board a
|
|
1607
|
-
// handful of ports from where it is bookmarked is still findable by hand,
|
|
1608
|
-
// while one hundreds of ports away (where an unbounded scan could leave it)
|
|
1609
|
-
// typically is not.
|
|
1610
|
-
const PORT_ATTEMPTS = 8;
|
|
1611
|
-
|
|
1612
|
-
/**
|
|
1613
|
-
* The ports one launch may try, in order, for a resolved instance — the
|
|
1614
|
-
* second half of the instance seam and pure like the first, so every row
|
|
1615
|
-
* below is reachable with no socket.
|
|
1616
|
-
*
|
|
1617
|
-
* An EXPLICIT port collapses to a single candidate: the operator named a
|
|
1618
|
-
* port, so there is nothing to scan and (guarded separately in serve()) no
|
|
1619
|
-
* holder to handshake with.
|
|
1620
|
-
*
|
|
1621
|
-
* A DERIVED one starts at the derived port — the stable, bookmarkable one —
|
|
1622
|
-
* and walks forward MODULO the span, never out of the window
|
|
1623
|
-
* resolveCockpitInstance() promises. Without the wrap a workspace hashing to
|
|
1624
|
-
* the top of the range would scan straight past 8634 into ports belonging to
|
|
1625
|
-
* nothing in this scheme, and the range this exists to stay inside would be
|
|
1626
|
-
* a range in name only.
|
|
1627
|
-
*/
|
|
1628
|
-
export function cockpitPorts({ port, derived }) {
|
|
1629
|
-
if (!derived) return [port];
|
|
1630
|
-
const offset = port - PORT_BASE;
|
|
1631
|
-
return Array.from({ length: PORT_ATTEMPTS }, (_, i) => PORT_BASE + ((offset + i) % PORT_SPAN));
|
|
1632
|
-
}
|
|
1633
|
-
|
|
1634
|
-
// One bind attempt, as a value rather than as an event. Resolves with null
|
|
1635
|
-
// on success and with the error otherwise — never rejects, because every
|
|
1636
|
-
// caller has to READ the code (EADDRINUSE is negotiable, everything else is
|
|
1637
|
-
// fatal) and a rejection would make that a try/catch around a control-flow
|
|
1638
|
-
// decision. The listeners are removed on whichever side loses: a server that
|
|
1639
|
-
// failed to bind is dropped, and one that bound gets serve()'s own long-
|
|
1640
|
-
// lived error handler instead of this one-shot.
|
|
1641
|
-
function bindFailure(server, port) {
|
|
1642
|
-
return new Promise((resolve) => {
|
|
1643
|
-
const onError = (e) => { server.removeListener("listening", onListening); resolve(e); };
|
|
1644
|
-
const onListening = () => { server.removeListener("error", onError); resolve(null); };
|
|
1645
|
-
server.once("error", onError);
|
|
1646
|
-
server.once("listening", onListening);
|
|
1647
|
-
server.listen(port, COCKPIT_HOST);
|
|
1648
|
-
});
|
|
1649
|
-
}
|
|
1650
|
-
|
|
1651
|
-
// Whether something already answers on COCKPIT_HOST:port, asked BEFORE the
|
|
1652
|
-
// bind rather than read off it: a 127.0.0.1 bind does not reliably fail when
|
|
1653
|
-
// the port is taken. On macOS/BSD, SO_REUSEADDR lets it succeed beside a
|
|
1654
|
-
// listener that holds every interface — a dev server, or a cockpit started
|
|
1655
|
-
// before the bind was narrowed to loopback — and the launch would then sit
|
|
1656
|
-
// on that holder's 127.0.0.1 traffic instead of stepping over it or reusing
|
|
1657
|
-
// it. Linux refuses that bind outright; this check gives both the same answer.
|
|
1658
|
-
// Resolves in bindFailure()'s vocabulary so the loop reads one shape: null
|
|
1659
|
-
// when the connection is refused (nothing holds the port), an EADDRINUSE
|
|
1660
|
-
// error when it connects or times out, and any other error as itself,
|
|
1661
|
-
// marked `heldCheck` — a fault of its own, like EACCES on a bind, which the
|
|
1662
|
-
// loop reports as this check's rather than the bind's, whatever code the
|
|
1663
|
-
// error carries. A timeout counts as held because a live holder whose accept
|
|
1664
|
-
// backlog is full drops the SYN rather than refusing it. The window between
|
|
1665
|
-
// this check and the bind is a race the loop accepts, like its others.
|
|
1666
|
-
function heldFailure(port) {
|
|
1667
|
-
return new Promise((resolve) => {
|
|
1668
|
-
const socket = connect({ host: COCKPIT_HOST, port });
|
|
1669
|
-
const held = () => {
|
|
1670
|
-
socket.destroy();
|
|
1671
|
-
resolve(Object.assign(new Error(`port ${port} answers on ${COCKPIT_HOST}`), { code: "EADDRINUSE" }));
|
|
1672
|
-
};
|
|
1673
|
-
socket.setTimeout(PROBE_TIMEOUT_MS, held);
|
|
1674
|
-
socket.once("connect", held);
|
|
1675
|
-
socket.once("error", (e) => resolve(e.code === "ECONNREFUSED" ? null : Object.assign(e, { heldCheck: true })));
|
|
1676
|
-
});
|
|
1677
|
-
}
|
|
1678
|
-
|
|
1679
|
-
// ~1s per attempt, and the whole reason this is a probe and not a lockfile:
|
|
1680
|
-
// a launch that cannot get an answer within a second must proceed, not
|
|
1681
|
-
// wait. A holder that accepts the connection and then says nothing is the
|
|
1682
|
-
// case that pays for this timer — nothing else in a socket read bounds it.
|
|
1683
|
-
// One silent window does not settle the question, though: nothing in a socket
|
|
1684
|
-
// read tells a port nobody holds from one whose holder was busy for that
|
|
1685
|
-
// second, and a box under load, a process still between its bind and its
|
|
1686
|
-
// identity write, or a dropped SYN all produce the second shape. The probe
|
|
1687
|
-
// retries once before it will call a silent port foreign.
|
|
1688
|
-
//
|
|
1689
|
-
// Until the tick's reads became asynchronous the commonest producer of that shape was this cockpit itself —
|
|
1690
|
-
// a same-workspace holder blocked inside its own synchronous gather() when
|
|
1691
|
-
// the probe arrived, for the 4.72–4.91s a board took to build, which no
|
|
1692
|
-
// number of retries at this timeout would have covered. That one is gone at
|
|
1693
|
-
// the source: the tick's reads are asynchronous and the server answers
|
|
1694
|
-
// throughout. Raising this timeout was
|
|
1695
|
-
// ruled out as the fix for it — it would have to clear a gather(), which
|
|
1696
|
-
// charges every launch past a stranger-held port that much per candidate.
|
|
1697
|
-
const PROBE_TIMEOUT_MS = 1000;
|
|
1698
|
-
// The one address a cockpit binds, and so the one address the probe and the
|
|
1699
|
-
// pre-bind check dial: whatever holds a candidate where this launch would
|
|
1700
|
-
// bind answers here. 127.0.0.1 rather than `localhost` keeps a resolver out
|
|
1701
|
-
// of the launch path, and loopback alone keeps the board — a read-only
|
|
1702
|
-
// mirror of the ledger — off every other machine on the network; remote
|
|
1703
|
-
// viewing goes through an `ssh -L` tunnel. IPv4 only: `::1` is left unbound,
|
|
1704
|
-
// which is why every URL printed below names 127.0.0.1 too. `localhost`
|
|
1705
|
-
// resolves `::1` first, and on `::1` a browser can reach some other process
|
|
1706
|
-
// that holds the same port.
|
|
1707
|
-
const COCKPIT_HOST = "127.0.0.1";
|
|
1708
|
-
// A holder is not necessarily a cockpit, and a second of localhost writes is
|
|
1709
|
-
// a lot of memory to accept from one. The board payload for a real run is
|
|
1710
|
-
// kilobytes; anything past this is not one, so it is refused as foreign
|
|
1711
|
-
// rather than buffered.
|
|
1712
|
-
const PROBE_BODY_CAP = 1024 * 1024;
|
|
1713
|
-
|
|
1714
|
-
/**
|
|
1715
|
-
* Ask whoever holds `port` which workspace it is serving. Returns that
|
|
1716
|
-
* workspace, or null for every other outcome there is — a refused
|
|
1717
|
-
* connection, a non-200, a body that is not JSON, a payload with no usable
|
|
1718
|
-
* `workspace`, a body over the cap, or a holder that never answers across
|
|
1719
|
-
* two attempts.
|
|
1720
|
-
*
|
|
1721
|
-
* Null is deliberately one value for all of them: the caller's question is
|
|
1722
|
-
* "is this my own cockpit", and every way of failing to prove that is the
|
|
1723
|
-
* same answer — foreign. A holder that IS this workspace's cockpit answers
|
|
1724
|
-
* with the board payload it already serves, so no endpoint is added for
|
|
1725
|
-
* this and the handshake reaches nothing a browser could not. The one
|
|
1726
|
-
* consequence to know: a cockpit started from a build older than the identity handshake
|
|
1727
|
-
* serves a payload with no `workspace` at all, so it reads as foreign and a
|
|
1728
|
-
* launch steps over it rather than reusing it — once, until that process is
|
|
1729
|
-
* restarted.
|
|
1730
|
-
*
|
|
1731
|
-
* A bare timeout gets one retry rather than folding straight into
|
|
1732
|
-
* "foreign": nothing in a socket read distinguishes "nobody is there" from
|
|
1733
|
-
* "busy for that second", and a loaded box produces the second shape. Only a
|
|
1734
|
-
* second silent window calls it, and says so on stderr distinctly from a
|
|
1735
|
-
* confirmed non-match — a shrug is not a verdict.
|
|
1736
|
-
*/
|
|
1737
|
-
export function probeCockpitWorkspace(port, timeoutMs = PROBE_TIMEOUT_MS) {
|
|
1738
|
-
return new Promise((resolve) => {
|
|
1739
|
-
let attempts = 0;
|
|
1740
|
-
const probeOnce = () => {
|
|
1741
|
-
let settled = false;
|
|
1742
|
-
const timer = setTimeout(() => {
|
|
1743
|
-
settled = true;
|
|
1744
|
-
req.destroy();
|
|
1745
|
-
attempts += 1;
|
|
1746
|
-
if (attempts < 2) { probeOnce(); return; }
|
|
1747
|
-
console.error(`${NAME}: no answer from port ${port} within ${timeoutMs * 2}ms — cannot confirm it is this workspace's cockpit`);
|
|
1748
|
-
resolve(null);
|
|
1749
|
-
}, timeoutMs);
|
|
1750
|
-
function finish(workspace) {
|
|
1751
|
-
if (settled) return;
|
|
1752
|
-
settled = true;
|
|
1753
|
-
clearTimeout(timer);
|
|
1754
|
-
// Destroy rather than let it drain: an unread body, or a holder
|
|
1755
|
-
// still writing one, would otherwise keep this socket — and the
|
|
1756
|
-
// launch — alive well past the answer.
|
|
1757
|
-
req.destroy();
|
|
1758
|
-
resolve(workspace);
|
|
1759
|
-
}
|
|
1760
|
-
const req = httpRequest({ host: COCKPIT_HOST, port, path: "/board.json", method: "GET" }, (res) => {
|
|
1761
|
-
if (res.statusCode !== 200) { finish(null); return; }
|
|
1762
|
-
let body = "";
|
|
1763
|
-
res.setEncoding("utf8");
|
|
1764
|
-
res.on("data", (d) => { body += d; if (body.length > PROBE_BODY_CAP) finish(null); });
|
|
1765
|
-
res.on("end", () => {
|
|
1766
|
-
let w;
|
|
1767
|
-
try { w = JSON.parse(body)?.workspace; } catch { finish(null); return; }
|
|
1768
|
-
// Exactly the construction side's rule, because it is literally
|
|
1769
|
-
// the same predicate: a non-string, or the empty string,
|
|
1770
|
-
// is no identity. `=== ours` would be false for the first anyway,
|
|
1771
|
-
// but an empty string could match an empty workspace and there
|
|
1772
|
-
// must be no such thing.
|
|
1773
|
-
finish(isWorkspaceId(w) ? w : null);
|
|
1774
|
-
});
|
|
1775
|
-
});
|
|
1776
|
-
req.on("error", () => finish(null));
|
|
1777
|
-
req.end();
|
|
1778
|
-
};
|
|
1779
|
-
probeOnce();
|
|
1780
|
-
});
|
|
1781
|
-
}
|
|
1782
|
-
|
|
1783
|
-
export async function serve({ port: portGiven, interval, open, tick }) {
|
|
1784
|
-
// Both the served state directory and the port come from
|
|
1785
|
-
// resolveCockpitInstance() now, rather than a cwd-relative `.fleet` and a
|
|
1786
|
-
// constant 8123. That is what lets two workspaces run two boards at once
|
|
1787
|
-
// without either writing into the other's state directory, and it ties the
|
|
1788
|
-
// board to the same workspace the ledger resolves itself against.
|
|
1789
|
-
//
|
|
1790
|
-
// A GIVEN-but-invalid --port is refused outright in main() and never
|
|
1791
|
-
// reaches here; an ABSENT one arrives as `portGiven` null, which is how the
|
|
1792
|
-
// seam is told to derive rather than obey.
|
|
1793
|
-
//
|
|
1794
|
-
// A bind failure no longer means one thing, so the two kinds of port part
|
|
1795
|
-
// company here. One this script DERIVED is negotiable: the loop below
|
|
1796
|
-
// handshakes with whoever holds it and steps over a stranger. One
|
|
1797
|
-
// the caller CHOSE is not — the refusal names that port bare and dies,
|
|
1798
|
-
// because scanning off it would serve the board somewhere the operator did
|
|
1799
|
-
// not ask for and reusing it would hand them someone else's. What tells
|
|
1800
|
-
// them apart is `instance.derived` and not truthiness on `portGiven`: an
|
|
1801
|
-
// explicit `--port 0` is falsy (a legal ephemeral bind), so the old
|
|
1802
|
-
// spelling gave it the derived port's treatment, and nothing pinned that.
|
|
1803
|
-
const instance = resolveCockpitInstance({ cwd: process.cwd(), ...cockpitWorkspace(process.cwd()), port: portGiven });
|
|
1804
|
-
const stateDir = instance.stateDir;
|
|
1805
|
-
const jsonPath = join(stateDir, "board.json");
|
|
1806
|
-
// A held port used to mean three different things this loop could
|
|
1807
|
-
// only tell apart by binding first and probing whichever candidate
|
|
1808
|
-
// happened to refuse — so a live cockpit that landed past a squatter
|
|
1809
|
-
// which has since departed was invisible the moment that squatter's port
|
|
1810
|
-
// freed (this process would just bind it directly), and a workspace with
|
|
1811
|
-
// no identity established (the degrade arm) still scanned past a held
|
|
1812
|
-
// port with nothing a handshake could ever match, reopening the
|
|
1813
|
-
// dual-cockpit hazard.
|
|
1814
|
-
//
|
|
1815
|
-
// Bind stays ahead of any handshake per candidate — only heldFailure()'s
|
|
1816
|
-
// bare connect precedes it: that is what lets two launches racing at start
|
|
1817
|
-
// settle on one winner quickly, the winner's identity published (below)
|
|
1818
|
-
// before it can block inside its own first tick.
|
|
1819
|
-
// But a successful bind is not the end of the story — once this process
|
|
1820
|
-
// holds a candidate, the REST of the window still gets checked for a
|
|
1821
|
-
// live cockpit that landed further along, exactly the shape a departed
|
|
1822
|
-
// squatter leaves behind, and only when nothing there matches does this
|
|
1823
|
-
// process keep what it bound. A held candidate is probed the same way,
|
|
1824
|
-
// one at a time as the loop reaches it. Neither check runs at all when
|
|
1825
|
-
// this workspace has no identity to match on: an explicit --port
|
|
1826
|
-
// (`!instance.derived`) and the degrade arm (no `isWorkspaceId` identity)
|
|
1827
|
-
// never had a handshake to reach in the first place, so a held port for
|
|
1828
|
-
// either stays fatal, exactly as it was before the handshake existed.
|
|
1829
|
-
const candidates = cockpitPorts(instance);
|
|
1830
|
-
const scannable = instance.derived && isWorkspaceId(instance.workspace);
|
|
1831
|
-
let server = null;
|
|
1832
|
-
for (let i = 0; i < candidates.length; i++) {
|
|
1833
|
-
const candidate = candidates[i];
|
|
1834
|
-
const attempt = createBoardServer(stateDir);
|
|
1835
|
-
// --port 0 asks the kernel for a port nobody holds; there is nothing to dial.
|
|
1836
|
-
const failure = (candidate === 0 ? null : await heldFailure(candidate)) ?? await bindFailure(attempt, candidate);
|
|
1837
|
-
if (!failure) {
|
|
1838
|
-
const rest = scannable ? candidates.slice(i + 1) : [];
|
|
1839
|
-
const holders = await Promise.all(rest.map((p) => probeCockpitWorkspace(p)));
|
|
1840
|
-
const matchAt = holders.indexOf(instance.workspace);
|
|
1841
|
-
if (matchAt === -1) { server = attempt; break; }
|
|
1842
|
-
attempt.close();
|
|
1843
|
-
const url = `http://${COCKPIT_HOST}:${rest[matchAt]}/`;
|
|
1844
|
-
console.error(`${NAME}: cockpit already running for this workspace on ${url}`);
|
|
1845
|
-
// Nothing is opened here, --open or not. This cockpit was
|
|
1846
|
-
// already running when this launch arrived, so its tab was the business
|
|
1847
|
-
// of the launch that started it; run-team's phase 0 relaunches on every
|
|
1848
|
-
// re-shortlist, and opening here stacked one more tab for the same
|
|
1849
|
-
// board each pass. Only a launch that binds a port and starts the
|
|
1850
|
-
// server opens one, below.
|
|
1851
|
-
//
|
|
1852
|
-
// Exit 0 — and explicitly, not by returning: a backgrounded launch
|
|
1853
|
-
// reports nothing but its exit code, and a handle left behind by the
|
|
1854
|
-
// probe would otherwise hang this process forever while it holds no
|
|
1855
|
-
// port at all.
|
|
1856
|
-
process.exit(0);
|
|
1857
|
-
}
|
|
1858
|
-
// Only a port that is TAKEN is a candidate for any of the below. EACCES
|
|
1859
|
-
// on a privileged port, EADDRNOTAVAIL on an unusable address, a pre-bind
|
|
1860
|
-
// connect that fails with anything but ECONNREFUSED: those are faults of
|
|
1861
|
-
// their own, and scanning past them would bury each one under an
|
|
1862
|
-
// exhausted-range message at the end that names the wrong problem. A bind
|
|
1863
|
-
// error dies with its own text; a held-check error dies naming the check,
|
|
1864
|
-
// which a raw connect message does not, and does so whatever code the
|
|
1865
|
-
// connect error carries: only a bare EADDRINUSE from the bind itself, or
|
|
1866
|
-
// the held signal heldFailure() resolves, means the port is taken.
|
|
1867
|
-
if (failure.heldCheck) die(`cannot check whether port ${candidate} is held: ${failure.message}`);
|
|
1868
|
-
if (failure.code !== "EADDRINUSE") die(failure.message);
|
|
1869
|
-
if (!scannable) die(`port ${candidate} in use — pass --port <n>`);
|
|
1870
|
-
const holder = await probeCockpitWorkspace(candidate);
|
|
1871
|
-
if (holder === instance.workspace) {
|
|
1872
|
-
const url = `http://${COCKPIT_HOST}:${candidate}/`;
|
|
1873
|
-
console.error(`${NAME}: cockpit already running for this workspace on ${url}`);
|
|
1874
|
-
// Already running, so nothing opens — the same rule as the arm above.
|
|
1875
|
-
process.exit(0);
|
|
1876
|
-
}
|
|
1877
|
-
console.error(`${NAME}: port ${candidate} is held by something that is not this workspace's cockpit — trying the next port`);
|
|
1878
|
-
}
|
|
1879
|
-
if (!server) die(`no free port for this workspace — tried ${candidates.join(", ")}; pass --port <n> to choose one`);
|
|
1880
|
-
|
|
1881
|
-
// Only now — with a bind this process is actually keeping — does it need
|
|
1882
|
-
// the state directory and board.html. Never for a launch either check
|
|
1883
|
-
// above already turned into a no-op: this shares the state directory
|
|
1884
|
-
// with whatever this workspace's live cockpit is doing, and touching it
|
|
1885
|
-
// before reuse was settled was a defect in the reuse
|
|
1886
|
-
// arm (mkdirSync/copyFileSync used to run before the candidate loop).
|
|
1887
|
-
mkdirSync(stateDir, { recursive: true });
|
|
1888
|
-
try { copyFileSync(join(SCRIPT_DIR, "board.html"), join(stateDir, "board.html")); }
|
|
1889
|
-
catch (e) { die(`cannot stage board.html into ${stateDir}: ${e.message}`); }
|
|
1890
|
-
|
|
1891
|
-
// A bind failure is handled above, one candidate at a time; this handler
|
|
1892
|
-
// owns everything a LISTENING server can still emit. Without it an 'error'
|
|
1893
|
-
// event after the bind has no listener at all and node rethrows it as an
|
|
1894
|
-
// uncaught exception — the one regression the loop above would otherwise
|
|
1895
|
-
// introduce by taking the old, always-attached handler away with it.
|
|
1896
|
-
server.on("error", (e) => die(e.message));
|
|
1897
|
-
|
|
1898
|
-
// Everything below is reached only by a process that HOLDS a port, which is
|
|
1899
|
-
// what the listen-callback gating bought and what this loop has to keep
|
|
1900
|
-
// paying for by position: tick() writes into stateDir, SHARED by every cwd
|
|
1901
|
-
// that resolves to this workspace, so a process that never binds must not
|
|
1902
|
-
// reach it. A second cockpit that ticked first would overwrite the live
|
|
1903
|
-
// one's board.json and reset every ticket's dwell clock.
|
|
1904
|
-
//
|
|
1905
|
-
// Announce the port we GOT, not the one we asked for. They differ for the
|
|
1906
|
-
// one value `--port 0` newly permits: listen(0) binds an ephemeral port, so
|
|
1907
|
-
// echoing the request prints — and --opens — http://127.0.0.1:0, which
|
|
1908
|
-
// reaches nothing while the board sits on a port nobody was told.
|
|
1909
|
-
// address() is only populated once listening, hence only here.
|
|
1910
|
-
const bound = server.address().port;
|
|
1911
|
-
console.error(`${NAME}: cockpit on http://${COCKPIT_HOST}:${bound} (interval ${interval}s)`);
|
|
1912
|
-
|
|
1913
|
-
// Publish identity the instant this port is ours — before the
|
|
1914
|
-
// first tick, which is the one that can be slow (its gather shells out to
|
|
1915
|
-
// gh and ledger.mjs). A sibling launch races this one by sending its
|
|
1916
|
-
// probe as soon as ITS bind attempt refuses, which can be well before
|
|
1917
|
-
// this process's first tick ever returns; the answer that probe needs
|
|
1918
|
-
// has to already be on disk, not waiting on a compute this process has
|
|
1919
|
-
// not started yet.
|
|
1920
|
-
// `port` rides along. This stub is a board payload like any other
|
|
1921
|
-
// for as long as the first tick takes, and a reader that finds it —
|
|
1922
|
-
// the operator, a script, the page — gets the same two identity fields
|
|
1923
|
-
// from it that every later tick writes. The handshake above still reads
|
|
1924
|
-
// only `workspace`.
|
|
1925
|
-
writeFileSync(`${jsonPath}.tmp`, JSON.stringify({ workspace: instance.workspace, port: bound }));
|
|
1926
|
-
renameSync(`${jsonPath}.tmp`, jsonPath);
|
|
1927
|
-
// Yield once so a connection already arriving — that same sibling's probe —
|
|
1928
|
-
// gets a chance to read the identity just written before this process starts
|
|
1929
|
-
// the first tick. The tick no longer blocks the loop, but its gather
|
|
1930
|
-
// still opens with a synchronous prev-board read before its first await, and
|
|
1931
|
-
// a turn of the loop costs nothing.
|
|
1932
|
-
await new Promise((resolve) => setImmediate(resolve));
|
|
1933
|
-
|
|
1934
|
-
// Deliberately not awaited: the first tick is the slow one, and everything
|
|
1935
|
-
// below it — the timer, and the two signal handlers that are the only way
|
|
1936
|
-
// this process is ever asked to stop — must be in place before it returns,
|
|
1937
|
-
// not after. Nothing here rejects; tick() catches its own faults and the
|
|
1938
|
-
// `ticking` flag it sets is cleared in a finally (see boardTick()).
|
|
1939
|
-
const tickArgs = { served: bound, stateDir, jsonPath, workspace: instance.workspace };
|
|
1940
|
-
tick(tickArgs);
|
|
1941
|
-
const timer = setInterval(() => tick(tickArgs), interval * 1000);
|
|
1942
|
-
|
|
1943
|
-
const stop = () => {
|
|
1944
|
-
clearInterval(timer);
|
|
1945
|
-
server.close(() => process.exit(0));
|
|
1946
|
-
server.closeAllConnections?.(); // drop keep-alive sockets so close() resolves promptly
|
|
1947
|
-
setTimeout(() => process.exit(0), 1000).unref(); // hard backstop if a socket somehow lingers
|
|
1948
|
-
};
|
|
1949
|
-
process.on("SIGINT", stop);
|
|
1950
|
-
process.on("SIGTERM", stop);
|
|
1951
|
-
|
|
1952
|
-
// --open, from this launch alone: it is the one that bound a port and
|
|
1953
|
-
// started a server, and the reuse arms above open nothing. Only
|
|
1954
|
-
// once the identity is on disk — a launcher running BEFORE that write put a
|
|
1955
|
-
// child squarely inside the window the identity stub exists to keep empty, where a
|
|
1956
|
-
// racing launch's probe finds no payload and reads this port as foreign —
|
|
1957
|
-
// and only after the tick, the timer and both signal handlers are in
|
|
1958
|
-
// place: `xdg-open` can run the browser it starts in the foreground and
|
|
1959
|
-
// return only when that browser exits, so a launcher awaited any earlier
|
|
1960
|
-
// could hold the first tick back for the whole session. openBrowser()
|
|
1961
|
-
// never throws; a launcher that is missing or fails is one warning line.
|
|
1962
|
-
if (open) await openBrowser(`http://${COCKPIT_HOST}:${bound}/`);
|
|
1963
|
-
await new Promise(() => {}); // run until signalled
|
|
1964
|
-
}
|
|
1965
|
-
|
|
1966
396
|
// An internal FAULT is not a refusal, and until this they were one
|
|
1967
397
|
// line. Every guard in this file refuses through die(), which writes its own
|
|
1968
398
|
// line and calls process.exit(2) itself (arg.mjs) rather than throwing, so
|