@feigi/fleet-ctl 0.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/plugin.json +9 -0
- package/LICENSE +202 -0
- package/NOTICE +18 -0
- package/agents/fleet-finisher.agent.md +7 -0
- package/agents/fleet-implementer-alt.agent.md +210 -0
- package/agents/fleet-implementer.agent.md +210 -0
- package/agents/fleet-merge-bot.agent.md +7 -0
- package/agents/fleet-review-comments.agent.md +40 -0
- package/agents/fleet-review-correctness.agent.md +43 -0
- package/agents/fleet-review-runner.agent.md +73 -0
- package/agents/fleet-review-silent-failure.agent.md +49 -0
- package/agents/fleet-review-simplify.agent.md +46 -0
- package/agents/fleet-review-snapshot.agent.md +24 -0
- package/agents/fleet-review-tests.agent.md +46 -0
- package/agents/fleet-review-types.agent.md +41 -0
- package/agents/fleet-review-verifier.agent.md +29 -0
- package/commands/review-and-fix.md +98 -0
- package/commands/run-merge-bot.md +357 -0
- package/commands/run-team-help.md +17 -0
- package/package.json +23 -0
- package/scripts/agent-test-dir-prose.test.mjs +59 -0
- package/scripts/agent-test.test.mjs +1636 -0
- package/scripts/ambient-git-vars-mjs-prose.test.mjs +354 -0
- package/scripts/ambient-git-vars-prose.test.mjs +192 -0
- package/scripts/ancestry-check-position-prose.test.mjs +175 -0
- package/scripts/apply-ruleset.test.mjs +420 -0
- package/scripts/arg-header-probes-prose.test.mjs +393 -0
- package/scripts/arg.mjs +600 -0
- package/scripts/arg.test.mjs +1354 -0
- package/scripts/board-cli.test.mjs +694 -0
- package/scripts/board-identity.test.mjs +429 -0
- package/scripts/board-liveness-banner.test.mjs +119 -0
- package/scripts/board-prev-shape.test.mjs +229 -0
- package/scripts/board-tryparse-null.test.mjs +119 -0
- package/scripts/board.html +471 -0
- package/scripts/board.mjs +2037 -0
- package/scripts/board.test.mjs +3086 -0
- package/scripts/brief-after-cut-prose.test.mjs +53 -0
- package/scripts/candidates-exit3-prose.test.mjs +302 -0
- package/scripts/candidates.mjs +674 -0
- package/scripts/candidates.test.mjs +2101 -0
- package/scripts/caveat-unification-prose.test.mjs +98 -0
- package/scripts/ci-comment-rot-prose.test.mjs +2025 -0
- package/scripts/ci-completes-premise-prose.test.mjs +257 -0
- package/scripts/ci-state-prose.test.mjs +113 -0
- package/scripts/ci-state.mjs +761 -0
- package/scripts/ci-state.test.mjs +1640 -0
- package/scripts/ci-vacuous-green.test.mjs +368 -0
- package/scripts/citation-sweep-prose.test.mjs +1572 -0
- package/scripts/claim-lifecycle.test.mjs +185 -0
- package/scripts/claim-ticket.sh +417 -0
- package/scripts/claim-ticket.test.mjs +1121 -0
- package/scripts/closing-keyword-prose.test.mjs +193 -0
- package/scripts/cockpit-launch-idempotent-prose.test.mjs +165 -0
- package/scripts/cockpit-tick-nonblocking.test.mjs +210 -0
- package/scripts/compute-board.mjs +579 -0
- package/scripts/compute-board.test.mjs +1060 -0
- package/scripts/compute-spend.mjs +329 -0
- package/scripts/compute-spend.test.mjs +451 -0
- package/scripts/cross-repo-citation-prose.test.mjs +156 -0
- package/scripts/cwd-isolation-pins.mjs +83 -0
- package/scripts/dedupe-guard-prose.test.mjs +243 -0
- package/scripts/derive-testcmd.sh +239 -0
- package/scripts/derive-testcmd.test.mjs +380 -0
- package/scripts/diff-stats.mjs +231 -0
- package/scripts/diff-stats.test.mjs +408 -0
- package/scripts/dispatch-block-golden-prose.test.mjs +1024 -0
- package/scripts/dispatch-block-pins-prose.test.mjs +615 -0
- package/scripts/drop-merged-label.sh +173 -0
- package/scripts/drop-merged-label.test.mjs +480 -0
- package/scripts/expected-jobs-prose.test.mjs +80 -0
- package/scripts/filing-bar-seat-prose.test.mjs +242 -0
- package/scripts/filing-claim-bar-prose.test.mjs +166 -0
- package/scripts/finisher-dispatch-premise-prose.test.mjs +312 -0
- package/scripts/finisher-halt-prose.test.mjs +106 -0
- package/scripts/finisher-name-prose.test.mjs +134 -0
- package/scripts/finisher-own-tree-prose.test.mjs +285 -0
- package/scripts/finisher-pin-race-prose.test.mjs +339 -0
- package/scripts/fix-applier-correction-rules-prose.test.mjs +201 -0
- package/scripts/fix-applier-result-file-prose.test.mjs +100 -0
- package/scripts/fleet-bootstrap +155 -0
- package/scripts/fleet-heartbeat.mjs +272 -0
- package/scripts/fleet-heartbeat.test.mjs +450 -0
- package/scripts/fleet-provenance +207 -0
- package/scripts/fleet-provenance.test.mjs +64 -0
- package/scripts/fleet-run +148 -0
- package/scripts/fleet-run.test.mjs +90 -0
- package/scripts/fleet-state.mjs +400 -0
- package/scripts/fleet-state.test.mjs +373 -0
- package/scripts/fleet-tick-prose.test.mjs +299 -0
- package/scripts/fleet-tick.mjs +832 -0
- package/scripts/fleet-tick.test.mjs +1332 -0
- package/scripts/force-with-lease-reason-prose.test.mjs +184 -0
- package/scripts/frontmatter-allowlist.json +64 -0
- package/scripts/frontmatter-check.mjs +256 -0
- package/scripts/frontmatter-check.test.mjs +436 -0
- package/scripts/git-env.mjs +124 -0
- package/scripts/git-env.test.mjs +149 -0
- package/scripts/git-status-untracked-mode-sweep.test.mjs +216 -0
- package/scripts/gone-walk.test.mjs +213 -0
- package/scripts/gp-sep-invariant-prose.test.mjs +188 -0
- package/scripts/head-moved-after-label-prose.test.mjs +233 -0
- package/scripts/immutable-body-claim-prose.test.mjs +413 -0
- package/scripts/implementer-model-tier.test.mjs +643 -0
- package/scripts/inflight-citation-prose.test.mjs +144 -0
- package/scripts/inflight-exit2-prose.test.mjs +81 -0
- package/scripts/inflight-probe-guard-prose.test.mjs +109 -0
- package/scripts/inflight-scan-scope-prose.test.mjs +57 -0
- package/scripts/inflight.sh +1106 -0
- package/scripts/inflight.test.mjs +2984 -0
- package/scripts/injection-control-prose.test.mjs +404 -0
- package/scripts/install-root-audit.test.mjs +464 -0
- package/scripts/instrument-check-prose.test.mjs +235 -0
- package/scripts/instruments.sh +394 -0
- package/scripts/instruments.test.mjs +787 -0
- package/scripts/issue-tracker-prose.test.mjs +71 -0
- package/scripts/json.sh +248 -0
- package/scripts/json.test.mjs +364 -0
- package/scripts/ledger-dispatch.test.mjs +516 -0
- package/scripts/ledger-grammar.mjs +85 -0
- package/scripts/ledger-grammar.test.mjs +142 -0
- package/scripts/ledger-read-require-file.test.mjs +197 -0
- package/scripts/ledger.mjs +1753 -0
- package/scripts/ledger.test.mjs +3554 -0
- package/scripts/line-distance-prose.test.mjs +245 -0
- package/scripts/liveness-rationale-prose.test.mjs +83 -0
- package/scripts/locale-pin-prose.test.mjs +189 -0
- package/scripts/member-outcome-prose.test.mjs +167 -0
- package/scripts/member-outcomes-header.test.mjs +148 -0
- package/scripts/member-outcomes-prose.test.mjs +63 -0
- package/scripts/member-outcomes.mjs +231 -0
- package/scripts/member-outcomes.test.mjs +507 -0
- package/scripts/member-prompt-prose.test.mjs +161 -0
- package/scripts/member-record.mjs +605 -0
- package/scripts/member-record.test.mjs +516 -0
- package/scripts/member-write-guard.mjs +279 -0
- package/scripts/member-write-guard.test.mjs +211 -0
- package/scripts/merge-commit-probe-prose.test.mjs +122 -0
- package/scripts/merge-gate.mjs +262 -0
- package/scripts/merge-gate.test.mjs +613 -0
- package/scripts/muted-git-guard-sweep.test.mjs +493 -0
- package/scripts/net-ssh-precedence-prose.test.mjs +91 -0
- package/scripts/net-watchdog-prose.test.mjs +79 -0
- package/scripts/net.sh +409 -0
- package/scripts/net.test.mjs +211 -0
- package/scripts/no-ci-gate-prose.test.mjs +108 -0
- package/scripts/no-undo-audit.sh +1134 -0
- package/scripts/no-undo-audit.test.mjs +3965 -0
- package/scripts/no-wave.test.mjs +138 -0
- package/scripts/node-floor-sweep.test.mjs +611 -0
- package/scripts/pointer-target-prose.test.mjs +186 -0
- package/scripts/pr-overlap.mjs +417 -0
- package/scripts/pr-overlap.test.mjs +695 -0
- package/scripts/printf-die-sweep.test.mjs +384 -0
- package/scripts/prompt-renderer.mjs +39 -0
- package/scripts/prompt-renderer.test.mjs +68 -0
- package/scripts/prose-pin.mjs +808 -0
- package/scripts/prose-pin.test.mjs +1034 -0
- package/scripts/prove-merge.sh +228 -0
- package/scripts/prove-merge.test.mjs +995 -0
- package/scripts/pull-table-relabel-prose.test.mjs +60 -0
- package/scripts/quiet-payload-prose.test.mjs +222 -0
- package/scripts/reap.sh +1768 -0
- package/scripts/reap.test.mjs +4395 -0
- package/scripts/reaping-prose.test.mjs +159 -0
- package/scripts/refuter-scratch-prose.test.mjs +135 -0
- package/scripts/release-label-required-prose.test.mjs +71 -0
- package/scripts/release-label-split-prose.test.mjs +169 -0
- package/scripts/release-ticket.sh +1716 -0
- package/scripts/release-ticket.test.mjs +5106 -0
- package/scripts/renovate-release-contract.test.mjs +379 -0
- package/scripts/repo-root.mjs +544 -0
- package/scripts/repo-root.test.mjs +873 -0
- package/scripts/reporter-output-rule-prose.test.mjs +208 -0
- package/scripts/review-agent-report-only.test.mjs +49 -0
- package/scripts/review-core-cwd-isolation.test.mjs +374 -0
- package/scripts/review-core-reads.test.mjs +478 -0
- package/scripts/review-core-refuter-scratch.test.mjs +148 -0
- package/scripts/review-core-snapshot-path.test.mjs +777 -0
- package/scripts/review-core-specialist-scratch.test.mjs +189 -0
- package/scripts/review-core-testcmd.test.mjs +288 -0
- package/scripts/review-core-unrun.test.mjs +530 -0
- package/scripts/review-core-unverified-discriminant.test.mjs +208 -0
- package/scripts/review-core.mjs +1028 -0
- package/scripts/review-eval-resolver-path.test.mjs +55 -0
- package/scripts/review-eval.mjs +197 -0
- package/scripts/review-host-fixture.mjs +73 -0
- package/scripts/review-in-run-retry.test.mjs +187 -0
- package/scripts/review-no-vendor-dispatch.test.mjs +45 -0
- package/scripts/review-path-default.test.mjs +796 -0
- package/scripts/review-runner-spawns.test.mjs +93 -0
- package/scripts/review-runner.test.mjs +155 -0
- package/scripts/review-tier-audit.test.mjs +140 -0
- package/scripts/run-artifact-pr-prose.test.mjs +341 -0
- package/scripts/run-merge-bot-prose.test.mjs +1391 -0
- package/scripts/scratch-partition-invariant-prose.test.mjs +74 -0
- package/scripts/scripts-path-citation-sweep.test.mjs +73 -0
- package/scripts/section-between-guard-prose.test.mjs +378 -0
- package/scripts/select-dimensions.test.mjs +674 -0
- package/scripts/shared-refusal.test.mjs +388 -0
- package/scripts/shell-traps-prose.test.mjs +507 -0
- package/scripts/shortlist.mjs +355 -0
- package/scripts/shortlist.test.mjs +366 -0
- package/scripts/slow-transport.mjs +72 -0
- package/scripts/snapshot-repo.test.mjs +772 -0
- package/scripts/snapshot-runner-audience-prose.test.mjs +129 -0
- package/scripts/spend-view.test.mjs +312 -0
- package/scripts/staleness-qualifier-prose.test.mjs +251 -0
- package/scripts/staleness-verdict-prose.test.mjs +142 -0
- package/scripts/staleness.mjs +414 -0
- package/scripts/staleness.test.mjs +893 -0
- package/scripts/stalled-member-liveness-prose.test.mjs +219 -0
- package/scripts/stash-prohibition-prose.test.mjs +313 -0
- package/scripts/strip-comments.mjs +44 -0
- package/scripts/tier-check.mjs +468 -0
- package/scripts/tier-check.test.mjs +726 -0
- package/scripts/tier-guard-gate-prose.test.mjs +216 -0
- package/scripts/tier-outcomes-header.test.mjs +586 -0
- package/scripts/tier-outcomes.mjs +441 -0
- package/scripts/tier-outcomes.test.mjs +342 -0
- package/scripts/tier-roles.mjs +250 -0
- package/scripts/tier-roles.test.mjs +316 -0
- package/scripts/tracker-block-copy-prose.test.mjs +288 -0
- package/scripts/triage-labels-gloss-prose.test.mjs +97 -0
- package/scripts/unattended-git-sweep.test.mjs +142 -0
- package/scripts/verify-sha-exit2-prose.test.mjs +269 -0
- package/scripts/verify-sha.sh +117 -0
- package/scripts/verify-sha.test.mjs +693 -0
- package/scripts/watcher-degraded-block.test.mjs +372 -0
- package/scripts/watcher-key-prose.test.mjs +106 -0
- package/scripts/within-run-pair-prose.test.mjs +208 -0
- package/scripts/worktree-audit.sh +482 -0
- package/scripts/worktree-audit.test.mjs +1407 -0
- package/scripts/worktree-head-prose.test.mjs +276 -0
- package/scripts/worktree-listing-sweep.test.mjs +217 -0
- package/scripts/worktree-model-prose.test.mjs +216 -0
- package/scripts/worktree.sh +470 -0
- package/skills/next-ticket/SKILL.md +138 -0
- package/skills/run-team/SKILL.md +3603 -0
- package/skills/run-team/references/ci-and-staleness.md +75 -0
- package/skills/run-team/references/correction-tickets.md +37 -0
- package/skills/run-team/references/isolation.md +23 -0
- package/skills/run-team/references/member-lifecycle.md +73 -0
- package/skills/run-team/references/reaping.md +73 -0
- package/skills/sizing-a-ticket/SKILL.md +39 -0
|
@@ -0,0 +1,2037 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// The cockpit's I/O layer. `build` gathers ledger + gh + CI state, calls the
|
|
3
|
+
// pure computeBoard(), and prints board.json. `serve` (below) loops build,
|
|
4
|
+
// atomic-writes .fleet/board.json, and serves board.html. The board never
|
|
5
|
+
// depends on the controller feeding it.
|
|
6
|
+
//
|
|
7
|
+
// Pipeline state is a pure function of ledger + GitHub. The spend panel adds
|
|
8
|
+
// a THIRD input that is neither — the local member-transcript tree, under
|
|
9
|
+
// ~/.omp/agent/sessions — so the "f(ledger, gh)" property no longer covers
|
|
10
|
+
// the whole model. It is
|
|
11
|
+
// telemetry, kept strictly to the side: it can only ever populate or omit
|
|
12
|
+
// `spend`, never change a ticket's stage.
|
|
13
|
+
//
|
|
14
|
+
// That transcript tree is keyed by PROJECT DIRECTORY, not by session, and one
|
|
15
|
+
// directory can hold several sessions at once. `serve` therefore resolves ONE
|
|
16
|
+
// session's transcript directory and keeps it for its whole life (#1583) — see
|
|
17
|
+
// spendDirPin() below — rather than re-picking the newest on every tick and
|
|
18
|
+
// alternating between two live runs' numbers in silence.
|
|
19
|
+
//
|
|
20
|
+
// LIMITATION, stated rather than solved: the session it keeps is whichever
|
|
21
|
+
// FIRST writes a transcript at or after the pin's own construction (#1679).
|
|
22
|
+
// Before that, a session that was already active when the pin was built —
|
|
23
|
+
// this run's own, mid-EACCES-fault, or a genuinely previous run's — is never
|
|
24
|
+
// latched; the pin keeps re-asking findSubagentsDir() every tick instead,
|
|
25
|
+
// which is what lets a transient fault or a stale session recover instead of
|
|
26
|
+
// freezing the panel for the server's whole life. What is not solved: two
|
|
27
|
+
// sessions that BOTH start writing after the pin exists, in the same project
|
|
28
|
+
// directory, are still indistinguishable — the board is scoped to a
|
|
29
|
+
// workspace and a workspace does not know that (#39) — so the first of them
|
|
30
|
+
// to pass the newest-transcript check wins and keeps winning. `--spend-dir
|
|
31
|
+
// <path>` is how an operator names the right one: it overrides the
|
|
32
|
+
// heuristic outright.
|
|
33
|
+
|
|
34
|
+
import { execFile, spawnSync } from "node:child_process";
|
|
35
|
+
import { readFileSync, writeFileSync, renameSync, existsSync, realpathSync, readdirSync, statSync, writeSync } from "node:fs";
|
|
36
|
+
import { classifyRole, computeSpend, attributeTools, mergeTools } from "./compute-spend.mjs";
|
|
37
|
+
import {
|
|
38
|
+
encodeProjectDir, isOmpSessionDirName, ompSessionTranscripts, foldOmpTranscript, ompMemberRecord,
|
|
39
|
+
} from "./member-record.mjs";
|
|
40
|
+
import { makeDie, defineFlags } from "./arg.mjs";
|
|
41
|
+
import { gitEnv, workspaceDirFromGitCommonDir } from "./git-env.mjs";
|
|
42
|
+
import { mergedReadPrs } from "./compute-board.mjs";
|
|
43
|
+
// #1597: the heartbeat's liveness mark, read here and never written. The
|
|
44
|
+
// cockpit is a READER of that key — the heartbeat is its only writer — and it
|
|
45
|
+
// reaches the file through the module that owns the filename rather than
|
|
46
|
+
// spelling `heartbeat.json` a second time. The PATH still comes from this
|
|
47
|
+
// file's own resolveCockpitInstance(), not from statePath(): that probe is
|
|
48
|
+
// already run once per launch here, with the `canonicalise` opt-in only this
|
|
49
|
+
// caller takes (#1582), and a second probe could answer differently.
|
|
50
|
+
import { readState, stateFileIn } from "./fleet-state.mjs";
|
|
51
|
+
import { fileURLToPath } from "node:url";
|
|
52
|
+
import { dirname, join, basename } from "node:path";
|
|
53
|
+
import { createServer, request as httpRequest } from "node:http";
|
|
54
|
+
import { inspect } from "node:util";
|
|
55
|
+
|
|
56
|
+
const NAME = "board";
|
|
57
|
+
const SCRIPT_DIR = dirname(fileURLToPath(import.meta.url));
|
|
58
|
+
// die()/arg()/has() shared with the other fleet scripts — see arg.mjs for
|
|
59
|
+
// the fail-open (#61/#169/#364) and pipe-safety (#176/#328/#363) rationale.
|
|
60
|
+
const die = makeDie(NAME);
|
|
61
|
+
const { arg, has, sweep, stray } = defineFlags(die, {
|
|
62
|
+
flags: {
|
|
63
|
+
ledger: "value",
|
|
64
|
+
prev: "value",
|
|
65
|
+
port: "value",
|
|
66
|
+
interval: "value",
|
|
67
|
+
"spend-since": "value",
|
|
68
|
+
"spend-dir": "value",
|
|
69
|
+
open: "bool",
|
|
70
|
+
},
|
|
71
|
+
positionals: ["build", "serve"],
|
|
72
|
+
});
|
|
73
|
+
// `ledger`/`prev`/`spend-since`/`port`/`interval` are all read with `||`/`??`
|
|
74
|
+
// fallbacks, so a trailing flag previously substituted a default in total
|
|
75
|
+
// silence — `--spend-since` with nothing after it silently widened the spend
|
|
76
|
+
// panel to all-time instead of the requested window, and `--ledger` with
|
|
77
|
+
// nothing after it silently read the DEFAULT ledger file instead of the one
|
|
78
|
+
// asked for.
|
|
79
|
+
//
|
|
80
|
+
// #468: a guard used to fire only where the flag was actually READ, and that
|
|
81
|
+
// was not every subcommand — `port` and `open` are USED in serve() alone, so
|
|
82
|
+
// `build --port` (trailing), `build --port abc` and `build --open=1` were all
|
|
83
|
+
// IGNORED at exit 0 rather than refused. main() now calls argPort()/
|
|
84
|
+
// has("open") once, ahead of the build/serve dispatch, so both malformed
|
|
85
|
+
// spellings refuse on EVERY subcommand — build just discards the (validated)
|
|
86
|
+
// return value, since nothing on that path has a server to bind or a browser
|
|
87
|
+
// to open. A WELL-FORMED --port/--open on build still does nothing there,
|
|
88
|
+
// same as before this fix: the guard checks the flag's SHAPE, not whether
|
|
89
|
+
// this subcommand has a use for it. `ledger`/`prev`/`spend-since`/`interval`
|
|
90
|
+
// were already read on the build path and already refused there.
|
|
91
|
+
// #1092: that last claim held for `ledger`/`spend-since`/`interval`, not for
|
|
92
|
+
// `prev` — `prev` was read on `build` alone, and serve() never read it at
|
|
93
|
+
// all. Hoisted in main() below, next to argPort()/has("open").
|
|
94
|
+
|
|
95
|
+
// #1546: the "is this a plain JSON object" predicate and its kind word, one
|
|
96
|
+
// copy for the reads in this file that reject a parsed-but-wrong payload
|
|
97
|
+
// WHOLE — gather's `--prev` payload, gather's per-entry `tickets[i]` check,
|
|
98
|
+
// and readMerged()'s `data.repository` (#1840). Each carried its own inline
|
|
99
|
+
// copy of both halves before, which is three places for one policy to drift in.
|
|
100
|
+
//
|
|
101
|
+
// TWO functions and not one, because `typeof` alone cannot name the fault the
|
|
102
|
+
// predicate rejects: it answers "object" for `null` and for `[]` alike, and
|
|
103
|
+
// those are exactly two of the three shapes turned away here, so a
|
|
104
|
+
// `typeof`-only diagnostic distinguishes neither from a real object. That is
|
|
105
|
+
// the same three-arm naming review-core.mjs's resolveDimensions keeps, for the
|
|
106
|
+
// same reason.
|
|
107
|
+
//
|
|
108
|
+
// Not every payload-shape check in this file is one of these, and the others
|
|
109
|
+
// are not oversights: mapCi's and tryParse's are both null-only, neither
|
|
110
|
+
// refusing a payload for being an array or a scalar. A settled, deliberately
|
|
111
|
+
// different policy — not more callers waiting to be converted.
|
|
112
|
+
function isJsonObject(v) {
|
|
113
|
+
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function jsonKind(v) {
|
|
117
|
+
return v === null ? "null" : Array.isArray(v) ? "array" : typeof v;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// #366: `Number(x) || default` treated a garbage --port/--interval exactly
|
|
121
|
+
// like an absent one — "abc" is NaN, NaN is falsy, so it silently became the
|
|
122
|
+
// default with no refusal. Same silent-fallback class as arg()'s own comment
|
|
123
|
+
// above and #361's --spend-since guard. `interval` is read from argv in two
|
|
124
|
+
// places (serve(), and gather()'s build payload); both call argInterval() so
|
|
125
|
+
// the check lives once, not as two copies that can drift apart. Neither
|
|
126
|
+
// guard runs on an already-typed value a caller passed in-process — arg()
|
|
127
|
+
// only fires when the caller falls through to reading raw argv.
|
|
128
|
+
function argPort() {
|
|
129
|
+
const raw = arg("port");
|
|
130
|
+
if (raw == null) return null;
|
|
131
|
+
const n = Number(raw);
|
|
132
|
+
if (!Number.isInteger(n) || n < 0 || n > 65535) die(`--port wants an integer 0-65535, got ${raw}`);
|
|
133
|
+
return n; // 0 is a real value — listen(0) binds an ephemeral port
|
|
134
|
+
}
|
|
135
|
+
// Bounded at BOTH ends, like argPort(). The ceiling is setInterval's 32-bit
|
|
136
|
+
// millisecond delay: hand it more and Node clamps the delay to 1ms with only a
|
|
137
|
+
// TimeoutOverflowWarning, so `--interval 3000000` (34 days) turns the rebuild
|
|
138
|
+
// loop into a spin loop shelling out to gh hundreds of times a second — the
|
|
139
|
+
// inverse of what was asked, announced by nothing the board prints (#435
|
|
140
|
+
// review). 2147483647ms / 1000, floored, is the last WHOLE second that fits;
|
|
141
|
+
// the ceiling is a hair under that in fractional seconds, which nobody types.
|
|
142
|
+
function argInterval() {
|
|
143
|
+
const raw = arg("interval");
|
|
144
|
+
if (raw == null) return null;
|
|
145
|
+
const n = Number(raw);
|
|
146
|
+
if (!Number.isFinite(n) || n <= 0 || n > 2147483) die(`--interval wants seconds > 0 and <= 2147483, got ${raw}`);
|
|
147
|
+
return n;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// Operator input at a trust boundary, so it fails loud. `Number(x) || null`
|
|
151
|
+
// silently turned every bad value into "no filter at all": a typo, or the
|
|
152
|
+
// natural mistake of passing seconds instead of milliseconds, produced a panel
|
|
153
|
+
// that rendered confidently over the WHOLE session while the operator believed
|
|
154
|
+
// it was scoped to one run. That is the same silent-zero failure the comment
|
|
155
|
+
// on gatherSpend describes; an earlier pass removed the `|| null` default but
|
|
156
|
+
// left the footgun, and the guard below is what actually closes it.
|
|
157
|
+
//
|
|
158
|
+
// Gate on PRESENCE, not on the value: `arg()` yields undefined for a trailing
|
|
159
|
+
// `--spend-since`, and `sinceRaw == null` read that as "flag absent", so the
|
|
160
|
+
// guard never fired. And on RANGE, not just finiteness: a seconds-magnitude
|
|
161
|
+
// epoch (~1.7e9) is finite, so the very mistake named above sailed through,
|
|
162
|
+
// counted every agent, and shipped its own bogus value into board.json's
|
|
163
|
+
// `since`. 1e12 ms is 2001-09-09, below any real run; a future boundary
|
|
164
|
+
// matches nothing at all.
|
|
165
|
+
//
|
|
166
|
+
// #1076: pulled out of gather() into its own function, like argPort()/
|
|
167
|
+
// argInterval() above, so main() can call it too (below) ahead of the
|
|
168
|
+
// build/serve dispatch and ahead of both branches' stray() call — before
|
|
169
|
+
// this fix the read sat inline inside gather(), below every stray() call on
|
|
170
|
+
// every path that reaches it, so a trailing `--spend-since` ahead of a stray
|
|
171
|
+
// positional refused under stray()'s generic wording instead of this one.
|
|
172
|
+
// gather() still calls this itself, in the same spot, so nothing about WHEN
|
|
173
|
+
// it validates changes for a caller that skips main() (same reasoning #468
|
|
174
|
+
// gives for argPort()/has("open") staying in serve() too).
|
|
175
|
+
function argSpendSince() {
|
|
176
|
+
const sinceRaw = arg("spend-since");
|
|
177
|
+
if (sinceRaw === null) return null;
|
|
178
|
+
const sinceMs = Number(sinceRaw);
|
|
179
|
+
if (!Number.isFinite(sinceMs) || sinceMs < 1e12 || sinceMs > Date.now()) {
|
|
180
|
+
die(`--spend-since wants epoch milliseconds, got ${sinceRaw}`);
|
|
181
|
+
}
|
|
182
|
+
return sinceMs;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
// #1583: the operator's override for the session heuristic (findSubagentsDir()
|
|
186
|
+
// below). A PATH, so there is no range or magnitude to check the way
|
|
187
|
+
// --spend-since and --interval have one — every malformed SHAPE this flag can
|
|
188
|
+
// take is already arg()'s: a trailing `--spend-dir`, an empty or whitespace
|
|
189
|
+
// value, a following flag eaten as the value, and the `--spend-dir=` form.
|
|
190
|
+
// What this read buys is that all four refuse under THIS flag's name instead
|
|
191
|
+
// of stray()'s generic "unexpected argument", and they do so before gather()
|
|
192
|
+
// shells out to anything — which is what declaring it in the flag table above
|
|
193
|
+
// and calling it from main() below are for, exactly as #1076 did for
|
|
194
|
+
// --spend-since. A named read rather than a bare arg() at each call site so
|
|
195
|
+
// the flag is spelled in one place and this reasoning has a home.
|
|
196
|
+
//
|
|
197
|
+
// Existence is deliberately NOT checked, and refusing an absent directory
|
|
198
|
+
// would refuse the one invocation this flag exists for: a session's own
|
|
199
|
+
// directory does not exist until that session's first agent spawns, and the
|
|
200
|
+
// cockpit launches in run-team phase 0, BEFORE that. An
|
|
201
|
+
// operator pinning THIS run's transcripts therefore names a directory that is
|
|
202
|
+
// not there yet, and it appears seconds later. A directory that never appears
|
|
203
|
+
// degrades per tick through gatherSpend's catch and hides the panel; it never
|
|
204
|
+
// renders zeroes and never dies.
|
|
205
|
+
//
|
|
206
|
+
// `undefined` for an absent flag, not the `null` argPort()/argInterval()/
|
|
207
|
+
// argSpendSince() return: `null` is a transcript-directory RESOLUTION in this
|
|
208
|
+
// file ("resolved, no session yet" — findSubagentsDir() below), and the
|
|
209
|
+
// absence of an override must not read as one.
|
|
210
|
+
function argSpendDir() {
|
|
211
|
+
return arg("spend-dir") ?? undefined;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
// Node's default stdout cap is 1 MiB and a capped child read FAILS past it
|
|
215
|
+
// rather than truncating (#807). Here that failure is indistinguishable from an
|
|
216
|
+
// unreachable tool: the read degrades to the caller's empty default and the
|
|
217
|
+
// cockpit is served a BLANK board at HTTP 200 with only a stderr line — the
|
|
218
|
+
// #246 symptom, which #803 moved up from the pipe buffer rather than removed.
|
|
219
|
+
// The ledger is append-mostly and shared by every fleet script, so the ceiling
|
|
220
|
+
// arms itself over the life of a run and gives no second warning. Bounded, not
|
|
221
|
+
// Infinity: a runaway child should still be stopped rather than allowed to
|
|
222
|
+
// exhaust the box. Same headroom staleness.mjs takes, for the same reason.
|
|
223
|
+
//
|
|
224
|
+
// Both child reads in this file take it. `tryRun` is NOT the single funnel —
|
|
225
|
+
// runCiState() spawns its own, because it needs the exit code that a plain
|
|
226
|
+
// tryRun discards — so a fix applied only here would leave that one uncapped.
|
|
227
|
+
const READ_OPTS = { encoding: "utf8", maxBuffer: 64 * 1024 * 1024 };
|
|
228
|
+
|
|
229
|
+
// #1713: every child read in this file is ASYNCHRONOUS, and that is
|
|
230
|
+
// load-bearing rather than stylistic. serve() ticks on a timer inside the same
|
|
231
|
+
// process that answers HTTP, so a SYNCHRONOUS read holds the event loop for as
|
|
232
|
+
// long as the child runs — measured at 4.72–4.91s for one board — and during
|
|
233
|
+
// that window this cockpit answers nothing at all. A relaunch's identity probe
|
|
234
|
+
// (PROBE_TIMEOUT_MS, one retry, ~2s in total) landing inside it therefore got
|
|
235
|
+
// no answer, read the port as foreign, and started a SECOND cockpit on this
|
|
236
|
+
// workspace's state directory: the duplicate #1585/#1660 exist to prevent,
|
|
237
|
+
// reached through timing rather than through a missing handshake. The browser
|
|
238
|
+
// page stalled for the same reason and the same duration, every tick.
|
|
239
|
+
//
|
|
240
|
+
// One thing execFileSync did that this has to keep doing by hand: given no
|
|
241
|
+
// `stdio` of its own it re-emits the child's captured stderr onto this
|
|
242
|
+
// process's stderr (node's own `process.stderr.write(ret.stderr)`) BEFORE it
|
|
243
|
+
// throws. That single oversized write is the subject of board-cli.test.mjs's
|
|
244
|
+
// #807/#363 flood row, so it is spelled out below — and on both arms, because
|
|
245
|
+
// the sync one wrote whether or not it went on to throw.
|
|
246
|
+
//
|
|
247
|
+
// This never throws; a failure is REPORTED in the record, in the field names
|
|
248
|
+
// execFileSync's throw used — `status` for an exit code, `signal` for a kill,
|
|
249
|
+
// `code` for a libuv/node fault. That translation is the whole reason this is
|
|
250
|
+
// not a bare `promisify(execFile)`: the async error carries the EXIT CODE in
|
|
251
|
+
// `err.code` (measured: `3`, a number), where the sync one carried `ENOENT` /
|
|
252
|
+
// `ENOBUFS` there and the exit code in `status`, and runCiState() below reads
|
|
253
|
+
// all three to tell those causes apart.
|
|
254
|
+
function execRead(cmd, args) {
|
|
255
|
+
return new Promise((resolve) => {
|
|
256
|
+
execFile(cmd, args, READ_OPTS, (err, stdout, stderr) => {
|
|
257
|
+
if (stderr) process.stderr.write(stderr);
|
|
258
|
+
resolve(err
|
|
259
|
+
? {
|
|
260
|
+
stdout, error: err,
|
|
261
|
+
status: typeof err.code === "number" ? err.code : null,
|
|
262
|
+
code: typeof err.code === "string" ? err.code : null,
|
|
263
|
+
signal: err.signal ?? null,
|
|
264
|
+
}
|
|
265
|
+
: { stdout, error: null, status: 0, code: null, signal: null });
|
|
266
|
+
});
|
|
267
|
+
});
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
// Every external read is wrapped: a failure returns null and the caller keeps a
|
|
271
|
+
// last-known value. Partial board beats a crashed loop or a false alarm.
|
|
272
|
+
async function tryRun(cmd, args) {
|
|
273
|
+
const r = await execRead(cmd, args);
|
|
274
|
+
if (r.error) { console.error(`${NAME}: ${cmd} ${args.join(" ")} failed: ${r.error.message}`); return null; }
|
|
275
|
+
return r.stdout;
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
// #1714: `serve --open`'s browser launcher, one per supported platform (ADR
|
|
279
|
+
// 0009). macOS ships `open`. Linux has no single program, but `xdg-open` is
|
|
280
|
+
// the freedesktop one every mainstream desktop provides; WSL usually lacks it
|
|
281
|
+
// and has `wslview` (wslu) instead, which hands the URL to the Windows default
|
|
282
|
+
// browser. Only a launcher that is NOT ON PATH passes the URL down the list:
|
|
283
|
+
// one that ran and failed is the right program meeting a real fault, and the
|
|
284
|
+
// next one would not fix that.
|
|
285
|
+
//
|
|
286
|
+
// Never throws and never exits. A tab that did not open is a warning naming
|
|
287
|
+
// the URL — the cockpit is up and serving either way, and the operator can
|
|
288
|
+
// open it by hand — so a missing launcher changes nothing about the exit code.
|
|
289
|
+
async function openBrowser(url) {
|
|
290
|
+
const tried = [];
|
|
291
|
+
for (const cmd of process.platform === "darwin" ? ["open"] : ["xdg-open", "wslview"]) {
|
|
292
|
+
const r = await execRead(cmd, [url]);
|
|
293
|
+
if (!r.error) return;
|
|
294
|
+
if (r.code === "ENOENT") { tried.push(`${cmd} not found`); continue; }
|
|
295
|
+
tried.push(r.status != null ? `${cmd} exited ${r.status}` : `${cmd} failed: ${r.error.message.split("\n")[0]}`);
|
|
296
|
+
break;
|
|
297
|
+
}
|
|
298
|
+
console.error(`${NAME}: WARNING --open could not open a browser (${tried.join(", ")}) — the cockpit is on ${url}`);
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
// Parse tool stdout defensively: a tool can exit 0 yet print malformed or
|
|
302
|
+
// warning-prefixed stdout. Treat that like a failed read (fall back to the
|
|
303
|
+
// caller's empty default), never let it crash the tick.
|
|
304
|
+
//
|
|
305
|
+
// A nullish INPUT and a null PARSED VALUE are two faults, and the first guard
|
|
306
|
+
// does not cover the second: `JSON.parse("null")` succeeds and yields null, so
|
|
307
|
+
// without the second guard a bare `null` payload arrives at the caller as its
|
|
308
|
+
// answer. Strictly `=== null`, never falsiness — `0`, `false` and `""` are all
|
|
309
|
+
// answers a caller can read, and refusing them would substitute a shape
|
|
310
|
+
// judgement this helper is not in a position to make.
|
|
311
|
+
//
|
|
312
|
+
// Null is guarded here and shape is not, because null is the only parse result
|
|
313
|
+
// no caller of this helper can use: every other one boxes and reads, null alone
|
|
314
|
+
// has no properties, whatever shape the caller wanted. Shape is the caller's
|
|
315
|
+
// question and keeps the caller's answer — withNumber below rejects a non-array
|
|
316
|
+
// for the `gh ... list` reads, gather()'s `--prev` read demands
|
|
317
|
+
// an object, and gather()'s ledger branch takes any shape ledger.mjs emits,
|
|
318
|
+
// deliberately, for the reason stated there. A shape policy could not be written
|
|
319
|
+
// in here anyway: `fallback` is `[]` where the open-PR read calls this and null where the
|
|
320
|
+
// ledger read does, so the helper is never told what its caller wanted — only
|
|
321
|
+
// that null is not it.
|
|
322
|
+
//
|
|
323
|
+
// Reported, and never as "parse failed": the parse succeeded, and keeping the
|
|
324
|
+
// state a read reached apart from the state it failed at is what #816 was about.
|
|
325
|
+
function tryParse(json, fallback, what) {
|
|
326
|
+
if (json == null) return fallback;
|
|
327
|
+
let parsed;
|
|
328
|
+
try { parsed = JSON.parse(json); }
|
|
329
|
+
catch (e) { console.error(`${NAME}: ${what} parse failed: ${e.message}`); return fallback; }
|
|
330
|
+
if (parsed === null) {
|
|
331
|
+
console.error(`${NAME}: ${what}: payload is JSON null, not a usable answer; falling back`);
|
|
332
|
+
return fallback;
|
|
333
|
+
}
|
|
334
|
+
return parsed;
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
// A row without a usable `number` cannot be placed: compute-board.mjs joins
|
|
338
|
+
// issues/PRs to ledger rows and to each other BY number (Map keys, Set
|
|
339
|
+
// membership, `.find`), so a numberless row does not fail to render on its
|
|
340
|
+
// own — it collides with every other numberless row on the shared `undefined`
|
|
341
|
+
// key. Drop it, loudly. candidates.mjs's row guard is a different shape —
|
|
342
|
+
// comprehensive and hard-failing (die() on the first bad row) — this one is
|
|
343
|
+
// narrower: it only checks `number`, the one field whose absence corrupts
|
|
344
|
+
// OTHER rows, and degrades instead of dying (#786).
|
|
345
|
+
//
|
|
346
|
+
// `rows` itself can be the wrong shape too: `tryParse` only checks that its
|
|
347
|
+
// input is valid JSON, not that it is an array, so a syntactically-valid
|
|
348
|
+
// object or scalar from `gh` would otherwise reach the `for...of` below and
|
|
349
|
+
// throw "rows is not iterable" — an uncaught throw that reaches main()'s
|
|
350
|
+
// build path or serve()'s tick catch, exactly the crash-instead-of-degrade
|
|
351
|
+
// failure this guard exists to prevent for individual rows.
|
|
352
|
+
function withNumber(rows, what) {
|
|
353
|
+
if (!Array.isArray(rows)) {
|
|
354
|
+
console.error(`${NAME}: ${what}: expected an array of rows, got ${JSON.stringify(rows)}`);
|
|
355
|
+
return [];
|
|
356
|
+
}
|
|
357
|
+
const kept = [];
|
|
358
|
+
for (const r of rows) {
|
|
359
|
+
if (r && typeof r.number === "number") kept.push(r);
|
|
360
|
+
else console.error(`${NAME}: ${what}: dropping row with no usable number: ${JSON.stringify(r)}`);
|
|
361
|
+
}
|
|
362
|
+
return kept;
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
// #2108: gh stops a `list` read at its `--limit` with exit 0 and no warning, so
|
|
366
|
+
// a read that came back exactly that long may have been cut there — "at least
|
|
367
|
+
// this many", never "this many". candidates.mjs's refuseIfCapped() and
|
|
368
|
+
// fleet-tick.mjs's PR_LIMIT/CLAIMED_LIMIT carry the same rule; this board is a
|
|
369
|
+
// display, so it discloses a capped read (computeBoard's `n+` and capNotice)
|
|
370
|
+
// rather than dying on one. Counted on the raw rows, before withNumber() drops
|
|
371
|
+
// any: gh's cap applies to what it returned, not to what this file kept.
|
|
372
|
+
const POOL_LIMIT = 100;
|
|
373
|
+
const OPEN_PR_LIMIT = 100;
|
|
374
|
+
function hitLimit(parsed, limit) {
|
|
375
|
+
return Array.isArray(parsed) && parsed.length >= limit;
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
// #1840: which of `prNums` gh calls MERGED, in ONE `gh api graphql` query —
|
|
379
|
+
// one aliased `pullRequest(number:)` field per PR, on the cwd's repository
|
|
380
|
+
// (gh's own `{owner}`/`{repo}` placeholders, the repo every other read here
|
|
381
|
+
// resolves) — so a PR merged at any age is found, and ten PRs cost what one
|
|
382
|
+
// does. It replaced `gh pr list --state merged --limit 100`, the repo's 100
|
|
383
|
+
// most recent merges: about six days on 2026-09-25, so a row PR merged
|
|
384
|
+
// before that and never seen MERGED rendered REVIEW, turned stale and
|
|
385
|
+
// counted as claimed. Measured 2026-09-26: 400 aliases answer in one call.
|
|
386
|
+
//
|
|
387
|
+
// An empty `prNums` makes no read at all. `state` is checked, so an entry gh
|
|
388
|
+
// does not call MERGED never makes a card MERGED on its own account.
|
|
389
|
+
//
|
|
390
|
+
// A body with an object `data.repository` IS an answer even at exit 1:
|
|
391
|
+
// GitHub resolves every alias it can and nulls the rest — a number that is
|
|
392
|
+
// not a PR comes back null beside a NOT_FOUND error, and gh exits 1 with the
|
|
393
|
+
// whole body on stdout (measured 2026-09-26, gh 2.101.0, which also names
|
|
394
|
+
// the number on stderr). Refusing that body would let one such row — a
|
|
395
|
+
// typo, or an amendment-2a row keyed by an issue number — put every other
|
|
396
|
+
// row PR back in REVIEW on every tick. A null alias reads as not merged,
|
|
397
|
+
// which is what a failed read means for that one PR.
|
|
398
|
+
//
|
|
399
|
+
// Real GitHub always answers EVERY requested `p<N>` alias, null or an
|
|
400
|
+
// object — never omits one — so an object naming NONE of `prNums` is not a
|
|
401
|
+
// shape the API produces, only a corrupted or truncated one; `isJsonObject`
|
|
402
|
+
// alone cannot tell that apart from a genuine "checked, nothing merged"
|
|
403
|
+
// answer, so it is checked for too. Anything else is a failed read: `[]`,
|
|
404
|
+
// and computeBoard()'s #1841 rule takes it from there.
|
|
405
|
+
async function readMerged(prNums) {
|
|
406
|
+
if (!prNums.length) return [];
|
|
407
|
+
const fields = prNums.map((n) => `p${n}:pullRequest(number:${n}){state}`).join(" ");
|
|
408
|
+
const r = await execRead("gh", ["api", "graphql", "-F", "owner={owner}", "-F", "name={repo}",
|
|
409
|
+
"-f", `query=query($owner:String!,$name:String!){repository(owner:$owner,name:$name){${fields}}}`]);
|
|
410
|
+
let repo;
|
|
411
|
+
try { repo = JSON.parse(r.stdout)?.data?.repository; } catch {}
|
|
412
|
+
if (!isJsonObject(repo) || !prNums.some((n) => Object.prototype.hasOwnProperty.call(repo, `p${n}`))) {
|
|
413
|
+
// `how` as runCiState() spells it; never r.error.message, which repeats
|
|
414
|
+
// the whole query — one field per PR — into every failed tick's line.
|
|
415
|
+
const how = r.code ?? (r.signal ? `killed by ${r.signal}` : `exit ${r.status}`);
|
|
416
|
+
console.error(`${NAME}: gh api graphql merged read (${prNums.length} PR${prNums.length === 1 ? "" : "s"}) failed (${how}) with no usable answer; they read as not merged`);
|
|
417
|
+
return [];
|
|
418
|
+
}
|
|
419
|
+
return prNums.filter((n) => repo[`p${n}`]?.state === "MERGED");
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
// labels: gh emits an array of {name,...} objects, but a malformed row can
|
|
423
|
+
// hand back a non-array `labels` (`.map` throws) or an array containing a
|
|
424
|
+
// null/malformed element (`.name` throws) — reproduced live: either crashes
|
|
425
|
+
// gather() entirely, reaching main()'s `die()` on the build path or freezing
|
|
426
|
+
// the board on its last-known value on the serve path. Strictly worse than
|
|
427
|
+
// this ticket's original "shows undefined on the page" bug. Drop-and-continue,
|
|
428
|
+
// like withNumber above: a bad label never takes its row's whole labels array
|
|
429
|
+
// down, and a bad labels field never takes the row down.
|
|
430
|
+
function labelsOf(row) {
|
|
431
|
+
if (!Array.isArray(row.labels)) return [];
|
|
432
|
+
return row.labels
|
|
433
|
+
.map((l) => (l && typeof l.name === "string") ? l.name : null)
|
|
434
|
+
.filter(Boolean);
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
// ci-state.mjs exits 0 for green, 1 for not-green or no-ci, 2 for a hard
|
|
438
|
+
// failure — no-ci is its own verdict and shares exit 1 because this call omits
|
|
439
|
+
// --declare-no-ci, the only thing that would move it to exit 0 — and on
|
|
440
|
+
// exit 1 it has ALREADY printed its verdict JSON to stdout before exiting, so a
|
|
441
|
+
// thrown exit 1 carries a real verdict. Feed that to mapCi: discarding e.stdout,
|
|
442
|
+
// as a plain tryRun would, makes red/still-running CI unreachable — every
|
|
443
|
+
// non-green PR reads as "unknown" and the red-ci flag, the top of the attention
|
|
444
|
+
// strip, never fires.
|
|
445
|
+
//
|
|
446
|
+
// What separates a verdict from a failed read is the EXIT CODE. Emptiness of
|
|
447
|
+
// stdout was only ever a proxy for it, and #262 retired the proxy: a quota
|
|
448
|
+
// refusal now names its cause on stdout on the way out at exit 2, so "non-empty
|
|
449
|
+
// stdout" began reading an outage as a reading. That payload carries no
|
|
450
|
+
// `status`, so mapCi answered "unknown" and gather()'s prevCi carry-forward —
|
|
451
|
+
// which only a null return reaches — was skipped, overwriting a PR's
|
|
452
|
+
// last-known-good CI state during a blip that clears itself. Exit 2 means the
|
|
453
|
+
// question could not be answered, whatever the script printed while saying so.
|
|
454
|
+
//
|
|
455
|
+
// The exit code is not sufficient on its own either (#875), for the symmetric
|
|
456
|
+
// reason: it reports that the child reached its own exit path, never that its
|
|
457
|
+
// payload arrived whole. `e.status !== 2` is also true of a signal kill, where
|
|
458
|
+
// `status` is null, and of a write cut mid-JSON at exit 1 — emit() over in
|
|
459
|
+
// ci-state.mjs abandons a short write it cannot retry, which keeps the exit
|
|
460
|
+
// code intact while losing the tail of the line. Those bytes were returned AS a
|
|
461
|
+
// verdict, mapCi could not parse them, and the non-null return skipped the very
|
|
462
|
+
// carry-forward #262 added: the #262 regression re-entering through the gate
|
|
463
|
+
// built to stop it. So both halves have to hold — a non-2 exit AND bytes that
|
|
464
|
+
// parse.
|
|
465
|
+
//
|
|
466
|
+
// The parse is the discriminator rather than "any abnormal termination", the
|
|
467
|
+
// other candidate, because only the parse gets both directions right. It
|
|
468
|
+
// catches the cut-off exit-1 write, which carries status 1 and no signal at all
|
|
469
|
+
// (measured), and it goes on ACCEPTING a complete payload from a child killed
|
|
470
|
+
// after writing it, as well as no-ci — a real exit-1 verdict whose own `status`
|
|
471
|
+
// field is null, so a status-shaped guard tightened far enough to catch a
|
|
472
|
+
// truncation starts refusing it and resurrects a red for a PR with no run
|
|
473
|
+
// behind it. Wholeness is the only question asked here; SHAPE stays mapCi's,
|
|
474
|
+
// which is total over every payload that parses.
|
|
475
|
+
async function runCiState(scriptDir, pr) {
|
|
476
|
+
const r = await execRead("node", [join(scriptDir, "ci-state.mjs"), "--pr", String(pr), "--quiet"]);
|
|
477
|
+
const out = r.stdout;
|
|
478
|
+
if (r.error) {
|
|
479
|
+
// `r.stdout` and not `error.stdout`: what the child managed to write before
|
|
480
|
+
// it died is the salvage this whole block exists for, and execRead's record
|
|
481
|
+
// carries it on every arm — including a spawn failure, where it is "".
|
|
482
|
+
if (r.status === 2 || !out.trim()) {
|
|
483
|
+
console.error(`${NAME}: ci-state --pr ${pr} failed: ${r.error.message}`);
|
|
484
|
+
return null;
|
|
485
|
+
}
|
|
486
|
+
// Its own line, not the one above: "failed" reads as "the child never
|
|
487
|
+
// answered", and an operator looking at a carried-forward CI value needs to
|
|
488
|
+
// know a payload DID arrive and was thrown away, and why.
|
|
489
|
+
//
|
|
490
|
+
// `how` reads the libuv/node `code` first — the three-way ci-state.mjs
|
|
491
|
+
// already uses at its own child reads — because one cause of this shape is
|
|
492
|
+
// OURS: overrunning READ_OPTS.maxBuffer is enforced by node killing the
|
|
493
|
+
// child, and that arrives as code ERR_CHILD_PROCESS_STDIO_MAXBUFFER
|
|
494
|
+
// (measured; the synchronous read this replaced reported the same cap as
|
|
495
|
+
// signal SIGTERM carrying code ENOBUFS). A signal-first `how` renders a cap
|
|
496
|
+
// this file sets as an outside kill, sending the operator after an OOM kill
|
|
497
|
+
// or a stray `kill -TERM`. The signal arm stays ahead of the exit arm
|
|
498
|
+
// behind it: `status` is null on a real signal kill, where "exit null"
|
|
499
|
+
// would name nothing to act on. execRead splits the async error's one
|
|
500
|
+
// `code` field back into these three, so all three arms still read as they
|
|
501
|
+
// did — measured: an exit 3 gives `status` 3 and no `code`, a SIGKILL gives
|
|
502
|
+
// `signal` and neither, an unreachable binary gives `code` ENOENT.
|
|
503
|
+
//
|
|
504
|
+
// Through the warn-once gate, keyed on the PR exactly as mapCi's
|
|
505
|
+
// `ci-parse` gate is and for the same reason: serve() re-gathers on a
|
|
506
|
+
// timer, so a payload truncated by a cause that persists is truncated
|
|
507
|
+
// again on every tick, and an ungated line spends one per PR per tick for
|
|
508
|
+
// as long as the cause lasts. Its own channel, `ci-salvage-nonzero`,
|
|
509
|
+
// distinct from both `ci-parse` and the exit-0 guard's `ci-salvage-exit0`
|
|
510
|
+
// below: for any one payload the three are mutually exclusive — bytes
|
|
511
|
+
// refused here return null and never reach mapCi — so a channel shared
|
|
512
|
+
// between any two of them would buy nothing, and would let whichever arm
|
|
513
|
+
// a PR happened to hit FIRST silence a later, structurally different
|
|
514
|
+
// failure on another arm for the rest of the run — measured: driving the
|
|
515
|
+
// same PR through this arm then the exit-0 guard below printed only the
|
|
516
|
+
// first tick's warning until the channels were split.
|
|
517
|
+
try { JSON.parse(out); }
|
|
518
|
+
catch (pe) {
|
|
519
|
+
const how = r.code ?? (r.signal ? `killed by ${r.signal}` : `exit ${r.status}`);
|
|
520
|
+
warnOnce("ci-salvage-nonzero", pr, `ci-state --pr ${pr} (${how}) left a payload that will not parse (${pe.message}); carrying the previous CI value forward rather than reading this as a verdict`);
|
|
521
|
+
return null;
|
|
522
|
+
}
|
|
523
|
+
return out;
|
|
524
|
+
}
|
|
525
|
+
// #1593: exit 0 was never covered by any of the checks above — they only run
|
|
526
|
+
// once the child read reports a failure, and a child that exits 0 reports
|
|
527
|
+
// none. So the same write cut mid-JSON that the failure block above salvages
|
|
528
|
+
// at exit 1 rode straight through here and into mapCi at exit 0, where an
|
|
529
|
+
// unparseable string maps to "unknown" and gather()'s carry-forward — which
|
|
530
|
+
// only a null return reaches — was skipped, discarding the PR's last-known
|
|
531
|
+
// CI value exactly as #262 did before the exit-2 case was fixed. Same parse
|
|
532
|
+
// check, same null return as the failure block above — but its OWN channel,
|
|
533
|
+
// `ci-salvage-exit0`, not that block's `ci-salvage-nonzero`: a
|
|
534
|
+
// zero-exit child does not get a looser contract than a non-zero one, and
|
|
535
|
+
// the two arms are structurally different failures that must not silence
|
|
536
|
+
// each other (see the channel-split comment above).
|
|
537
|
+
//
|
|
538
|
+
// Emptiness is checked before the parse, and gets its own wording: an empty
|
|
539
|
+
// `out` is not a corrupted payload, it is no payload at all — "left a
|
|
540
|
+
// payload that will not parse" is a true diagnosis of truncated JSON and a
|
|
541
|
+
// false one of a child that printed nothing, the same distinction the
|
|
542
|
+
// empty/status-2 branch above draws for a non-zero exit.
|
|
543
|
+
try { JSON.parse(out); }
|
|
544
|
+
catch (pe) {
|
|
545
|
+
const msg = out.trim()
|
|
546
|
+
? `ci-state --pr ${pr} (exit 0) left a payload that will not parse (${pe.message}); carrying the previous CI value forward rather than reading this as a verdict`
|
|
547
|
+
: `ci-state --pr ${pr} (exit 0) never answered; carrying the previous CI value forward rather than reading this as a verdict`;
|
|
548
|
+
warnOnce("ci-salvage-exit0", pr, msg);
|
|
549
|
+
return null;
|
|
550
|
+
}
|
|
551
|
+
return out;
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
// Every warn-once gate in this file routes through here. The stored key is the
|
|
555
|
+
// CHANNEL joined to the caller's key, never the caller's key alone: the gates
|
|
556
|
+
// below are keyed on paths, and two of them are keyed on the SAME transcript
|
|
557
|
+
// path, so a bare-key Set would let one channel's warning consume the other's
|
|
558
|
+
// line for that file — a behaviour change, not a refactor. NUL joins them
|
|
559
|
+
// because no channel name or path can hold one, so no two distinct (channel,
|
|
560
|
+
// key) pairs can collide. Every caller keys on a PR, a path, or the fault's
|
|
561
|
+
// own message, so `key` is never empty.
|
|
562
|
+
const warnedOnce = new Set();
|
|
563
|
+
function warnOnce(channel, key, msg) {
|
|
564
|
+
const k = `${channel}\0${key}`;
|
|
565
|
+
if (warnedOnce.has(k)) return;
|
|
566
|
+
warnedOnce.add(k);
|
|
567
|
+
console.error(`${NAME}: ${msg}`);
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
// The `ci-parse` gate is keyed on the PR, not on the payload: `serve` rebuilds
|
|
571
|
+
// every ~15s and calls mapCi once per PR per tick, so a payload that is broken
|
|
572
|
+
// is broken on every tick, and a payload-keyed gate would flood anyway the
|
|
573
|
+
// moment the garbage varies between ticks. A single global flag is the other
|
|
574
|
+
// wrong answer — it would let the first broken PR mask every later one for the
|
|
575
|
+
// rest of the run, which is the silence this gate exists to end.
|
|
576
|
+
|
|
577
|
+
// ci-state's verdict already excludes behind-count staleness. Map it, and treat
|
|
578
|
+
// anything not cleanly green-or-completed-red as unknown — never a false red.
|
|
579
|
+
//
|
|
580
|
+
// `pr` is carried for the warn below and nothing else: an unparseable payload
|
|
581
|
+
// has no field to identify itself by, and "some PR's CI payload was garbage" is
|
|
582
|
+
// not actionable. The caller has the number in hand.
|
|
583
|
+
export function mapCi(ciJson, pr) {
|
|
584
|
+
// A NULL payload, which is a failed read runCiState() has already reported
|
|
585
|
+
// on stderr. Warning again here would report one failure twice. Null
|
|
586
|
+
// strictly, not falsiness: an EMPTY payload is not that case. Since #1593
|
|
587
|
+
// runCiState() parse-checks its exit-0 return too, so its own callers never
|
|
588
|
+
// hand this an empty string any more — but mapCi() is exported and total
|
|
589
|
+
// over any caller, not just this file's, so a `!ciJson` guard that swallowed
|
|
590
|
+
// "" as though it had been reported would still be wrong. It falls through
|
|
591
|
+
// to the parse below instead, which is where it earns its line.
|
|
592
|
+
if (ciJson == null) return "unknown";
|
|
593
|
+
let d;
|
|
594
|
+
// A payload that will not parse is a THIRD state, and the return value cannot
|
|
595
|
+
// carry it: "unknown" is what the regression gate pins, since a false red is
|
|
596
|
+
// worse than no verdict. So the distinction leaves through stderr or not at
|
|
597
|
+
// all. #875 closed this for runCiState()'s catch block (a payload that will
|
|
598
|
+
// not parse there is a failed read, reaching gather()'s carry-forward);
|
|
599
|
+
// #1593 closed it for the exit-0 arm the same way (see runCiState() above),
|
|
600
|
+
// so a write cut mid-JSON no longer reaches mapCi from gather() on EITHER
|
|
601
|
+
// arm — a lost write now reads as a failed read there too, and that PR's
|
|
602
|
+
// last-known CI value stands instead of reverting to "unknown". This catch
|
|
603
|
+
// stays live regardless: mapCi() is exported and total over any string
|
|
604
|
+
// handed to it, parseable or not, and its own tests drive it directly
|
|
605
|
+
// without going through runCiState() at all.
|
|
606
|
+
try { d = JSON.parse(ciJson); }
|
|
607
|
+
catch (e) {
|
|
608
|
+
warnOnce("ci-parse", pr, `PR ${pr} ci-state payload is not JSON (${e.message}); reading its CI as unknown, so its red-ci flag stays down`);
|
|
609
|
+
return "unknown";
|
|
610
|
+
}
|
|
611
|
+
// JSON.parse("null") succeeds and yields d === null. Nullishness, not
|
|
612
|
+
// object-ness, is the discriminator: `[]` and `{}` are typeof "object" just
|
|
613
|
+
// as null is, but null alone has no properties to read, so the status gate
|
|
614
|
+
// throws a TypeError on it where every other parsed payload boxes and reads
|
|
615
|
+
// its status as undefined. Hence a guard with its own return, rather than a
|
|
616
|
+
// payload that reaches the status gate and answers "unknown" there. Silent,
|
|
617
|
+
// not warned: the status gate already answers every parseable payload it
|
|
618
|
+
// cannot read a status from without a line, and a bare "null" is no more
|
|
619
|
+
// corrupt than those.
|
|
620
|
+
if (d === null) return "unknown";
|
|
621
|
+
if (d.status !== "completed") return "unknown"; // still running, or no run yet (status null)
|
|
622
|
+
if (d.verdict === "green") return "green";
|
|
623
|
+
if (d.verdict === "not-green") return "red";
|
|
624
|
+
return "unknown";
|
|
625
|
+
}
|
|
626
|
+
|
|
627
|
+
// Where this session's member transcripts live:
|
|
628
|
+
// ~/.omp/agent/sessions/<encoded-cwd>/<ISO>_<uuid>/
|
|
629
|
+
// The encoder lives in member-record.mjs (#1342), shared with
|
|
630
|
+
// member-outcomes.mjs; it is re-exported here under its original name so
|
|
631
|
+
// nothing importing `encodeProjectDir` from this file needs to change.
|
|
632
|
+
export { encodeProjectDir };
|
|
633
|
+
|
|
634
|
+
// The session uuid is not knowable from here, so take the most recently
|
|
635
|
+
// active one. Rank on the newest TRANSCRIPT mtime, not on the session
|
|
636
|
+
// directory's own: a directory's mtime moves when an entry is created or
|
|
637
|
+
// removed, never when a file inside it is appended to. Ranking on the
|
|
638
|
+
// directory therefore tracked the last agent SPAWN rather than the last
|
|
639
|
+
// agent activity — and since the cockpit launches in run-team phase 0,
|
|
640
|
+
// before the first agent spawns, the live session has no transcript yet and
|
|
641
|
+
// a PREVIOUS session won. The board would render a prior run's spend as
|
|
642
|
+
// this run's, then silently switch when the first agent landed. That is the
|
|
643
|
+
// one failure mode here that produces confidently wrong numbers rather than
|
|
644
|
+
// no numbers.
|
|
645
|
+
//
|
|
646
|
+
// Returns { error } when there is no project dir for this cwd — a bug that
|
|
647
|
+
// never fixes itself — and null when one resolves but holds no sessions
|
|
648
|
+
// yet, which is normal at run start. Collapsing those two into one bare
|
|
649
|
+
// null is what hid the encoding bug above. A listing that THROWS is
|
|
650
|
+
// { error } too.
|
|
651
|
+
export function findSubagentsDir(home = process.env.HOME, cwd = process.cwd()) {
|
|
652
|
+
try {
|
|
653
|
+
const tree = sessionDirs(home, cwd);
|
|
654
|
+
if (tree.dirs === null) {
|
|
655
|
+
return { error: `no transcript dir for cwd ${cwd} (looked in ${tree.root})` };
|
|
656
|
+
}
|
|
657
|
+
const cands = tree.dirs
|
|
658
|
+
.map((d) => ({ d, m: newestTranscriptMs(d) }))
|
|
659
|
+
.sort((a, b) => b.m - a.m);
|
|
660
|
+
return cands.length ? cands[0].d : null;
|
|
661
|
+
} catch (e) { return { error: `transcript lookup failed: ${e.message}` }; }
|
|
662
|
+
}
|
|
663
|
+
|
|
664
|
+
// The candidate session directories for this cwd. `dirs: null` means there
|
|
665
|
+
// is no project dir here at all; `[]` means there is one holding no session
|
|
666
|
+
// yet. `root` is where it looked, for the error above.
|
|
667
|
+
//
|
|
668
|
+
// `encodeProjectDir` realpath-resolves a cwd outside $HOME, which throws
|
|
669
|
+
// ENOENT when that cwd does not exist. No omp session can be keyed on such a
|
|
670
|
+
// cwd, so THAT is this tree's absence — not a lookup fault. Any OTHER error
|
|
671
|
+
// (EACCES on an ancestor directory, say) is a real fault, not an absence,
|
|
672
|
+
// and must not be relabelled as one: swallowing it here would crash
|
|
673
|
+
// silently with no signal anything went wrong. It is rethrown, uncaught,
|
|
674
|
+
// into findSubagentsDir's own catch — the same fate a listing failure below
|
|
675
|
+
// already gets, deliberately.
|
|
676
|
+
function sessionDirs(home, cwd) {
|
|
677
|
+
const sessions = join(home, ".omp", "agent", "sessions");
|
|
678
|
+
let root;
|
|
679
|
+
try {
|
|
680
|
+
root = join(sessions, encodeProjectDir(cwd, { home }));
|
|
681
|
+
} catch (e) {
|
|
682
|
+
if (e.code !== "ENOENT") throw e;
|
|
683
|
+
return { root: sessions, dirs: null };
|
|
684
|
+
}
|
|
685
|
+
if (!existsSync(root)) return { root, dirs: null };
|
|
686
|
+
const dirs = readdirSync(root, { withFileTypes: true })
|
|
687
|
+
.filter((e) => e.isDirectory() && isOmpSessionDirName(e.name))
|
|
688
|
+
.map((e) => join(root, e.name));
|
|
689
|
+
return { root, dirs };
|
|
690
|
+
}
|
|
691
|
+
|
|
692
|
+
// Newest *.jsonl mtime anywhere under a session's transcript dir, 0 if it
|
|
693
|
+
// holds none. Recursive: a nested member (a dispatcher's own further
|
|
694
|
+
// fan-out, one directory level down — the same walk ompSessionTranscripts
|
|
695
|
+
// does to book their spend) can be the only fresh activity in an otherwise
|
|
696
|
+
// idle-looking session, and a scan bounded to the top level would score
|
|
697
|
+
// that session 0 and lose it to a genuinely stale sibling.
|
|
698
|
+
//
|
|
699
|
+
// A dir whose transcripts are all unreadable loses to one that is readable,
|
|
700
|
+
// which is the behaviour we want when picking "the live session".
|
|
701
|
+
//
|
|
702
|
+
// The scan is wrapped for the same reason the per-file stat below is. This runs
|
|
703
|
+
// once per CANDIDATE, so an uncaught throw here does not just lose one dir — it
|
|
704
|
+
// escapes findSubagentsDir's try and turns the whole lookup into { error },
|
|
705
|
+
// blacking out every readable session over one bad sibling. Scoring 0 is what
|
|
706
|
+
// the comment above already promises: a dir we cannot read simply loses.
|
|
707
|
+
function newestTranscriptMs(dir) {
|
|
708
|
+
let names;
|
|
709
|
+
try { names = readdirSync(dir, { recursive: true }); } catch { return 0; }
|
|
710
|
+
let newest = 0;
|
|
711
|
+
for (const f of names) {
|
|
712
|
+
if (!f.endsWith(".jsonl")) continue;
|
|
713
|
+
try { newest = Math.max(newest, statSync(join(dir, f)).mtimeMs); } catch { /* raced away */ }
|
|
714
|
+
}
|
|
715
|
+
return newest;
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
// #1583: the transcript directory a `serve` process is bound to, resolved
|
|
719
|
+
// once it can be trusted and reused by every tick after it. findSubagentsDir()
|
|
720
|
+
// above ranks sessions by newest transcript mtime and gather() reached it
|
|
721
|
+
// through gatherSpend() on EVERY tick (~15s by default), so two sessions live
|
|
722
|
+
// under one project directory took turns winning: the panel alternated
|
|
723
|
+
// between two runs' numbers with nothing on the page or on stderr to say it
|
|
724
|
+
// had switched.
|
|
725
|
+
//
|
|
726
|
+
// The pin holds the first answer that COULD BE THIS RUN'S, not the first
|
|
727
|
+
// non-null answer and not the first call (#1679). findSubagentsDir() has
|
|
728
|
+
// three returns and none of them is safe to latch on sight: a directory
|
|
729
|
+
// resolved at pin-construction time can be a PREVIOUS run's session — newer
|
|
730
|
+
// than nothing else that exists yet, so it wins the ranking, but not this
|
|
731
|
+
// run's — and `{ error }` can be a transient fault (EACCES on a directory
|
|
732
|
+
// mid-permission-change, EMFILE, EIO) recovering on the very next tick just
|
|
733
|
+
// as easily as it can be the truly unresolvable "bug that never fixes
|
|
734
|
+
// itself" the ticket originally reasoned about. Latching either one turns
|
|
735
|
+
// the self-correcting degradation this file's header describes into a
|
|
736
|
+
// permanent one: measured (#1679), a chmod'd-then-restored session tree left
|
|
737
|
+
// the OLD `??=` pin stuck on `{ error }` forever while the unpinned lookup
|
|
738
|
+
// recovered on its very next tick, and a prior run's session dir
|
|
739
|
+
// present at launch left the old pin on yesterday's numbers for the whole of
|
|
740
|
+
// today's run, even once today's first agent had written its own transcript.
|
|
741
|
+
//
|
|
742
|
+
// So `launchMs`, captured once at construction, is the boundary: `null` (no
|
|
743
|
+
// session anywhere yet) and `{ error }` (unresolvable OR transiently
|
|
744
|
+
// unreadable — indistinguishable from here, so neither is trusted) both keep
|
|
745
|
+
// re-asking, same one scan per tick the `null` case always cost. A resolved
|
|
746
|
+
// directory whose own newest transcript predates `launchMs` is treated the
|
|
747
|
+
// same way — returned as this tick's best-effort answer, so the panel still
|
|
748
|
+
// renders it, but not cached — because a transcript that stopped moving
|
|
749
|
+
// before this pin existed cannot be evidence of THIS run's activity. Only a
|
|
750
|
+
// directory whose newest transcript is at or after `launchMs` latches, which
|
|
751
|
+
// is the one fact available here that says "something is writing to this
|
|
752
|
+
// session on my watch", never a previous run's signature.
|
|
753
|
+
//
|
|
754
|
+
// An explicit directory skips the heuristic entirely — never resolved, never
|
|
755
|
+
// re-picked, and findSubagentsDir() is never called at all, so a tree it could
|
|
756
|
+
// not read cannot degrade a panel the operator has already named the source
|
|
757
|
+
// for. `home`/`cwd` are captured HERE rather than read per call for the same
|
|
758
|
+
// reason the resolution is: a pin that could answer for a different workspace
|
|
759
|
+
// later is not a pin.
|
|
760
|
+
//
|
|
761
|
+
// The limitation this leaves is stated at the top of this file: two sessions
|
|
762
|
+
// that both start writing after the pin exists are still indistinguishable.
|
|
763
|
+
// --spend-dir is the way out.
|
|
764
|
+
export function spendDirPin(explicit, home = process.env.HOME, cwd = process.cwd()) {
|
|
765
|
+
if (explicit != null) return () => explicit;
|
|
766
|
+
const launchMs = Date.now();
|
|
767
|
+
let pinned = null;
|
|
768
|
+
return () => {
|
|
769
|
+
if (pinned !== null) return pinned;
|
|
770
|
+
const answer = findSubagentsDir(home, cwd);
|
|
771
|
+
if (typeof answer !== "string") return answer; // null or { error }: neither is a trustworthy answer to latch
|
|
772
|
+
if (newestTranscriptMs(answer) < launchMs) return answer; // predates this pin — could be a previous run's
|
|
773
|
+
return (pinned = answer);
|
|
774
|
+
};
|
|
775
|
+
}
|
|
776
|
+
|
|
777
|
+
// The `no-spend-dir` gate warns at most once per process PER DISTINCT ERROR.
|
|
778
|
+
// `dir.error` is not constant — findSubagentsDir words an unresolvable project
|
|
779
|
+
// dir differently from a lookup that threw — so it is keyed on the message
|
|
780
|
+
// itself, not the empty string this gate used to key on: an empty key
|
|
781
|
+
// collapsed both wordings onto the one `no-spend-dir\0` slot, so whichever
|
|
782
|
+
// fault landed first for a process consumed the slot and a later, genuinely
|
|
783
|
+
// different fault never reached stderr again for the rest of the run. Keying
|
|
784
|
+
// on `dir.error` fixes that without losing the steady-state behaviour: `cwd`
|
|
785
|
+
// and `HOME` are fixed for the life of `serve`, so a repeating identical fault
|
|
786
|
+
// still costs one line, not one per tick. Either way this gate only ever
|
|
787
|
+
// controlled the repeated stderr LINE — a fault that differs still reaches the
|
|
788
|
+
// browser on the tick it happens, through the `{ error }` gatherSpend returns
|
|
789
|
+
// for it, which board.html renders as the panel's text. The board gathers
|
|
790
|
+
// every ~15s and a line repeating at that rate just trains the eye to ignore
|
|
791
|
+
// it.
|
|
792
|
+
//
|
|
793
|
+
// The `skips` gate is the same rule, per transcript: a file that is broken is
|
|
794
|
+
// broken every tick, and at the default 15s interval three of them are 720 lines
|
|
795
|
+
// an hour. Keyed on the FULL PATH, not the bare filename — gatherSpend
|
|
796
|
+
// re-resolves its dir on every tick, so a bare-filename key would silence a
|
|
797
|
+
// genuinely different broken file living under a second session directory. The
|
|
798
|
+
// count still reaches the browser every tick via `skipped`, which is the route
|
|
799
|
+
// that matters here.
|
|
800
|
+
|
|
801
|
+
// Scope is the SESSION directory, which is the closest thing to a run
|
|
802
|
+
// boundary that actually exists on disk — one session, one folder,
|
|
803
|
+
// identified by its own NAME: `<ISO>_<uuid>` (member-record.mjs's
|
|
804
|
+
// isOmpSessionDirName, the rule its own readers dispatch on).
|
|
805
|
+
//
|
|
806
|
+
// `sinceMs` is opt-in and defaults to no filter. An earlier attempt defaulted it
|
|
807
|
+
// to the ledger's mtime as a "run start" marker; that is wrong and silently
|
|
808
|
+
// reported zero, because the controller rewrites ledger rows continuously, so the
|
|
809
|
+
// mtime is always ~now and every transcript sorts as older than it. Kept as an
|
|
810
|
+
// explicit option for the one case the session scope cannot cover: a single
|
|
811
|
+
// session that spans two fleet runs, where the caller knows the boundary and the
|
|
812
|
+
// board does not.
|
|
813
|
+
//
|
|
814
|
+
// Three returns, deliberately distinct — collapsing them into one bare null is
|
|
815
|
+
// what let the path-encoding bug live: `{ ok: false, error }` is a bug the
|
|
816
|
+
// operator must act on and the UI shows it; `null` is the normal "nothing yet"
|
|
817
|
+
// and the UI hides the panel; `{ ok: true, ... }` is data.
|
|
818
|
+
//
|
|
819
|
+
// `ok` is an explicit TAG, and it is what the page switches on — never the
|
|
820
|
+
// presence or the truthiness of any other field. Reading the error case off
|
|
821
|
+
// `error`'s truthiness is what #959 was: `e.message` is "" for an error thrown
|
|
822
|
+
// without one and `undefined` for a thrown non-Error, so two shapes the catch
|
|
823
|
+
// below can emit matched neither the error branch nor a success shape, and the
|
|
824
|
+
// panel HID — a fault rendered as an idle run, the one conflation this panel
|
|
825
|
+
// exists to remove. A presence check would have fixed the "" case and still
|
|
826
|
+
// mis-routed the `undefined` one, and either is a refactor away from a
|
|
827
|
+
// truthiness check returning, because nothing in the data says which field is
|
|
828
|
+
// the tag. This follows `ledger.mjs`'s `tracker`: a boolean checked before any
|
|
829
|
+
// success-only field is read.
|
|
830
|
+
export function gatherSpend({ dir = findSubagentsDir(), sinceMs = null, topN = 8, explicit = false } = {}) {
|
|
831
|
+
try {
|
|
832
|
+
// #1583: a caller-supplied `null` is a RESOLUTION from one that owns a pin
|
|
833
|
+
// (spendDirPin() above) — the project directory is there and holds no
|
|
834
|
+
// session yet — and must not run the heuristic a second time; only an
|
|
835
|
+
// omitted `dir` (every gatherSpend test driver, and `build`, which is one
|
|
836
|
+
// gather per process and so needs no pin) defaults to it. A default
|
|
837
|
+
// parameter fires on `undefined` alone, never `null`, which is exactly
|
|
838
|
+
// that distinction — the hand-rolled `if (dir === undefined) dir =
|
|
839
|
+
// findSubagentsDir();` this used to spell out is redundant with it.
|
|
840
|
+
//
|
|
841
|
+
// `explicit` (#1679) is true only when `dir` came from the operator's
|
|
842
|
+
// own --spend-dir, never from the heuristic or an unresolved pin — see
|
|
843
|
+
// its one use below, at the empty-directory branch.
|
|
844
|
+
const dirError = dir?.error;
|
|
845
|
+
if (dirError) {
|
|
846
|
+
warnOnce("no-spend-dir", dirError, dirError);
|
|
847
|
+
return { ok: false, error: dirError };
|
|
848
|
+
}
|
|
849
|
+
if (!dir) return null; // resolved, but this session has spawned no agents yet
|
|
850
|
+
// #1679/#1302: only for an EXPLICIT --spend-dir — the heuristic's own
|
|
851
|
+
// findSubagentsDir() already dispatches on isOmpSessionDirName, so a
|
|
852
|
+
// resolved-but-non-heuristic `dir` here only ever arrives from the
|
|
853
|
+
// operator naming a directory directly. Without this check the
|
|
854
|
+
// mis-levelled path this same function's comments already name (the
|
|
855
|
+
// encoded-cwd project dir instead of its own <ISO>_<uuid> child) walked
|
|
856
|
+
// straight into readOmpSpend below, which recurses over every nested
|
|
857
|
+
// .jsonl with no name check of its own, and booked every session's
|
|
858
|
+
// transcripts — including the controller's own main-session one — as
|
|
859
|
+
// "agents" instead of refusing.
|
|
860
|
+
if (explicit && !isOmpSessionDirName(basename(dir))) {
|
|
861
|
+
const error = `${dir} is not an omp <ISO>_<uuid> session directory`;
|
|
862
|
+
warnOnce("bad-spend-dir", dir, `--spend-dir ${error}`);
|
|
863
|
+
return { ok: false, error };
|
|
864
|
+
}
|
|
865
|
+
|
|
866
|
+
const { agents, toolTables, skipped, damaged } = readOmpSpend(dir, sinceMs);
|
|
867
|
+
if (!agents.length) {
|
|
868
|
+
// #1894: `damaged` belongs here beside `skipped`. An omp transcript with
|
|
869
|
+
// no parseable assistant-with-usage line folds to no model, so
|
|
870
|
+
// readOmpSpend drops it without a throw — `skipped` stays 0 — and its
|
|
871
|
+
// non-last parse failures are the only trace that the directory held a
|
|
872
|
+
// transcript at all. Reading `skipped` alone sent that down the empty
|
|
873
|
+
// path below: a hidden panel, or an explicit override told the directory
|
|
874
|
+
// "holds no agent transcripts". A torn LAST line never counts as damaged,
|
|
875
|
+
// so a live write's partial first line still takes the empty path.
|
|
876
|
+
// A wholly-corrupt transcript with a readable "not executed" tool
|
|
877
|
+
// result but no assistant-with-usage line still drops here rather
|
|
878
|
+
// than booking at zero spend.
|
|
879
|
+
//
|
|
880
|
+
// `damaged` counts LINES, `skipped` whole transcripts, so each keeps its
|
|
881
|
+
// own clause — the lines one in board.html's damagedPhrase wording. "all
|
|
882
|
+
// N transcripts unreadable" stays for `skipped` alone: beside damaged
|
|
883
|
+
// lines it would count only the whole files and read as the entire loss.
|
|
884
|
+
if (damaged) {
|
|
885
|
+
const lost = [`${damaged} damaged transcript line${damaged === 1 ? "" : "s"}`];
|
|
886
|
+
if (skipped) lost.unshift(`${skipped} transcript${skipped === 1 ? "" : "s"} unreadable`);
|
|
887
|
+
return { ok: false, error: `no agent turn readable: ${lost.join("; ")}` };
|
|
888
|
+
}
|
|
889
|
+
if (skipped) return { ok: false, error: `all ${skipped} transcripts unreadable` };
|
|
890
|
+
// #1679: only for an EXPLICIT override — never the heuristic's own
|
|
891
|
+
// "resolved, no session yet" `null` case two arms up, which is the
|
|
892
|
+
// normal state at launch and must stay silent. An operator who named
|
|
893
|
+
// this exact directory has a panel that just went quiet with nothing
|
|
894
|
+
// saying whether that is the normal "not written yet" wait or a typo'd
|
|
895
|
+
// / mis-levelled path (e.g. the encoded-cwd directory instead of its
|
|
896
|
+
// own `<ISO>_<uuid>` child) that will never resolve.
|
|
897
|
+
if (explicit) warnOnce("empty-spend-dir", dir, `--spend-dir ${dir} exists but holds no agent transcripts`);
|
|
898
|
+
return null;
|
|
899
|
+
}
|
|
900
|
+
const spend = computeSpend({ agents, topN });
|
|
901
|
+
const tools = mergeTools(toolTables);
|
|
902
|
+
// What fraction of cache_creation the tool table actually explains. It is
|
|
903
|
+
// never 100%: only a turn that FOLLOWS a tool result can be attributed to a
|
|
904
|
+
// tool, and an agent's first turn — usually its largest single write, the
|
|
905
|
+
// system prompt and context — follows nothing. Surfacing the coverage keeps
|
|
906
|
+
// the two columns honest about being different bases; without it the tool
|
|
907
|
+
// percentages silently read as shares of the headline number, which they
|
|
908
|
+
// are not.
|
|
909
|
+
const attributed = tools.reduce((n, t) => n + t.cacheWrite, 0);
|
|
910
|
+
const attributedPct = spend.totals.cacheWrite > 0 ? (attributed / spend.totals.cacheWrite) * 100 : 0;
|
|
911
|
+
// `ok` last, so a future field named `ok` on computeSpend's return cannot
|
|
912
|
+
// silently untag a success (a later spread key always wins over an earlier one).
|
|
913
|
+
return { ...spend, tools, attributedPct, skipped, damaged, since: sinceMs, ok: true };
|
|
914
|
+
} catch (e) {
|
|
915
|
+
// A real bug, not an empty run — say so rather than hiding the panel, which
|
|
916
|
+
// is what turned the last type surprise in here into "no panel appeared".
|
|
917
|
+
// `e.message` is carried as-is, including the "" and `undefined` a
|
|
918
|
+
// message-less throw would give it: the tag above is what routes this to the
|
|
919
|
+
// error panel, so an unhelpful message costs wording, never the panel.
|
|
920
|
+
// #1679: an explicit --spend-dir naming a directory that does not exist
|
|
921
|
+
// YET (the legitimate, tested case) throws ENOENT here on every tick
|
|
922
|
+
// until it appears, and this catch used to print unconditionally — one
|
|
923
|
+
// line per ~15s tick, forever. Routed through warnOnce, keyed on the
|
|
924
|
+
// message the same way the `{ error }` arm above it already is, so a
|
|
925
|
+
// repeating fault costs one stderr line, not one per tick.
|
|
926
|
+
warnOnce("spend-read-failed", e.message, `spend read failed: ${e.message}`);
|
|
927
|
+
return { ok: false, error: e.message };
|
|
928
|
+
}
|
|
929
|
+
}
|
|
930
|
+
|
|
931
|
+
// omp's side (#1716): one agent per member transcript anywhere under the
|
|
932
|
+
// session dir — a nested member's too, at its own spawnDepth — read by
|
|
933
|
+
// member-record.mjs's own omp reader over the walk readOmpSession uses:
|
|
934
|
+
// foldOmpTranscript once per file, then ompMemberRecord on that fold, never
|
|
935
|
+
// a second parse of omp's line shape. So each row's totals, model and role
|
|
936
|
+
// are exactly the member record's: role from `session_init`'s agent
|
|
937
|
+
// definition, task and AgentId, label the AgentId itself (the path-relative
|
|
938
|
+
// stem, `review-pr-12/Security` for a nested one). The same fold's `entries`
|
|
939
|
+
// are the tool stream (#1717), so the tool table goes through attributeTools.
|
|
940
|
+
//
|
|
941
|
+
// Per-transcript tolerance is this file's, not readOmpSession's: readOmpSession
|
|
942
|
+
// (used by the bulk scrape) lets a wrong-shape refusal propagate, and here
|
|
943
|
+
// both — an unreadable file and a wrong-shape refusal — are one transcript's
|
|
944
|
+
// fault, so readOmpSpend, this file's own reader, instead catches both per-
|
|
945
|
+
// transcript, landing them in `skipped` with a stderr line. A transcript
|
|
946
|
+
// ompMemberRecord answers null for (no assistant turn yet — a member
|
|
947
|
+
// dispatched this second) has spent nothing, so it is neither booked nor
|
|
948
|
+
// skipped.
|
|
949
|
+
//
|
|
950
|
+
// `damaged` is real — the tool-attribution stream (#1717) is a join
|
|
951
|
+
// across lines (a toolCall's id names its tool, a pending result batch bills
|
|
952
|
+
// the next turn), so a dropped MIDDLE line can silently shift spend onto a
|
|
953
|
+
// neighbouring tool instead of just costing its own turn's totals — the
|
|
954
|
+
// hazard foldOmpTranscript's `malformedNonLastLines` counts. This reader
|
|
955
|
+
// sums it across
|
|
956
|
+
// the transcript regardless of whether the file ends up booked as an agent,
|
|
957
|
+
// so a transcript that is corrupt where its assistant-with-usage line should
|
|
958
|
+
// be still surfaces here instead of falling through `if (!m) continue` unseen.
|
|
959
|
+
function readOmpSpend(dir, sinceMs) {
|
|
960
|
+
const agents = [];
|
|
961
|
+
const toolTables = [];
|
|
962
|
+
let skipped = 0;
|
|
963
|
+
let damaged = 0;
|
|
964
|
+
for (const { file, agent, spawnDepth } of ompSessionTranscripts(dir)) {
|
|
965
|
+
try {
|
|
966
|
+
if (sinceMs != null && statSync(file).mtimeMs < sinceMs) continue;
|
|
967
|
+
const folded = foldOmpTranscript(readFileSync(file, "utf8"), file);
|
|
968
|
+
damaged += folded.malformedNonLastLines;
|
|
969
|
+
const m = ompMemberRecord(folded, agent, spawnDepth);
|
|
970
|
+
if (!m) continue;
|
|
971
|
+
// Both halves before either is recorded, so `skipped++` below always
|
|
972
|
+
// means "this transcript contributed nothing".
|
|
973
|
+
const tools = attributeTools(folded.entries);
|
|
974
|
+
agents.push({
|
|
975
|
+
label: m.member, role: m.role, model: m.model,
|
|
976
|
+
cacheWrite: m.tokens_cache_create, output: m.tokens_out, cacheRead: m.tokens_cache_read,
|
|
977
|
+
});
|
|
978
|
+
toolTables.push(tools);
|
|
979
|
+
} catch (e) {
|
|
980
|
+
skipped++;
|
|
981
|
+
warnOnce("skips", file, `skipping ${file}: ${e.message}`);
|
|
982
|
+
}
|
|
983
|
+
}
|
|
984
|
+
return { agents, toolTables, skipped, damaged };
|
|
985
|
+
}
|
|
986
|
+
|
|
987
|
+
// `workspace`/`port` are the caller's answers, never read in here (#1584):
|
|
988
|
+
// resolveCockpitInstance() already decided both, and a second derivation in
|
|
989
|
+
// this function could disagree with the one the server actually bound. They
|
|
990
|
+
// join the payload HERE, alongside the repo fields above, because this is the
|
|
991
|
+
// boundary where every impure input meets the pure model — computeBoard() only
|
|
992
|
+
// echoes them. Defaulted to null, which is also the degrade arm's workspace
|
|
993
|
+
// and the value #1585's handshake refuses to match on, so a caller with no
|
|
994
|
+
// instance to name (every gather() test driver) says so rather than omitting
|
|
995
|
+
// the fields.
|
|
996
|
+
//
|
|
997
|
+
// `spendDir` is the caller's PINNED transcript directory (#1583) and is the one
|
|
998
|
+
// parameter here whose ABSENCE is not a default to fill in: serve() hands the
|
|
999
|
+
// same pin's answer to every tick, and its three shapes — a directory, `null`
|
|
1000
|
+
// for "resolved, no session yet", `{ error }` for unresolvable — all have to
|
|
1001
|
+
// reach gatherSpend() as themselves. Only a caller that passed nothing at all
|
|
1002
|
+
// falls through to the default below, which reads the override flag directly:
|
|
1003
|
+
// `build` is one gather per process, so it needs the override but never a pin,
|
|
1004
|
+
// and that read sits here for the same reason argSpendSince()'s does — a
|
|
1005
|
+
// caller that skips main() still validates its own argv. With neither the pin
|
|
1006
|
+
// nor the flag, gatherSpend() resolves for itself exactly as it did before
|
|
1007
|
+
// this ticket, which is what keeps `build`'s output unchanged by it.
|
|
1008
|
+
//
|
|
1009
|
+
// `spendDirExplicit` (#1679) is read the same way, independently of
|
|
1010
|
+
// `spendDir` itself: serve() always passes a resolved `spendDir` (the pin's
|
|
1011
|
+
// answer), never leaving it to default, so `spendDir`'s own presence cannot
|
|
1012
|
+
// say whether an operator named it. Whether --spend-dir was given is a fact
|
|
1013
|
+
// about argv, unrelated to which of gatherSpend's three shapes the pin
|
|
1014
|
+
// currently holds.
|
|
1015
|
+
// #1713: async, because every child read below is. The event loop this frees
|
|
1016
|
+
// belongs to serve()'s HTTP server, which shares this process — see execRead's
|
|
1017
|
+
// note above for what the synchronous version cost. `build` awaits it and is
|
|
1018
|
+
// otherwise unchanged: one gather per process, nothing else waiting on it.
|
|
1019
|
+
export async function gather({ ledgerFile, prevFile, stateFile = null, scriptDir = SCRIPT_DIR, interval, workspace = null, port = null, spendDir = argSpendDir(), spendDirExplicit = argSpendDir() != null }) {
|
|
1020
|
+
// The one read that must not crash the gather: a corrupt/partial board.json
|
|
1021
|
+
// (the fallback safety net itself) is ignored, not fatal. That holds for a
|
|
1022
|
+
// SHAPE fault as much as a parse fault (#1192) — the guard below rejects the
|
|
1023
|
+
// payload here so both leave through the one catch, which names the file the
|
|
1024
|
+
// operator passed. A wrong-typed `tickets` left to reach the prevCi map
|
|
1025
|
+
// instead throws `.filter is not a function` out of gather(), which made a
|
|
1026
|
+
// corrupt prev board fatal after all and blamed an "intermediate value".
|
|
1027
|
+
//
|
|
1028
|
+
// Validated HERE and not per-read, deliberately: this payload has three more
|
|
1029
|
+
// readers (`prev?.repo`/`prev?.repoUrl` below, and compute-board.mjs's dwell
|
|
1030
|
+
// tracking, which consumes the whole `prev` this returns), and the prevCi
|
|
1031
|
+
// expression's `|| []` is the demonstration — it defends against an ABSENT
|
|
1032
|
+
// `tickets`, never a present one of the wrong type. This guard covers that one
|
|
1033
|
+
// shape — `prev` is an object, `tickets` is an array of objects — not every
|
|
1034
|
+
// field those three readers go on to trust: a wrong-typed `repo`, `repoUrl`, or
|
|
1035
|
+
// `sinceEnteredStage` still reaches them unchanged. Those `?.`/`|| []` defaults
|
|
1036
|
+
// stay as the belt to these braces.
|
|
1037
|
+
let prev = null;
|
|
1038
|
+
if (prevFile && existsSync(prevFile)) {
|
|
1039
|
+
try {
|
|
1040
|
+
// JSON.parse SUCCEEDS on `null`, a bare number, a string and an array,
|
|
1041
|
+
// none of which is a board; `null` in particular is absent, not an
|
|
1042
|
+
// object, and `typeof null` alone would let it through. Same check and
|
|
1043
|
+
// same wording as readMerged()'s `data.repository` read, which is this
|
|
1044
|
+
// repo's precedent for rejecting a parsed-but-wrong payload at its own
|
|
1045
|
+
// read — since #1546 literally the same, both calling the shared predicate.
|
|
1046
|
+
const p = JSON.parse(readFileSync(prevFile, "utf8"));
|
|
1047
|
+
if (!isJsonObject(p)) throw new TypeError(`expected a JSON object, got ${jsonKind(p)}`);
|
|
1048
|
+
// Nullish `tickets` is ABSENT and stays usable: `|| []` reads it as the
|
|
1049
|
+
// empty carry-forward, which is what a board with no PRs on it says.
|
|
1050
|
+
// Only a present-and-wrong-typed one is a fault.
|
|
1051
|
+
if (p.tickets != null) {
|
|
1052
|
+
if (!Array.isArray(p.tickets))
|
|
1053
|
+
throw new TypeError(`expected tickets to be an array, got ${typeof p.tickets}`);
|
|
1054
|
+
// Per ENTRY too, and not because a `[null]` is exotic: `Array.isArray`
|
|
1055
|
+
// is satisfied by an array of anything, and the very next thing the
|
|
1056
|
+
// prevCi map does is read `t.pr` off each element. The whole payload
|
|
1057
|
+
// goes, not the bad entry — a board with one unreadable ticket is not a board
|
|
1058
|
+
// whose others can be trusted to carry CI state forward, and filtering here
|
|
1059
|
+
// (drop the bad entry, keep the rest) would make this a new, fourth policy for
|
|
1060
|
+
// one payload class in this file — mapCi's null-only guard and tryParse's
|
|
1061
|
+
// unguarded read are the other two — rather than the reject-whole-payload
|
|
1062
|
+
// policy this guard already shares with readMerged()'s own read.
|
|
1063
|
+
const bad = p.tickets.findIndex((t) => !isJsonObject(t));
|
|
1064
|
+
if (bad !== -1)
|
|
1065
|
+
throw new TypeError(`expected tickets[${bad}] to be a JSON object, got ${jsonKind(p.tickets[bad])}`);
|
|
1066
|
+
}
|
|
1067
|
+
prev = p;
|
|
1068
|
+
}
|
|
1069
|
+
catch (e) { console.error(`${NAME}: ignoring unreadable prev board ${prevFile}: ${e.message}`); }
|
|
1070
|
+
}
|
|
1071
|
+
|
|
1072
|
+
// `--require-file` turns an absent ledger into a refusal at exit 2 rather
|
|
1073
|
+
// than the empty payload a real empty ledger returns (#816). Without it the
|
|
1074
|
+
// two are byte-identical on stdout, and tryParse's fallback is that same
|
|
1075
|
+
// empty shape besides — so an unread ledger, one read empty, and a read whose
|
|
1076
|
+
// answer would not parse were three states with one rendering, on the one
|
|
1077
|
+
// subcommand this cockpit consumes.
|
|
1078
|
+
//
|
|
1079
|
+
// The three stay three here because each is a different observation, not a
|
|
1080
|
+
// different value of one: null from tryRun is a read that did not happen (the
|
|
1081
|
+
// refusal, or an unreachable node), null from tryParse is a read whose answer
|
|
1082
|
+
// was unusable, and anything else is the ledger. `tryParse`'s fallback is
|
|
1083
|
+
// null rather than the empty shape for exactly that reason — the empty shape
|
|
1084
|
+
// is a real answer and must not double as the failure.
|
|
1085
|
+
const ledgerJson = await tryRun("node", [join(scriptDir, "ledger.mjs"), "--file", ledgerFile, "--require-file", "read"]);
|
|
1086
|
+
// "read" means ledgerJson parsed as JSON, not that it conforms to the
|
|
1087
|
+
// {rows,filed,ruled} shape — tryParse only checks syntax, so a
|
|
1088
|
+
// syntactically-valid-but-wrong-shape payload from ledger.mjs would still
|
|
1089
|
+
// be labelled "read" here. ledger.mjs is this repo's own, already-tested
|
|
1090
|
+
// producer of this JSON, so that gap is accepted rather than guarded.
|
|
1091
|
+
const parsedLedger = tryParse(ledgerJson, null, "ledger read");
|
|
1092
|
+
// Strictly `!== null`, never falsiness — a ledger payload that parses to
|
|
1093
|
+
// `0`, `false` or `""` is a real answer tryParse already forwarded (see
|
|
1094
|
+
// tryParse's own comment above), and treating it as falsy here would
|
|
1095
|
+
// silently discard it into `unparsed`, the exact bug class tryParse's
|
|
1096
|
+
// guard exists to prevent, one caller downstream of the fix.
|
|
1097
|
+
const ledger = parsedLedger !== null
|
|
1098
|
+
? { ...parsedLedger, state: "read" }
|
|
1099
|
+
: { rows: [], filed: [], ruled: [], state: ledgerJson == null ? "unread" : "unparsed" };
|
|
1100
|
+
|
|
1101
|
+
const issuesJson = await tryRun("gh", ["issue", "list", "--label", "ready-for-agent",
|
|
1102
|
+
"--state", "open", "--limit", String(POOL_LIMIT), "--json", "number,title,labels"]);
|
|
1103
|
+
// title: falls back to the same `#<number>` placeholder titleFor() already
|
|
1104
|
+
// uses for an issue it cannot find at all (compute-board.mjs). An unrowed
|
|
1105
|
+
// issue becomes a POOL card straight from this array — compute-board.mjs's
|
|
1106
|
+
// POOL loop reads `iss.title` RAW, never through titleFor()'s fallback
|
|
1107
|
+
// chain — so this row genuinely needs a guaranteed string: an issue found
|
|
1108
|
+
// but unable to describe itself reads as its number rather than literal
|
|
1109
|
+
// `undefined` on the operator's page (#786).
|
|
1110
|
+
//
|
|
1111
|
+
// Its null fallback, not the open-PR read's `[]` below, is deliberate
|
|
1112
|
+
// (#1597 follow-up): this read is the pool's ONLY source, and
|
|
1113
|
+
// compute-board.mjs's stall() needs to tell a genuinely empty pool from a
|
|
1114
|
+
// `gh` outage the same way it already tells an empty ledger from an unread
|
|
1115
|
+
// one — a `[]` fallback collapses both to the identical shape before a
|
|
1116
|
+
// caller here could split them back apart.
|
|
1117
|
+
const issuesParsed = tryParse(issuesJson, null, "gh issue list");
|
|
1118
|
+
const poolOk = issuesParsed !== null;
|
|
1119
|
+
const poolCapped = hitLimit(issuesParsed, POOL_LIMIT);
|
|
1120
|
+
const issues = withNumber(poolOk ? issuesParsed : [], "gh issue list").map((i) => ({
|
|
1121
|
+
number: i.number,
|
|
1122
|
+
title: typeof i.title === "string" ? i.title : `#${i.number}`,
|
|
1123
|
+
labels: labelsOf(i),
|
|
1124
|
+
}));
|
|
1125
|
+
|
|
1126
|
+
const prsJson = await tryRun("gh", ["pr", "list", "--state", "open", "--limit", String(OPEN_PR_LIMIT),
|
|
1127
|
+
"--json", "number,state,labels,title,headRefOid"]);
|
|
1128
|
+
// No default for `title` or `state` here, unlike the issue row above — raw
|
|
1129
|
+
// passthrough, deliberately. `title`: compute-board.mjs's titleFor() already
|
|
1130
|
+
// falls through a falsy `pr.title` to the real issue title (`if (pr &&
|
|
1131
|
+
// pr.title) return pr.title;`); nothing else reads a PR row's `title` field
|
|
1132
|
+
// raw, so defaulting it to `#<number>` made it unconditionally truthy and
|
|
1133
|
+
// SILENTLY DISABLED that fallback — a titleless PR row showed the PR number
|
|
1134
|
+
// instead of the real issue title, worse than doing nothing. `state`: its
|
|
1135
|
+
// only consumer is `pr.state === "OPEN"` (compute-board.mjs), already false
|
|
1136
|
+
// for `undefined` exactly as it was for the old "UNKNOWN" sentinel, so the
|
|
1137
|
+
// default was inert — pure indirection with no behaviour to show for it.
|
|
1138
|
+
const prsParsed = tryParse(prsJson, [], "gh pr list");
|
|
1139
|
+
const prsCapped = hitLimit(prsParsed, OPEN_PR_LIMIT);
|
|
1140
|
+
const prs = withNumber(prsParsed, "gh pr list").map((p) => ({
|
|
1141
|
+
number: p.number,
|
|
1142
|
+
state: p.state,
|
|
1143
|
+
title: p.title,
|
|
1144
|
+
labels: labelsOf(p),
|
|
1145
|
+
// (#2083) compute-board.mjs's reviewBacklog needs it to tell a
|
|
1146
|
+
// past-pin halt already answered by the automatic re-review apart from
|
|
1147
|
+
// one still owed a fresh one — the same field fleet-tick.mjs's
|
|
1148
|
+
// openPrs() already requires.
|
|
1149
|
+
headRefOid: p.headRefOid,
|
|
1150
|
+
}));
|
|
1151
|
+
|
|
1152
|
+
// #1820: MERGED is gh's answer, not a ledger token — no rule writes `MERGED
|
|
1153
|
+
// <sha>`, and the open list above drops a PR the moment it merges. #1840:
|
|
1154
|
+
// asked only about mergedReadPrs()'s set — row PRs absent from the open
|
|
1155
|
+
// list, with no token, not carried forward (#1841) — in one batched read
|
|
1156
|
+
// that answers whatever their merge age; see readMerged(). A failed read
|
|
1157
|
+
// is `[]`, and #1841's carry-forward in computeBoard() covers exactly the
|
|
1158
|
+
// PRs this set leaves out, so a failure costs only a PR never yet seen
|
|
1159
|
+
// MERGED, which reads REVIEW.
|
|
1160
|
+
const merged = await readMerged(mergedReadPrs({ ledger, prs, prev }));
|
|
1161
|
+
|
|
1162
|
+
// CI per open PR. On failure, carry the previous board's value for that PR.
|
|
1163
|
+
const prevCi = new Map((prev?.tickets || []).filter((t) => t.pr != null).map((t) => [t.pr, t.ci]));
|
|
1164
|
+
const ci = {};
|
|
1165
|
+
// Awaited one at a time rather than raced with Promise.all, and that is a
|
|
1166
|
+
// decision rather than an oversight: this loop spawns one `node
|
|
1167
|
+
// ci-state.mjs` per open PR and each of those hits the GitHub API, so a fan
|
|
1168
|
+
// of 40 at once is a rate-limit and a load spike where a queue of 40 is
|
|
1169
|
+
// neither. Nothing here waits on the loop any more — the server answers
|
|
1170
|
+
// throughout it (#1713) — so the only thing concurrency would buy is a
|
|
1171
|
+
// shorter tick, against an interval measured in seconds. The warn-once
|
|
1172
|
+
// lines below also stay in PR order this way.
|
|
1173
|
+
for (const p of prs) {
|
|
1174
|
+
const out = await runCiState(scriptDir, p.number);
|
|
1175
|
+
ci[p.number] = out === null ? (prevCi.get(p.number) ?? "unknown") : mapCi(out, p.number);
|
|
1176
|
+
}
|
|
1177
|
+
|
|
1178
|
+
// Repo identity + web URL for PR links — the url carries the host, so links
|
|
1179
|
+
// resolve on GitHub Enterprise, not just github.com. From the fleet's cwd, so
|
|
1180
|
+
// the board stays repo-agnostic. On failure, carry the previous board's values.
|
|
1181
|
+
const repoJson = await tryRun("gh", ["repo", "view", "--json", "nameWithOwner,url"]);
|
|
1182
|
+
let repo = prev?.repo ?? null;
|
|
1183
|
+
let repoUrl = prev?.repoUrl ?? null;
|
|
1184
|
+
if (repoJson) {
|
|
1185
|
+
try { const d = JSON.parse(repoJson); repo = d.nameWithOwner ?? repo; repoUrl = d.url ?? repoUrl; }
|
|
1186
|
+
catch (e) { console.error(`${NAME}: gh repo view parse failed: ${e.message}`); }
|
|
1187
|
+
}
|
|
1188
|
+
|
|
1189
|
+
// #1076: guard's own rationale (fail loud, gate on presence and on range,
|
|
1190
|
+
// not just finiteness) now lives at argSpendSince()'s definition above,
|
|
1191
|
+
// alongside argPort()/argInterval() — this call is unchanged in when it
|
|
1192
|
+
// runs, only in where the check itself is written.
|
|
1193
|
+
const sinceMs = argSpendSince();
|
|
1194
|
+
const spend = gatherSpend({ dir: spendDir, sinceMs, explicit: spendDirExplicit });
|
|
1195
|
+
// #1597: the heartbeat's mark, raw. readState() never throws — an absent
|
|
1196
|
+
// file is the ordinary state of a run whose heartbeat has not beaten yet,
|
|
1197
|
+
// and an unreadable or corrupt one announces itself on stderr and degrades
|
|
1198
|
+
// to no mark, which computeBoard() renders as no panel rather than as a
|
|
1199
|
+
// death it cannot substantiate. So no try/catch here and no `tryRun` shape:
|
|
1200
|
+
// the degrade lives in the module that owns the file.
|
|
1201
|
+
//
|
|
1202
|
+
// `null` when no caller named a state file, and DISTINCT from a file that
|
|
1203
|
+
// is simply absent: both omit the surface today, but only the second is a
|
|
1204
|
+
// reading. Defaulted rather than resolved here for gather()'s own reason —
|
|
1205
|
+
// every caller in this file passes the instance's answer, and a second
|
|
1206
|
+
// resolution could name a different workspace's beat.
|
|
1207
|
+
// `ticked` rides beside `beat`, same file same read, and under the same
|
|
1208
|
+
// "no try/catch, no tryRun shape" rule just above — fleet-tick.mjs's own
|
|
1209
|
+
// liveness key (#1597 follow-up), for the busy-stretch case `beat` alone
|
|
1210
|
+
// cannot see (fleet-state.mjs's assessBeat has the rule).
|
|
1211
|
+
const priorState = stateFile ? readState(stateFile, NAME) : null;
|
|
1212
|
+
const beat = priorState?.beat ?? null;
|
|
1213
|
+
const ticked = priorState?.ticked ?? null;
|
|
1214
|
+
return { ledger, issues, prs, merged, ci, prev, repo, repoUrl, workspace, port, spend, beat, ticked, poolOk,
|
|
1215
|
+
poolCapped, prsCapped,
|
|
1216
|
+
now: Date.now(), interval: interval ?? argInterval() ?? 15 };
|
|
1217
|
+
}
|
|
1218
|
+
|
|
1219
|
+
async function main() {
|
|
1220
|
+
// #365: a misspelled flag was never looked for, so `serve --prot 9000`
|
|
1221
|
+
// served on the default 8123 in silence. In main(), not at module scope:
|
|
1222
|
+
// board.test.mjs and board-cli.test.mjs both import from this module, so a
|
|
1223
|
+
// module-scope sweep would read the TEST RUNNER's argv.
|
|
1224
|
+
//
|
|
1225
|
+
// One set for both subcommands, deliberately. `--port`/`--open` are USED
|
|
1226
|
+
// only by serve() and `--prev` only by build, so a WELL-FORMED `build
|
|
1227
|
+
// --port 5` is accepted and its value simply unused — narrowing the set per
|
|
1228
|
+
// subcommand would close that too, but that is a larger design question
|
|
1229
|
+
// (per-subcommand arg schemas) this ticket does not take; refusing a flag
|
|
1230
|
+
// this file does accept somewhere is not this ticket's business. What
|
|
1231
|
+
// build no longer does is stay silent on a MALFORMED one — see #468 below.
|
|
1232
|
+
//
|
|
1233
|
+
// Above `cmd`, so `board.mjs --prot 9000` names the stray rather than
|
|
1234
|
+
// printing the usage line for a missing subcommand. `build`/`serve` carry
|
|
1235
|
+
// no `--` and are never the sweep's business.
|
|
1236
|
+
sweep();
|
|
1237
|
+
const cmd = process.argv[2];
|
|
1238
|
+
// #1656: no default applied here any more — `build` and `serve` now each
|
|
1239
|
+
// apply their own. `build` has no workspace instance to default against
|
|
1240
|
+
// (no state directory, no board), so it keeps today's cwd-relative literal
|
|
1241
|
+
// below. `serve` defaults against `resolveCockpitInstance()`'s stateDir
|
|
1242
|
+
// instead, so an absent --ledger still points at the SAME workspace the
|
|
1243
|
+
// served state directory does, rather than the caller's raw cwd.
|
|
1244
|
+
const ledgerFile = arg("ledger");
|
|
1245
|
+
|
|
1246
|
+
// #468: argPort()/has("open") used to run only inside serve(), so `build
|
|
1247
|
+
// --port abc` and `build --open=1` were accepted and silently ignored — the
|
|
1248
|
+
// malformed spellings these guards exist to refuse never ran on that path.
|
|
1249
|
+
// Called here, once, ahead of the build/serve dispatch (and ahead of both
|
|
1250
|
+
// branches' own stray() call, so a malformed value still wins the specific
|
|
1251
|
+
// wording over stray()'s generic one, same ordering rule arg.mjs documents
|
|
1252
|
+
// for every other value guard in this file). Ahead of the `cmd` check too,
|
|
1253
|
+
// so `board.mjs --port abc` with NO subcommand names the flag rather than
|
|
1254
|
+
// falling through to the usage die below — the same precedence the #365
|
|
1255
|
+
// sweep note above claims for a stray, now true of these two guards as
|
|
1256
|
+
// well. Both orderings are pinned in board.test.mjs; before this fix the
|
|
1257
|
+
// no-subcommand shape printed the usage line (measured). The return values are
|
|
1258
|
+
// deliberately discarded on the build path: build has no server to bind or
|
|
1259
|
+
// browser to open, so a WELL-FORMED --port/--open still does nothing here,
|
|
1260
|
+
// exactly like before this fix — only the malformed spellings now refuse.
|
|
1261
|
+
// serve() below still calls its own argPort()/has("open"); re-evaluating a
|
|
1262
|
+
// pure read of argv costs nothing and keeps the EXPORTED serve() validating
|
|
1263
|
+
// its own argv for a caller that skips main(). Nothing in this repo is such
|
|
1264
|
+
// a caller today — every serve() test drives the real CLI, which enters
|
|
1265
|
+
// main() — but serve() is public surface, so the guard stays with it.
|
|
1266
|
+
// #1092: unlike --port/--open (never read on `build` before #468) or
|
|
1267
|
+
// --ledger/--spend-since/--interval (already read on `build`, per the
|
|
1268
|
+
// header comment above), --prev was read on exactly one subcommand and it
|
|
1269
|
+
// was the wrong one to skip: `arg("prev")` sat inside the `build` branch
|
|
1270
|
+
// alone, and serve()'s own signature carries no `prev` parameter at all —
|
|
1271
|
+
// so `serve --prev`, `serve --prev=x` and `serve --prev --port 9000` all
|
|
1272
|
+
// fell through with no guard ever firing (measured), the last one blaming
|
|
1273
|
+
// --port's innocent value once stray() reached it instead. Hoisted here
|
|
1274
|
+
// for the same reason #468 hoisted argPort()/has("open") below it — ahead
|
|
1275
|
+
// of the dispatch and both branches' stray() calls — and ahead of argPort()
|
|
1276
|
+
// itself so a caller who gets BOTH flags wrong at once (`--port --prev`,
|
|
1277
|
+
// each trailing with no value) still hears about --prev specifically,
|
|
1278
|
+
// rather than whichever guard happens to run first. The old in-branch read
|
|
1279
|
+
// inside `build` is gone; this is now the only read, and its value reaches
|
|
1280
|
+
// gather() exactly as before — discarded on serve, same as --port/--open
|
|
1281
|
+
// are discarded on build.
|
|
1282
|
+
const prevFile = arg("prev");
|
|
1283
|
+
argPort();
|
|
1284
|
+
has("open");
|
|
1285
|
+
|
|
1286
|
+
// #1076: same fail-open shape as --port/--open above (#468) — this closes
|
|
1287
|
+
// the two flags PR #1090 (#468) left standing. `argInterval()`'s read had
|
|
1288
|
+
// two call sites — inside serve() directly, and embedded in gather()'s
|
|
1289
|
+
// return (`interval ?? argInterval() ?? 15`), which build's dispatch below
|
|
1290
|
+
// reaches too — and the --spend-since read sat inside gather() (now
|
|
1291
|
+
// `argSpendSince()`, extracted above for exactly this reason); all three
|
|
1292
|
+
// sat below every stray() call on every path that reaches them. A trailing
|
|
1293
|
+
// `--interval`/`--spend-since` ahead of a stray positional therefore
|
|
1294
|
+
// refused under stray()'s generic wording, naming the next token instead
|
|
1295
|
+
// of the flag actually given wrong — measured, `serve --interval --open x`
|
|
1296
|
+
// said `unexpected argument 'x'` before this hoist, and `build --interval
|
|
1297
|
+
// --open x` / `build --spend-since --open x` likewise. Same fix, same
|
|
1298
|
+
// place: call both here, once, ahead of the build/serve dispatch and
|
|
1299
|
+
// ahead of both branches' own stray() call, exactly where
|
|
1300
|
+
// argPort()/has("open") already sit — build discards both return values,
|
|
1301
|
+
// same as it already discards argPort()'s. serve() below still calls its
|
|
1302
|
+
// own argInterval() (via `interval ?? argInterval() ?? 15`) and gather()
|
|
1303
|
+
// still calls its own argSpendSince() — re-evaluating a pure read of argv
|
|
1304
|
+
// costs nothing, and keeps both validating their own argv for a caller
|
|
1305
|
+
// that skips main(), same reasoning #468 gives for argPort()/has("open").
|
|
1306
|
+
argInterval();
|
|
1307
|
+
argSpendSince();
|
|
1308
|
+
// #1583: `--spend-dir` joins them for the same two reasons, from the day it
|
|
1309
|
+
// ships rather than one ticket later — it is read on both subcommands (in
|
|
1310
|
+
// gather()'s default, and through serve()'s pin), and a trailing
|
|
1311
|
+
// `--spend-dir` ahead of a stray positional has to name itself instead of
|
|
1312
|
+
// the token behind it. build discards the value here exactly as it discards
|
|
1313
|
+
// argPort()'s; gather() below does the read that reaches the panel.
|
|
1314
|
+
argSpendDir();
|
|
1315
|
+
|
|
1316
|
+
// #463: sweep() above only refuses a `--`-prefixed token; a bare or
|
|
1317
|
+
// single-dash stray alongside a valid subcommand (`build --ledger x junk`)
|
|
1318
|
+
// rode along in silence the same way. Below the `cmd` check, deliberately
|
|
1319
|
+
// unlike sweep() above it: `board.mjs junk` is an unknown SUBCOMMAND, which
|
|
1320
|
+
// the usage die below already names as such, and stray() has no business
|
|
1321
|
+
// relitigating that with its own generic wording.
|
|
1322
|
+
//
|
|
1323
|
+
// Each branch guards itself rather than one call covering both: hoisting
|
|
1324
|
+
// stray() above the `cmd` check the way sweep() sits above it would make
|
|
1325
|
+
// `board.mjs junk --bogus` refuse the stray instead of falling through to
|
|
1326
|
+
// the usage die below, which is `cmd`'s wrong-subcommand case to name, not
|
|
1327
|
+
// stray()'s to relitigate.
|
|
1328
|
+
if (cmd === "build") {
|
|
1329
|
+
stray();
|
|
1330
|
+
const { computeBoard } = await import("./compute-board.mjs");
|
|
1331
|
+
// #1584: a snapshot printed here outlives the process that printed it —
|
|
1332
|
+
// redirected to a file, pasted into a ticket, read back by the next
|
|
1333
|
+
// launch — so it says which workspace it describes and which port that
|
|
1334
|
+
// workspace's cockpit answers on. The same seam serve() uses, so the two
|
|
1335
|
+
// subcommands can never name different instances from one cwd.
|
|
1336
|
+
//
|
|
1337
|
+
// No `port:` argument, deliberately: --port is read and DISCARDED on this
|
|
1338
|
+
// path (#468 above), and honouring it here would give the flag a meaning
|
|
1339
|
+
// on `build` it has never had. The DERIVED port is the identity anyway —
|
|
1340
|
+
// it is the port this workspace is reachable on, which is what a stray
|
|
1341
|
+
// snapshot needs to name; the port some one-shot invocation happened to
|
|
1342
|
+
// ask for is not.
|
|
1343
|
+
//
|
|
1344
|
+
// The default ledger stays the cwd-relative literal #1656 left here. That
|
|
1345
|
+
// is not an oversight to fix in passing: `build` prints to stdout and
|
|
1346
|
+
// writes no state directory, so the argument that moved serve()'s default
|
|
1347
|
+
// onto the workspace does not reach it, and changing it would change what
|
|
1348
|
+
// an existing `build` reads.
|
|
1349
|
+
const instance = resolveCockpitInstance({ cwd: process.cwd(), gitCommonDir: gitCommonDir() });
|
|
1350
|
+
const model = computeBoard(await gather({
|
|
1351
|
+
ledgerFile: ledgerFile || ".fleet/ledger.md", prevFile,
|
|
1352
|
+
// #1597: the heartbeat's file, from the SAME instance the identity
|
|
1353
|
+
// fields below come from — not the cwd-relative literal the ledger
|
|
1354
|
+
// default keeps. That literal is `build`'s own back-compatibility (see
|
|
1355
|
+
// the note above); the mark has no existing `build` behaviour to
|
|
1356
|
+
// preserve, so it starts out resolved, and a snapshot printed from a
|
|
1357
|
+
// worktree names the run's real beat instead of a file that is not
|
|
1358
|
+
// there.
|
|
1359
|
+
stateFile: stateFileIn(instance.stateDir),
|
|
1360
|
+
workspace: instance.workspace, port: instance.port,
|
|
1361
|
+
}));
|
|
1362
|
+
console.log(JSON.stringify(model, null, 2));
|
|
1363
|
+
return;
|
|
1364
|
+
}
|
|
1365
|
+
if (cmd === "serve") {
|
|
1366
|
+
stray();
|
|
1367
|
+
await serve({ ledgerFile });
|
|
1368
|
+
return;
|
|
1369
|
+
}
|
|
1370
|
+
die("usage: board.mjs build|serve [--ledger <path>] [--port N] [--interval N] [--open] [--spend-since <epoch-ms>] [--spend-dir <path>]");
|
|
1371
|
+
}
|
|
1372
|
+
|
|
1373
|
+
import { copyFileSync, mkdirSync } from "node:fs";
|
|
1374
|
+
|
|
1375
|
+
export function createBoardServer(dir) {
|
|
1376
|
+
return createServer((req, res) => {
|
|
1377
|
+
const url = (req.url || "/").split("?")[0];
|
|
1378
|
+
const path = url === "/" || url === "/board.html" ? join(dir, "board.html")
|
|
1379
|
+
: url === "/board.json" ? join(dir, "board.json") : null;
|
|
1380
|
+
if (!path || !existsSync(path)) { res.writeHead(404); res.end("not found"); return; }
|
|
1381
|
+
const type = path.endsWith(".json") ? "application/json" : "text/html; charset=utf-8";
|
|
1382
|
+
res.writeHead(200, { "content-type": type, "cache-control": "no-store" });
|
|
1383
|
+
res.end(readFileSync(path));
|
|
1384
|
+
});
|
|
1385
|
+
}
|
|
1386
|
+
|
|
1387
|
+
// A cockpit instance is identified by its WORKSPACE — the directory holding
|
|
1388
|
+
// the shared git dir — not by the process's cwd and not by the machine. Two
|
|
1389
|
+
// workspaces therefore get two boards on two ports, both live and neither
|
|
1390
|
+
// aware of the other, and one workspace derives the SAME port on every run,
|
|
1391
|
+
// so that URL survives runs, reboots and node versions.
|
|
1392
|
+
//
|
|
1393
|
+
// BASE is the port this file hardcoded before any of this existed;
|
|
1394
|
+
// resolveCockpitInstance()'s degrade arm, with no workspace to hash, still
|
|
1395
|
+
// defaults to it. SPAN = 512 was kept deliberately (ruling on #39/#1657): a
|
|
1396
|
+
// collision between two DIFFERENT workspaces is not priced into the width but
|
|
1397
|
+
// carried by serve()'s launch loop, which probes whoever holds the derived
|
|
1398
|
+
// port, reuses that cockpit when it is this workspace's own, and otherwise
|
|
1399
|
+
// scans on through cockpitPorts()'s PORT_ATTEMPTS candidates. The accepted
|
|
1400
|
+
// cost is launch order: whichever colliding workspace starts second binds a
|
|
1401
|
+
// port other than the one its hash derives.
|
|
1402
|
+
const PORT_BASE = 8123;
|
|
1403
|
+
const PORT_SPAN = 512;
|
|
1404
|
+
|
|
1405
|
+
// FNV-1a, 32-bit, written out inline. Three properties this needs that no
|
|
1406
|
+
// crypto digest and no Math.random has together: stable across node versions
|
|
1407
|
+
// and across machines (nothing in here reads the engine, the host or the
|
|
1408
|
+
// clock), dependency-free, and cheap enough to run on every start. Math.imul
|
|
1409
|
+
// is the whole reason it is spelled this way — a plain `h * 0x01000193`
|
|
1410
|
+
// leaves exact integer range after two rounds and silently stops being FNV.
|
|
1411
|
+
// `>>> 0` is load-bearing, not decoration: without it `h` stays SIGNED, so
|
|
1412
|
+
// `h % PORT_SPAN` can come back negative and the derived port lands BELOW
|
|
1413
|
+
// base, outside the window this function's own contract promises.
|
|
1414
|
+
function workspaceHash(key) {
|
|
1415
|
+
let h = 0x811c9dc5;
|
|
1416
|
+
for (let i = 0; i < key.length; i++) {
|
|
1417
|
+
h ^= key.charCodeAt(i);
|
|
1418
|
+
h = Math.imul(h, 0x01000193);
|
|
1419
|
+
}
|
|
1420
|
+
return h >>> 0;
|
|
1421
|
+
}
|
|
1422
|
+
|
|
1423
|
+
// The one spelling of "this value is a workspace identity", read by every
|
|
1424
|
+
// side of the cockpit handshake (#1661). The invariant is that null and the
|
|
1425
|
+
// empty string are never an identity to match on, and it used to be carried
|
|
1426
|
+
// by two independently-written guards — resolveCockpitInstance()'s
|
|
1427
|
+
// `workspace === null` below and probeCockpitWorkspace()'s
|
|
1428
|
+
// `typeof w === "string" && w !== ""` — correct only because both were
|
|
1429
|
+
// written consistently, not because anything stopped one from moving without
|
|
1430
|
+
// the other. What a drift buys is silent and cross-workspace: let the
|
|
1431
|
+
// construction side call the empty string an identity while the parsing side
|
|
1432
|
+
// still accepts it, and two cockpits in two different workspaces, neither
|
|
1433
|
+
// with an identity established, match each other's board and one reuses the
|
|
1434
|
+
// other — a hand-off nothing else in this file would refuse, since the
|
|
1435
|
+
// degrade arm's "no identity to match on" is the only thing keeping a held
|
|
1436
|
+
// port fatal there.
|
|
1437
|
+
//
|
|
1438
|
+
// A non-empty string, and nothing more: no trim(). A wholly-whitespace
|
|
1439
|
+
// answer to `--git-common-dir` is already refused one layer down, by
|
|
1440
|
+
// git-env.mjs's workspaceDirFromGitCommonDir(), so no identity reaching
|
|
1441
|
+
// either call site can be whitespace — the construction side gets that
|
|
1442
|
+
// function's return value and the parsing side gets a payload some process
|
|
1443
|
+
// wrote from it. A second whitespace rule here would be one more guard of
|
|
1444
|
+
// exactly the kind this predicate exists to stop writing.
|
|
1445
|
+
//
|
|
1446
|
+
// Not exported, for workspaceHash()'s reason above it: nothing outside this
|
|
1447
|
+
// file asks the question, and every widening of it is already pinned from
|
|
1448
|
+
// outside through the two call sites — mutation-verified for this extraction
|
|
1449
|
+
// (#1661), each mutant killed by a test that was already in board.test.mjs:
|
|
1450
|
+
// `v != null && v !== ""` by the probe's not-a-string row, `typeof v ===
|
|
1451
|
+
// "string"` by its empty-workspace row, a degrade arm publishing `""` by
|
|
1452
|
+
// resolveCockpitInstance's three degrade rows, and dropping it from
|
|
1453
|
+
// serve()'s `scannable` by the CLI's held-port-on-the-degrade-arm row. So no
|
|
1454
|
+
// test is added here: sharing the predicate is what makes the construction
|
|
1455
|
+
// side's rows constrain the parsing side and back, which is a STRONGER suite
|
|
1456
|
+
// than before, not one with a hole a new row could fill.
|
|
1457
|
+
function isWorkspaceId(v) {
|
|
1458
|
+
return typeof v === "string" && v !== "";
|
|
1459
|
+
}
|
|
1460
|
+
|
|
1461
|
+
/**
|
|
1462
|
+
* The cockpit's instance seam, and the only one. Given a cwd, the string
|
|
1463
|
+
* `git rev-parse --git-common-dir` answered with — INJECTED, never read in
|
|
1464
|
+
* here, which is what keeps the worktree case and the resolution-failed case
|
|
1465
|
+
* both plain table rows — and an explicitly requested port if there was one,
|
|
1466
|
+
* decide which state directory this cockpit serves and which port it binds.
|
|
1467
|
+
*
|
|
1468
|
+
* Pure: it listens to nothing, spawns nothing and writes nothing, so every
|
|
1469
|
+
* branch below is reachable from a test with no git repo and no socket. The
|
|
1470
|
+
* one thing it reads is realpath — asked for by `canonicalise: true` below,
|
|
1471
|
+
* and unable to fail the call either way.
|
|
1472
|
+
*
|
|
1473
|
+
* `--git-common-dir` answers with the MAIN checkout's git dir from inside a
|
|
1474
|
+
* linked worktree, so every worktree of one repo resolves to ONE state
|
|
1475
|
+
* directory. That resolution is not spelled here: since #1658 it is
|
|
1476
|
+
* git-env.mjs's workspaceDirFromGitCommonDir(), the same function
|
|
1477
|
+
* ledger.mjs's defaultLedgerPath() and fleet-state.mjs's statePath() resolve
|
|
1478
|
+
* the run's single ledger and single heartbeat with — so the board, the
|
|
1479
|
+
* ledger and the heartbeat cannot disagree about which run they belong to.
|
|
1480
|
+
* The `canonicalise` opt-in is this caller's alone: it is what makes a
|
|
1481
|
+
* symlinked route to one workspace derive that workspace's port instead of a
|
|
1482
|
+
* second, private one, and neither of the other two takes it (canonicalising
|
|
1483
|
+
* their answer would change the path each of them prints without changing
|
|
1484
|
+
* which file it names).
|
|
1485
|
+
*/
|
|
1486
|
+
export function resolveCockpitInstance({ cwd = process.cwd(), gitCommonDir, port } = {}) {
|
|
1487
|
+
// `port != null`, never truthiness: --port 0 is a real request (an
|
|
1488
|
+
// ephemeral bind, #366/#435) and reading it as "absent" would derive a port
|
|
1489
|
+
// straight over the top of one the caller explicitly asked for.
|
|
1490
|
+
const forced = port != null;
|
|
1491
|
+
const workspace = workspaceDirFromGitCommonDir(gitCommonDir, cwd, { canonicalise: true });
|
|
1492
|
+
// Asked as `!isWorkspaceId(...)` rather than `=== null`: the question this
|
|
1493
|
+
// arm answers is "was an identity established", and what counts as one is
|
|
1494
|
+
// the predicate above — the same one the probe parses with, so the two
|
|
1495
|
+
// sides cannot answer it differently. The behaviour is today's exactly:
|
|
1496
|
+
// workspaceDirFromGitCommonDir() answers null for every unusable
|
|
1497
|
+
// `--git-common-dir` and dirname() cannot answer "". It is the SHAPE of
|
|
1498
|
+
// the question that stops being written out twice.
|
|
1499
|
+
if (!isWorkspaceId(workspace)) {
|
|
1500
|
+
// Degrade, never die: a non-git or otherwise unusual checkout still gets
|
|
1501
|
+
// a board. The wording is defaultLedgerPath()'s rather than a second
|
|
1502
|
+
// dialect for the same failure, trailing parenthetical included — that
|
|
1503
|
+
// parenthetical names what is degraded HERE, which is not what is
|
|
1504
|
+
// degraded there. No cause is interpolated where the ledger interpolates
|
|
1505
|
+
// one: this function never ran the probe, so it has none to name, and the
|
|
1506
|
+
// ledger's own template already emits exactly this arm when its cause is
|
|
1507
|
+
// empty.
|
|
1508
|
+
console.error(`${NAME}: WARNING could not resolve --git-common-dir; using cwd-relative .fleet (a second cockpit in another workspace may collide on this port and this state directory)`);
|
|
1509
|
+
// Absolute, like the resolved arm, but anchored on the cwd — which is
|
|
1510
|
+
// what "cwd-relative" resolves to and what this script's fs calls did
|
|
1511
|
+
// with the bare `.fleet` they used before. No workspace was established,
|
|
1512
|
+
// so there is no key to hash and the port is BASE: today's default,
|
|
1513
|
+
// unchanged, for the case that used to be the only case.
|
|
1514
|
+
return { stateDir: join(cwd, ".fleet"), workspace: null, port: forced ? port : PORT_BASE, derived: !forced };
|
|
1515
|
+
}
|
|
1516
|
+
return {
|
|
1517
|
+
stateDir: join(workspace, ".fleet"),
|
|
1518
|
+
workspace,
|
|
1519
|
+
port: forced ? port : PORT_BASE + (workspaceHash(workspace) % PORT_SPAN),
|
|
1520
|
+
derived: !forced,
|
|
1521
|
+
};
|
|
1522
|
+
}
|
|
1523
|
+
|
|
1524
|
+
// The impure half, deliberately outside the seam above. Bounded for the
|
|
1525
|
+
// reason #1199 bounded the ledger's identical probe: an unbounded git that
|
|
1526
|
+
// never returns hangs serve() before it binds anything, with nothing on
|
|
1527
|
+
// stderr to say why. Ambient GIT_DIR/GIT_WORK_TREE scrubbed (#1599) — either
|
|
1528
|
+
// one answers `--git-common-dir` for a DIFFERENT repository, which would
|
|
1529
|
+
// serve this cockpit out of someone else's workspace at exit 0, in silence.
|
|
1530
|
+
// A non-zero exit, a stall and git missing entirely all land on "" and take
|
|
1531
|
+
// the degrade arm above; the seam is total over whatever comes back.
|
|
1532
|
+
const GIT_TIMEOUT_MS = 10_000;
|
|
1533
|
+
function gitCommonDir() {
|
|
1534
|
+
const r = spawnSync("git", ["rev-parse", "--git-common-dir"], { encoding: "utf8", timeout: GIT_TIMEOUT_MS, env: gitEnv() });
|
|
1535
|
+
return r.status === 0 ? r.stdout : "";
|
|
1536
|
+
}
|
|
1537
|
+
|
|
1538
|
+
// How many ports one launch may try before it gives up, and the whole cost
|
|
1539
|
+
// of the scan: the worst case is ATTEMPTS × (a bind plus a probe), so a
|
|
1540
|
+
// workspace whose derived port sits in a crowded corner of the range still
|
|
1541
|
+
// fails in seconds rather than walking all 512. It also bounds how far a
|
|
1542
|
+
// cockpit can land from the stable URL its workspace derives — a board a
|
|
1543
|
+
// handful of ports from where it is bookmarked is still findable by hand,
|
|
1544
|
+
// while one hundreds of ports away (where an unbounded scan could leave it)
|
|
1545
|
+
// typically is not.
|
|
1546
|
+
const PORT_ATTEMPTS = 8;
|
|
1547
|
+
|
|
1548
|
+
/**
|
|
1549
|
+
* The ports one launch may try, in order, for a resolved instance — the
|
|
1550
|
+
* second half of the instance seam and pure like the first, so every row
|
|
1551
|
+
* below is reachable with no socket.
|
|
1552
|
+
*
|
|
1553
|
+
* An EXPLICIT port collapses to a single candidate: the operator named a
|
|
1554
|
+
* port, so there is nothing to scan and (guarded separately in serve()) no
|
|
1555
|
+
* holder to handshake with.
|
|
1556
|
+
*
|
|
1557
|
+
* A DERIVED one starts at the derived port — the stable, bookmarkable one —
|
|
1558
|
+
* and walks forward MODULO the span, never out of the window
|
|
1559
|
+
* resolveCockpitInstance() promises. Without the wrap a workspace hashing to
|
|
1560
|
+
* the top of the range would scan straight past 8634 into ports belonging to
|
|
1561
|
+
* nothing in this scheme, and the range this exists to stay inside would be
|
|
1562
|
+
* a range in name only.
|
|
1563
|
+
*/
|
|
1564
|
+
export function cockpitPorts({ port, derived }) {
|
|
1565
|
+
if (!derived) return [port];
|
|
1566
|
+
const offset = port - PORT_BASE;
|
|
1567
|
+
return Array.from({ length: PORT_ATTEMPTS }, (_, i) => PORT_BASE + ((offset + i) % PORT_SPAN));
|
|
1568
|
+
}
|
|
1569
|
+
|
|
1570
|
+
// One bind attempt, as a value rather than as an event. Resolves with null
|
|
1571
|
+
// on success and with the error otherwise — never rejects, because every
|
|
1572
|
+
// caller has to READ the code (EADDRINUSE is negotiable, everything else is
|
|
1573
|
+
// fatal) and a rejection would make that a try/catch around a control-flow
|
|
1574
|
+
// decision. The listeners are removed on whichever side loses: a server that
|
|
1575
|
+
// failed to bind is dropped, and one that bound gets serve()'s own long-
|
|
1576
|
+
// lived error handler instead of this one-shot.
|
|
1577
|
+
function bindFailure(server, port) {
|
|
1578
|
+
return new Promise((resolve) => {
|
|
1579
|
+
const onError = (e) => { server.removeListener("listening", onListening); resolve(e); };
|
|
1580
|
+
const onListening = () => { server.removeListener("error", onError); resolve(null); };
|
|
1581
|
+
server.once("error", onError);
|
|
1582
|
+
server.once("listening", onListening);
|
|
1583
|
+
server.listen(port);
|
|
1584
|
+
});
|
|
1585
|
+
}
|
|
1586
|
+
|
|
1587
|
+
// ~1s per attempt, and the whole reason this is a probe and not a lockfile:
|
|
1588
|
+
// a launch that cannot get an answer within a second must proceed, not
|
|
1589
|
+
// wait. A holder that accepts the connection and then says nothing is the
|
|
1590
|
+
// case that pays for this timer — nothing else in a socket read bounds it.
|
|
1591
|
+
// One silent window does not settle the question, though: nothing in a socket
|
|
1592
|
+
// read tells a port nobody holds from one whose holder was busy for that
|
|
1593
|
+
// second, and a box under load, a process still between its bind and its
|
|
1594
|
+
// identity write, or a dropped SYN all produce the second shape. The probe
|
|
1595
|
+
// retries once before it will call a silent port foreign (#1660).
|
|
1596
|
+
//
|
|
1597
|
+
// Until #1713 the commonest producer of that shape was this cockpit itself —
|
|
1598
|
+
// a same-workspace holder blocked inside its own synchronous gather() when
|
|
1599
|
+
// the probe arrived, for the 4.72–4.91s a board took to build, which no
|
|
1600
|
+
// number of retries at this timeout would have covered. That one is gone at
|
|
1601
|
+
// the source: the tick's reads are asynchronous and the server answers
|
|
1602
|
+
// throughout (cockpit-tick-nonblocking.test.mjs). Raising this timeout was
|
|
1603
|
+
// ruled out as the fix for it — it would have to clear a gather(), which
|
|
1604
|
+
// charges every launch past a stranger-held port that much per candidate.
|
|
1605
|
+
const PROBE_TIMEOUT_MS = 1000;
|
|
1606
|
+
// 127.0.0.1 rather than `localhost`: no resolver in the path of a launch,
|
|
1607
|
+
// and no chance of asking a different address than the one every cockpit
|
|
1608
|
+
// here binds. The announced URL stays `localhost`, which is the operator's
|
|
1609
|
+
// spelling, not this probe's.
|
|
1610
|
+
const PROBE_HOST = "127.0.0.1";
|
|
1611
|
+
// A holder is not necessarily a cockpit, and a second of localhost writes is
|
|
1612
|
+
// a lot of memory to accept from one. The board payload for a real run is
|
|
1613
|
+
// kilobytes; anything past this is not one, so it is refused as foreign
|
|
1614
|
+
// rather than buffered.
|
|
1615
|
+
const PROBE_BODY_CAP = 1024 * 1024;
|
|
1616
|
+
|
|
1617
|
+
/**
|
|
1618
|
+
* Ask whoever holds `port` which workspace it is serving. Returns that
|
|
1619
|
+
* workspace, or null for every other outcome there is — a refused
|
|
1620
|
+
* connection, a non-200, a body that is not JSON, a payload with no usable
|
|
1621
|
+
* `workspace`, a body over the cap, or a holder that never answers across
|
|
1622
|
+
* two attempts.
|
|
1623
|
+
*
|
|
1624
|
+
* Null is deliberately one value for all of them: the caller's question is
|
|
1625
|
+
* "is this my own cockpit", and every way of failing to prove that is the
|
|
1626
|
+
* same answer — foreign. A holder that IS this workspace's cockpit answers
|
|
1627
|
+
* with the board payload it already serves, so no endpoint is added for
|
|
1628
|
+
* this and the handshake reaches nothing a browser could not. The one
|
|
1629
|
+
* consequence to know: a cockpit started from a build older than #1585
|
|
1630
|
+
* serves a payload with no `workspace` at all, so it reads as foreign and a
|
|
1631
|
+
* launch steps over it rather than reusing it — once, until that process is
|
|
1632
|
+
* restarted.
|
|
1633
|
+
*
|
|
1634
|
+
* A bare timeout gets one retry (#1660) rather than folding straight into
|
|
1635
|
+
* "foreign": nothing in a socket read distinguishes "nobody is there" from
|
|
1636
|
+
* "busy for that second", and a loaded box produces the second shape. Only a
|
|
1637
|
+
* second silent window calls it, and says so on stderr distinctly from a
|
|
1638
|
+
* confirmed non-match — a shrug is not a verdict.
|
|
1639
|
+
*/
|
|
1640
|
+
export function probeCockpitWorkspace(port, timeoutMs = PROBE_TIMEOUT_MS) {
|
|
1641
|
+
return new Promise((resolve) => {
|
|
1642
|
+
let attempts = 0;
|
|
1643
|
+
const probeOnce = () => {
|
|
1644
|
+
let settled = false;
|
|
1645
|
+
const timer = setTimeout(() => {
|
|
1646
|
+
settled = true;
|
|
1647
|
+
req.destroy();
|
|
1648
|
+
attempts += 1;
|
|
1649
|
+
if (attempts < 2) { probeOnce(); return; }
|
|
1650
|
+
console.error(`${NAME}: no answer from port ${port} within ${timeoutMs * 2}ms — cannot confirm it is this workspace's cockpit`);
|
|
1651
|
+
resolve(null);
|
|
1652
|
+
}, timeoutMs);
|
|
1653
|
+
function finish(workspace) {
|
|
1654
|
+
if (settled) return;
|
|
1655
|
+
settled = true;
|
|
1656
|
+
clearTimeout(timer);
|
|
1657
|
+
// Destroy rather than let it drain: an unread body, or a holder
|
|
1658
|
+
// still writing one, would otherwise keep this socket — and the
|
|
1659
|
+
// launch — alive well past the answer.
|
|
1660
|
+
req.destroy();
|
|
1661
|
+
resolve(workspace);
|
|
1662
|
+
}
|
|
1663
|
+
const req = httpRequest({ host: PROBE_HOST, port, path: "/board.json", method: "GET" }, (res) => {
|
|
1664
|
+
if (res.statusCode !== 200) { finish(null); return; }
|
|
1665
|
+
let body = "";
|
|
1666
|
+
res.setEncoding("utf8");
|
|
1667
|
+
res.on("data", (d) => { body += d; if (body.length > PROBE_BODY_CAP) finish(null); });
|
|
1668
|
+
res.on("end", () => {
|
|
1669
|
+
let w;
|
|
1670
|
+
try { w = JSON.parse(body)?.workspace; } catch { finish(null); return; }
|
|
1671
|
+
// Exactly the construction side's rule, because it is literally
|
|
1672
|
+
// the same predicate (#1661): a non-string, or the empty string,
|
|
1673
|
+
// is no identity. `=== ours` would be false for the first anyway,
|
|
1674
|
+
// but an empty string could match an empty workspace and there
|
|
1675
|
+
// must be no such thing.
|
|
1676
|
+
finish(isWorkspaceId(w) ? w : null);
|
|
1677
|
+
});
|
|
1678
|
+
});
|
|
1679
|
+
req.on("error", () => finish(null));
|
|
1680
|
+
req.end();
|
|
1681
|
+
};
|
|
1682
|
+
probeOnce();
|
|
1683
|
+
});
|
|
1684
|
+
}
|
|
1685
|
+
|
|
1686
|
+
export async function serve({ ledgerFile, port, interval, open, spendDir } = {}) {
|
|
1687
|
+
// Both the served state directory and the port come from
|
|
1688
|
+
// resolveCockpitInstance() now, rather than a cwd-relative `.fleet` and a
|
|
1689
|
+
// constant 8123. That is what lets two workspaces run two boards at once
|
|
1690
|
+
// without either writing into the other's state directory, and it ties the
|
|
1691
|
+
// board to the same workspace the ledger resolves itself against.
|
|
1692
|
+
//
|
|
1693
|
+
// A GIVEN-but-invalid --port is refused outright by argPort() and never
|
|
1694
|
+
// reaches here; an ABSENT one leaves `portGiven` nullish, which is how the
|
|
1695
|
+
// seam is told to derive rather than obey. `??` and not `||`, for #366's
|
|
1696
|
+
// reason: --port 0 is a legal ephemeral bind and `||` would discard it.
|
|
1697
|
+
//
|
|
1698
|
+
// A bind failure no longer means one thing, so the two kinds of port part
|
|
1699
|
+
// company here. One this script DERIVED is negotiable: the loop below
|
|
1700
|
+
// handshakes with whoever holds it and steps over a stranger (#1585). One
|
|
1701
|
+
// the caller CHOSE is not — the refusal names that port bare and dies,
|
|
1702
|
+
// because scanning off it would serve the board somewhere the operator did
|
|
1703
|
+
// not ask for and reusing it would hand them someone else's. What tells
|
|
1704
|
+
// them apart is `instance.derived` and not truthiness on `portGiven`: an
|
|
1705
|
+
// explicit `--port 0` is falsy (#366's legal ephemeral bind), so the old
|
|
1706
|
+
// spelling gave it the derived port's treatment, and nothing pinned that.
|
|
1707
|
+
const portGiven = port ?? argPort();
|
|
1708
|
+
interval = interval ?? argInterval() ?? 15;
|
|
1709
|
+
open = open ?? has("open");
|
|
1710
|
+
// #1583: built HERE, once, and read by every tick below. Beside the other
|
|
1711
|
+
// argv reads rather than inside tick() for the obvious reason — a pin rebuilt
|
|
1712
|
+
// per tick is a pin in name only — and above the port loop because it costs
|
|
1713
|
+
// nothing to carry: spendDirPin() touches no filesystem until its first call,
|
|
1714
|
+
// so the reuse and degrade arms that exit before ticking pay nothing for it.
|
|
1715
|
+
// `spendDir ?? argSpendDir()` (#1679), matching the `port ?? argPort()`
|
|
1716
|
+
// shape above: every other argv-read option here takes an in-process
|
|
1717
|
+
// override, and this one hadn't, so the only way to drive --spend-dir
|
|
1718
|
+
// through `serve` at all was the real CLI — no test exercised it.
|
|
1719
|
+
const spendPin = spendDirPin(spendDir ?? argSpendDir());
|
|
1720
|
+
const { computeBoard } = await import("./compute-board.mjs");
|
|
1721
|
+
const instance = resolveCockpitInstance({ cwd: process.cwd(), gitCommonDir: gitCommonDir(), port: portGiven });
|
|
1722
|
+
const stateDir = instance.stateDir;
|
|
1723
|
+
const jsonPath = join(stateDir, "board.json");
|
|
1724
|
+
// #1656: the ledger's own default (ledger.mjs's defaultLedgerPath()) is
|
|
1725
|
+
// never reached here — board.mjs always passes an explicit --file — so an
|
|
1726
|
+
// absent --ledger has to be defaulted against the SAME instance the state
|
|
1727
|
+
// directory came from, not a cwd-relative literal. A worktree or a
|
|
1728
|
+
// subdirectory cwd previously left this pointing at a ledger.md that does
|
|
1729
|
+
// not exist there, while the state directory (above) had already moved to
|
|
1730
|
+
// the workspace: the board and the ledger could disagree about which run
|
|
1731
|
+
// they belonged to, exactly what resolveCockpitInstance() exists to rule
|
|
1732
|
+
// out (#1656 review).
|
|
1733
|
+
ledgerFile = ledgerFile || join(stateDir, "ledger.md");
|
|
1734
|
+
// `served` is the port this process actually BOUND, handed in rather than
|
|
1735
|
+
// closed over: it is not knowable until listen() returns (--port 0 is an
|
|
1736
|
+
// ephemeral bind, #366/#435, and the loop below may also land past a
|
|
1737
|
+
// candidate it could not take), and a tick that reached for `portGiven`
|
|
1738
|
+
// instead would stamp every board served on an ephemeral port with a
|
|
1739
|
+
// `port: 0` no browser could ever reach. A parameter makes that
|
|
1740
|
+
// unreachable rather than merely unlikely — there is no earlier value in
|
|
1741
|
+
// scope for it to pick up.
|
|
1742
|
+
// One tick at a time, and the flag is load-bearing rather than defensive.
|
|
1743
|
+
// Before #1713 the timer's callback was synchronous, so node could not start
|
|
1744
|
+
// a second tick while the first was still inside gather() — it just fired
|
|
1745
|
+
// late. An async tick has no such floor: a gather that outruns `interval`
|
|
1746
|
+
// (a `gh` outage riding out its own timeouts, an operator's `--interval 1`)
|
|
1747
|
+
// would let the timer stack ticks on top of each other, and each of those
|
|
1748
|
+
// reads `prevFile` at its start and renames over it at its end. Two in
|
|
1749
|
+
// flight means double the `gh` and `ci-state.mjs` children — the very load
|
|
1750
|
+
// that made the tick slow — and, worse, a LATER-started tick can finish
|
|
1751
|
+
// first and be overwritten by the older one's payload, walking every
|
|
1752
|
+
// ticket's dwell clock and carried-forward CI value backwards.
|
|
1753
|
+
//
|
|
1754
|
+
// SKIPPED, not queued: a tick recomputes the whole board from scratch, so
|
|
1755
|
+
// the one that would have been queued has nothing in it the next one does
|
|
1756
|
+
// not redo. Announced once per process through the same warn-once gate
|
|
1757
|
+
// every other repeating condition in this file uses — a board falling
|
|
1758
|
+
// behind its interval is worth saying, and worth saying only once.
|
|
1759
|
+
let ticking = false;
|
|
1760
|
+
const tick = async (served) => {
|
|
1761
|
+
if (ticking) {
|
|
1762
|
+
warnOnce("tick-overlap", String(interval),
|
|
1763
|
+
`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`);
|
|
1764
|
+
return;
|
|
1765
|
+
}
|
|
1766
|
+
ticking = true;
|
|
1767
|
+
try {
|
|
1768
|
+
// #1585: the identity a second launch's handshake reads off this
|
|
1769
|
+
// cockpit. It rides the board payload deliberately, rather than a
|
|
1770
|
+
// lockfile or a second endpoint: a payload exists only while the
|
|
1771
|
+
// process serving it does, so nothing written here can outlive this
|
|
1772
|
+
// cockpit and send the next launch at a port nobody holds. It is null
|
|
1773
|
+
// on the degrade arm — no workspace was established — which is exactly
|
|
1774
|
+
// the value no launch may ever match on.
|
|
1775
|
+
//
|
|
1776
|
+
// #1584: joined at gather(), not stamped onto the finished model. The
|
|
1777
|
+
// assignment that used to sit below this line wrote a field the pure
|
|
1778
|
+
// model did not declare, so `build` printed a board with no identity
|
|
1779
|
+
// at all and only the served copy carried one.
|
|
1780
|
+
const model = computeBoard(await gather({
|
|
1781
|
+
ledgerFile, prevFile: jsonPath, interval,
|
|
1782
|
+
// #1597: beside the ledger and out of the same state directory, so
|
|
1783
|
+
// the board, the ledger and the heartbeat cannot disagree about which
|
|
1784
|
+
// run they belong to — the invariant resolveCockpitInstance() exists
|
|
1785
|
+
// for. Re-derived per tick rather than closed over, exactly like
|
|
1786
|
+
// `ledgerFile`: it is a pure join on a directory settled at bind time.
|
|
1787
|
+
stateFile: stateFileIn(stateDir),
|
|
1788
|
+
workspace: instance.workspace, port: served,
|
|
1789
|
+
// The pinned transcript directory, not a fresh lookup: every tick after
|
|
1790
|
+
// the first gets the SAME answer, which is what stops the panel
|
|
1791
|
+
// alternating between two sessions under one project directory (#1583).
|
|
1792
|
+
spendDir: spendPin(),
|
|
1793
|
+
}));
|
|
1794
|
+
const tmp = `${jsonPath}.tmp`;
|
|
1795
|
+
writeFileSync(tmp, JSON.stringify(model)); // atomic: write tmp, rename over target
|
|
1796
|
+
renameSync(tmp, jsonPath);
|
|
1797
|
+
} catch (e) { console.error(`${NAME}: build tick failed: ${e.message}`); }
|
|
1798
|
+
finally { ticking = false; }
|
|
1799
|
+
};
|
|
1800
|
+
|
|
1801
|
+
// #1660: a held port used to mean three different things this loop could
|
|
1802
|
+
// only tell apart by binding first and probing whichever candidate
|
|
1803
|
+
// happened to refuse — so a live cockpit that landed past a squatter
|
|
1804
|
+
// which has since departed was invisible the moment that squatter's port
|
|
1805
|
+
// freed (this process would just bind it directly), and a workspace with
|
|
1806
|
+
// no identity established (the degrade arm) still scanned past a held
|
|
1807
|
+
// port with nothing a handshake could ever match, reopening the
|
|
1808
|
+
// dual-cockpit hazard #1656 closed.
|
|
1809
|
+
//
|
|
1810
|
+
// Bind stays the FIRST thing tried per candidate: that is what lets two
|
|
1811
|
+
// launches racing at start settle on one winner quickly, the winner's
|
|
1812
|
+
// identity published (below) before it can block inside its own gather().
|
|
1813
|
+
// But a successful bind is not the end of the story — once this process
|
|
1814
|
+
// holds a candidate, the REST of the window still gets checked for a
|
|
1815
|
+
// live cockpit that landed further along, exactly the shape a departed
|
|
1816
|
+
// squatter leaves behind, and only when nothing there matches does this
|
|
1817
|
+
// process keep what it bound. A held candidate is probed the same way,
|
|
1818
|
+
// one at a time as the loop reaches it. Neither check runs at all when
|
|
1819
|
+
// this workspace has no identity to match on: an explicit --port
|
|
1820
|
+
// (`!instance.derived`) and the degrade arm (no `isWorkspaceId` identity)
|
|
1821
|
+
// never had a handshake to reach in the first place, so a held port for
|
|
1822
|
+
// either stays fatal, exactly as it was before #1585 existed.
|
|
1823
|
+
const candidates = cockpitPorts(instance);
|
|
1824
|
+
const scannable = instance.derived && isWorkspaceId(instance.workspace);
|
|
1825
|
+
let server = null;
|
|
1826
|
+
for (let i = 0; i < candidates.length; i++) {
|
|
1827
|
+
const candidate = candidates[i];
|
|
1828
|
+
const attempt = createBoardServer(stateDir);
|
|
1829
|
+
const failure = await bindFailure(attempt, candidate);
|
|
1830
|
+
if (!failure) {
|
|
1831
|
+
const rest = scannable ? candidates.slice(i + 1) : [];
|
|
1832
|
+
const holders = await Promise.all(rest.map((p) => probeCockpitWorkspace(p)));
|
|
1833
|
+
const matchAt = holders.indexOf(instance.workspace);
|
|
1834
|
+
if (matchAt === -1) { server = attempt; break; }
|
|
1835
|
+
attempt.close();
|
|
1836
|
+
const url = `http://localhost:${rest[matchAt]}/`;
|
|
1837
|
+
console.error(`${NAME}: cockpit already running for this workspace on ${url}`);
|
|
1838
|
+
// Nothing is opened here, --open or not (#1714). This cockpit was
|
|
1839
|
+
// already running when this launch arrived, so its tab was the business
|
|
1840
|
+
// of the launch that started it; run-team's phase 0 relaunches on every
|
|
1841
|
+
// re-shortlist, and opening here stacked one more tab for the same
|
|
1842
|
+
// board each pass. Only a launch that binds a port and starts the
|
|
1843
|
+
// server opens one, below.
|
|
1844
|
+
//
|
|
1845
|
+
// Exit 0 — and explicitly, not by returning: a backgrounded launch
|
|
1846
|
+
// reports nothing but its exit code, and a handle left behind by the
|
|
1847
|
+
// probe would otherwise hang this process forever while it holds no
|
|
1848
|
+
// port at all.
|
|
1849
|
+
process.exit(0);
|
|
1850
|
+
}
|
|
1851
|
+
// Only a port that is TAKEN is a candidate for any of the below. EACCES
|
|
1852
|
+
// on a privileged port, EADDRNOTAVAIL on an unusable address: those are
|
|
1853
|
+
// faults of their own, and scanning past them would bury each one under
|
|
1854
|
+
// an exhausted-range message at the end that names the wrong problem.
|
|
1855
|
+
if (failure.code !== "EADDRINUSE") die(failure.message);
|
|
1856
|
+
if (!scannable) die(`port ${candidate} in use — pass --port <n>`);
|
|
1857
|
+
const holder = await probeCockpitWorkspace(candidate);
|
|
1858
|
+
if (holder === instance.workspace) {
|
|
1859
|
+
const url = `http://localhost:${candidate}/`;
|
|
1860
|
+
console.error(`${NAME}: cockpit already running for this workspace on ${url}`);
|
|
1861
|
+
// Already running, so nothing opens — the same rule as the arm above.
|
|
1862
|
+
process.exit(0);
|
|
1863
|
+
}
|
|
1864
|
+
console.error(`${NAME}: port ${candidate} is held by something that is not this workspace's cockpit — trying the next port`);
|
|
1865
|
+
}
|
|
1866
|
+
if (!server) die(`no free port for this workspace — tried ${candidates.join(", ")}; pass --port <n> to choose one`);
|
|
1867
|
+
|
|
1868
|
+
// Only now — with a bind this process is actually keeping — does it need
|
|
1869
|
+
// the state directory and board.html. Never for a launch either check
|
|
1870
|
+
// above already turned into a no-op: this shares the state directory
|
|
1871
|
+
// with whatever this workspace's live cockpit is doing, and touching it
|
|
1872
|
+
// before reuse was settled is what #1660's review flagged in the reuse
|
|
1873
|
+
// arm (mkdirSync/copyFileSync used to run before the candidate loop).
|
|
1874
|
+
mkdirSync(stateDir, { recursive: true });
|
|
1875
|
+
try { copyFileSync(join(SCRIPT_DIR, "board.html"), join(stateDir, "board.html")); }
|
|
1876
|
+
catch (e) { die(`cannot stage board.html into ${stateDir}: ${e.message}`); }
|
|
1877
|
+
|
|
1878
|
+
// A bind failure is handled above, one candidate at a time; this handler
|
|
1879
|
+
// owns everything a LISTENING server can still emit. Without it an 'error'
|
|
1880
|
+
// event after the bind has no listener at all and node rethrows it as an
|
|
1881
|
+
// uncaught exception — the one regression the loop above would otherwise
|
|
1882
|
+
// introduce by taking the old, always-attached handler away with it.
|
|
1883
|
+
server.on("error", (e) => die(e.message));
|
|
1884
|
+
|
|
1885
|
+
// Everything below is reached only by a process that HOLDS a port, which is
|
|
1886
|
+
// what #1656's listen-callback gating bought and what this loop has to keep
|
|
1887
|
+
// paying for by position: tick() writes into stateDir, SHARED by every cwd
|
|
1888
|
+
// that resolves to this workspace, so a process that never binds must not
|
|
1889
|
+
// reach it. A second cockpit that ticked first would overwrite the live
|
|
1890
|
+
// one's board.json and reset every ticket's dwell clock.
|
|
1891
|
+
//
|
|
1892
|
+
// Announce the port we GOT, not the one we asked for. They differ for the
|
|
1893
|
+
// one value #366 newly permits: listen(0) binds an ephemeral port, so
|
|
1894
|
+
// echoing the request prints — and --opens — http://localhost:0, which
|
|
1895
|
+
// reaches nothing while the board sits on a port nobody was told (#435
|
|
1896
|
+
// review). address() is only populated once listening, hence only here.
|
|
1897
|
+
const bound = server.address().port;
|
|
1898
|
+
console.error(`${NAME}: cockpit on http://localhost:${bound} (interval ${interval}s)`);
|
|
1899
|
+
|
|
1900
|
+
// #1660: publish identity the instant this port is ours — before the
|
|
1901
|
+
// first tick, which is the one that can be slow (gather() shells out to
|
|
1902
|
+
// gh and ledger.mjs). A sibling launch races this one by sending its
|
|
1903
|
+
// probe as soon as ITS bind attempt refuses, which can be well before
|
|
1904
|
+
// this process's first gather() ever returns; the answer that probe needs
|
|
1905
|
+
// has to already be on disk, not waiting on a compute this process has
|
|
1906
|
+
// not started yet.
|
|
1907
|
+
// #1584: `port` rides along. This stub is a board payload like any other
|
|
1908
|
+
// for as long as the first gather() takes, and a reader that finds it —
|
|
1909
|
+
// the operator, a script, the page — gets the same two identity fields
|
|
1910
|
+
// from it that every later tick writes. The handshake above still reads
|
|
1911
|
+
// only `workspace`.
|
|
1912
|
+
writeFileSync(`${jsonPath}.tmp`, JSON.stringify({ workspace: instance.workspace, port: bound }));
|
|
1913
|
+
renameSync(`${jsonPath}.tmp`, jsonPath);
|
|
1914
|
+
// Yield once so a connection already arriving — that same sibling's probe —
|
|
1915
|
+
// gets a chance to read the identity just written before this process starts
|
|
1916
|
+
// the first tick. The tick no longer blocks the loop (#1713), but gather()
|
|
1917
|
+
// still opens with a synchronous prev-board read before its first await, and
|
|
1918
|
+
// a turn of the loop costs nothing.
|
|
1919
|
+
await new Promise((resolve) => setImmediate(resolve));
|
|
1920
|
+
|
|
1921
|
+
// Deliberately not awaited: the first tick is the slow one, and everything
|
|
1922
|
+
// below it — the timer, and the two signal handlers that are the only way
|
|
1923
|
+
// this process is ever asked to stop — must be in place before it returns,
|
|
1924
|
+
// not after. Nothing here rejects; tick() catches its own faults and the
|
|
1925
|
+
// `ticking` flag it sets is cleared in a finally.
|
|
1926
|
+
tick(bound);
|
|
1927
|
+
const timer = setInterval(() => tick(bound), interval * 1000);
|
|
1928
|
+
|
|
1929
|
+
const stop = () => {
|
|
1930
|
+
clearInterval(timer);
|
|
1931
|
+
server.close(() => process.exit(0));
|
|
1932
|
+
server.closeAllConnections?.(); // drop keep-alive sockets so close() resolves promptly
|
|
1933
|
+
setTimeout(() => process.exit(0), 1000).unref(); // hard backstop if a socket somehow lingers
|
|
1934
|
+
};
|
|
1935
|
+
process.on("SIGINT", stop);
|
|
1936
|
+
process.on("SIGTERM", stop);
|
|
1937
|
+
|
|
1938
|
+
// --open, from this launch alone: it is the one that bound a port and
|
|
1939
|
+
// started a server, and the reuse arms above open nothing (#1714). Only
|
|
1940
|
+
// once the identity is on disk — a launcher running BEFORE that write put a
|
|
1941
|
+
// child squarely inside the window #1660 exists to keep empty, where a
|
|
1942
|
+
// racing launch's probe finds no payload and reads this port as foreign —
|
|
1943
|
+
// and only after the tick, the timer and both signal handlers are in
|
|
1944
|
+
// place: `xdg-open` can run the browser it starts in the foreground and
|
|
1945
|
+
// return only when that browser exits, so a launcher awaited any earlier
|
|
1946
|
+
// could hold the first tick back for the whole session. openBrowser()
|
|
1947
|
+
// never throws; a launcher that is missing or fails is one warning line.
|
|
1948
|
+
if (open) await openBrowser(`http://localhost:${bound}/`);
|
|
1949
|
+
await new Promise(() => {}); // run until signalled
|
|
1950
|
+
}
|
|
1951
|
+
|
|
1952
|
+
// #1093: an internal FAULT is not a refusal, and until this they were one
|
|
1953
|
+
// line. Every guard in this file refuses through die(), which writes its own
|
|
1954
|
+
// line and calls process.exit(2) itself (arg.mjs) rather than throwing, so
|
|
1955
|
+
// nothing a caller can type unwinds as far as the catch below. Re-checked
|
|
1956
|
+
// against the tree rather than taken from the ticket: every `throw` in this
|
|
1957
|
+
// file — readOmpSpend's per-transcript catch, and the three prev-board shape guards
|
|
1958
|
+
// gather() gained in #1192 — is caught by the try that raises it, so the whole
|
|
1959
|
+
// population reaching this handler is this script breaking. Handing that
|
|
1960
|
+
// to die() printed a bug under the wording and the exit code a typo gets — one
|
|
1961
|
+
// `board: <text>` line, exit 2, no stack — and an operator could not tell the
|
|
1962
|
+
// two apart.
|
|
1963
|
+
//
|
|
1964
|
+
// So the entry point gets its own path and its own code, and die() is left
|
|
1965
|
+
// exactly as the other nine scripts have it. 70 is sysexits.h's EX_SOFTWARE,
|
|
1966
|
+
// "an internal software error has been detected", and it spends nothing the
|
|
1967
|
+
// fleet's exit vocabulary already means: 0 is the answer, 1 is a verdict (this
|
|
1968
|
+
// script has none to give), 2 is every refusal here, 3 is candidates.mjs's
|
|
1969
|
+
// minted verdict, and 126+ is the band a shell mints for itself. Stated in the
|
|
1970
|
+
// script-surface table of docs/specs/2026-07-23-fleet-plugin-design.md, which
|
|
1971
|
+
// board.mjs had no row in at all before this.
|
|
1972
|
+
const FAULT_EXIT = 70;
|
|
1973
|
+
|
|
1974
|
+
// The diagnostic, and it can never come back empty. Read off `stack` rather
|
|
1975
|
+
// than `instanceof Error`: the stack is what a fault owes the operator, and
|
|
1976
|
+
// asking for it directly needs no error TYPE — the hierarchy #1093 rules out.
|
|
1977
|
+
// A thrown non-Error has no stack and used to arrive as `e.message ===
|
|
1978
|
+
// undefined`, so the CLI printed the literal `board: undefined`; inspect()
|
|
1979
|
+
// renders every value there is — `undefined`, `null`, `""`, a circular object
|
|
1980
|
+
// — as something with bytes in it.
|
|
1981
|
+
export function faultText(e) {
|
|
1982
|
+
return typeof e?.stack === "string" && e.stack !== "" ? e.stack : `non-Error rejection: ${inspect(e)}`;
|
|
1983
|
+
}
|
|
1984
|
+
|
|
1985
|
+
// writeSync and the leading newline for die()'s own reasons (arg.mjs): tryRun
|
|
1986
|
+
// re-emits gh's stderr through this process's async stream, so a stack queued
|
|
1987
|
+
// behind it on a pipe is what process.exit() discards. The empty catch is
|
|
1988
|
+
// die()'s too — the message can be lost, the exit code cannot.
|
|
1989
|
+
//
|
|
1990
|
+
// A single writeSync call can also short-write — return the count it
|
|
1991
|
+
// managed and throw nothing at all — or throw EAGAIN outright, the same
|
|
1992
|
+
// failure #889 gave die() (arg.mjs) a bounded retry loop for, and PR #1523
|
|
1993
|
+
// then gave staleness.mjs's verdict() too. board.mjs has exactly one
|
|
1994
|
+
// writeSync call site — this one — and #1549 moved arg.mjs's die() and
|
|
1995
|
+
// staleness.mjs's verdict() onto the shared writeAll() and deleted
|
|
1996
|
+
// ci-state.mjs's emit() outright, so fault() is now the only script-level
|
|
1997
|
+
// function left hand-rolling this loop directly: it carries the largest
|
|
1998
|
+
// single payload of any of them, a full stack, not a one-line refusal — so
|
|
1999
|
+
// it is the one most likely to collide with a saturated pipe and lose the
|
|
2000
|
+
// diagnostic silently. The loop below mirrors writeAll()'s shape: resume a
|
|
2001
|
+
// short write where writeSync left off, and retry
|
|
2002
|
+
// EAGAIN after a 1ms Atomics.wait, capped at MAX_EAGAIN_RETRIES so a reader
|
|
2003
|
+
// that never drains still reaches process.exit() below instead of hanging
|
|
2004
|
+
// forever. A sibling script that wants a fault path adopts this shape
|
|
2005
|
+
// rather than spelling a second one; it is deliberately not in arg.mjs,
|
|
2006
|
+
// which exists to hold the helpers that already had copies to collapse.
|
|
2007
|
+
const MAX_EAGAIN_RETRIES = 200;
|
|
2008
|
+
|
|
2009
|
+
// Shared across every retry: Atomics.wait never writes or notifies it, so one
|
|
2010
|
+
// instance times out exactly as a fresh one would, without allocating a
|
|
2011
|
+
// SharedArrayBuffer on every EAGAIN.
|
|
2012
|
+
const IDLE = new Int32Array(new SharedArrayBuffer(4));
|
|
2013
|
+
|
|
2014
|
+
function fault(e) {
|
|
2015
|
+
try {
|
|
2016
|
+
let buf = Buffer.from(`\n${NAME}: internal fault (exit ${FAULT_EXIT}) — a bug in ${NAME}.mjs, not in what you typed\n${faultText(e)}\n`);
|
|
2017
|
+
let retries = 0;
|
|
2018
|
+
while (buf.length) {
|
|
2019
|
+
try {
|
|
2020
|
+
buf = buf.subarray(writeSync(2, buf));
|
|
2021
|
+
} catch (writeErr) {
|
|
2022
|
+
if (writeErr.code !== "EAGAIN" || ++retries > MAX_EAGAIN_RETRIES) break;
|
|
2023
|
+
Atomics.wait(IDLE, 0, 0, 1);
|
|
2024
|
+
}
|
|
2025
|
+
}
|
|
2026
|
+
} catch {
|
|
2027
|
+
// Message may be lost; the exit code below must not be.
|
|
2028
|
+
}
|
|
2029
|
+
process.exit(FAULT_EXIT);
|
|
2030
|
+
}
|
|
2031
|
+
|
|
2032
|
+
// Only run main() as a CLI, never when imported by a test. realpathSync resolves
|
|
2033
|
+
// both sides (relative argv, symlinks) so the equality is reliable regardless of
|
|
2034
|
+
// how node was invoked.
|
|
2035
|
+
const isCLI = process.argv[1] &&
|
|
2036
|
+
realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url));
|
|
2037
|
+
if (isCLI) main().catch(fault);
|