@feigi/fleet-ctl 3.35.4 → 3.35.6

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.35.4",
3
+ "version": "3.35.6",
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": {
package/scripts/arg.mjs CHANGED
@@ -59,6 +59,10 @@
59
59
  // its command line must be named in this header. Read the grep's output, plus
60
60
  // the scripts named here, for the roster — the scripts this header names
61
61
  // exemplify a way of qualifying, and were never the whole of it.
62
+ // board-common.mjs is the one row the grep returns with no command line
63
+ // behind it: it binds makeDie for board.mjs, which binds defineFlags in an
64
+ // import of its own, so the grep returns the module and not the script. A
65
+ // test runs it too, and holds it to exiting in silence.
62
66
  //
63
67
  // fleet-tick.mjs and fleet-heartbeat.mjs sit outside arg()/has(), and
64
68
  // deliberately: each parses its flags with node:util's parseArgs, so its
@@ -0,0 +1,84 @@
1
+ // What board.mjs's gather side, its server side and its tick loop all use: the
2
+ // script's NAME and die(), the one warn-once gate, and the asynchronous child
3
+ // read. warnOnce's set is the only mutable state among them, and all three
4
+ // sides spend keys on it, so it lives here rather than with any one of them.
5
+ import { execFile } from "node:child_process";
6
+ import { makeDie } from "./arg.mjs";
7
+
8
+ export const NAME = "board";
9
+ // die() shared with the other fleet scripts — see arg.mjs for the fail-open
10
+ // and pipe-safety rationale.
11
+ export const die = makeDie(NAME);
12
+
13
+ // Every warn-once gate in board.mjs routes through here. The stored key is the
14
+ // CHANNEL joined to the caller's key, never the caller's key alone: gates share
15
+ // key values — ci-salvage-nonzero, ci-salvage-exit0 and ci-parse are all keyed
16
+ // on the same PR — so a bare-key Set would let one channel's warning consume
17
+ // another's line for that PR, a behaviour change, not a refactor. NUL joins
18
+ // them because no channel name holds one, so the joined string splits back to
19
+ // exactly one (channel, key) pair whatever the key holds. Returns whether it
20
+ // wrote, for a caller that bounds how many keys it spends.
21
+ const warnedOnce = new Set();
22
+ export function warnOnce(channel, key, msg) {
23
+ const k = `${channel}\0${key}`;
24
+ if (warnedOnce.has(k)) return false;
25
+ warnedOnce.add(k);
26
+ console.error(`${NAME}: ${msg}`);
27
+ return true;
28
+ }
29
+
30
+ // Node's default stdout cap is 1 MiB and a capped child read FAILS past it
31
+ // rather than truncating. Here that failure is indistinguishable from an
32
+ // unreachable tool: the read degrades to the caller's empty default and the
33
+ // cockpit is served a BLANK board at HTTP 200 with only a stderr line — the
34
+ // same blank-board symptom the old pipe-buffer limit produced, which the raised
35
+ // ceiling moved up rather than removed.
36
+ // The ledger is append-mostly and shared by every fleet script, so the ceiling
37
+ // arms itself over the life of a run and gives no second warning. Bounded, not
38
+ // Infinity: a runaway child should still be stopped rather than allowed to
39
+ // exhaust the box. Same headroom staleness.mjs takes, for the same reason.
40
+ //
41
+ // Both child reads in board.mjs take it. `tryRun` is NOT the single funnel —
42
+ // runCiState() spawns its own, because it needs the exit code that a plain
43
+ // tryRun discards — so a fix applied only there would leave that one uncapped.
44
+ export const READ_OPTS = { encoding: "utf8", maxBuffer: 64 * 1024 * 1024 };
45
+
46
+ // Every child read in board.mjs is ASYNCHRONOUS, and that is
47
+ // load-bearing rather than stylistic. serve() ticks on a timer inside the same
48
+ // process that answers HTTP, so a SYNCHRONOUS read holds the event loop for as
49
+ // long as the child runs — measured at 4.72–4.91s for one board — and during
50
+ // that window this cockpit answers nothing at all. A relaunch's identity probe
51
+ // (PROBE_TIMEOUT_MS, one retry, ~2s in total) landing inside it therefore got
52
+ // no answer, read the port as foreign, and started a SECOND cockpit on this
53
+ // workspace's state directory: the duplicate the launch handshake and the identity stub exist to prevent,
54
+ // reached through timing rather than through a missing handshake. The browser
55
+ // page stalled for the same reason and the same duration, every tick.
56
+ //
57
+ // One thing execFileSync did that this has to keep doing by hand: given no
58
+ // `stdio` of its own it re-emits the child's captured stderr onto this
59
+ // process's stderr (node's own `process.stderr.write(ret.stderr)`) BEFORE it
60
+ // throws. That write is spelled out below, and on both arms, because the sync
61
+ // one wrote whether or not it went on to throw.
62
+ //
63
+ // This never throws; a failure is REPORTED in the record, in the field names
64
+ // execFileSync's throw used — `status` for an exit code, `signal` for a kill,
65
+ // `code` for a libuv/node fault. That translation is the whole reason this is
66
+ // not a bare `promisify(execFile)`: the async error carries the EXIT CODE in
67
+ // `err.code` (measured: `3`, a number), where the sync one carried `ENOENT` /
68
+ // `ENOBUFS` there and the exit code in `status`, and board.mjs's runCiState()
69
+ // reads all three to tell those causes apart.
70
+ export function execRead(cmd, args) {
71
+ return new Promise((resolve) => {
72
+ execFile(cmd, args, READ_OPTS, (err, stdout, stderr) => {
73
+ if (stderr) process.stderr.write(stderr);
74
+ resolve(err
75
+ ? {
76
+ stdout, error: err,
77
+ status: typeof err.code === "number" ? err.code : null,
78
+ code: typeof err.code === "string" ? err.code : null,
79
+ signal: err.signal ?? null,
80
+ }
81
+ : { stdout, error: null, status: 0, code: null, signal: null });
82
+ });
83
+ });
84
+ }
package/scripts/board.mjs CHANGED
@@ -31,13 +31,13 @@
31
31
  // <path>` is how an operator names the right one: it overrides the
32
32
  // heuristic outright.
33
33
 
34
- import { execFile } from "node:child_process";
35
34
  import { readFileSync, writeFileSync, renameSync, existsSync, readdirSync, statSync, writeSync } from "node:fs";
36
35
  import { classifyRole, computeSpend, attributeTools, mergeTools } from "./compute-spend.mjs";
37
36
  import {
38
37
  encodeProjectDir, isOmpSessionDirName, ompSessionTranscripts, foldOmpTranscript, ompMemberRecord,
39
38
  } from "./member-record.mjs";
40
- import { makeDie, defineFlags } from "./arg.mjs";
39
+ import { defineFlags } from "./arg.mjs";
40
+ import { NAME, die, warnOnce, execRead } from "./board-common.mjs";
41
41
  import { fleetFile, FleetDirUnresolvable } from "./fleet-dir.mjs";
42
42
  import { mergedReadPrs } from "./compute-board.mjs";
43
43
  // The heartbeat's liveness mark, read here and never written. The
@@ -58,11 +58,9 @@ import { createServer, request as httpRequest } from "node:http";
58
58
  import { connect } from "node:net";
59
59
  import { inspect } from "node:util";
60
60
 
61
- const NAME = "board";
62
61
  const SCRIPT_DIR = dirname(fileURLToPath(import.meta.url));
63
- // die()/arg()/has() shared with the other fleet scripts — see arg.mjs for
62
+ // arg()/has() shared with the other fleet scripts — see arg.mjs for
64
63
  // the fail-open and pipe-safety rationale.
65
- const die = makeDie(NAME);
66
64
  const { arg, has, sweep, stray } = defineFlags(die, {
67
65
  flags: {
68
66
  ledger: "value",
@@ -85,8 +83,8 @@ const { arg, has, sweep, stray } = defineFlags(die, {
85
83
  // A guard used to fire only where the flag was actually READ, and that
86
84
  // was not every subcommand — `port` and `open` are USED in serve() alone, so
87
85
  // `build --port` (trailing), `build --port abc` and `build --open=1` were all
88
- // IGNORED at exit 0 rather than refused. main() now calls argPort()/
89
- // has("open") once, ahead of the build/serve dispatch, so both malformed
86
+ // IGNORED at exit 0 rather than refused. main() now reads --port and
87
+ // --open once, ahead of the build/serve dispatch, so both malformed
90
88
  // spellings refuse on EVERY subcommand — build just discards the (validated)
91
89
  // return value, since nothing on that path has a server to bind or a browser
92
90
  // to open. A WELL-FORMED --port/--open on build still does nothing there,
@@ -95,7 +93,7 @@ const { arg, has, sweep, stray } = defineFlags(die, {
95
93
  // were already read on the build path and already refused there.
96
94
  // That last claim held for `ledger`/`spend-since`/`interval`, not for
97
95
  // `prev` — `prev` was read on `build` alone, and serve() never read it at
98
- // all. Hoisted in main() below, next to argPort()/has("open").
96
+ // all. Hoisted in main() below, next to the --port/--open reads.
99
97
 
100
98
  // The "is this a plain JSON object" predicate and its kind word, one
101
99
  // copy for the reads in this file that reject a parsed-but-wrong payload
@@ -125,11 +123,9 @@ function jsonKind(v) {
125
123
  // `Number(x) || default` treated a garbage --port/--interval exactly
126
124
  // like an absent one — "abc" is NaN, NaN is falsy, so it silently became the
127
125
  // default with no refusal. Same silent-fallback class as arg()'s own comment
128
- // above and the --spend-since guard. `interval` is read from argv in two
129
- // places (serve(), and gather()'s build payload); both call argInterval() so
130
- // the check lives once, not as two copies that can drift apart. Neither
131
- // guard runs on an already-typed value a caller passed in-process — arg()
132
- // only fires when the caller falls through to reading raw argv.
126
+ // above and the --spend-since guard. main() is the only caller of either and
127
+ // hands gather() and serve() the resolved value, so neither guard runs on an
128
+ // already-typed value a caller passed in-process.
133
129
  function argPort() {
134
130
  const raw = arg("port");
135
131
  if (raw == null) return null;
@@ -174,9 +170,8 @@ function argInterval() {
174
170
  // this fix the read sat inline inside gather(), below every stray() call on
175
171
  // every path that reaches it, so a trailing `--spend-since` ahead of a stray
176
172
  // positional refused under stray()'s generic wording instead of this one.
177
- // gather() still calls this itself, in the same spot, so nothing about WHEN
178
- // it validates changes for a caller that skips main() (same reasoning as
179
- // for argPort()/has("open") staying in serve() too).
173
+ // main() is now its only caller: gather() takes the resolved value as
174
+ // `spendSince`.
180
175
  function argSpendSince() {
181
176
  const sinceRaw = arg("spend-since");
182
177
  if (sinceRaw === null) return null;
@@ -216,63 +211,6 @@ function argSpendDir() {
216
211
  return arg("spend-dir") ?? undefined;
217
212
  }
218
213
 
219
- // Node's default stdout cap is 1 MiB and a capped child read FAILS past it
220
- // rather than truncating. Here that failure is indistinguishable from an
221
- // unreachable tool: the read degrades to the caller's empty default and the
222
- // cockpit is served a BLANK board at HTTP 200 with only a stderr line — the
223
- // same blank-board symptom the old pipe-buffer limit produced, which the raised
224
- // ceiling moved up rather than removed.
225
- // The ledger is append-mostly and shared by every fleet script, so the ceiling
226
- // arms itself over the life of a run and gives no second warning. Bounded, not
227
- // Infinity: a runaway child should still be stopped rather than allowed to
228
- // exhaust the box. Same headroom staleness.mjs takes, for the same reason.
229
- //
230
- // Both child reads in this file take it. `tryRun` is NOT the single funnel —
231
- // runCiState() spawns its own, because it needs the exit code that a plain
232
- // tryRun discards — so a fix applied only here would leave that one uncapped.
233
- const READ_OPTS = { encoding: "utf8", maxBuffer: 64 * 1024 * 1024 };
234
-
235
- // Every child read in this file is ASYNCHRONOUS, and that is
236
- // load-bearing rather than stylistic. serve() ticks on a timer inside the same
237
- // process that answers HTTP, so a SYNCHRONOUS read holds the event loop for as
238
- // long as the child runs — measured at 4.72–4.91s for one board — and during
239
- // that window this cockpit answers nothing at all. A relaunch's identity probe
240
- // (PROBE_TIMEOUT_MS, one retry, ~2s in total) landing inside it therefore got
241
- // no answer, read the port as foreign, and started a SECOND cockpit on this
242
- // workspace's state directory: the duplicate the launch handshake and the identity stub exist to prevent,
243
- // reached through timing rather than through a missing handshake. The browser
244
- // page stalled for the same reason and the same duration, every tick.
245
- //
246
- // One thing execFileSync did that this has to keep doing by hand: given no
247
- // `stdio` of its own it re-emits the child's captured stderr onto this
248
- // process's stderr (node's own `process.stderr.write(ret.stderr)`) BEFORE it
249
- // throws. That single oversized write is the subject of a flood row in the CLI tests,
250
- // so it is spelled out below — and on both arms, because
251
- // the sync one wrote whether or not it went on to throw.
252
- //
253
- // This never throws; a failure is REPORTED in the record, in the field names
254
- // execFileSync's throw used — `status` for an exit code, `signal` for a kill,
255
- // `code` for a libuv/node fault. That translation is the whole reason this is
256
- // not a bare `promisify(execFile)`: the async error carries the EXIT CODE in
257
- // `err.code` (measured: `3`, a number), where the sync one carried `ENOENT` /
258
- // `ENOBUFS` there and the exit code in `status`, and runCiState() below reads
259
- // all three to tell those causes apart.
260
- function execRead(cmd, args) {
261
- return new Promise((resolve) => {
262
- execFile(cmd, args, READ_OPTS, (err, stdout, stderr) => {
263
- if (stderr) process.stderr.write(stderr);
264
- resolve(err
265
- ? {
266
- stdout, error: err,
267
- status: typeof err.code === "number" ? err.code : null,
268
- code: typeof err.code === "string" ? err.code : null,
269
- signal: err.signal ?? null,
270
- }
271
- : { stdout, error: null, status: 0, code: null, signal: null });
272
- });
273
- });
274
- }
275
-
276
214
  // Every external read is wrapped: a failure returns null and the caller keeps a
277
215
  // last-known value. Partial board beats a crashed loop or a false alarm.
278
216
  async function tryRun(cmd, args) {
@@ -353,7 +291,7 @@ function tryParse(json, fallback, what) {
353
291
  // input is valid JSON, not that it is an array, so a syntactically-valid
354
292
  // object or scalar from `gh` would otherwise reach the `for...of` below and
355
293
  // throw "rows is not iterable" — an uncaught throw that reaches main()'s
356
- // build path or serve()'s tick catch, exactly the crash-instead-of-degrade
294
+ // build path or the serve tick's catch, exactly the crash-instead-of-degrade
357
295
  // failure this guard exists to prevent for individual rows.
358
296
  function withNumber(rows, what) {
359
297
  if (!Array.isArray(rows)) {
@@ -557,24 +495,6 @@ async function runCiState(scriptDir, pr) {
557
495
  return out;
558
496
  }
559
497
 
560
- // Every warn-once gate in this file routes through here. The stored key is the
561
- // CHANNEL joined to the caller's key, never the caller's key alone: the gates
562
- // below are keyed on paths, and two of them are keyed on the SAME transcript
563
- // path, so a bare-key Set would let one channel's warning consume the other's
564
- // line for that file — a behaviour change, not a refactor. NUL joins them
565
- // because no channel name or path can hold one, so no two distinct (channel,
566
- // key) pairs can collide. Every caller keys on a PR, a path, the fault's own
567
- // message, or a refused Host's rendering, so `key` is never empty. Returns
568
- // whether it wrote, for a caller that bounds how many keys it spends.
569
- const warnedOnce = new Set();
570
- function warnOnce(channel, key, msg) {
571
- const k = `${channel}\0${key}`;
572
- if (warnedOnce.has(k)) return false;
573
- warnedOnce.add(k);
574
- console.error(`${NAME}: ${msg}`);
575
- return true;
576
- }
577
-
578
498
  // The `ci-parse` gate is keyed on the PR, not on the payload: `serve` rebuilds
579
499
  // every ~15s and calls mapCi once per PR per tick, so a payload that is broken
580
500
  // is broken on every tick, and a payload-keyed gate would flood anyway the
@@ -1009,29 +929,26 @@ function readOmpSpend(dir, sinceMs) {
1009
929
  // instance to name (every gather() test driver) says so rather than omitting
1010
930
  // the fields.
1011
931
  //
1012
- // `spendDir` is the caller's PINNED transcript directory and is the one
1013
- // parameter here whose ABSENCE is not a default to fill in: serve() hands the
1014
- // same pin's answer to every tick, and its three shapes — a directory, `null`
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`
1015
935
  // for "resolved, no session yet", `{ error }` for unresolvable — all have to
1016
- // reach gatherSpend() as themselves. Only a caller that passed nothing at all
1017
- // falls through to the default below, which reads the override flag directly:
1018
- // `build` is one gather per process, so it needs the override but never a pin,
1019
- // and that read sits here for the same reason argSpendSince()'s does — a
1020
- // caller that skips main() still validates its own argv. With neither the pin
1021
- // nor the flag, gatherSpend() resolves for itself exactly as it did before
1022
- // this ticket, which is what keeps `build`'s output unchanged by it.
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.
1023
939
  //
1024
- // `spendDirExplicit` is read the same way, independently of
1025
- // `spendDir` itself: serve() always passes a resolved `spendDir` (the pin's
1026
- // answer), never leaving it to default, so `spendDir`'s own presence cannot
1027
- // say whether an operator named it. Whether --spend-dir was given is a fact
1028
- // about argv, unrelated to which of gatherSpend's three shapes the pin
1029
- // currently holds.
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.
1030
947
  // Async, because every child read below is. The event loop this frees
1031
948
  // belongs to serve()'s HTTP server, which shares this process — see execRead's
1032
- // note above for what the synchronous version cost. `build` awaits it and is
949
+ // note in board-common.mjs for what the synchronous version cost. `build` awaits it and is
1033
950
  // otherwise unchanged: one gather per process, nothing else waiting on it.
1034
- export async function gather({ ledgerFile, prevFile, stateFile = null, scriptDir = SCRIPT_DIR, interval, workspace = null, port = null, spendDir = argSpendDir(), spendDirExplicit = argSpendDir() != null }) {
951
+ export async function gather({ ledgerFile, prevFile, stateFile = null, scriptDir = SCRIPT_DIR, interval, workspace = null, port = null, spendDir, spendDirExplicit = false, spendSince = null }) {
1035
952
  // The one read that must not crash the gather: a corrupt/partial board.json
1036
953
  // (the fallback safety net itself) is ignored, not fatal. That holds for a
1037
954
  // SHAPE fault as much as a parse fault — the guard below rejects the
@@ -1202,11 +1119,9 @@ export async function gather({ ledgerFile, prevFile, stateFile = null, scriptDir
1202
1119
  }
1203
1120
 
1204
1121
  // The guard's own rationale (fail loud, gate on presence and on range,
1205
- // not just finiteness) now lives at argSpendSince()'s definition above,
1206
- // alongside argPort()/argInterval() — this call is unchanged in when it
1207
- // runs, only in where the check itself is written.
1208
- const sinceMs = argSpendSince();
1209
- const spend = gatherSpend({ dir: spendDir, sinceMs, explicit: spendDirExplicit });
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 });
1210
1125
  // The heartbeat's mark, raw. readState() never throws — an absent
1211
1126
  // file is the ordinary state of a run whose heartbeat has not beaten yet,
1212
1127
  // and an unreadable or corrupt one announces itself on stderr and degrades
@@ -1233,7 +1148,7 @@ export async function gather({ ledgerFile, prevFile, stateFile = null, scriptDir
1233
1148
  const stallOwnerOf = isStalled(assessBeat({ beat, ticked, now })) ? stallOwner(priorState, NAME) : null;
1234
1149
  return { ledger, issues, prs, merged, ci, prev, repo, repoUrl, workspace, port, spend, beat, ticked, stallOwner: stallOwnerOf, poolOk,
1235
1150
  poolCapped, prsCapped,
1236
- now, interval: interval ?? argInterval() ?? 15 };
1151
+ now, interval };
1237
1152
  }
1238
1153
 
1239
1154
  async function main() {
@@ -1274,15 +1189,11 @@ async function main() {
1274
1189
  // falling through to the usage die below — the same precedence the
1275
1190
  // sweep note above claims for a stray, now true of these two guards as
1276
1191
  // well. Both orderings are pinned in the board tests; before this fix the
1277
- // no-subcommand shape printed the usage line (measured). The return values are
1278
- // deliberately discarded on the build path: build has no server to bind or
1279
- // browser to open, so a WELL-FORMED --port/--open still does nothing here,
1280
- // exactly like before this fix — only the malformed spellings now refuse.
1281
- // serve() below still calls its own argPort()/has("open"); re-evaluating a
1282
- // pure read of argv costs nothing and keeps the EXPORTED serve() validating
1283
- // its own argv for a caller that skips main(). Nothing in this repo is such
1284
- // a caller today — every serve() test drives the real CLI, which enters
1285
- // main() — but serve() is public surface, so the guard stays with it.
1192
+ // no-subcommand shape printed the usage line (measured). The values reach
1193
+ // serve() alone: build has no server to bind or browser to open, so a
1194
+ // WELL-FORMED --port/--open still does nothing there, exactly like before
1195
+ // this fix — only the malformed spellings now refuse. serve() reads no argv
1196
+ // of its own; these reads are the only ones.
1286
1197
  // --prev: unlike --port/--open (never read on `build` before they were hoisted) or
1287
1198
  // --ledger/--spend-since/--interval (already read on `build`, per the
1288
1199
  // header comment above), --prev was read on exactly one subcommand and it
@@ -1300,8 +1211,8 @@ async function main() {
1300
1211
  // gather() exactly as before — discarded on serve, same as --port/--open
1301
1212
  // are discarded on build.
1302
1213
  const prevFile = arg("prev");
1303
- argPort();
1304
- has("open");
1214
+ const port = argPort();
1215
+ const open = has("open");
1305
1216
 
1306
1217
  // Same fail-open shape as --port/--open above — this closes
1307
1218
  // the two flags that hoisting left standing. `argInterval()`'s read had
@@ -1317,21 +1228,17 @@ async function main() {
1317
1228
  // --open x` / `build --spend-since --open x` likewise. Same fix, same
1318
1229
  // place: call both here, once, ahead of the build/serve dispatch and
1319
1230
  // ahead of both branches' own stray() call, exactly where
1320
- // argPort()/has("open") already sit — build discards both return values,
1321
- // same as it already discards argPort()'s. serve() below still calls its
1322
- // own argInterval() (via `interval ?? argInterval() ?? 15`) and gather()
1323
- // still calls its own argSpendSince() — re-evaluating a pure read of argv
1324
- // costs nothing, and keeps both validating their own argv for a caller
1325
- // that skips main(), same reasoning as for argPort()/has("open").
1326
- argInterval();
1327
- argSpendSince();
1231
+ // argPort()/has("open") already sit. These are now the only reads:
1232
+ // gather() and serve() take the resolved values, and the branch below that
1233
+ // runs hands them on.
1234
+ const interval = argInterval() ?? 15;
1235
+ const spendSince = argSpendSince();
1328
1236
  // `--spend-dir` joins them for the same two reasons, from the day it
1329
- // ships rather than one ticket later — it is read on both subcommands (in
1330
- // gather()'s default, and through serve()'s pin), and a trailing
1237
+ // ships rather than one ticket later — it reaches both subcommands (gather()
1238
+ // on build, the tick loop's pin on serve), and a trailing
1331
1239
  // `--spend-dir` ahead of a stray positional has to name itself instead of
1332
- // the token behind it. build discards the value here exactly as it discards
1333
- // argPort()'s; gather() below does the read that reaches the panel.
1334
- argSpendDir();
1240
+ // the token behind it.
1241
+ const spendDir = argSpendDir();
1335
1242
 
1336
1243
  // sweep() above only refuses a `--`-prefixed token; a bare or
1337
1244
  // single-dash stray alongside a valid subcommand (`build --ledger x junk`)
@@ -1378,18 +1285,110 @@ async function main() {
1378
1285
  // there.
1379
1286
  stateFile: stateFileIn(instance.stateDir),
1380
1287
  workspace: instance.workspace, port: instance.port,
1288
+ interval, spendDir, spendDirExplicit: spendDir != null, spendSince,
1381
1289
  }));
1382
1290
  console.log(JSON.stringify(model, null, 2));
1383
1291
  return;
1384
1292
  }
1385
1293
  if (cmd === "serve") {
1386
1294
  stray();
1387
- await serve({ ledgerFile });
1295
+ await serve({ port, interval, open, tick: await boardTick({ ledgerFile, interval, spendDir, spendSince }) });
1388
1296
  return;
1389
1297
  }
1390
1298
  die("usage: board.mjs build|serve [--ledger <path>] [--port N] [--interval N] [--open] [--spend-since <epoch-ms>] [--spend-dir <path>]");
1391
1299
  }
1392
1300
 
1301
+ // The tick serve() runs on its timer — gather() → computeBoard() → board.json —
1302
+ // built by main() and handed to serve(), which calls it with the port it bound
1303
+ // and the state directory, board.json path and workspace it resolved. serve()
1304
+ // owns the socket, the timer and the identity handshake; what a tick reads and
1305
+ // writes is owned here.
1306
+ //
1307
+ // The pin is built HERE, once, and read by every tick. Outside the returned
1308
+ // tick for the obvious reason — a pin rebuilt per tick is a pin in name only —
1309
+ // and ahead of serve()'s port loop because it costs nothing to carry:
1310
+ // spendDirPin() touches no filesystem until its first call, so the reuse and
1311
+ // degrade arms that exit before ticking pay nothing for it.
1312
+ async function boardTick({ ledgerFile, interval, spendDir, spendSince }) {
1313
+ const spendPin = spendDirPin(spendDir);
1314
+ const { computeBoard } = await import("./compute-board.mjs");
1315
+ // One tick at a time, and the flag is load-bearing rather than defensive.
1316
+ // The timer's callback used to be synchronous, so node could not start
1317
+ // a second tick while the first was still inside gather() — it just fired
1318
+ // late. An async tick has no such floor: a gather that outruns `interval`
1319
+ // (a `gh` outage riding out its own timeouts, an operator's `--interval 1`)
1320
+ // would let the timer stack ticks on top of each other, and each of those
1321
+ // reads `prevFile` at its start and renames over it at its end. Two in
1322
+ // flight means double the `gh` and `ci-state.mjs` children — the very load
1323
+ // that made the tick slow — and, worse, a LATER-started tick can finish
1324
+ // first and be overwritten by the older one's payload, walking every
1325
+ // ticket's dwell clock and carried-forward CI value backwards.
1326
+ //
1327
+ // SKIPPED, not queued: a tick recomputes the whole board from scratch, so
1328
+ // the one that would have been queued has nothing in it the next one does
1329
+ // not redo. Announced once per process through the same warn-once gate
1330
+ // every other repeating condition in this file uses — a board falling
1331
+ // behind its interval is worth saying, and worth saying only once.
1332
+ let ticking = false;
1333
+ // `served` is the port this process actually BOUND, handed in rather than
1334
+ // closed over: it is not knowable until listen() returns (--port 0 is an
1335
+ // ephemeral bind, and serve()'s port loop may also land past a
1336
+ // candidate it could not take), and a tick that reached for the port asked
1337
+ // for instead would stamp every board served on an ephemeral port with a
1338
+ // `port: 0` no browser could ever reach. A parameter makes that
1339
+ // unreachable rather than merely unlikely — there is no earlier value in
1340
+ // scope for it to pick up.
1341
+ return async ({ served, stateDir, jsonPath, workspace }) => {
1342
+ if (ticking) {
1343
+ warnOnce("tick-overlap", String(interval),
1344
+ `a board tick is still running after ${interval}s; skipping this one — the board will be older than its interval until the reads it is waiting on return`);
1345
+ return;
1346
+ }
1347
+ ticking = true;
1348
+ try {
1349
+ // The identity a second launch's handshake reads off this
1350
+ // cockpit. It rides the board payload deliberately, rather than a
1351
+ // lockfile or a second endpoint: a payload exists only while the
1352
+ // process serving it does, so nothing written here can outlive this
1353
+ // cockpit and send the next launch at a port nobody holds. It is null
1354
+ // on the degrade arm — no workspace was established — which is exactly
1355
+ // the value no launch may ever match on.
1356
+ //
1357
+ // Joined at gather(), not stamped onto the finished model. The
1358
+ // assignment that used to sit below this line wrote a field the pure
1359
+ // model did not declare, so `build` printed a board with no identity
1360
+ // at all and only the served copy carried one.
1361
+ const model = computeBoard(await gather({
1362
+ // The ledger's own default (ledger.mjs's defaultLedgerPath()) is
1363
+ // never reached here — board.mjs always passes an explicit --file — so an
1364
+ // absent --ledger has to be defaulted against the SAME instance the state
1365
+ // directory came from, not a cwd-relative literal. A worktree or a
1366
+ // subdirectory cwd previously left this pointing at a ledger.md that does
1367
+ // not exist there, while the state directory had already moved to
1368
+ // the workspace: the board and the ledger could disagree about which run
1369
+ // they belonged to, exactly what resolveCockpitInstance() exists to rule
1370
+ // out.
1371
+ ledgerFile: ledgerFile || join(stateDir, "ledger.md"), prevFile: jsonPath, interval,
1372
+ // Beside the ledger and out of the same state directory, so
1373
+ // the board, the ledger and the heartbeat cannot disagree about which
1374
+ // run they belong to — the invariant resolveCockpitInstance() exists
1375
+ // for. Re-derived per tick rather than closed over, exactly like
1376
+ // the ledger default: a pure join on a directory settled at bind time.
1377
+ stateFile: stateFileIn(stateDir),
1378
+ workspace, port: served,
1379
+ // The pinned transcript directory, not a fresh lookup: every tick after
1380
+ // the first gets the SAME answer, which is what stops the panel
1381
+ // alternating between two sessions under one project directory.
1382
+ spendDir: spendPin(), spendDirExplicit: spendDir != null, spendSince,
1383
+ }));
1384
+ const tmp = `${jsonPath}.tmp`;
1385
+ writeFileSync(tmp, JSON.stringify(model)); // atomic: write tmp, rename over target
1386
+ renameSync(tmp, jsonPath);
1387
+ } catch (e) { console.error(`${NAME}: build tick failed: ${e.message}`); }
1388
+ finally { ticking = false; }
1389
+ };
1390
+ }
1391
+
1393
1392
  import { copyFileSync, mkdirSync } from "node:fs";
1394
1393
 
1395
1394
  // The names a browser on this machine can legitimately put in `Host` to reach
@@ -1778,17 +1777,16 @@ export function probeCockpitWorkspace(port, timeoutMs = PROBE_TIMEOUT_MS) {
1778
1777
  });
1779
1778
  }
1780
1779
 
1781
- export async function serve({ ledgerFile, port, interval, open, spendDir } = {}) {
1780
+ export async function serve({ port: portGiven, interval, open, tick }) {
1782
1781
  // Both the served state directory and the port come from
1783
1782
  // resolveCockpitInstance() now, rather than a cwd-relative `.fleet` and a
1784
1783
  // constant 8123. That is what lets two workspaces run two boards at once
1785
1784
  // without either writing into the other's state directory, and it ties the
1786
1785
  // board to the same workspace the ledger resolves itself against.
1787
1786
  //
1788
- // A GIVEN-but-invalid --port is refused outright by argPort() and never
1789
- // reaches here; an ABSENT one leaves `portGiven` nullish, which is how the
1790
- // seam is told to derive rather than obey. `??` and not `||`:
1791
- // --port 0 is a legal ephemeral bind and `||` would discard it.
1787
+ // A GIVEN-but-invalid --port is refused outright in main() and never
1788
+ // reaches here; an ABSENT one arrives as `portGiven` null, which is how the
1789
+ // seam is told to derive rather than obey.
1792
1790
  //
1793
1791
  // A bind failure no longer means one thing, so the two kinds of port part
1794
1792
  // company here. One this script DERIVED is negotiable: the loop below
@@ -1799,100 +1797,9 @@ export async function serve({ ledgerFile, port, interval, open, spendDir } = {})
1799
1797
  // them apart is `instance.derived` and not truthiness on `portGiven`: an
1800
1798
  // explicit `--port 0` is falsy (a legal ephemeral bind), so the old
1801
1799
  // spelling gave it the derived port's treatment, and nothing pinned that.
1802
- const portGiven = port ?? argPort();
1803
- interval = interval ?? argInterval() ?? 15;
1804
- open = open ?? has("open");
1805
- // Built HERE, once, and read by every tick below. Beside the other
1806
- // argv reads rather than inside tick() for the obvious reason — a pin rebuilt
1807
- // per tick is a pin in name only — and above the port loop because it costs
1808
- // nothing to carry: spendDirPin() touches no filesystem until its first call,
1809
- // so the reuse and degrade arms that exit before ticking pay nothing for it.
1810
- // `spendDir ?? argSpendDir()`, matching the `port ?? argPort()`
1811
- // shape above: every other argv-read option here takes an in-process
1812
- // override, and this one hadn't, so the only way to drive --spend-dir
1813
- // through `serve` at all was the real CLI — no test exercised it.
1814
- const spendPin = spendDirPin(spendDir ?? argSpendDir());
1815
- const { computeBoard } = await import("./compute-board.mjs");
1816
1800
  const instance = resolveCockpitInstance({ cwd: process.cwd(), ...cockpitWorkspace(process.cwd()), port: portGiven });
1817
1801
  const stateDir = instance.stateDir;
1818
1802
  const jsonPath = join(stateDir, "board.json");
1819
- // The ledger's own default (ledger.mjs's defaultLedgerPath()) is
1820
- // never reached here — board.mjs always passes an explicit --file — so an
1821
- // absent --ledger has to be defaulted against the SAME instance the state
1822
- // directory came from, not a cwd-relative literal. A worktree or a
1823
- // subdirectory cwd previously left this pointing at a ledger.md that does
1824
- // not exist there, while the state directory (above) had already moved to
1825
- // the workspace: the board and the ledger could disagree about which run
1826
- // they belonged to, exactly what resolveCockpitInstance() exists to rule
1827
- // out.
1828
- ledgerFile = ledgerFile || join(stateDir, "ledger.md");
1829
- // `served` is the port this process actually BOUND, handed in rather than
1830
- // closed over: it is not knowable until listen() returns (--port 0 is an
1831
- // ephemeral bind, and the loop below may also land past a
1832
- // candidate it could not take), and a tick that reached for `portGiven`
1833
- // instead would stamp every board served on an ephemeral port with a
1834
- // `port: 0` no browser could ever reach. A parameter makes that
1835
- // unreachable rather than merely unlikely — there is no earlier value in
1836
- // scope for it to pick up.
1837
- // One tick at a time, and the flag is load-bearing rather than defensive.
1838
- // The timer's callback used to be synchronous, so node could not start
1839
- // a second tick while the first was still inside gather() — it just fired
1840
- // late. An async tick has no such floor: a gather that outruns `interval`
1841
- // (a `gh` outage riding out its own timeouts, an operator's `--interval 1`)
1842
- // would let the timer stack ticks on top of each other, and each of those
1843
- // reads `prevFile` at its start and renames over it at its end. Two in
1844
- // flight means double the `gh` and `ci-state.mjs` children — the very load
1845
- // that made the tick slow — and, worse, a LATER-started tick can finish
1846
- // first and be overwritten by the older one's payload, walking every
1847
- // ticket's dwell clock and carried-forward CI value backwards.
1848
- //
1849
- // SKIPPED, not queued: a tick recomputes the whole board from scratch, so
1850
- // the one that would have been queued has nothing in it the next one does
1851
- // not redo. Announced once per process through the same warn-once gate
1852
- // every other repeating condition in this file uses — a board falling
1853
- // behind its interval is worth saying, and worth saying only once.
1854
- let ticking = false;
1855
- const tick = async (served) => {
1856
- if (ticking) {
1857
- warnOnce("tick-overlap", String(interval),
1858
- `a board tick is still running after ${interval}s; skipping this one — the board will be older than its interval until the reads it is waiting on return`);
1859
- return;
1860
- }
1861
- ticking = true;
1862
- try {
1863
- // The identity a second launch's handshake reads off this
1864
- // cockpit. It rides the board payload deliberately, rather than a
1865
- // lockfile or a second endpoint: a payload exists only while the
1866
- // process serving it does, so nothing written here can outlive this
1867
- // cockpit and send the next launch at a port nobody holds. It is null
1868
- // on the degrade arm — no workspace was established — which is exactly
1869
- // the value no launch may ever match on.
1870
- //
1871
- // Joined at gather(), not stamped onto the finished model. The
1872
- // assignment that used to sit below this line wrote a field the pure
1873
- // model did not declare, so `build` printed a board with no identity
1874
- // at all and only the served copy carried one.
1875
- const model = computeBoard(await gather({
1876
- ledgerFile, prevFile: jsonPath, interval,
1877
- // Beside the ledger and out of the same state directory, so
1878
- // the board, the ledger and the heartbeat cannot disagree about which
1879
- // run they belong to — the invariant resolveCockpitInstance() exists
1880
- // for. Re-derived per tick rather than closed over, exactly like
1881
- // `ledgerFile`: it is a pure join on a directory settled at bind time.
1882
- stateFile: stateFileIn(stateDir),
1883
- workspace: instance.workspace, port: served,
1884
- // The pinned transcript directory, not a fresh lookup: every tick after
1885
- // the first gets the SAME answer, which is what stops the panel
1886
- // alternating between two sessions under one project directory.
1887
- spendDir: spendPin(),
1888
- }));
1889
- const tmp = `${jsonPath}.tmp`;
1890
- writeFileSync(tmp, JSON.stringify(model)); // atomic: write tmp, rename over target
1891
- renameSync(tmp, jsonPath);
1892
- } catch (e) { console.error(`${NAME}: build tick failed: ${e.message}`); }
1893
- finally { ticking = false; }
1894
- };
1895
-
1896
1803
  // A held port used to mean three different things this loop could
1897
1804
  // only tell apart by binding first and probing whichever candidate
1898
1805
  // happened to refuse — so a live cockpit that landed past a squatter
@@ -1905,7 +1812,7 @@ export async function serve({ ledgerFile, port, interval, open, spendDir } = {})
1905
1812
  // Bind stays ahead of any handshake per candidate — only heldFailure()'s
1906
1813
  // bare connect precedes it: that is what lets two launches racing at start
1907
1814
  // settle on one winner quickly, the winner's identity published (below)
1908
- // before it can block inside its own gather().
1815
+ // before it can block inside its own first tick.
1909
1816
  // But a successful bind is not the end of the story — once this process
1910
1817
  // holds a candidate, the REST of the window still gets checked for a
1911
1818
  // live cockpit that landed further along, exactly the shape a departed
@@ -2001,14 +1908,14 @@ export async function serve({ ledgerFile, port, interval, open, spendDir } = {})
2001
1908
  console.error(`${NAME}: cockpit on http://${COCKPIT_HOST}:${bound} (interval ${interval}s)`);
2002
1909
 
2003
1910
  // Publish identity the instant this port is ours — before the
2004
- // first tick, which is the one that can be slow (gather() shells out to
1911
+ // first tick, which is the one that can be slow (its gather shells out to
2005
1912
  // gh and ledger.mjs). A sibling launch races this one by sending its
2006
1913
  // probe as soon as ITS bind attempt refuses, which can be well before
2007
- // this process's first gather() ever returns; the answer that probe needs
1914
+ // this process's first tick ever returns; the answer that probe needs
2008
1915
  // has to already be on disk, not waiting on a compute this process has
2009
1916
  // not started yet.
2010
1917
  // `port` rides along. This stub is a board payload like any other
2011
- // for as long as the first gather() takes, and a reader that finds it —
1918
+ // for as long as the first tick takes, and a reader that finds it —
2012
1919
  // the operator, a script, the page — gets the same two identity fields
2013
1920
  // from it that every later tick writes. The handshake above still reads
2014
1921
  // only `workspace`.
@@ -2016,7 +1923,7 @@ export async function serve({ ledgerFile, port, interval, open, spendDir } = {})
2016
1923
  renameSync(`${jsonPath}.tmp`, jsonPath);
2017
1924
  // Yield once so a connection already arriving — that same sibling's probe —
2018
1925
  // gets a chance to read the identity just written before this process starts
2019
- // the first tick. The tick no longer blocks the loop, but gather()
1926
+ // the first tick. The tick no longer blocks the loop, but its gather
2020
1927
  // still opens with a synchronous prev-board read before its first await, and
2021
1928
  // a turn of the loop costs nothing.
2022
1929
  await new Promise((resolve) => setImmediate(resolve));
@@ -2025,9 +1932,10 @@ export async function serve({ ledgerFile, port, interval, open, spendDir } = {})
2025
1932
  // below it — the timer, and the two signal handlers that are the only way
2026
1933
  // this process is ever asked to stop — must be in place before it returns,
2027
1934
  // not after. Nothing here rejects; tick() catches its own faults and the
2028
- // `ticking` flag it sets is cleared in a finally.
2029
- tick(bound);
2030
- const timer = setInterval(() => tick(bound), interval * 1000);
1935
+ // `ticking` flag it sets is cleared in a finally (see boardTick()).
1936
+ const tickArgs = { served: bound, stateDir, jsonPath, workspace: instance.workspace };
1937
+ tick(tickArgs);
1938
+ const timer = setInterval(() => tick(tickArgs), interval * 1000);
2031
1939
 
2032
1940
  const stop = () => {
2033
1941
  clearInterval(timer);
@@ -813,7 +813,7 @@ export function deriveRun({ rows, dispatched, drain }, prs, closed = new Set(),
813
813
  && !fixRunning(st) && !st.inFlight)
814
814
  .map(([n]) => n).sort(asc),
815
815
  // Open, not signed off, closing an issue (GitHub's own linked set — a
816
- // chore PR closing nothing is review work nobody in the run will ever be
816
+ // PR closing nothing is review work nobody in the run will ever be
817
817
  // dispatched against), with no live or returned review on record —
818
818
  // or a returned review its finisher halted `past-pin` against: the
819
819
  // head carries commits no reviewer read, so it is owed a review again
@@ -26,18 +26,20 @@
26
26
  // Explicit `-uall`, never bare `--porcelain`: `status.showUntrackedFiles=no`
27
27
  // silences untracked files otherwise.
28
28
  //
29
- // THE RUN'S OWN BOOKKEEPING IS NOT A STRAY WRITE. Two tracked files in the
29
+ // THE RUN'S OWN BOOKKEEPING IS NOT A STRAY WRITE. Three tracked files in the
30
30
  // main checkout are written by the controller itself mid-run:
31
31
  // `docs/metrics/tier-outcomes.tsv`, appended each time it rules a PR's review
32
- // (run-team/SKILL.md, `tier-outcomes.mjs append`), and
33
- // `docs/metrics/member-outcomes.tsv`, rewritten by the member-facts scrape.
32
+ // (run-team/SKILL.md, `tier-outcomes.mjs append`),
33
+ // `docs/metrics/member-outcomes.tsv`, rewritten by the member-facts scrape, and
34
+ // `docs/metrics/ticket-features.tsv`, which `metrics-refresh.mjs` drains the
35
+ // pending Pull rows into at phase 0 and again at close-out.
34
36
  // Compared like any other path, the first append would hold every
35
37
  // dispatching row for the rest of the run, and clearing it with `--record`
36
38
  // after every ruling would certify whatever stray write landed beside it.
37
- // So `snapshot()` leaves exactly those two paths out, for the reason
38
- // instruments.sh leaves `docs/metrics/` out of its pin. Two named files, not
39
+ // So `snapshot()` leaves exactly those three paths out, for the reason
40
+ // instruments.sh leaves `docs/metrics/` out of its pin. Three named files, not
39
41
  // the directory: anything else under `docs/metrics/` is still a stray write.
40
- // The price: a member's leaked write to one of those two files goes unseen.
42
+ // The price: a member's leaked write to one of those three files goes unseen.
41
43
  //
42
44
  // FOUR ANSWERS, worktree-audit.sh's three plus the baseline's own refusal:
43
45
  // clean — the porcelain entries and hashes equal the baseline's.
@@ -81,7 +83,7 @@ import { gitEnv, workspaceDirFromGitCommonDir } from "./git-env.mjs";
81
83
 
82
84
  export const BASELINE_FILE = "main-checkout.sha";
83
85
  export const RECORD_COMMAND = "~/.fleet/bin/fleet-run main-checkout.mjs --record";
84
- const RUN_BOOKKEEPING = new Set(["docs/metrics/tier-outcomes.tsv", "docs/metrics/member-outcomes.tsv"]);
86
+ const RUN_BOOKKEEPING = new Set(["docs/metrics/tier-outcomes.tsv", "docs/metrics/member-outcomes.tsv", "docs/metrics/ticket-features.tsv"]);
85
87
  const HEADER = "fleet main-checkout baseline v1";
86
88
  const GIT_TIMEOUT_MS = 30_000;
87
89
  const MAX_BUFFER = 64 * 1024 * 1024;
@@ -0,0 +1,122 @@
1
+ #!/usr/bin/env node
2
+ // The run's two metrics duties that keep the router's inputs current: move the
3
+ // pending ticket-features rows into the tracked corpus, then refresh the cost
4
+ // guard over it.
5
+ //
6
+ // metrics-refresh.mjs [--repo <dir>]
7
+ //
8
+ // --repo the workspace whose `.fleet/` and `docs/metrics/` the duties read
9
+ // and write; default the main checkout of the repository the cwd is
10
+ // in, where the router script appends its pending rows
11
+ //
12
+ // DRAIN. `ticket-router.mjs route` appends one row per Pull to
13
+ // `.fleet/ticket-features.pending.tsv`; this moves them into
14
+ // `docs/metrics/ticket-features.tsv`, deduped on `session` + `agent`, and
15
+ // deletes the pending file. A crash between the write and the delete leaves
16
+ // rows the next drain finds already there, so a second run changes nothing.
17
+ //
18
+ // COST GUARD. `pr-cost.mjs --guard` rewrites `.fleet/cost-guard.json`, which
19
+ // the router reads and fails closed without. It needs all three metrics TSVs;
20
+ // a workspace that lacks one has no corpus to guard yet (its first run), so the
21
+ // guard is skipped with a line naming the missing file and
22
+ // `.fleet/cost-guard.json` is left as it is. Its exit 3 (a cell tripped) and 4
23
+ // (no verdict yet — the baseline cell has too few merged PRs) are verdicts the
24
+ // router and `fleet-tick.mjs` consume, not failures; any other non-zero exit is.
25
+ //
26
+ // One `metrics-refresh: <duty>: …` line per duty on stdout. Exit 0 when
27
+ // neither duty failed; 1 when one failed — named on stderr, and the duty after
28
+ // it did not run (each is safe to run again); 2 on a usage error.
29
+
30
+ import { spawnSync } from "node:child_process";
31
+ import { existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
32
+ import { dirname, join, resolve } from "node:path";
33
+ import { fileURLToPath } from "node:url";
34
+ import { makeDie, defineFlags } from "./arg.mjs";
35
+ import { gitEnv } from "./git-env.mjs";
36
+ import { FleetDirUnresolvable, fleetFile } from "./fleet-dir.mjs";
37
+ import { isCLI } from "./is-cli.mjs";
38
+ import { FEATURE_COLUMNS, parseFeatures } from "./pr-cost.mjs";
39
+
40
+ const NAME = "metrics-refresh";
41
+ const PR_COST = fileURLToPath(new URL("./pr-cost.mjs", import.meta.url));
42
+ const PENDING = join(".fleet", "ticket-features.pending.tsv");
43
+ const FEATURES = join("docs", "metrics", "ticket-features.tsv");
44
+ const CORPUS = [join("docs", "metrics", "member-outcomes.tsv"), join("docs", "metrics", "tier-outcomes.tsv"), FEATURES];
45
+ const GUARD = join(".fleet", "cost-guard.json");
46
+ // pr-cost.mjs --guard: 0 no cell tripped, 3 a cell tripped, 4 no verdict yet —
47
+ // all three are verdicts its readers consume; anything else is a failure.
48
+ const GUARD_VERDICT_EXITS = new Set([0, 3, 4]);
49
+ const MAX_BUFFER = 64 * 1024 * 1024;
50
+
51
+ const say = (line) => process.stdout.write(`${NAME}: ${line}\n`);
52
+ const headerOf = (text) => String(text).split("\n").find((l) => l.trim() && !l.startsWith("#")).split("\t");
53
+ const pullKey = (r) => `${r.session}\0${r.agent}`;
54
+
55
+ function drain(repo) {
56
+ const pending = join(repo, PENDING);
57
+ if (!existsSync(pending)) return say(`drain: nothing pending in ${PENDING}`);
58
+ const pendingText = readFileSync(pending, "utf8");
59
+ const incoming = parseFeatures(pendingText);
60
+ const target = join(repo, FEATURES);
61
+ let text = existsSync(target) ? readFileSync(target, "utf8") : `${FEATURE_COLUMNS.join("\t")}\n`;
62
+ const seen = new Set(parseFeatures(text).map(pullKey));
63
+ const header = headerOf(text);
64
+ const unknown = headerOf(pendingText).filter((c) => !header.includes(c));
65
+ if (unknown.length) throw new Error(`${PENDING} carries ${unknown.join(", ")}, which ${FEATURES} has no column for`);
66
+ const added = [];
67
+ for (const r of incoming) {
68
+ if (seen.has(pullKey(r))) continue;
69
+ seen.add(pullKey(r));
70
+ added.push(header.map((c) => r[c] ?? "").join("\t"));
71
+ }
72
+ if (added.length) {
73
+ if (!text.endsWith("\n")) text += "\n";
74
+ mkdirSync(dirname(target), { recursive: true });
75
+ writeFileSync(`${target}.tmp`, `${text}${added.join("\n")}\n`);
76
+ renameSync(`${target}.tmp`, target);
77
+ }
78
+ unlinkSync(pending);
79
+ say(`drain: ${added.length} row${added.length === 1 ? "" : "s"} from ${PENDING} into ${FEATURES} (${incoming.length - added.length} already there)`);
80
+ }
81
+
82
+ function costGuard(repo) {
83
+ const missing = CORPUS.filter((f) => !existsSync(join(repo, f)));
84
+ if (missing.length) return say(`cost guard: skipped, ${missing.join(", ")} not found — no corpus to guard yet; ${GUARD} left as it is`);
85
+ const out = join(repo, GUARD);
86
+ const r = spawnSync(process.execPath, [PR_COST, "--guard", "--out", out], {
87
+ cwd: repo, encoding: "utf8", env: gitEnv(), maxBuffer: MAX_BUFFER,
88
+ });
89
+ if (!GUARD_VERDICT_EXITS.has(r.status)) {
90
+ throw new Error(`pr-cost.mjs --guard exited ${r.error?.code ?? r.status ?? r.signal}: ${String(r.stderr ?? "").trim()}`);
91
+ }
92
+ const g = JSON.parse(readFileSync(out, "utf8"));
93
+ const tripped = g.tripped.map((t) => (typeof t === "string" ? t : t?.cell));
94
+ say(`cost guard: verdict ${g.verdict}${tripped.length ? ` (tripped: ${tripped.join(", ")})` : ""}, pr-cost.mjs exit ${r.status}; ${GUARD} computed ${g.computed_at}`);
95
+ }
96
+
97
+ function main() {
98
+ const die = makeDie(NAME);
99
+ const F = defineFlags(die, { flags: { repo: "value" } });
100
+ F.sweep();
101
+ F.stray();
102
+ let repo = F.arg("repo") === null ? null : resolve(F.arg("repo"));
103
+ if (repo === null) {
104
+ try {
105
+ repo = dirname(fleetFile(null));
106
+ } catch (e) {
107
+ if (!(e instanceof FleetDirUnresolvable)) throw e;
108
+ die(`${e.message} — pass --repo <dir>`);
109
+ }
110
+ }
111
+ for (const [name, duty] of [["drain", drain], ["cost guard", costGuard]]) {
112
+ try {
113
+ duty(repo);
114
+ } catch (e) {
115
+ process.stderr.write(`${NAME}: ${name} failed: ${e.message}\n`);
116
+ process.exitCode = 1;
117
+ return;
118
+ }
119
+ }
120
+ }
121
+
122
+ if (isCLI(import.meta.url)) main();
@@ -276,9 +276,10 @@ phase, or in any later one, asks the maintainer which tickets to take.
276
276
  writes `member-write-guard` cannot see — an `eval` cell, a `bash` that
277
277
  `cd`s or `git -C`s into this checkout. `.fleet/`, `.worktrees/` and
278
278
  `.agent-brain/` are gitignored and never trip it. Nor does this run's own
279
- bookkeeping: `docs/metrics/tier-outcomes.tsv` and
280
- `docs/metrics/member-outcomes.tsv`, which you write mid-run, are left out
281
- by name — anything else under `docs/metrics/` still trips it. **The same
279
+ bookkeeping: `docs/metrics/tier-outcomes.tsv`,
280
+ `docs/metrics/member-outcomes.tsv` and `docs/metrics/ticket-features.tsv`,
281
+ which you write mid-run, are left out by name — anything else under
282
+ `docs/metrics/` still trips it. **The same
282
283
  command is the clear, and it overwrites; it never compares.** On `MAIN-CHECKOUT-DIRTY`
283
284
  the maintainer resolves the stray paths FIRST — inspect, keep or remove
284
285
  them — and only then re-runs `--record`; re-recording over unresolved paths
@@ -327,6 +328,23 @@ phase, or in any later one, asks the maintainer which tickets to take.
327
328
  there unnoticed because the only thing that ever read the live gate was a
328
329
  person choosing to.
329
330
 
331
+ **Drain the pending ticket-features rows and refresh the cost guard, after
332
+ the fast-forward and before the first Pull is routed.**
333
+ `~/.fleet/bin/fleet-run metrics-refresh.mjs` moves
334
+ `.fleet/ticket-features.pending.tsv` into `docs/metrics/ticket-features.tsv`,
335
+ deduped on `session`+`agent` — this recovers the rows of a run that crashed
336
+ before its close-out — and then runs `pr-cost.mjs --guard`, rewriting
337
+ `.fleet/cost-guard.json`, which the router reads and fails closed without
338
+ (no file: the default cell only). The guard has to be fresh before the
339
+ first Pull is routed, so the verdict reflects any rows just recovered. Exit
340
+ 0: both ran. The guard's own exit 3 (a cell tripped) and 4 (no verdict yet)
341
+ are verdicts the router and `fleet-tick.mjs` read, never failures; the
342
+ script absorbs them. A workspace that lacks one of the three metrics TSVs
343
+ has no corpus to guard yet — its first run: the script prints a line naming
344
+ the missing file, skips the guard and exits 0. Exit 1 or 2 stops the run
345
+ before its first Pull: report the line the script printed on stderr, fix
346
+ the cause and run it again — each duty is safe to repeat.
347
+
330
348
  **Launch the cockpit.** On every phase-0 pass, not just the first:
331
349
  `node ~/.fleet/bin/fleet-run board.mjs serve --open &` in the
332
350
  background. It is a read-only mirror of `.fleet/ledger.md` + `gh` — you never
@@ -453,15 +471,16 @@ phase, or in any later one, asks the maintainer which tickets to take.
453
471
  timed out. It is never a loop: no third derivation, and never a cache
454
472
  written by hand.
455
473
 
456
- **Fold in every PR a prior run left open, before shortlisting.** A chore PR
457
- carrying that run's own metrics, or ticket work whose review was deferred —
458
- both are reviewable work no member otherwise picks up, because the Shortlist
459
- holds ISSUES and nothing looks at inherited PRs. Queue each for review exactly as
460
- ticket work: same review workflow, same fix-applier, same finisher. Measured
461
- 2026-09-03 — a prior run's ticket PR arrived this way and its review found a defect its own PR
462
- body called unreviewed, and a chore PR's review then caught two metrics rows the
463
- controller had missed in its own close-out, so a chore PR is not exempt from
464
- being wrong. Reviewing them next run is also what stops one pinning
474
+ **Fold in every PR a prior run left open, before shortlisting.** However it
475
+ is named and whatever it carries — ticket work whose review was deferred, or
476
+ that run's own metrics — it is reviewable work no member otherwise picks up,
477
+ because the Shortlist holds ISSUES and nothing looks at inherited PRs. Queue
478
+ each for review exactly as ticket work: same review workflow, same
479
+ fix-applier, same finisher. Measured 2026-09-03 — a prior run's ticket PR
480
+ arrived this way and its review found a defect its own PR body called
481
+ unreviewed, and a metrics PR's review then caught two metrics rows the
482
+ controller had missed in its own close-out, so no PR is exempt from being
483
+ wrong. Reviewing them next run is also what stops one pinning
465
484
  `fleet-tick`'s backlog forever: unreviewable AND uncounted is the state
466
485
  that strands it.
467
486
 
@@ -1396,27 +1415,35 @@ why in `note`.
1396
1415
  Each WARNING names a PR this run's ledger marks `reviewed=` that has no row yet
1397
1416
  — append it before committing if it is an implementer PR.
1398
1417
 
1399
- Both files are the run's own artifacts and neither commits itself. Carry them to
1400
- main the same way the run carries any other controller-authored change; leaving a
1401
- regenerated 5,000-row corpus uncommitted in the checkout is how it gets discarded by
1402
- the next `git checkout` with nothing to show it ever ran.
1403
-
1404
- **Commit both to `chore/run-artifacts-<date>` and open a PR — at end of run, and
1405
- that branch name is the convention rather than a suggestion.** Phase 0's
1406
- fast-forward step calls this the previous run's close-out PR and says the rules
1407
- THIS run needs arrive in it, so the next controller goes looking for it by shape;
1408
- a name of your own invention still merges and still cannot be found. Suffix a
1409
- letter when the date already has one (`chore/run-artifacts-2026-08-23b`).
1410
-
1411
- **Data rows and rule-doc prose never share a PR — one branch each, and when the
1412
- rules here compete this is the one to keep.** The two halves have opposite cost
1413
- profiles, and bundling makes the cheap-to-strand half gate the expensive one.
1414
- Stranding a data row loses it: `member-outcomes.tsv` is regenerated from harness
1415
- transcripts this repo does not own, so re-running the scrape later is worth only
1416
- what the harness still holds. Stranding a rule change costs the status quo, which
1417
- is where it already was. So `chore/run-artifacts-<date>` carries the two
1418
- `docs/metrics/` files and nothing else, and prose that wants review goes on its
1419
- own branch with its own PR.
1418
+ **Drain the pending ticket-features rows and refresh the cost guard, after
1419
+ the member-outcomes scrape and every `tier-outcomes.mjs append`, before the
1420
+ metrics files are committed.** `~/.fleet/bin/fleet-run metrics-refresh.mjs`
1421
+ moves `.fleet/ticket-features.pending.tsv` — the row the router script
1422
+ appended for each Pull at dispatch — into `docs/metrics/ticket-features.tsv`,
1423
+ deduped on `session`+`agent`, so this run's own rows are in the file that gets
1424
+ committed; that file is a run artifact too and is committed with the other
1425
+ two. It then runs `pr-cost.mjs --guard`, which rewrites
1426
+ `.fleet/cost-guard.json` from all three files. Exit 0: both ran. The guard's
1427
+ own exit 3 (a cell tripped) and 4 (no verdict yet, baseline too thin) are
1428
+ verdicts the router and `fleet-tick.mjs` read, never failures; the script
1429
+ absorbs them. Exit 1 names the duty that failed on stderr and the duty after it
1430
+ did not run; exit 2 is a usage error. At close-out a failure is reported to the
1431
+ maintainer and does not stop the commit — the pending file stays in `.fleet/`
1432
+ and the next run's phase-0 pass drains it — but never commit the metrics files
1433
+ with a drain that failed claiming the corpus is complete.
1434
+
1435
+ The metrics files are the run's own artifacts and none commits itself. Carry
1436
+ them to main the same way the run carries any other controller-authored change;
1437
+ leaving a regenerated 5,000-row corpus uncommitted in the checkout is how it gets
1438
+ discarded by the next `git checkout` with nothing to show it ever ran.
1439
+
1440
+ **Commit the metrics files and open a PR — at end of run.** The branch name is
1441
+ the repository's choice. A PR still open when the run ends is one phase 0's
1442
+ fold-in queues for review next run, however it is named, so the files reach
1443
+ `main` through the same review as ticket work rather than being lost. Stranding
1444
+ a data row loses it: `member-outcomes.tsv` is regenerated from harness
1445
+ transcripts the fleet does not own, so re-running the scrape later is worth
1446
+ only what the harness still holds.
1420
1447
 
1421
1448
  **Why not decide inside one run.** A run holds 2-3 implementer PRs, and ticket
1422
1449
  difficulty swamps the tier effect — a gojq parity harness and a two-statement
@@ -3578,20 +3605,20 @@ where the controller itself runs from.
3578
3605
  (**Resolving a finisher halt**) — and it
3579
3606
  prints them as `review-due=`. Exact, not a wider read: the ledger records
3580
3607
  which PRs are under review or reviewed, so nothing about it is guesswork. The
3581
- closing-issue test is what keeps it from widening: a chore PR you author
3582
- yourself closes nothing and is left unlabelled for the maintainer, so no
3583
- member of the fleet will ever review it, and counting it floors the backlog at
3584
- a depth nothing in the run can drain — the implementer gate then holds for the
3585
- rest of the run against a queue of nothing. GitHub's own linked-issue
3586
- set decides that, not a keyword regex over the body.
3587
- **That exemption is for the chore PR THIS run
3588
- authors, never one a PRIOR run left open** — step 0 folds those into this
3589
- run's review queue, so count one when you reason about backlog BY HAND. **The
3590
- `fleet-tick.mjs` number still excludes it**: nothing in its filter
3591
- distinguishes an inherited chore PR from this run's own, since a PR closing no
3592
- issue fails the closing-issue test either way — folding one in cannot reach
3593
- the count. So the by-hand judgement and the script's output differ here, and
3594
- such a PR's review is dispatched by hand.
3608
+ closing-issue test is what keeps it from widening: a PR that closes no issue
3609
+ — one you author yourself, for instance — is left unlabelled for the
3610
+ maintainer, so no member of the fleet will ever review it, and counting it
3611
+ floors the backlog at a depth nothing in the run can drain — the implementer
3612
+ gate then holds for the rest of the run against a queue of nothing.
3613
+ GitHub's own linked-issue set decides that, not a keyword regex over the body.
3614
+ **That exemption is for a PR THIS run authors, never one a PRIOR run left
3615
+ open** — step 0 folds those into this run's review queue, so count one when
3616
+ you reason about backlog BY HAND. **The `fleet-tick.mjs` number still
3617
+ excludes it**: nothing in its filter distinguishes an inherited PR from this
3618
+ run's own, since a PR closing no issue fails the closing-issue test either
3619
+ way — folding one in cannot reach the count. So the by-hand judgement and
3620
+ the script's output differ here, and such a PR's review is dispatched by
3621
+ hand.
3595
3622
 
3596
3623
  **Defaults: 2 implementers, 6 reviewers — no hard cap on either.** Reviewer
3597
3624
  slots in use ≈ I·(T_review + 0.94·T_fix)/T_impl ≈ 1.95·I (medians since
@@ -3667,12 +3694,12 @@ A starved implementer queue never stalls the review or merge side.
3667
3694
  **The run's own artifact PR is exempt, and it is exempt because this invariant
3668
3695
  does not reach it:** what the line forbids is a fleet member signing off its own
3669
3696
  ticket work, which presupposes an issue, an implementer, a `review-pr` run and a
3670
- finisher, and the data-only close-out PR you author has none of them. Label and
3697
+ finisher, and the metrics PR you author has none of them. Label and
3671
3698
  merge that one yourself instead of re-deriving a blocker from this line and
3672
3699
  stranding the rows behind it. The exemption belongs to the run that authors the
3673
3700
  PR and does not outlive it: one still open when the run ends is a PR a prior run
3674
3701
  left open, which phase 0 folds into the next run's review queue as ticket work —
3675
- and a chore PR is not exempt from being wrong, only from waiting on a reviewer
3702
+ and a PR is not exempt from being wrong, only from waiting on a reviewer
3676
3703
  no phase of this run will ever dispatch against it.
3677
3704
  - **Every member acts through the maintainer's `gh` credentials, so no write is
3678
3705
  attributable.** Any invariant about *who* did something is unenforceable after