@feigi/fleet-ctl 3.39.4 → 3.39.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,611 @@
1
+ // The cockpit's HTTP half: everything downstream of a built model. It owns the
2
+ // listener (createBoardServer), the cockpit instance's identity — one workspace,
3
+ // one derived port, one state directory — the port scan and the cross-workspace
4
+ // handshake that lets a second launch reuse a live cockpit, the `--open`
5
+ // browser launcher, and serve() itself, which binds, publishes the identity and
6
+ // hands the tick to a callback it is given.
7
+ //
8
+ // serve() does not read the ledger, does not call `gh` or gather(), and does
9
+ // not import compute-board.mjs: what a tick computes is its caller's business.
10
+
11
+ import { writeFileSync, renameSync, existsSync, readFileSync, mkdirSync, copyFileSync } from "node:fs";
12
+ import { NAME, die, warnOnce, execRead } from "./board-common.mjs";
13
+ import { fleetFile, FleetDirUnresolvable } from "./fleet-dir.mjs";
14
+ import { fileURLToPath } from "node:url";
15
+ import { dirname, join } from "node:path";
16
+ import { createServer, request as httpRequest } from "node:http";
17
+ import { connect } from "node:net";
18
+
19
+ const SCRIPT_DIR = dirname(fileURLToPath(import.meta.url));
20
+
21
+ // `serve --open`'s browser launcher, one per supported platform.
22
+ // macOS ships `open`. Linux has no single program, but `xdg-open` is
23
+ // the freedesktop one every mainstream desktop provides; WSL usually lacks it
24
+ // and has `wslview` (wslu) instead, which hands the URL to the Windows default
25
+ // browser. Only a launcher that is NOT ON PATH passes the URL down the list:
26
+ // one that ran and failed is the right program meeting a real fault, and the
27
+ // next one would not fix that.
28
+ //
29
+ // Never throws and never exits. A tab that did not open is a warning naming
30
+ // the URL — the cockpit is up and serving either way, and the operator can
31
+ // open it by hand — so a missing launcher changes nothing about the exit code.
32
+ async function openBrowser(url) {
33
+ const tried = [];
34
+ for (const cmd of process.platform === "darwin" ? ["open"] : ["xdg-open", "wslview"]) {
35
+ const r = await execRead(cmd, [url]);
36
+ if (!r.error) return;
37
+ if (r.code === "ENOENT") { tried.push(`${cmd} not found`); continue; }
38
+ tried.push(r.status != null ? `${cmd} exited ${r.status}` : `${cmd} failed: ${r.error.message.split("\n")[0]}`);
39
+ break;
40
+ }
41
+ console.error(`${NAME}: WARNING --open could not open a browser (${tried.join(", ")}) — the cockpit is on ${url}`);
42
+ }
43
+
44
+ // The names a browser on this machine can legitimately put in `Host` to reach
45
+ // a loopback-only cockpit. DNS rebinding points an attacker-chosen name at
46
+ // 127.0.0.1, and the browser then sends THAT name as `Host`, so the hostname —
47
+ // not the peer address, which is loopback either way — is what separates the
48
+ // operator's own tab from a rebound page. The port is deliberately not
49
+ // compared: an `ssh -L` forward reaches the cockpit under a different local
50
+ // port, and the port tells a rebound page nothing it could not scan for.
51
+ const COCKPIT_HOSTNAMES = new Set(["127.0.0.1", "localhost", "[::1]"]);
52
+ // A bracketed IPv6 literal or a bare name, then an optional `:port` — anything
53
+ // else (userinfo, a second colon outside brackets, a path) is not a Host value.
54
+ const HOST_HEADER = /^(\[[^\]]+\]|[^:[\]]+)(?::\d*)?$/;
55
+ function isCockpitHost(host) {
56
+ const m = HOST_HEADER.exec(host ?? "");
57
+ return m !== null && COCKPIT_HOSTNAMES.has(m[1].toLowerCase());
58
+ }
59
+
60
+ // A refused Host is the operator's only clue to why the tab shows a 403 — an
61
+ // unlisted spelling of loopback, or a rebound page probing the port — so the
62
+ // refusal goes to stderr, once per distinct Host. The value is the client's,
63
+ // so it is rendered as a JSON string (quotes, backslashes and C0 controls
64
+ // escaped), with DEL, the C1 controls and the U+2028/U+2029 line separators,
65
+ // which JSON leaves bare, escaped too, and cut to a bounded length: it cannot
66
+ // split or forge a log line. A rebound page can
67
+ // send unlimited distinct Hosts, so each server logs at most
68
+ // REFUSED_HOST_LOG_CAP of them, then one notice, then nothing new.
69
+ const REFUSED_HOST_LOG_CAP = 16;
70
+ const REFUSED_HOST_SHOWN = 100;
71
+ const COCKPIT_HOST_LIST = [...COCKPIT_HOSTNAMES].join(", ");
72
+ export function renderRefusedHost(host) {
73
+ if (host === undefined) return "a request with no Host header";
74
+ const json = JSON.stringify(host.slice(0, REFUSED_HOST_SHOWN))
75
+ .replace(/[\u007f-\u009f\u2028\u2029]/g, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, "0")}`);
76
+ return `Host ${json}${host.length > REFUSED_HOST_SHOWN ? `… (${host.length} chars)` : ""}`;
77
+ }
78
+
79
+ export function createBoardServer(dir) {
80
+ let refusedHostsLogged = 0;
81
+ function logRefusedHost(host) {
82
+ if (refusedHostsLogged > REFUSED_HOST_LOG_CAP) return;
83
+ if (refusedHostsLogged === REFUSED_HOST_LOG_CAP) {
84
+ refusedHostsLogged++;
85
+ console.error(`${NAME}: ${REFUSED_HOST_LOG_CAP} distinct Hosts refused; further refused Hosts are not logged`);
86
+ return;
87
+ }
88
+ const shown = renderRefusedHost(host);
89
+ if (warnOnce("host-refused", shown, `refused ${shown} — not a loopback name (${COCKPIT_HOST_LIST}); answered 403`)) refusedHostsLogged++;
90
+ }
91
+ return createServer((req, res) => {
92
+ // Checked before routing, so an unknown path on a foreign Host is as
93
+ // opaque as a known one: 403, never a 404 that tells a rebound page which
94
+ // paths exist.
95
+ if (!isCockpitHost(req.headers.host)) {
96
+ logRefusedHost(req.headers.host);
97
+ res.writeHead(403); res.end("forbidden"); return;
98
+ }
99
+ const url = (req.url || "/").split("?")[0];
100
+ const path = url === "/" || url === "/board.html" ? join(dir, "board.html")
101
+ : url === "/board.json" ? join(dir, "board.json") : null;
102
+ if (!path || !existsSync(path)) { res.writeHead(404); res.end("not found"); return; }
103
+ const type = path.endsWith(".json") ? "application/json" : "text/html; charset=utf-8";
104
+ res.writeHead(200, { "content-type": type, "cache-control": "no-store" });
105
+ res.end(readFileSync(path));
106
+ });
107
+ }
108
+
109
+ // A cockpit instance is identified by its WORKSPACE — the directory holding
110
+ // the shared git dir — not by the process's cwd and not by the machine. Two
111
+ // workspaces therefore get two boards on two ports, both live and neither
112
+ // aware of the other, and one workspace derives the SAME port on every run,
113
+ // so that URL survives runs, reboots and node versions.
114
+ //
115
+ // BASE is the port this file hardcoded before any of this existed;
116
+ // resolveCockpitInstance()'s degrade arm, with no workspace to hash, still
117
+ // defaults to it. SPAN = 512 was kept deliberately: a
118
+ // collision between two DIFFERENT workspaces is not priced into the width but
119
+ // carried by serve()'s launch loop, which probes whoever holds the derived
120
+ // port, reuses that cockpit when it is this workspace's own, and otherwise
121
+ // scans on through cockpitPorts()'s PORT_ATTEMPTS candidates. The accepted
122
+ // cost is launch order: whichever colliding workspace starts second binds a
123
+ // port other than the one its hash derives.
124
+ const PORT_BASE = 8123;
125
+ const PORT_SPAN = 512;
126
+
127
+ // FNV-1a, 32-bit, written out inline. Three properties this needs that no
128
+ // crypto digest and no Math.random has together: stable across node versions
129
+ // and across machines (nothing in here reads the engine, the host or the
130
+ // clock), dependency-free, and cheap enough to run on every start. Math.imul
131
+ // is the whole reason it is spelled this way — a plain `h * 0x01000193`
132
+ // leaves exact integer range after two rounds and silently stops being FNV.
133
+ // `>>> 0` is load-bearing, not decoration: without it `h` stays SIGNED, so
134
+ // `h % PORT_SPAN` can come back negative and the derived port lands BELOW
135
+ // base, outside the window this function's own contract promises.
136
+ function workspaceHash(key) {
137
+ let h = 0x811c9dc5;
138
+ for (let i = 0; i < key.length; i++) {
139
+ h ^= key.charCodeAt(i);
140
+ h = Math.imul(h, 0x01000193);
141
+ }
142
+ return h >>> 0;
143
+ }
144
+
145
+ // The one spelling of "this value is a workspace identity", read by every
146
+ // side of the cockpit handshake. The invariant is that null and the
147
+ // empty string are never an identity to match on, and it used to be carried
148
+ // by two independently-written guards — resolveCockpitInstance()'s
149
+ // `workspace === null` below and probeCockpitWorkspace()'s
150
+ // `typeof w === "string" && w !== ""` — correct only because both were
151
+ // written consistently, not because anything stopped one from moving without
152
+ // the other. What a drift buys is silent and cross-workspace: let the
153
+ // construction side call the empty string an identity while the parsing side
154
+ // still accepts it, and two cockpits in two different workspaces, neither
155
+ // with an identity established, match each other's board and one reuses the
156
+ // other — a hand-off nothing else in this file would refuse, since the
157
+ // degrade arm's "no identity to match on" is the only thing keeping a held
158
+ // port fatal there.
159
+ //
160
+ // A non-empty string, and nothing more: no trim(). A wholly-whitespace
161
+ // answer to `--git-common-dir` is already refused one layer down, by
162
+ // git-env.mjs's workspaceDirFromGitCommonDir() inside fleet-dir.mjs's
163
+ // fleetFile(), so no identity reaching either call site can be whitespace —
164
+ // the construction side gets the workspace fleetFile() resolved and the
165
+ // parsing side gets a payload some process wrote from it. A second whitespace
166
+ // rule here would be one more guard of exactly the kind this predicate exists
167
+ // to stop writing.
168
+ //
169
+ // Not exported, for workspaceHash()'s reason above it: nothing outside this
170
+ // file asks the question, and every widening of it is already pinned from
171
+ // outside through the two call sites — mutation-verified for this extraction
172
+ // and each mutant was killed by a test that already existed in the board tests:
173
+ // `v != null && v !== ""` by the probe's not-a-string row, `typeof v ===
174
+ // "string"` by its empty-workspace row, a degrade arm publishing `""` by
175
+ // resolveCockpitInstance's three degrade rows, and dropping it from
176
+ // serve()'s `scannable` by the CLI's held-port-on-the-degrade-arm row. So no
177
+ // test is added here: sharing the predicate is what makes the construction
178
+ // side's rows constrain the parsing side and back, which is a STRONGER suite
179
+ // than before, not one with a hole a new row could fill.
180
+ function isWorkspaceId(v) {
181
+ return typeof v === "string" && v !== "";
182
+ }
183
+
184
+ /**
185
+ * The cockpit's instance seam, and the only one. Given a cwd, the workspace
186
+ * this cockpit belongs to — INJECTED, already resolved, or null when it could
187
+ * not be — and an explicitly requested port if there was one, decide which
188
+ * state directory this cockpit serves and which port it binds.
189
+ *
190
+ * Pure: it listens to nothing, spawns nothing, reads nothing and writes
191
+ * nothing, so every branch below is reachable from a test with no git repo
192
+ * and no socket.
193
+ *
194
+ * The workspace comes from fleet-dir.mjs's fleetFile(), the same locator the
195
+ * run's ledger and heartbeat are resolved with — so the board, the ledger and
196
+ * the heartbeat cannot disagree about which run they belong to — asked with
197
+ * the `canonicalise` opt-in only this caller takes: a symlinked route to one
198
+ * workspace must derive that workspace's port instead of a second, private
199
+ * one.
200
+ *
201
+ * `why` is fleetFile()'s message when it could not answer — it names what
202
+ * failed, and the degrade warning below carries it, as the ledger's does.
203
+ * Absent, the warning names the failure without a reason.
204
+ */
205
+ export function resolveCockpitInstance({ cwd = process.cwd(), workspace, why, port } = {}) {
206
+ // `port != null`, never truthiness: --port 0 is a real request (an
207
+ // ephemeral bind) and reading it as "absent" would derive a port
208
+ // straight over the top of one the caller explicitly asked for.
209
+ const forced = port != null;
210
+ // Asked as `!isWorkspaceId(...)` rather than `=== null`: the question this
211
+ // arm answers is "was an identity established", and what counts as one is
212
+ // the predicate above — the same one the probe parses with, so the two
213
+ // sides cannot answer it differently.
214
+ if (!isWorkspaceId(workspace)) {
215
+ // Degrade, never die: a non-git or otherwise unusual checkout still gets
216
+ // a board. The wording is the ledger's rather than a second dialect for
217
+ // the same failure, trailing parenthetical included — that parenthetical
218
+ // names what is degraded HERE, which is not what is degraded there.
219
+ 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)`);
220
+ // Absolute, like the resolved arm, but anchored on the cwd — which is
221
+ // what "cwd-relative" resolves to and what this script's fs calls did
222
+ // with the bare `.fleet` they used before. No workspace was established,
223
+ // so there is no key to hash and the port is BASE: today's default,
224
+ // unchanged, for the case that used to be the only case.
225
+ return { stateDir: join(cwd, ".fleet"), workspace: null, port: forced ? port : PORT_BASE, derived: !forced };
226
+ }
227
+ return {
228
+ stateDir: join(workspace, ".fleet"),
229
+ workspace,
230
+ port: forced ? port : PORT_BASE + (workspaceHash(workspace) % PORT_SPAN),
231
+ derived: !forced,
232
+ };
233
+ }
234
+
235
+ // The impure half, deliberately outside the seam above: the `{ workspace }`
236
+ // fleetFile() resolves from `cwd`, or `{ workspace: null, why }` when it
237
+ // cannot — which takes the degrade arm above, so a non-git checkout, a stalled
238
+ // git and git missing entirely all still get a board, with the reason on its
239
+ // warning. Spread into resolveCockpitInstance()'s arguments.
240
+ export function cockpitWorkspace(cwd) {
241
+ try {
242
+ return { workspace: dirname(fleetFile(null, { cwd, canonicalise: true })) };
243
+ } catch (e) {
244
+ if (!(e instanceof FleetDirUnresolvable)) throw e;
245
+ return { workspace: null, why: e.message };
246
+ }
247
+ }
248
+
249
+ // How many ports one launch may try before it gives up, and the whole cost
250
+ // of the scan: the worst case is ATTEMPTS × (a bind plus a probe), so a
251
+ // workspace whose derived port sits in a crowded corner of the range still
252
+ // fails in seconds rather than walking all 512. It also bounds how far a
253
+ // cockpit can land from the stable URL its workspace derives — a board a
254
+ // handful of ports from where it is bookmarked is still findable by hand,
255
+ // while one hundreds of ports away (where an unbounded scan could leave it)
256
+ // typically is not.
257
+ const PORT_ATTEMPTS = 8;
258
+
259
+ /**
260
+ * The ports one launch may try, in order, for a resolved instance — the
261
+ * second half of the instance seam and pure like the first, so every row
262
+ * below is reachable with no socket.
263
+ *
264
+ * An EXPLICIT port collapses to a single candidate: the operator named a
265
+ * port, so there is nothing to scan and (guarded separately in serve()) no
266
+ * holder to handshake with.
267
+ *
268
+ * A DERIVED one starts at the derived port — the stable, bookmarkable one —
269
+ * and walks forward MODULO the span, never out of the window
270
+ * resolveCockpitInstance() promises. Without the wrap a workspace hashing to
271
+ * the top of the range would scan straight past 8634 into ports belonging to
272
+ * nothing in this scheme, and the range this exists to stay inside would be
273
+ * a range in name only.
274
+ */
275
+ export function cockpitPorts({ port, derived }) {
276
+ if (!derived) return [port];
277
+ const offset = port - PORT_BASE;
278
+ return Array.from({ length: PORT_ATTEMPTS }, (_, i) => PORT_BASE + ((offset + i) % PORT_SPAN));
279
+ }
280
+
281
+ // One bind attempt, as a value rather than as an event. Resolves with null
282
+ // on success and with the error otherwise — never rejects, because every
283
+ // caller has to READ the code (EADDRINUSE is negotiable, everything else is
284
+ // fatal) and a rejection would make that a try/catch around a control-flow
285
+ // decision. The listeners are removed on whichever side loses: a server that
286
+ // failed to bind is dropped, and one that bound gets serve()'s own long-
287
+ // lived error handler instead of this one-shot.
288
+ function bindFailure(server, port) {
289
+ return new Promise((resolve) => {
290
+ const onError = (e) => { server.removeListener("listening", onListening); resolve(e); };
291
+ const onListening = () => { server.removeListener("error", onError); resolve(null); };
292
+ server.once("error", onError);
293
+ server.once("listening", onListening);
294
+ server.listen(port, COCKPIT_HOST);
295
+ });
296
+ }
297
+
298
+ // Whether something already answers on COCKPIT_HOST:port, asked BEFORE the
299
+ // bind rather than read off it: a 127.0.0.1 bind does not reliably fail when
300
+ // the port is taken. On macOS/BSD, SO_REUSEADDR lets it succeed beside a
301
+ // listener that holds every interface — a dev server, or a cockpit started
302
+ // before the bind was narrowed to loopback — and the launch would then sit
303
+ // on that holder's 127.0.0.1 traffic instead of stepping over it or reusing
304
+ // it. Linux refuses that bind outright; this check gives both the same answer.
305
+ // Resolves in bindFailure()'s vocabulary so the loop reads one shape: null
306
+ // when the connection is refused (nothing holds the port), an EADDRINUSE
307
+ // error when it connects or times out, and any other error as itself,
308
+ // marked `heldCheck` — a fault of its own, like EACCES on a bind, which the
309
+ // loop reports as this check's rather than the bind's, whatever code the
310
+ // error carries. A timeout counts as held because a live holder whose accept
311
+ // backlog is full drops the SYN rather than refusing it. The window between
312
+ // this check and the bind is a race the loop accepts, like its others.
313
+ function heldFailure(port) {
314
+ return new Promise((resolve) => {
315
+ const socket = connect({ host: COCKPIT_HOST, port });
316
+ const held = () => {
317
+ socket.destroy();
318
+ resolve(Object.assign(new Error(`port ${port} answers on ${COCKPIT_HOST}`), { code: "EADDRINUSE" }));
319
+ };
320
+ socket.setTimeout(PROBE_TIMEOUT_MS, held);
321
+ socket.once("connect", held);
322
+ socket.once("error", (e) => resolve(e.code === "ECONNREFUSED" ? null : Object.assign(e, { heldCheck: true })));
323
+ });
324
+ }
325
+
326
+ // ~1s per attempt, and the whole reason this is a probe and not a lockfile:
327
+ // a launch that cannot get an answer within a second must proceed, not
328
+ // wait. A holder that accepts the connection and then says nothing is the
329
+ // case that pays for this timer — nothing else in a socket read bounds it.
330
+ // One silent window does not settle the question, though: nothing in a socket
331
+ // read tells a port nobody holds from one whose holder was busy for that
332
+ // second, and a box under load, a process still between its bind and its
333
+ // identity write, or a dropped SYN all produce the second shape. The probe
334
+ // retries once before it will call a silent port foreign.
335
+ //
336
+ // Until the tick's reads became asynchronous the commonest producer of that shape was this cockpit itself —
337
+ // a same-workspace holder blocked inside its own synchronous gather() when
338
+ // the probe arrived, for the 4.72–4.91s a board took to build, which no
339
+ // number of retries at this timeout would have covered. That one is gone at
340
+ // the source: the tick's reads are asynchronous and the server answers
341
+ // throughout. Raising this timeout was
342
+ // ruled out as the fix for it — it would have to clear a gather(), which
343
+ // charges every launch past a stranger-held port that much per candidate.
344
+ const PROBE_TIMEOUT_MS = 1000;
345
+ // The one address a cockpit binds, and so the one address the probe and the
346
+ // pre-bind check dial: whatever holds a candidate where this launch would
347
+ // bind answers here. 127.0.0.1 rather than `localhost` keeps a resolver out
348
+ // of the launch path, and loopback alone keeps the board — a read-only
349
+ // mirror of the ledger — off every other machine on the network; remote
350
+ // viewing goes through an `ssh -L` tunnel. IPv4 only: `::1` is left unbound,
351
+ // which is why every URL printed below names 127.0.0.1 too. `localhost`
352
+ // resolves `::1` first, and on `::1` a browser can reach some other process
353
+ // that holds the same port.
354
+ const COCKPIT_HOST = "127.0.0.1";
355
+ // A holder is not necessarily a cockpit, and a second of localhost writes is
356
+ // a lot of memory to accept from one. The board payload for a real run is
357
+ // kilobytes; anything past this is not one, so it is refused as foreign
358
+ // rather than buffered.
359
+ const PROBE_BODY_CAP = 1024 * 1024;
360
+
361
+ /**
362
+ * Ask whoever holds `port` which workspace it is serving. Returns that
363
+ * workspace, or null for every other outcome there is — a refused
364
+ * connection, a non-200, a body that is not JSON, a payload with no usable
365
+ * `workspace`, a body over the cap, or a holder that never answers across
366
+ * two attempts.
367
+ *
368
+ * Null is deliberately one value for all of them: the caller's question is
369
+ * "is this my own cockpit", and every way of failing to prove that is the
370
+ * same answer — foreign. A holder that IS this workspace's cockpit answers
371
+ * with the board payload it already serves, so no endpoint is added for
372
+ * this and the handshake reaches nothing a browser could not. The one
373
+ * consequence to know: a cockpit started from a build older than the identity handshake
374
+ * serves a payload with no `workspace` at all, so it reads as foreign and a
375
+ * launch steps over it rather than reusing it — once, until that process is
376
+ * restarted.
377
+ *
378
+ * A bare timeout gets one retry rather than folding straight into
379
+ * "foreign": nothing in a socket read distinguishes "nobody is there" from
380
+ * "busy for that second", and a loaded box produces the second shape. Only a
381
+ * second silent window calls it, and says so on stderr distinctly from a
382
+ * confirmed non-match — a shrug is not a verdict.
383
+ */
384
+ export function probeCockpitWorkspace(port, timeoutMs = PROBE_TIMEOUT_MS) {
385
+ return new Promise((resolve) => {
386
+ let attempts = 0;
387
+ const probeOnce = () => {
388
+ let settled = false;
389
+ const timer = setTimeout(() => {
390
+ settled = true;
391
+ req.destroy();
392
+ attempts += 1;
393
+ if (attempts < 2) { probeOnce(); return; }
394
+ console.error(`${NAME}: no answer from port ${port} within ${timeoutMs * 2}ms — cannot confirm it is this workspace's cockpit`);
395
+ resolve(null);
396
+ }, timeoutMs);
397
+ function finish(workspace) {
398
+ if (settled) return;
399
+ settled = true;
400
+ clearTimeout(timer);
401
+ // Destroy rather than let it drain: an unread body, or a holder
402
+ // still writing one, would otherwise keep this socket — and the
403
+ // launch — alive well past the answer.
404
+ req.destroy();
405
+ resolve(workspace);
406
+ }
407
+ const req = httpRequest({ host: COCKPIT_HOST, port, path: "/board.json", method: "GET" }, (res) => {
408
+ if (res.statusCode !== 200) { finish(null); return; }
409
+ let body = "";
410
+ res.setEncoding("utf8");
411
+ res.on("data", (d) => { body += d; if (body.length > PROBE_BODY_CAP) finish(null); });
412
+ res.on("end", () => {
413
+ let w;
414
+ try { w = JSON.parse(body)?.workspace; } catch { finish(null); return; }
415
+ // Exactly the construction side's rule, because it is literally
416
+ // the same predicate: a non-string, or the empty string,
417
+ // is no identity. `=== ours` would be false for the first anyway,
418
+ // but an empty string could match an empty workspace and there
419
+ // must be no such thing.
420
+ finish(isWorkspaceId(w) ? w : null);
421
+ });
422
+ });
423
+ req.on("error", () => finish(null));
424
+ req.end();
425
+ };
426
+ probeOnce();
427
+ });
428
+ }
429
+
430
+ export async function serve({ port: portGiven, interval, open, tick }) {
431
+ // Both the served state directory and the port come from
432
+ // resolveCockpitInstance() now, rather than a cwd-relative `.fleet` and a
433
+ // constant 8123. That is what lets two workspaces run two boards at once
434
+ // without either writing into the other's state directory, and it ties the
435
+ // board to the same workspace the ledger resolves itself against.
436
+ //
437
+ // A GIVEN-but-invalid --port is refused outright in main() and never
438
+ // reaches here; an ABSENT one arrives as `portGiven` null, which is how the
439
+ // seam is told to derive rather than obey.
440
+ //
441
+ // A bind failure no longer means one thing, so the two kinds of port part
442
+ // company here. One this script DERIVED is negotiable: the loop below
443
+ // handshakes with whoever holds it and steps over a stranger. One
444
+ // the caller CHOSE is not — the refusal names that port bare and dies,
445
+ // because scanning off it would serve the board somewhere the operator did
446
+ // not ask for and reusing it would hand them someone else's. What tells
447
+ // them apart is `instance.derived` and not truthiness on `portGiven`: an
448
+ // explicit `--port 0` is falsy (a legal ephemeral bind), so the old
449
+ // spelling gave it the derived port's treatment, and nothing pinned that.
450
+ const instance = resolveCockpitInstance({ cwd: process.cwd(), ...cockpitWorkspace(process.cwd()), port: portGiven });
451
+ const stateDir = instance.stateDir;
452
+ const jsonPath = join(stateDir, "board.json");
453
+ // A held port used to mean three different things this loop could
454
+ // only tell apart by binding first and probing whichever candidate
455
+ // happened to refuse — so a live cockpit that landed past a squatter
456
+ // which has since departed was invisible the moment that squatter's port
457
+ // freed (this process would just bind it directly), and a workspace with
458
+ // no identity established (the degrade arm) still scanned past a held
459
+ // port with nothing a handshake could ever match, reopening the
460
+ // dual-cockpit hazard.
461
+ //
462
+ // Bind stays ahead of any handshake per candidate — only heldFailure()'s
463
+ // bare connect precedes it: that is what lets two launches racing at start
464
+ // settle on one winner quickly, the winner's identity published (below)
465
+ // before it can block inside its own first tick.
466
+ // But a successful bind is not the end of the story — once this process
467
+ // holds a candidate, the REST of the window still gets checked for a
468
+ // live cockpit that landed further along, exactly the shape a departed
469
+ // squatter leaves behind, and only when nothing there matches does this
470
+ // process keep what it bound. A held candidate is probed the same way,
471
+ // one at a time as the loop reaches it. Neither check runs at all when
472
+ // this workspace has no identity to match on: an explicit --port
473
+ // (`!instance.derived`) and the degrade arm (no `isWorkspaceId` identity)
474
+ // never had a handshake to reach in the first place, so a held port for
475
+ // either stays fatal, exactly as it was before the handshake existed.
476
+ const candidates = cockpitPorts(instance);
477
+ const scannable = instance.derived && isWorkspaceId(instance.workspace);
478
+ let server = null;
479
+ for (let i = 0; i < candidates.length; i++) {
480
+ const candidate = candidates[i];
481
+ const attempt = createBoardServer(stateDir);
482
+ // --port 0 asks the kernel for a port nobody holds; there is nothing to dial.
483
+ const failure = (candidate === 0 ? null : await heldFailure(candidate)) ?? await bindFailure(attempt, candidate);
484
+ if (!failure) {
485
+ const rest = scannable ? candidates.slice(i + 1) : [];
486
+ const holders = await Promise.all(rest.map((p) => probeCockpitWorkspace(p)));
487
+ const matchAt = holders.indexOf(instance.workspace);
488
+ if (matchAt === -1) { server = attempt; break; }
489
+ attempt.close();
490
+ const url = `http://${COCKPIT_HOST}:${rest[matchAt]}/`;
491
+ console.error(`${NAME}: cockpit already running for this workspace on ${url}`);
492
+ // Nothing is opened here, --open or not. This cockpit was
493
+ // already running when this launch arrived, so its tab was the business
494
+ // of the launch that started it; run-team's phase 0 relaunches on every
495
+ // re-shortlist, and opening here stacked one more tab for the same
496
+ // board each pass. Only a launch that binds a port and starts the
497
+ // server opens one, below.
498
+ //
499
+ // Exit 0 — and explicitly, not by returning: a backgrounded launch
500
+ // reports nothing but its exit code, and a handle left behind by the
501
+ // probe would otherwise hang this process forever while it holds no
502
+ // port at all.
503
+ process.exit(0);
504
+ }
505
+ // Only a port that is TAKEN is a candidate for any of the below. EACCES
506
+ // on a privileged port, EADDRNOTAVAIL on an unusable address, a pre-bind
507
+ // connect that fails with anything but ECONNREFUSED: those are faults of
508
+ // their own, and scanning past them would bury each one under an
509
+ // exhausted-range message at the end that names the wrong problem. A bind
510
+ // error dies with its own text; a held-check error dies naming the check,
511
+ // which a raw connect message does not, and does so whatever code the
512
+ // connect error carries: only a bare EADDRINUSE from the bind itself, or
513
+ // the held signal heldFailure() resolves, means the port is taken.
514
+ if (failure.heldCheck) die(`cannot check whether port ${candidate} is held: ${failure.message}`);
515
+ if (failure.code !== "EADDRINUSE") die(failure.message);
516
+ if (!scannable) die(`port ${candidate} in use — pass --port <n>`);
517
+ const holder = await probeCockpitWorkspace(candidate);
518
+ if (holder === instance.workspace) {
519
+ const url = `http://${COCKPIT_HOST}:${candidate}/`;
520
+ console.error(`${NAME}: cockpit already running for this workspace on ${url}`);
521
+ // Already running, so nothing opens — the same rule as the arm above.
522
+ process.exit(0);
523
+ }
524
+ console.error(`${NAME}: port ${candidate} is held by something that is not this workspace's cockpit — trying the next port`);
525
+ }
526
+ if (!server) die(`no free port for this workspace — tried ${candidates.join(", ")}; pass --port <n> to choose one`);
527
+
528
+ // Only now — with a bind this process is actually keeping — does it need
529
+ // the state directory and board.html. Never for a launch either check
530
+ // above already turned into a no-op: this shares the state directory
531
+ // with whatever this workspace's live cockpit is doing, and touching it
532
+ // before reuse was settled was a defect in the reuse
533
+ // arm (mkdirSync/copyFileSync used to run before the candidate loop).
534
+ mkdirSync(stateDir, { recursive: true });
535
+ try { copyFileSync(join(SCRIPT_DIR, "board.html"), join(stateDir, "board.html")); }
536
+ catch (e) { die(`cannot stage board.html into ${stateDir}: ${e.message}`); }
537
+
538
+ // A bind failure is handled above, one candidate at a time; this handler
539
+ // owns everything a LISTENING server can still emit. Without it an 'error'
540
+ // event after the bind has no listener at all and node rethrows it as an
541
+ // uncaught exception — the one regression the loop above would otherwise
542
+ // introduce by taking the old, always-attached handler away with it.
543
+ server.on("error", (e) => die(e.message));
544
+
545
+ // Everything below is reached only by a process that HOLDS a port, which is
546
+ // what the listen-callback gating bought and what this loop has to keep
547
+ // paying for by position: tick() writes into stateDir, SHARED by every cwd
548
+ // that resolves to this workspace, so a process that never binds must not
549
+ // reach it. A second cockpit that ticked first would overwrite the live
550
+ // one's board.json and reset every ticket's dwell clock.
551
+ //
552
+ // Announce the port we GOT, not the one we asked for. They differ for the
553
+ // one value `--port 0` newly permits: listen(0) binds an ephemeral port, so
554
+ // echoing the request prints — and --opens — http://127.0.0.1:0, which
555
+ // reaches nothing while the board sits on a port nobody was told.
556
+ // address() is only populated once listening, hence only here.
557
+ const bound = server.address().port;
558
+ console.error(`${NAME}: cockpit on http://${COCKPIT_HOST}:${bound} (interval ${interval}s)`);
559
+
560
+ // Publish identity the instant this port is ours — before the
561
+ // first tick, which is the one that can be slow (its gather shells out to
562
+ // gh and ledger.mjs). A sibling launch races this one by sending its
563
+ // probe as soon as ITS bind attempt refuses, which can be well before
564
+ // this process's first tick ever returns; the answer that probe needs
565
+ // has to already be on disk, not waiting on a compute this process has
566
+ // not started yet.
567
+ // `port` rides along. This stub is a board payload like any other
568
+ // for as long as the first tick takes, and a reader that finds it —
569
+ // the operator, a script, the page — gets the same two identity fields
570
+ // from it that every later tick writes. The handshake above still reads
571
+ // only `workspace`.
572
+ writeFileSync(`${jsonPath}.tmp`, JSON.stringify({ workspace: instance.workspace, port: bound }));
573
+ renameSync(`${jsonPath}.tmp`, jsonPath);
574
+ // Yield once so a connection already arriving — that same sibling's probe —
575
+ // gets a chance to read the identity just written before this process starts
576
+ // the first tick. The tick no longer blocks the loop, but its gather
577
+ // still opens with a synchronous prev-board read before its first await, and
578
+ // a turn of the loop costs nothing.
579
+ await new Promise((resolve) => setImmediate(resolve));
580
+
581
+ // Deliberately not awaited: the first tick is the slow one, and everything
582
+ // below it — the timer, and the two signal handlers that are the only way
583
+ // this process is ever asked to stop — must be in place before it returns,
584
+ // not after. Nothing here rejects; tick() catches its own faults and the
585
+ // `ticking` flag it sets is cleared in a finally (see boardTick()).
586
+ const tickArgs = { served: bound, stateDir, jsonPath, workspace: instance.workspace };
587
+ tick(tickArgs);
588
+ const timer = setInterval(() => tick(tickArgs), interval * 1000);
589
+
590
+ const stop = () => {
591
+ clearInterval(timer);
592
+ server.close(() => process.exit(0));
593
+ server.closeAllConnections?.(); // drop keep-alive sockets so close() resolves promptly
594
+ setTimeout(() => process.exit(0), 1000).unref(); // hard backstop if a socket somehow lingers
595
+ };
596
+ process.on("SIGINT", stop);
597
+ process.on("SIGTERM", stop);
598
+
599
+ // --open, from this launch alone: it is the one that bound a port and
600
+ // started a server, and the reuse arms above open nothing. Only
601
+ // once the identity is on disk — a launcher running BEFORE that write put a
602
+ // child squarely inside the window the identity stub exists to keep empty, where a
603
+ // racing launch's probe finds no payload and reads this port as foreign —
604
+ // and only after the tick, the timer and both signal handlers are in
605
+ // place: `xdg-open` can run the browser it starts in the foreground and
606
+ // return only when that browser exits, so a launcher awaited any earlier
607
+ // could hold the first tick back for the whole session. openBrowser()
608
+ // never throws; a launcher that is missing or fails is one warning line.
609
+ if (open) await openBrowser(`http://${COCKPIT_HOST}:${bound}/`);
610
+ await new Promise(() => {}); // run until signalled
611
+ }