@feigi/fleet-ctl 3.35.5 → 3.35.7

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.
@@ -12,7 +12,7 @@ argument-hint: [pr-number]
12
12
  **Write every ruling to `<scratch>/dispositions-<your name>.json`, `<your name>` the `fix-pr-<pr>[-x]` you were dispatched as (standalone, `fix-pr-<pr>`) — the disposition record `dispositions-check.mjs` judges against the review result file before any finisher is dispatched.** It is `{"head": "<the review file's head>", "run": "<the run root's name in the review path>", "entries": [ … ]}` — `run` the `<run>` of the review path your prompt names, which the check holds against the one the PR's latest `reviewed=` names, so a record written against an earlier review of the same PR, a same-head one included, is a mismatch (standalone, with no ledger naming a run, leave it out): one entry per `survived` finding and per `unverified` finding, plus one per `refuted` finding you reverse. Each entry carries `bucket` (`survived|unverified|refuted`), `index` (its position in that bucket of the review file — stable, since a round's file never changes), `scope` (`in|out`), `claimKind` (`behavior|shape`) and `disposition` (`apply|defer`), and where they apply `reason`, `issue` (the number you filed it to or commented on), `verdictPath` (an in-scope suggestion's refuter verdict file) and `remedyFiles` (the files its remedy names). A `refuted` entry carries `scope`, `claimKind` and `disposition` like every other entry, and a non-empty `reason` holding the evidence that reverses it; a missing or blank `reason` is a mismatch. The check reads scope off the diff before it reads your entry: a finding with no `line`, or on a line `git diff` touches from the PR's merge-base with `origin/main` to the review's `head`, is in scope whatever `scope` says, and only otherwise does the declared one stand. An in-scope `survived` finding deferred passes only with `reason` `false-rationale`, `mutual-exclusion`, `remedy-worse` or `remedy-outside-diff`. `remedy-outside-diff` — the remedy would edit a file the PR's diff does not touch — also needs `remedyFiles` to name at least one file absent from `git diff` from that merge-base to the review's `head`: none named, or every one in that diff, is a mismatch. A `critical` or `important` finding deferred for it goes to a human instead of passing: the script exits 1 with verdict `escalate`, `ledger.mjs dispatch` refuses the PR's finisher, and nothing retries it; a `suggestion` deferred for it passes. Any other reason, none, or a `survived` or `unverified` finding with no entry is a mismatch: the script exits 1 naming each violating entry's bucket, index and rule, and `ledger.mjs dispatch` refuses the PR's finisher. `disposition` has no `dismiss`: an in-scope `survived` finding verified correct, needing no change, is deferred with `reason` `false-rationale` and filed on the closed suggestion-band record — step 5's `PR #<pr> review: the suggestion band, checked`.
13
13
  3. **Run `testCmd` before you commit**, from the worktree, copied verbatim — not a runner you picked. `testCmd` is the command your dispatcher handed you; **standalone, with no dispatcher to hand you one, it is the repo's own test command**, the Test entrypoint in the repo's Recipe cache (`derive-testcmd.sh <repo> test` prints it). Read it off the repo, never invent one: "not a runner you picked" is what this step forbids, and on the standalone path nothing else defines the referent. With no usable Recipe cache (`derive-testcmd.sh` refuses), run the Recipe derivation step first — dispatch a `task` member, agent `fleet-recipe-deriver`, its prompt naming the main checkout's absolute path as `<repo>` and a scratch directory of its own; it proves both commands in a throwaway worktree and writes the cache only on proof, and its `RECIPE NOT PROVEN` is a stop, reported with its reason. Never fall back to a runner of your own choosing. `tests 0` is a FAILED run, not a pass: a glob matching nothing still exits 0. **Zero is not the only no-work count.** A run reporting **0 passes with no failures** skipped everything it collected, and a count **materially below the whole suite** means you ran a partial tree — this suite reported `tests 937` when this line was written, so compare what you get against a full run rather than against zero. The number drifts; that is the safe direction, because a stale one produces a loud false red while its absence produces a silent false green. Red, zero-test, or either no-work count → fix it or move the finding to defer; never commit over it. Then commit and push — `git push origin HEAD:<branch>`, the explicit refspec: this step also runs from a `--detach` worktree (`run-team/SKILL.md`'s worktree-recreation form), where a bare `git push` exits 128 (`fatal: You are not currently on a branch`) and any push whose destination is `HEAD` rather than a full or branch refname (`-u` or not, forced or not) exits 1 (`error: The destination you provided is not a full refname`) — and report the test result alongside the SHA. **Then reconcile the PR body with what you actually did.** It merges into the permanent record and nothing downstream re-derives it: your commit messages are yours to fix and usually get fixed, the body is neither. Removing a change, or reversing one, leaves the body asserting work the diff no longer contains. Measured twice in one run — one body kept asserting a calibration its own fix had just deleted as false, another kept claiming a hunk the fix had removed as "this diff owns it" — both caught by a finisher's reading rather than by any rule, and both would otherwise have merged intact. `gh pr edit <pr> --body-file <path>`, and re-read the body against the final diff rather than against your memory of it. **Never `--no-verify`.** The fleet runs in repos it knows nothing about: it must not assume a pre-commit hook exists, and must never bypass one that does — a hook that fails is a finding to report, not an obstacle. Nothing re-reviews what you commit here, so this run is the only gate between your edit and a merge.
14
14
  4. **Under the fleet, do not hold this wait.** The controller owns a persistent CI Monitor and dispatches a finisher once your report has arrived and CI is green — so push, then report to the controller a **final verdict** (every specialist you dispatched + its outcome + your apply/defer adjudication + the pushed SHA) and stop. A specialist that has neither reported nor been relayed to you is not a verdict line — ask the controller for it by name before ruling; see **Specialists**. The controller keys "review complete" on that verdict, **never on you merely going idle** — a slow specialist can still be running when your turn ends, and finishing off idle-alone ships a premature label (observed: a PR labelled while its contract-test specialist was still running and about to surface a vacuous pin). A turn-based reviewer re-reading `gh pr checks` each idle cycle rebuilds its whole context for nothing the Monitor lacks. **Standalone (no controller): watch** the run until the diff-validating jobs are green (bind via `ci-state.mjs` below); fix a **genuine** failure and repeat from 3. **Staleness is not a failure:** a `rebase-check` red or heavy jobs `skipped` **solely from a non-zero behind-count** never clears by waiting and must not be rebased away here — see **`skipped` is not `passed`** and **Do NOT rebase to label** below for what it looks like and why. Stop watching and go to 6. A turn-based reviewer that "waits for green" on a behind PR stalls forever and ends its turn without labelling. **`ci-state.mjs` returns `verdict: "no-ci"`** → there is no run to watch, so don't: go straight to 6 and let that step's `--declare-no-ci` branch decide.
15
- 5. File each deferred finding: `gh issue create --label <ready-for-agent|needs-triage>` with the finding, `file:line`, why deferred, `Deferred from PR #<pr> review`, and **the finding's `dimension` in the issue body** — the review returns it on every finding, and a backlog that does not carry it cannot be attributed to the specialist that generated it. **The label follows the finding's state, not this step** — but it is never omitted; an unlabelled issue is invisible to both `candidates.mjs --require-label` and the cockpit's pool query, reachable only by a human. **The bar here is whether the DEFECT is confirmed — never whether the remedy is settled.** Confirmed defect with the remedy still open → `ready-for-agent`, and say in the body that the remedy is open. Torn → `needs-triage`, narrowed: torn means **unsure anything is broken**, not unsure how to fix it. **A finding a refuter CHECKED and did not survive is neither** — it is not a confirmed defect, and you are not unsure whether anything is broken: you measured that nothing is. Refutations go as **one issue per review, titled `PR #<pr> review: the suggestion band, checked`, labelled `wontfix`, and CLOSED** — a run that files them open instead has to be corrected afterwards, as one was on 2026-08-27. Left open they read as queued agent work and rot into filing artifacts; a measured triage pass found a quarter of its `needs-triage` backlog was refuted records, bulk-closable by title shape. Closed is still a durable home — `check` reads the tracker at `--state all`, so a future run re-deriving the finding lands on the evidence rather than re-litigating it. Split the band only where an entry is **not** a refutation: a residual the refuter surfaced, or a finding refused as out of scope and never checked, is real deferred work — and real deferred work earns its own open issue only past a second bar. **Worth a claim: a finding whose own claim is that correct code could be shaped better — style, naming, layout, redundancy, a micro-simplification — never gets its own open issue.** Its only open question is "is this worth doing?", which answers itself under the repriced triage bar: measured 2026-08-15→31, 133 issues were triage-closed `wontfix` in sixteen days, 121 of them review deferrals, mostly this shape. Append it to the same closed record issue under a `Below the claim bar` heading — `file:line`, dimension, the claim, and a re-open trigger per entry. Closed is a durable home for these too: `check` reads `--state all`, so a run re-deriving the finding lands on the record instead of re-filing — and a later review returning the same finding as `survived`, or a maintainer hitting it, is the promotion signal: file it open then, citing the record. **An in-scope rediscovery step 2 applied is that same promotion signal, and it files nothing** — so the record carries no mark unless you write one: run `check` over each finding step 2 applied as well, and where its tracker rows put one on a `Below the claim bar` entry, comment on that record issue, opening `Promoted — applied, not filed`, and name the entry, that its refuter let it through, and the commit carrying the fix. That comment is the promotion mark this path leaves, and it is **not** a cross-reference — measured on this tracker, a comment mints `cross-referenced` on the issue its own text *names*, never on the issue it sits under (a comment citing a second issue landed on that issue's timeline and nowhere else), so the fixed opening is what carries the signal instead. **The bar reads the finding's claim, never its review band** — a finding that alleges wrong behavior, whatever band it sat in, `unverified`-with-crashed-refuters included, is above this bar and files open under the confirmed/torn split, which is why a band cannot carry this decision. Do **not** reach for phase 0's **decided?** test here. That is a *consumption* gate, priced for a seat where implementer divergence costs a claim, a worktree and a dispatch; at filing time divergence costs one PR review the maintainer already runs. Same test, two seats, opposite correct answers — and reading it in this seat took `needs-triage` from 11 to 135 before it was repriced (ruled 2026-08-18). **Dedupe through `~/.fleet/bin/fleet-run ledger.mjs check "<subject>"`, never a bare `gh issue list --search`** — the duplicate class that guard exists to catch was filed from *here*: the ledger row for the finding rediscovered five times in one measured run carries a reviewer's own source tag, `(review-pr-108)`. `check` reads this run's filed list *and* the tracker at `--state all`, so a closed duplicate still counts. Exit **1** is already filed in this run; exit **3** is a clean ledger with matching tracker rows that score against the subject — read the ones it prints and comment on the existing follow-up rather than filing a second issue. **Exit 0 is not automatically "safe to file"**: it covers `clean`, `soft-hit` and `unverified` alike, and an unreachable `gh` degrades to a ledger-only answer that says `TRACKER NOT CHECKED`, so read the stdout `verdict` to tell a tracker that was searched and clean from one nobody read — under `unverified`, search it yourself before filing — or, for the applied-promotion comment above, before treating a tracker nobody could read as a reason to skip it. **`soft-hit` is the answer that costs most to misread**: it means related rows were found and none of them was established as a duplicate — a near-miss above the floor, or tracker rows the scorer rates 0.00 — so read the rows it printed and decide, and never treat that exit 0 as permission. Exit **2** is a usage error, meaning nothing was checked at all: fix the invocation and re-run, never read it as a duplicate. Full exit-code and `verdict` semantics live in `$(~/.fleet/bin/fleet-run --root)/skills/run-team/SKILL.md`'s **Run ledger** section — read them there rather than restating them here. **The guard dedupes, it never drops:** a duplicate becomes a comment on the issue that already covers it, never a dropped finding. **Record every issue you create, at once:** immediately after each `gh issue create`, run `~/.fleet/bin/fleet-run ledger.mjs filed <N> "<subject>"` — `<N>` the number `gh issue create` printed, and **the same subject string you passed to `check`**, so the next `check` for that finding meets it in the filed list instead of scoring a rewording. Without it the guard's ledger half never holds a row, and its exit **1** can never fire. If `filed` fails, retry it once; if it fails again, leave the issue alone — it exists and is correct — and report it as `unrecorded: #N <subject>`, so the controller runs `filed` for it. Report `filed: #N <subject>` for every issue you created — under the fleet, in your report to the controller. **The one window the guard cannot see:** `check` → `gh issue create` → `filed` is three commands, and the ledger's lock covers each alone, so two filers can both read `clean` in the seconds before either records. That gap is accepted, never a reason to skip `filed`. Post the numbers as one PR comment.
15
+ 5. File each deferred finding: `gh issue create --label <ready-for-agent|needs-triage>` with the finding, `file:line`, why deferred, `Deferred from PR #<pr> review`, and **the finding's `dimension` in the issue body** — the review returns it on every finding, and a backlog that does not carry it cannot be attributed to the specialist that generated it. **The label follows the finding's state, not this step** — but it is never omitted; an unlabelled issue is invisible to both `candidates.mjs --require-label` and the cockpit's pool query, reachable only by a human. **The bar here is whether the DEFECT is confirmed — never whether the remedy is settled.** Confirmed defect with the remedy still open → `ready-for-agent`, and say in the body that the remedy is open. Torn → `needs-triage`, narrowed: torn means **unsure anything is broken**, not unsure how to fix it. **A finding a refuter CHECKED and did not survive is neither** — it is not a confirmed defect, and you are not unsure whether anything is broken: you measured that nothing is. Refutations go as **one issue per review, titled `PR #<pr> review: the suggestion band, checked`, labelled `wontfix`, and CLOSED** — a run that files them open instead has to be corrected afterwards, as one was on 2026-08-27. Left open they read as queued agent work and rot into filing artifacts; a measured triage pass found a quarter of its `needs-triage` backlog was refuted records, bulk-closable by title shape. Closed is still a durable home — `check` reads the tracker at `--state all`, so a future run re-deriving the finding lands on the evidence rather than re-litigating it. Split the band only where an entry is **not** a refutation: a residual the refuter surfaced, or a finding refused as out of scope and never checked, is real deferred work — and real deferred work earns its own open issue only past a second bar. **Worth a claim: a finding whose own claim is that correct code could be shaped better — style, naming, layout, redundancy, a micro-simplification — never gets its own open issue.** **Neither does a gap in a prose guard — a test holding prose to its wording — unless something acts on the guarded text: an agent follows it as an instruction (a skill, a command, an agent definition, a script's header or usage text, `AGENTS.md`), or a program other than its own guard reads it.** Whether anything does is your judgement, as `claimKind` is, and a gap below this bar is recorded `claimKind: shape`. A gap in a guard's own code — a slow pattern, a dead branch, an unchecked spawn result — takes the stakes of the prose it guards, and a helper several guards share takes the highest of theirs. A missed wording already in the tree is no guard gap — that prose is wrong — and neither is an input already in the tree that trips a guard's code; each files on its own merits. Once the prose is corrected, the observed wording may join the guard's literal ban, never a reader built to catch wordings nobody has written. A below-bar finding's only open question is "is this worth doing?", which answers itself under the repriced triage bar: measured 2026-08-15→31, 133 issues were triage-closed `wontfix` in sixteen days, 121 of them review deferrals, mostly this shape. Append it to the same closed record issue under a `Below the claim bar` heading — `file:line`, dimension, the claim, and a re-open trigger per entry. Closed is a durable home for these too: `check` reads `--state all`, so a run re-deriving the finding lands on the record instead of re-filing — and a later review returning the same finding as `survived`, or a maintainer hitting it, is the promotion signal: file it open then, citing the record. **An in-scope rediscovery step 2 applied is that same promotion signal, and it files nothing** — so the record carries no mark unless you write one: run `check` over each finding step 2 applied as well, and where its tracker rows put one on a `Below the claim bar` entry, comment on that record issue, opening `Promoted — applied, not filed`, and name the entry, that its refuter let it through, and the commit carrying the fix. That comment is the promotion mark this path leaves, and it is **not** a cross-reference — measured on this tracker, a comment mints `cross-referenced` on the issue its own text *names*, never on the issue it sits under (a comment citing a second issue landed on that issue's timeline and nowhere else), so the fixed opening is what carries the signal instead. **The bar reads the finding's claim, never its review band** — a finding that alleges wrong behavior, whatever band it sat in, `unverified`-with-crashed-refuters included, is above this bar and files open under the confirmed/torn split, which is why a band cannot carry this decision. Do **not** reach for phase 0's **decided?** test here. That is a *consumption* gate, priced for a seat where implementer divergence costs a claim, a worktree and a dispatch; at filing time divergence costs one PR review the maintainer already runs. Same test, two seats, opposite correct answers — and reading it in this seat took `needs-triage` from 11 to 135 before it was repriced (ruled 2026-08-18). **Dedupe through `~/.fleet/bin/fleet-run ledger.mjs check "<subject>"`, never a bare `gh issue list --search`** — the duplicate class that guard exists to catch was filed from *here*: the ledger row for the finding rediscovered five times in one measured run carries a reviewer's own source tag, `(review-pr-108)`. `check` reads this run's filed list *and* the tracker at `--state all`, so a closed duplicate still counts. Exit **1** is already filed in this run; exit **3** is a clean ledger with matching tracker rows that score against the subject — read the ones it prints and comment on the existing follow-up rather than filing a second issue. **Exit 0 is not automatically "safe to file"**: it covers `clean`, `soft-hit` and `unverified` alike, and an unreachable `gh` degrades to a ledger-only answer that says `TRACKER NOT CHECKED`, so read the stdout `verdict` to tell a tracker that was searched and clean from one nobody read — under `unverified`, search it yourself before filing — or, for the applied-promotion comment above, before treating a tracker nobody could read as a reason to skip it. **`soft-hit` is the answer that costs most to misread**: it means related rows were found and none of them was established as a duplicate — a near-miss above the floor, or tracker rows the scorer rates 0.00 — so read the rows it printed and decide, and never treat that exit 0 as permission. Exit **2** is a usage error, meaning nothing was checked at all: fix the invocation and re-run, never read it as a duplicate. Full exit-code and `verdict` semantics live in `$(~/.fleet/bin/fleet-run --root)/skills/run-team/SKILL.md`'s **Run ledger** section — read them there rather than restating them here. **The guard dedupes, it never drops:** a duplicate becomes a comment on the issue that already covers it, never a dropped finding. **Record every issue you create, at once:** immediately after each `gh issue create`, run `~/.fleet/bin/fleet-run ledger.mjs filed <N> "<subject>"` — `<N>` the number `gh issue create` printed, and **the same subject string you passed to `check`**, so the next `check` for that finding meets it in the filed list instead of scoring a rewording. Without it the guard's ledger half never holds a row, and its exit **1** can never fire. If `filed` fails, retry it once; if it fails again, leave the issue alone — it exists and is correct — and report it as `unrecorded: #N <subject>`, so the controller runs `filed` for it. Report `filed: #N <subject>` for every issue you created — under the fleet, in your report to the controller. **The one window the guard cannot see:** `check` → `gh issue create` → `filed` is three commands, and the ledger's lock covers each alone, so two filers can both read `clean` in the seconds before either records. That gap is accepted, never a reason to skip `filed`. Post the numbers as one PR comment.
16
16
  **A duplicate that should hold an open deferral is relabelled up, never down.** Where the guard lands a finding whose home is an open issue on an existing one that is open and labelled `needs-triage` while the finding's state calls for `ready-for-agent` — a defect its refuters confirmed — relabel it with `gh issue edit <N> --remove-label needs-triage --add-label ready-for-agent`, and cite the refuters' verdict in the comment you leave there. Never relabel `ready-for-agent` down to `needs-triage`: a `ready-for-agent` issue already holds a `needs-triage` finding, and a later run's crashed refuters are no reason to send a confirmed defect back to triage. A closed one cannot hold it: file a new open issue citing it, as the promotion rule above does for the closed record.
17
17
  **Name where each deferral went, in the disposition record.** Every entry you defer carries `issue`: the number of the issue you filed it to, commented it onto, or appended it to — the closed `PR #<pr> review: the suggestion band, checked` record included. An in-scope `suggestion`'s entry — an `unverified` finding with `refutersDispatched` of zero — also carries `verdictPath`, applied or deferred: the absolute path of a file holding its refuter's verdict as JSON, `{"refuted": <boolean>, "reason": "<string>"}`, under your own `<scratch>/pr<N>/fix-XXXXXXXX/<finding>/` run root. `dispositions-check.mjs` reads each named issue back through `gh issue view --json labels,state,title` and each verdict file off disk; a mismatch names the row of its filing table the entry broke, so move or relabel that filing to the home the row names and run the check again. With `gh` unreachable, or an issue it cannot read, that filing goes unchecked: with nothing else broken the verdict is `unchecked` — never `ok`, and it exits 1 — so run the check again once `gh` answers.
18
18
  6. Diff-check green (run-bound per `ci-state.mjs`; under staleness see **`skipped` is not `passed`** for what the label then rests on) **and** deferrals filed **and** the PR carrying exactly one release label (`patch`/`minor`/`major`, counting only those three; **required on every PR** — `release-label.yml` auto-adds `patch` when none is present and hard-fails on more than one, so this never needs to check whether the repo defines the gate at all, and `gh label list` settles nothing here any more) **and** `dispositions-check.mjs --member fix-pr-<pr> --scratch <scratch>` run over your own record exiting 0 (standalone that is yours to run, from the worktree, after step 2 writes `<scratch>/dispositions-fix-pr-<pr>.json`; `--review <path>` names the review file, which you write yourself from the findings step 1 collected, in the shape **The review result file** describes — `pr`, `head`, `snapshot`, `counts` and the `survived`, `refuted` and `unverified` buckets; standalone you pass `--no-ledger` with it, so it writes no token and the exit status is the verdict — a `.fleet/ledger.md` the repository already holds is a previous run's, and without the flag it exits 2 for a ledger with no row for you; under the fleet `ledger.mjs dispatch` has already refused a finisher without it) → `gh pr comment <pr> --body "ready-to-merge-head: <prHead>"`, `prHead` being the full SHA your green `ci-state.mjs` reading reported, which the merge bot reads as the head the label was applied to, then `gh pr edit <pr> --add-label ready-to-merge`. Do not merge. A non-zero dispositions exit halts you before the label, and you report the violations it printed. Zero or more than one release label halts you before the label, naming which you found — a timed-out `gh pr create` opens the PR with its `--label` unapplied and no exit status to react to, and nothing after this step re-derives the release label. **Under the fleet a finisher does this** — a fresh small agent the controller dispatches (after your final verdict, never on your bare idle). Gate it on the diff-validating **`check`** job, **not** on `ci-state --quiet` exit 0, which a behind PR — the normal case once any sibling merges — never reaches: a `rebase-check` red or heavy jobs `skipped` off the behind-count hold it short of full green, so an exit-0 gate strands every behind PR unlabelled. Label when `check` is present and green **and no heavy job (the diff-validating suites — *not* the `rebase-check` currency gate) is in `failure`** — a `skipped` heavy job is behind-count staleness and fine — **solely** off that count, which is a condition to establish rather than infer, see the five-condition note in `$(~/.fleet/bin/fleet-run --root)/skills/run-team/SKILL.md`'s fix-applier prompt block. A `failure` is the diff's own fault and blocks the label, else a genuinely broken PR gets labelled off a green `check` and burns a merge-bot rebase+CI cycle before the failure resurfaces. Read per-job state for this: run `ci-state.mjs` **without** `--quiet`, or read its `jobs` — the `--quiet` payload drops the per-job `jobs`/`missing` and the `dropped` list, keeping `reasons` (which still distinguishes `is failure` from `is skipped`). You reach step 6 yourself only when green is already in hand at push time.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@feigi/fleet-ctl",
3
- "version": "3.35.5",
3
+ "version": "3.35.7",
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);