@feigi/fleet-ctl 3.106.1 → 3.108.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@feigi/fleet-ctl",
3
- "version": "3.106.1",
3
+ "version": "3.108.0",
4
4
  "description": "Agent fleet: run-team controller, merge bot, PR reviewer, and the ticket pipeline they share",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -23,8 +23,10 @@
23
23
  // which session is this run's. The run says it: phase 0 records the
24
24
  // controller's own session directory in its receipt, `.fleet/phase0.json`,
25
25
  // and receiptSpendDir() below reads it back on every tick — never latched,
26
- // because a cockpit outlives the run that launched it and has to follow the
27
- // next run's receipt. `--spend-dir <path>` overrides the receipt outright.
26
+ // because a cockpit lives as long as its run's controller, which can start
27
+ // another run from the same omp session, and a phase-0 relaunch reuses a
28
+ // running server; either way it has to follow the next run's receipt.
29
+ // `--spend-dir <path>` overrides the receipt outright.
28
30
 
29
31
  import { readFileSync, existsSync, statSync } from "node:fs";
30
32
  import { computeSpend, attributeTools, mergeTools } from "./compute-spend.mjs";
@@ -405,9 +407,10 @@ export function mapCi(ciJson, pr) {
405
407
  // the directory its ledger and heartbeat come from, so the three cannot
406
408
  // disagree about which run they belong to — through phase0-receipt.mjs's
407
409
  // readReceipt, the one reading of that file. The caller reads it on EVERY
408
- // tick and keeps nothing: a cockpit survives across runs (a phase-0 relaunch
409
- // reuses a running server), so a session held from an earlier tick would
410
- // keep showing the previous run's spend once the next run's receipt lands.
410
+ // tick and keeps nothing: a cockpit survives across runs (a new run from the
411
+ // same omp session keeps it, and a phase-0 relaunch reuses a running server),
412
+ // so a session held from an earlier tick would keep showing the previous
413
+ // run's spend once the next run's receipt lands.
411
414
  //
412
415
  // A receipt with no session to give is `{ error }`, which the panel shows:
413
416
  // the board names no session rather than guessing one. So is a recorded
@@ -578,14 +578,13 @@ export async function serve({ port: portGiven, interval, open, tick }) {
578
578
  // a turn of the loop costs nothing.
579
579
  await new Promise((resolve) => setImmediate(resolve));
580
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()).
581
+ // A tick that answers `true` has written its board and found the run's
582
+ // controller gone: the cockpit lives as long as that controller, and stop()
583
+ // below is its way out, the same one a signal takes. Any other answer, a
584
+ // skipped tick's `undefined` included, serves on.
586
585
  const tickArgs = { served: bound, stateDir, jsonPath, workspace: instance.workspace };
587
- tick(tickArgs);
588
- const timer = setInterval(() => tick(tickArgs), interval * 1000);
586
+ const runTick = async () => { if (await tick(tickArgs) === true) stop(); };
587
+ const timer = setInterval(runTick, interval * 1000);
589
588
 
590
589
  const stop = () => {
591
590
  clearInterval(timer);
@@ -595,6 +594,11 @@ export async function serve({ port: portGiven, interval, open, tick }) {
595
594
  };
596
595
  process.on("SIGINT", stop);
597
596
  process.on("SIGTERM", stop);
597
+ // Deliberately not awaited: the first tick is the slow one, and the timer
598
+ // and both signal handlers above are already in place. Nothing here
599
+ // rejects; tick() catches its own faults and the `ticking` flag it sets is
600
+ // cleared in a finally (see boardTick()).
601
+ runTick();
598
602
 
599
603
  // --open, from this launch alone: it is the one that bound a port and
600
604
  // started a server, and the reuse arms above open nothing. Only
@@ -607,5 +611,5 @@ export async function serve({ port: portGiven, interval, open, tick }) {
607
611
  // could hold the first tick back for the whole session. openBrowser()
608
612
  // never throws; a launcher that is missing or fails is one warning line.
609
613
  if (open) await openBrowser(`http://${COCKPIT_HOST}:${bound}/`);
610
- await new Promise(() => {}); // run until signalled
614
+ await new Promise(() => {}); // run until signalled, or until a tick answers true (the run's controller is gone)
611
615
  }
package/scripts/board.mjs CHANGED
@@ -23,6 +23,7 @@ import { serve, resolveCockpitInstance, cockpitWorkspace } from "./board-server.
23
23
  // the `canonicalise` opt-in only that caller takes, and a second resolution
24
24
  // could answer differently.
25
25
  import { stateFileIn } from "./fleet-state.mjs";
26
+ import { cockpitLifetime, controllerVerdict } from "./cockpit-lifetime.mjs";
26
27
  import { isCLI } from "./is-cli.mjs";
27
28
  import { join } from "node:path";
28
29
  import { inspect } from "node:util";
@@ -317,10 +318,16 @@ async function main() {
317
318
  // owns the socket, the timer and the identity handshake; what a tick reads and
318
319
  // writes is owned here.
319
320
  //
321
+ // The tick answers `true` when the cockpit is to exit: it has just written its
322
+ // board and the Controller record in the heartbeat file names a controller
323
+ // that is gone (cockpit-lifetime.mjs says when). serve() stops through its own
324
+ // stop() on that answer. Nothing else is ever signalled.
325
+ //
320
326
  // The spend source is settled per TICK, never held across ticks: with no
321
327
  // --spend-dir, every tick reads the session the phase-0 receipt records now.
322
- // A cockpit outlives the run that launched it — a phase-0 relaunch reuses a
323
- // running server — so it has to follow the next run's receipt.
328
+ // A cockpit lives as long as its run's controller, and a new run from the same
329
+ // omp session — or a phase-0 relaunch that reuses a running server — has to be
330
+ // followed through its receipt.
324
331
  async function boardTick({ ledgerFile, interval, spendDir, spendSince }) {
325
332
  const { computeBoard } = await import("./compute-board.mjs");
326
333
  // One tick at a time, and the flag is load-bearing rather than defensive.
@@ -337,10 +344,20 @@ async function boardTick({ ledgerFile, interval, spendDir, spendSince }) {
337
344
  //
338
345
  // SKIPPED, not queued: a tick recomputes the whole board from scratch, so
339
346
  // the one that would have been queued has nothing in it the next one does
340
- // not redo. Announced once per process through the same warn-once gate
341
- // every other repeating condition in this file uses — a board falling
342
- // behind its interval is worth saying, and worth saying only once.
347
+ // not redo. Announced once per process through board-common.mjs's warn-once
348
+ // gate — a board falling behind its interval is worth saying, and worth
349
+ // saying only once.
343
350
  let ticking = false;
351
+ // Carried from tick to tick besides `ticking`: whether this cockpit has yet
352
+ // seen its run's controller alive, and why the process table last could not
353
+ // be read. The record itself is read afresh every tick — a latched
354
+ // controller would end a cockpit whose record a new run had replaced.
355
+ let armed = false;
356
+ // Null until the table fails to read, and null again from the first tick it
357
+ // reads. Each outage is said once, and so is each new reason within one: a
358
+ // warnOnce gate would say the first outage of the process's life and none
359
+ // after it.
360
+ let unreadable = null;
344
361
  // `served` is the port this process actually BOUND, handed in rather than
345
362
  // closed over: it is not knowable until listen() returns (--port 0 is an
346
363
  // ephemeral bind, and serve()'s port loop may also land past a
@@ -369,7 +386,7 @@ async function boardTick({ ledgerFile, interval, spendDir, spendSince }) {
369
386
  // assignment that used to sit below this line wrote a field the pure
370
387
  // model did not declare, so `build` printed a board with no identity
371
388
  // at all and only the served copy carried one.
372
- const model = computeBoard(await gather({
389
+ const gathered = await gather({
373
390
  // The ledger's own default (ledger.mjs's defaultLedgerPath()) is
374
391
  // never reached here — board.mjs always passes an explicit --file — so an
375
392
  // absent --ledger has to be defaulted against the SAME instance the state
@@ -390,10 +407,26 @@ async function boardTick({ ledgerFile, interval, spendDir, spendSince }) {
390
407
  // The operator's --spend-dir, else the receipt as it stands at this
391
408
  // tick, read from the same state directory as the ledger and heartbeat.
392
409
  ...spendSource(spendDir, stateDir), spendSince,
393
- }));
410
+ });
411
+ const model = computeBoard(gathered);
394
412
  const tmp = `${jsonPath}.tmp`;
395
413
  writeFileSync(tmp, JSON.stringify(model)); // atomic: write tmp, rename over target
396
414
  renameSync(tmp, jsonPath);
415
+ // After the board is written, so the last board an exiting cockpit
416
+ // leaves is this tick's. A record or process table that cannot be read
417
+ // gives no verdict, and a drain (the Liveness mark's `stopped`) is not
418
+ // read at all.
419
+ const verdict = controllerVerdict(gathered.controller, undefined, (why) => {
420
+ if (why !== unreadable) console.error(`${NAME}: ${why} — the cockpit cannot tell whether its run's controller is alive, so it keeps serving`);
421
+ unreadable = why;
422
+ });
423
+ if (verdict !== null) unreadable = null;
424
+ const next = cockpitLifetime(armed, verdict);
425
+ armed = next.armed;
426
+ if (next.exit) {
427
+ console.error(`${NAME}: the controller of this run (pid ${gathered.controller.pid}) is gone — the cockpit exits`);
428
+ return true;
429
+ }
397
430
  } catch (e) { console.error(`${NAME}: build tick failed: ${e.message}`); }
398
431
  finally { ticking = false; }
399
432
  };
@@ -0,0 +1,53 @@
1
+ // How long the cockpit lives: as long as the controller its run recorded, and
2
+ // no longer. The cockpit is spawned detached (phase0.mjs), so nothing ties it
3
+ // to the omp session that started it; this is the one thing that ends it
4
+ // short of a signal. The decision is a pure function of two values, in the
5
+ // board's own split (compute-board.mjs pure, board-gather.mjs impure), so a
6
+ // test feeds it verdicts instead of killing processes. boardTick() in
7
+ // board.mjs reads the record and the process table and acts on the answer.
8
+
9
+ import { judgeController, processSource, ProcUnreadable } from "./proc.mjs";
10
+
11
+ // What the verdict on the Controller record means for the cockpit, this tick.
12
+ //
13
+ // `verdict` is judgeController()'s answer, or null when there is none to give:
14
+ // no record, or a process table that could not be read. Null is not a death
15
+ // and not a life — it neither arms the cockpit nor ends it, which is also how
16
+ // a heartbeat file that could not be read behaves, since readState() answers
17
+ // that with no record.
18
+ //
19
+ // Any verdict but `dead` is a live controller, and the first one ARMS the
20
+ // cockpit. judgeController()'s `none`, its answer for a missing record, never
21
+ // arrives here: controllerVerdict() below answers a missing record with null.
22
+ // Until the cockpit is armed a `dead` verdict means nothing: a cockpit launched
23
+ // by hand between runs finds the last run's record and must not exit on it.
24
+ // Once armed, the first `dead` ends it. `armed` is the caller's to carry from
25
+ // tick to tick; the record is judged afresh on every one, so a record
26
+ // replaced by a new live controller keeps an armed cockpit serving.
27
+ //
28
+ // A drain is not an input: a controller that has stopped beating is still a
29
+ // controller, and judgeController() never reads the beat.
30
+ export function cockpitLifetime(armed, verdict) {
31
+ if (verdict === null) return { armed, exit: false };
32
+ if (verdict === "dead") return { armed, exit: armed };
33
+ return { armed: true, exit: false };
34
+ }
35
+
36
+ // judgeController() for the cockpit: the record against the process table as
37
+ // it stands now, with no ancestry — it passes an empty chain, so `ancestor`
38
+ // never occurs, and every verdict but `dead` reads the same here. Null when
39
+ // there is no record or the table cannot be read, `onUnreadable` told why.
40
+ // `makeSource` is a parameter for the reason proc.mjs's FLEET_PROC_TABLE
41
+ // exists: a test suite run under a live omp session must not judge that one.
42
+ // Nothing here signals a process; judgeController() reads, and kill(pid, 0)
43
+ // only asks.
44
+ export function controllerVerdict(record, makeSource = processSource, onUnreadable = () => {}) {
45
+ if (!record) return null;
46
+ try {
47
+ return judgeController(record, makeSource(), []);
48
+ } catch (e) {
49
+ if (!(e instanceof ProcUnreadable)) throw e;
50
+ onUnreadable(e.message);
51
+ return null;
52
+ }
53
+ }
@@ -356,9 +356,10 @@ export function writeState(path, name, prev, patch) {
356
356
  // Two readers consume this key and neither of them writes it: fleet-tick at
357
357
  // the start of a run (so a run that died overnight announces itself even when
358
358
  // no cockpit survived it) and board.mjs on every cockpit tick (the better
359
- // surface, the weaker guarantee — whether a backgrounded cockpit outlives the
360
- // session that spawned it is unmeasured and harness-dependent, so the mark is
361
- // the artifact and the cockpit is one renderer of it).
359
+ // surface, the weaker guarantee — the cockpit lives as long as its run's
360
+ // controller (cockpit-lifetime.mjs), so a stopped or stalled run's mark stays
361
+ // on screen while that controller's omp session is open and is gone with it,
362
+ // and the mark is the artifact that outlasts it, the cockpit one renderer of it).
362
363
  //
363
364
  // Both live here for the reason the module header already gives about the
364
365
  // path and the shape: what travels between scripts is the rule, never a copy
@@ -0,0 +1,182 @@
1
+ #!/usr/bin/env node
2
+ // The Label map: the string the consumer's tracker uses for each Label role.
3
+ // This module owns the map's cache format — the file, its validity rules, the
4
+ // writer and the reader every role-reading script imports — and the `show`
5
+ // verb. It derives nothing: the derivation step is `ensure`, which is not
6
+ // here yet, so every refusal below names it as the step that writes the map.
7
+ //
8
+ // THE CACHE is `.fleet/labels.json`, resolved through fleet-dir.mjs's
9
+ // fleetFile() like the pre-flight marker, so a member in its own worktree and
10
+ // the controller in the main checkout name one file. `.fleet/` is gitignored,
11
+ // so the file is never committed, and it is never written by hand. Content:
12
+ // derivedAt ISO time of the derivation that wrote it
13
+ // table what the triage-label table said then: { present, rows: {role: string} }
14
+ // roles every Label role -> the string the tracker uses
15
+ // origin every Label role -> "table" | "default" | "maintainer"
16
+ //
17
+ // VALID STRINGS (labelStringFaults): non-empty after trimming, at most 50
18
+ // characters, no `"` and no `\`, and no two roles mapping to one string,
19
+ // compared ignoring case.
20
+ //
21
+ // THE READER (readLabelMap) returns `roles` when the cache parses, holds every
22
+ // Label role and passes the string rules; anything else throws
23
+ // LabelMapUnreadable. It never reads the tracker's live label list and has no
24
+ // defaults: an absent or broken map is a refusal, never a guess.
25
+ //
26
+ // THE WRITER (writeLabelMap) writes the whole cache to a temp file beside the
27
+ // target and renames it over the target, so a reader never sees half of it.
28
+ // It writes what it is handed: checking the map is its caller's step.
29
+ //
30
+ // CLI:
31
+ // label-map.mjs show [<role>] the mapped string for <role>, or the whole
32
+ // `roles` object as JSON with no role.
33
+ // Exit 0 printed; 1 no cache or an invalid one, the message naming `ensure`;
34
+ // 2 an unknown role, no repository, or a usage refusal (any other verb).
35
+ //
36
+ // Zero deps: node builtins and sibling scripts only.
37
+
38
+ import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
39
+ import { dirname } from "node:path";
40
+ import { isCLI } from "./is-cli.mjs";
41
+ import { makeDie, writeAll } from "./arg.mjs";
42
+ import { fleetFile, FleetDirUnresolvable } from "./fleet-dir.mjs";
43
+
44
+ const NAME = "label-map";
45
+ const die = makeDie(NAME);
46
+ const USAGE = "usage: label-map.mjs show [<role>]";
47
+ const MAX_LENGTH = 50;
48
+ const DERIVE = "run `label-map.mjs ensure`, the Label map derivation step";
49
+
50
+ export const LABEL_MAP_FILE = "labels.json";
51
+
52
+ export const LABEL_ROLES = Object.freeze([
53
+ "needs-triage",
54
+ "needs-info",
55
+ "ready-for-agent",
56
+ "ready-for-human",
57
+ "wontfix",
58
+ "in-progress",
59
+ "onhold",
60
+ "ready-to-merge",
61
+ ]);
62
+
63
+ export class LabelMapUnreadable extends Error {
64
+ constructor(message) {
65
+ super(message);
66
+ this.name = "LabelMapUnreadable";
67
+ }
68
+ }
69
+
70
+ // The rule a single string breaks on its own, or null.
71
+ function stringFault(value) {
72
+ if (value === undefined) return "missing";
73
+ if (typeof value !== "string") return `not a string (${JSON.stringify(value)})`;
74
+ if (value.trim() === "") return "empty after trimming";
75
+ if (value.length > MAX_LENGTH) return `longer than ${MAX_LENGTH} characters (${value.length})`;
76
+ if (value.includes('"')) return 'contains `"`';
77
+ if (value.includes("\\")) return "contains `\\`";
78
+ return null;
79
+ }
80
+
81
+ /**
82
+ * Every way `roles` (role -> string) breaks the Label map's string rules, as
83
+ * `[{ role, rule }]` in role order; empty when it breaks none. A role absent
84
+ * from `roles` is a fault too. Two roles mapping to one string, compared
85
+ * ignoring case, is reported once, on the later role, its rule naming the
86
+ * earlier one; a string that already breaks a rule on its own is not compared.
87
+ */
88
+ export function labelStringFaults(roles) {
89
+ const faults = [];
90
+ const seen = new Map();
91
+ for (const role of LABEL_ROLES) {
92
+ const value = Object.hasOwn(roles, role) ? roles[role] : undefined;
93
+ const rule = stringFault(value);
94
+ if (rule) {
95
+ faults.push({ role, rule });
96
+ continue;
97
+ }
98
+ const key = value.toLowerCase();
99
+ const first = seen.get(key);
100
+ if (first) faults.push({ role, rule: `maps to the same string as ${first} (${JSON.stringify(value)}), compared ignoring case` });
101
+ else seen.set(key, role);
102
+ }
103
+ return faults;
104
+ }
105
+
106
+ /**
107
+ * Write `map` ({ derivedAt, table, roles, origin }) as the cache of the
108
+ * repository `cwd` belongs to, through a temp file beside it, and return the
109
+ * cache's path. Throws FleetDirUnresolvable outside a repository, and the
110
+ * filesystem's own error when the file cannot be written.
111
+ */
112
+ export function writeLabelMap(map, { cwd = process.cwd() } = {}) {
113
+ const file = fleetFile(LABEL_MAP_FILE, { cwd });
114
+ const tmp = `${file}.${process.pid}.tmp`;
115
+ mkdirSync(dirname(file), { recursive: true });
116
+ try {
117
+ writeFileSync(tmp, `${JSON.stringify(map)}\n`);
118
+ renameSync(tmp, file);
119
+ } catch (e) {
120
+ // The write's own error is the one to report: a temp file that cannot be
121
+ // removed (a directory in its place) must not replace it.
122
+ try { rmSync(tmp, { force: true }); } catch {}
123
+ throw e;
124
+ }
125
+ return file;
126
+ }
127
+
128
+ /**
129
+ * The `roles` object (every Label role -> its string) of the cache of the
130
+ * repository `cwd` belongs to. Throws LabelMapUnreadable, its message naming
131
+ * `ensure`, when the cache is absent, does not parse, lacks a role or breaks
132
+ * the string rules; throws FleetDirUnresolvable outside a repository.
133
+ */
134
+ export function readLabelMap({ cwd = process.cwd() } = {}) {
135
+ const file = fleetFile(LABEL_MAP_FILE, { cwd });
136
+ let text;
137
+ try {
138
+ text = readFileSync(file, "utf8");
139
+ } catch (e) {
140
+ if (e.code === "ENOENT") throw new LabelMapUnreadable(`no Label map at ${file}: ${DERIVE}`);
141
+ throw new LabelMapUnreadable(`cannot read the Label map at ${file} (${e.code ?? e.message}): ${DERIVE}`);
142
+ }
143
+ let cache;
144
+ try {
145
+ cache = JSON.parse(text);
146
+ } catch (e) {
147
+ throw new LabelMapUnreadable(`the Label map at ${file} does not parse (${e.message}): ${DERIVE}`);
148
+ }
149
+ const roles = cache?.roles;
150
+ if (roles === null || typeof roles !== "object" || Array.isArray(roles)) {
151
+ throw new LabelMapUnreadable(`the Label map at ${file} holds no \`roles\` object: ${DERIVE}`);
152
+ }
153
+ const faults = labelStringFaults(roles);
154
+ if (faults.length) {
155
+ const why = faults.map(({ role, rule }) => `${role}: ${rule}`).join("; ");
156
+ throw new LabelMapUnreadable(`the Label map at ${file} is invalid — ${why}: ${DERIVE}`);
157
+ }
158
+ return Object.fromEntries(LABEL_ROLES.map((role) => [role, roles[role]]));
159
+ }
160
+
161
+ function main() {
162
+ const [verb, ...rest] = process.argv.slice(2);
163
+ if (verb !== "show") die(verb === undefined ? USAGE : `unknown verb ${JSON.stringify(verb)}; ${USAGE}`);
164
+ if (rest.length > 1) die(`show takes at most one role, got: ${rest.join(" ")}; ${USAGE}`);
165
+ const [role] = rest;
166
+ if (role !== undefined && !LABEL_ROLES.includes(role)) {
167
+ die(`unknown role ${JSON.stringify(role)}; the roles are ${LABEL_ROLES.join(", ")}`);
168
+ }
169
+ let roles;
170
+ try {
171
+ roles = readLabelMap();
172
+ } catch (e) {
173
+ if (e instanceof FleetDirUnresolvable) die(e.message);
174
+ if (!(e instanceof LabelMapUnreadable)) throw e;
175
+ writeAll(2, `\n${NAME}: ${e.message}\n`);
176
+ process.exitCode = 1;
177
+ return;
178
+ }
179
+ console.log(role === undefined ? JSON.stringify(roles) : roles[role]);
180
+ }
181
+
182
+ if (isCLI(import.meta.url)) main();
@@ -183,8 +183,8 @@ else — either way it gets its own board, just not always on the port its
183
183
  hash predicts.
184
184
 
185
185
  The spend panel reads the session directory this run's phase-0 receipt
186
- records, re-read on every tick, so a cockpit that outlives a run follows the
187
- next run's receipt. Until that directory exists and holds a member transcript
186
+ records, re-read on every tick, so a cockpit that serves a later run follows
187
+ that run's receipt. Until that directory exists and holds a member transcript
188
188
  the panel stays hidden; with no receipt, or one recording no session, it says
189
189
  `no session recorded — run phase 0 or pass --spend-dir`. Passing
190
190
  `--spend-dir <path>` to phase 0 overrides the receipt —
@@ -195,6 +195,16 @@ running leaves it reading what it read, flag or not. To put a running
195
195
  cockpit on `--spend-dir`, stop it first: SIGTERM to the pid phase 0's
196
196
  `cockpit` line printed when it launched that server.
197
197
 
198
+ The cockpit lives as long as the controller its run recorded — the omp
199
+ session that owns the run — and exits itself once that session is gone. A
200
+ drained run's cockpit stays up while its session stays open, so you can
201
+ still watch it. A run started from the same session, or from a later one,
202
+ records its own controller, and the cockpit keeps serving it. A cockpit
203
+ launched by hand between runs, while the record still names a dead
204
+ controller, keeps serving until a record names a live one. An unreadable
205
+ heartbeat file or process table is not a death. Nothing at close-out stops
206
+ it and nothing signals its pid.
207
+
198
208
  ## Rotate the ledger
199
209
 
200
210
  **Rotate the ledger before the fold-in below and before shortlisting —