@feigi/fleet-ctl 3.27.0 → 3.28.1

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.
@@ -13,6 +13,7 @@ argument-hint: [pr-number]
13
13
  3. **Run `testCmd` before you commit**, from the worktree, copied verbatim — not a runner you picked. `testCmd` is the command your dispatcher handed you; **standalone, with no dispatcher to hand you one, it is the repo's own test command**, the Test entrypoint in the repo's Recipe cache (`derive-testcmd.sh <repo> test` prints it). Read it off the repo, never invent one: "not a runner you picked" is what this step forbids, and on the standalone path nothing else defines the referent. With no usable Recipe cache (`derive-testcmd.sh` refuses), run the Recipe derivation step first — dispatch a `task` member, agent `fleet-recipe-deriver`, its prompt naming the main checkout's absolute path as `<repo>` and a scratch directory of its own; it proves both commands in a throwaway worktree and writes the cache only on proof, and its `RECIPE NOT PROVEN` is a stop, reported with its reason. Never fall back to a runner of your own choosing. `tests 0` is a FAILED run, not a pass: a glob matching nothing still exits 0. **Zero is not the only no-work count.** A run reporting **0 passes with no failures** skipped everything it collected, and a count **materially below the whole suite** means you ran a partial tree — this suite reported `tests 937` when this line was written, so compare what you get against a full run rather than against zero. The number drifts; that is the safe direction, because a stale one produces a loud false red while its absence produces a silent false green. Red, zero-test, or either no-work count → fix it or move the finding to defer; never commit over it. Then commit and push — `git push origin HEAD:<branch>`, the explicit refspec: this step also runs from a `--detach` worktree (`run-team/SKILL.md`'s worktree-recreation form), where a bare `git push` exits 128 (`fatal: You are not currently on a branch`) and any push whose destination is `HEAD` rather than a full or branch refname (`-u` or not, forced or not) exits 1 (`error: The destination you provided is not a full refname`) — and report the test result alongside the SHA. **Then reconcile the PR body with what you actually did.** It merges into the permanent record and nothing downstream re-derives it: your commit messages are yours to fix and usually get fixed, the body is neither. Removing a change, or reversing one, leaves the body asserting work the diff no longer contains. Measured twice in one run — one body kept asserting a calibration its own fix had just deleted as false, another kept claiming a hunk the fix had removed as "this diff owns it" — both caught by a finisher's reading rather than by any rule, and both would otherwise have merged intact. `gh pr edit <pr> --body-file <path>`, and re-read the body against the final diff rather than against your memory of it. **Never `--no-verify`.** The fleet runs in repos it knows nothing about: it must not assume a pre-commit hook exists, and must never bypass one that does — a hook that fails is a finding to report, not an obstacle. Nothing re-reviews what you commit here, so this run is the only gate between your edit and a merge.
14
14
  4. **Under the fleet, do not hold this wait.** The controller owns a persistent CI Monitor and dispatches a finisher once your report has arrived and CI is green — so push, then report to the controller a **final verdict** (every specialist you dispatched + its outcome + your apply/defer adjudication + the pushed SHA) and stop. A specialist that has neither reported nor been relayed to you is not a verdict line — ask the controller for it by name before ruling; see **Specialists**. The controller keys "review complete" on that verdict, **never on you merely going idle** — a slow specialist can still be running when your turn ends, and finishing off idle-alone ships a premature label (observed: a PR labelled while its contract-test specialist was still running and about to surface a vacuous pin). A turn-based reviewer re-reading `gh pr checks` each idle cycle rebuilds its whole context for nothing the Monitor lacks. **Standalone (no controller): watch** the run until the diff-validating jobs are green (bind via `ci-state.mjs` below); fix a **genuine** failure and repeat from 3. **Staleness is not a failure:** a `rebase-check` red or heavy jobs `skipped` **solely from a non-zero behind-count** never clears by waiting and must not be rebased away here — see **`skipped` is not `passed`** and **Do NOT rebase to label** below for what it looks like and why. Stop watching and go to 6. A turn-based reviewer that "waits for green" on a behind PR stalls forever and ends its turn without labelling. **`ci-state.mjs` returns `verdict: "no-ci"`** → there is no run to watch, so don't: go straight to 6 and let that step's `--declare-no-ci` branch decide.
15
15
  5. File each deferred finding: `gh issue create --label <ready-for-agent|needs-triage>` with the finding, `file:line`, why deferred, `Deferred from PR #<pr> review`, and **the finding's `dimension` in the issue body** — the review returns it on every finding, and a backlog that does not carry it cannot be attributed to the specialist that generated it. **The label follows the finding's state, not this step** — but it is never omitted; an unlabelled issue is invisible to both `candidates.mjs --require-label` and the cockpit's pool query, reachable only by a human. **The bar here is whether the DEFECT is confirmed — never whether the remedy is settled.** Confirmed defect with the remedy still open → `ready-for-agent`, and say in the body that the remedy is open. Torn → `needs-triage`, narrowed: torn means **unsure anything is broken**, not unsure how to fix it. **A finding a refuter CHECKED and did not survive is neither** — it is not a confirmed defect, and you are not unsure whether anything is broken: you measured that nothing is. Refutations go as **one issue per review, titled `PR #<pr> review: the suggestion band, checked`, labelled `wontfix`, and CLOSED** — a run that files them open instead has to be corrected afterwards, as one was on 2026-08-27. Left open they read as queued agent work and rot into filing artifacts; a measured triage pass found a quarter of its `needs-triage` backlog was refuted records, bulk-closable by title shape. Closed is still a durable home — `check` reads the tracker at `--state all`, so a future run re-deriving the finding lands on the evidence rather than re-litigating it. Split the band only where an entry is **not** a refutation: a residual the refuter surfaced, or a finding refused as out of scope and never checked, is real deferred work — and real deferred work earns its own open issue only past a second bar. **Worth a claim: a finding whose own claim is that correct code could be shaped better — style, naming, layout, redundancy, a micro-simplification — never gets its own open issue.** Its only open question is "is this worth doing?", which answers itself under the repriced triage bar: measured 2026-08-15→31, 133 issues were triage-closed `wontfix` in sixteen days, 121 of them review deferrals, mostly this shape. Append it to the same closed record issue under a `Below the claim bar` heading — `file:line`, dimension, the claim, and a re-open trigger per entry. Closed is a durable home for these too: `check` reads `--state all`, so a run re-deriving the finding lands on the record instead of re-filing — and a later review returning the same finding as `survived`, or a maintainer hitting it, is the promotion signal: file it open then, citing the record. **An in-scope rediscovery step 2 applied is that same promotion signal, and it files nothing** — so the record carries no mark unless you write one: run `check` over each finding step 2 applied as well, and where its tracker rows put one on a `Below the claim bar` entry, comment on that record issue, opening `Promoted — applied, not filed`, and name the entry, that its refuter let it through, and the commit carrying the fix. That comment is the promotion mark this path leaves, and it is **not** a cross-reference — measured on this tracker, a comment mints `cross-referenced` on the issue its own text *names*, never on the issue it sits under (a comment citing a second issue landed on that issue's timeline and nowhere else), so the fixed opening is what carries the signal instead. **The bar reads the finding's claim, never its review band** — a finding that alleges wrong behavior, whatever band it sat in, `unverified`-with-crashed-refuters included, is above this bar and files open under the confirmed/torn split, which is why a band cannot carry this decision. Do **not** reach for phase 0's **decided?** test here. That is a *consumption* gate, priced for a seat where implementer divergence costs a claim, a worktree and a dispatch; at filing time divergence costs one PR review the maintainer already runs. Same test, two seats, opposite correct answers — and reading it in this seat took `needs-triage` from 11 to 135 before it was repriced (ruled 2026-08-18). **Dedupe through `~/.fleet/bin/fleet-run ledger.mjs check "<subject>"`, never a bare `gh issue list --search`** — the duplicate class that guard exists to catch was filed from *here*: the ledger row for the finding rediscovered five times in one measured run carries a reviewer's own source tag, `(review-pr-108)`. `check` reads this run's filed list *and* the tracker at `--state all`, so a closed duplicate still counts. Exit **1** is already filed in this run; exit **3** is a clean ledger with matching tracker rows that score against the subject — read the ones it prints and comment on the existing follow-up rather than filing a second issue. **Exit 0 is not automatically "safe to file"**: it covers `clean`, `soft-hit` and `unverified` alike, and an unreachable `gh` degrades to a ledger-only answer that says `TRACKER NOT CHECKED`, so read the stdout `verdict` to tell a tracker that was searched and clean from one nobody read — under `unverified`, search it yourself before filing — or, for the applied-promotion comment above, before treating a tracker nobody could read as a reason to skip it. **`soft-hit` is the answer that costs most to misread**: it means related rows were found and none of them was established as a duplicate — a near-miss above the floor, or tracker rows the scorer rates 0.00 — so read the rows it printed and decide, and never treat that exit 0 as permission. Exit **2** is a usage error, meaning nothing was checked at all: fix the invocation and re-run, never read it as a duplicate. Full exit-code and `verdict` semantics live in `$(~/.fleet/bin/fleet-run --root)/skills/run-team/SKILL.md`'s **Run ledger** section — read them there rather than restating them here. **The guard dedupes, it never drops:** a duplicate becomes a comment on the issue that already covers it, never a dropped finding. **Record every issue you create, at once:** immediately after each `gh issue create`, run `~/.fleet/bin/fleet-run ledger.mjs filed <N> "<subject>"` — `<N>` the number `gh issue create` printed, and **the same subject string you passed to `check`**, so the next `check` for that finding meets it in the filed list instead of scoring a rewording. Without it the guard's ledger half never holds a row, and its exit **1** can never fire. If `filed` fails, retry it once; if it fails again, leave the issue alone — it exists and is correct — and report it as `unrecorded: #N <subject>`, so the controller runs `filed` for it. Report `filed: #N <subject>` for every issue you created — under the fleet, in your report to the controller. **The one window the guard cannot see:** `check` → `gh issue create` → `filed` is three commands, and the ledger's lock covers each alone, so two filers can both read `clean` in the seconds before either records. That gap is accepted, never a reason to skip `filed`. Post the numbers as one PR comment.
16
+ **A duplicate that should hold an open deferral is relabelled up, never down.** Where the guard lands a finding whose home is an open issue on an existing one that is open and labelled `needs-triage` while the finding's state calls for `ready-for-agent` — a defect its refuters confirmed — relabel it with `gh issue edit <N> --remove-label needs-triage --add-label ready-for-agent`, and cite the refuters' verdict in the comment you leave there. Never relabel `ready-for-agent` down to `needs-triage`: a `ready-for-agent` issue already holds a `needs-triage` finding, and a later run's crashed refuters are no reason to send a confirmed defect back to triage. A closed one cannot hold it: file a new open issue citing it, as the promotion rule above does for the closed record.
16
17
  **Name where each deferral went, in the disposition record.** Every entry you defer carries `issue`: the number of the issue you filed it to, commented it onto, or appended it to — the closed `PR #<pr> review: the suggestion band, checked` record included. An in-scope `suggestion`'s entry — an `unverified` finding with `refutersDispatched` of zero — also carries `verdictPath`, applied or deferred: the absolute path of a file holding its refuter's verdict as JSON, `{"refuted": <boolean>, "reason": "<string>"}`, under your own `<scratch>/pr<N>/fix-XXXXXXXX/<finding>/` run root. `dispositions-check.mjs` reads each named issue back through `gh issue view --json labels,state,title` and each verdict file off disk; a mismatch names the row of its filing table the entry broke, so move or relabel that filing to the home the row names and run the check again. With `gh` unreachable, or an issue it cannot read, that filing goes unchecked: with nothing else broken the verdict is `unchecked` — never `ok`, and it exits 1 — so run the check again once `gh` answers.
17
18
  6. Diff-check green (run-bound per `ci-state.mjs`; under staleness see **`skipped` is not `passed`** for what the label then rests on) **and** deferrals filed **and** the PR carrying exactly one release label (`patch`/`minor`/`major`, counting only those three; **required on every PR** — `release-label.yml` auto-adds `patch` when none is present and hard-fails on more than one, so this never needs to check whether the repo defines the gate at all, and `gh label list` settles nothing here any more) **and** `dispositions-check.mjs --member fix-pr-<pr> --scratch <scratch>` run over your own record exiting 0 (standalone that is yours to run, from the worktree, after step 2 writes `<scratch>/dispositions-<pr>.json`; it reads the review file beside it, which you write yourself from the findings step 1 collected, in the shape **The review result file** describes — `pr`, `head`, `snapshot`, `counts` and the `survived`, `refuted` and `unverified` buckets; standalone you pass `--no-ledger`, so it writes no token and the exit status is the verdict — a `.fleet/ledger.md` the repository already holds is a previous run's, and without the flag it exits 2 for a ledger with no row for you; under the fleet `ledger.mjs dispatch` has already refused a finisher without it) → `gh pr edit <pr> --add-label ready-to-merge`. Do not merge. A non-zero dispositions exit halts you before the label, and you report the violations it printed. Zero or more than one release label halts you before the label, naming which you found — a timed-out `gh pr create` opens the PR with its `--label` unapplied and no exit status to react to, and nothing after this step re-derives the release label. **Under the fleet a finisher does this** — a fresh small agent the controller dispatches (after your final verdict, never on your bare idle). Gate it on the diff-validating **`check`** job, **not** on `ci-state --quiet` exit 0, which a behind PR — the normal case once any sibling merges — never reaches: a `rebase-check` red or heavy jobs `skipped` off the behind-count hold it short of full green, so an exit-0 gate strands every behind PR unlabelled. Label when `check` is present and green **and no heavy job (the diff-validating suites — *not* the `rebase-check` currency gate) is in `failure`** — a `skipped` heavy job is behind-count staleness and fine — **solely** off that count, which is a condition to establish rather than infer, see the five-condition note in `$(~/.fleet/bin/fleet-run --root)/skills/run-team/SKILL.md`'s fix-applier prompt block. A `failure` is the diff's own fault and blocks the label, else a genuinely broken PR gets labelled off a green `check` and burns a merge-bot rebase+CI cycle before the failure resurfaces. Read per-job state for this: run `ci-state.mjs` **without** `--quiet`, or read its `jobs` — the `--quiet` payload drops the per-job `jobs`/`missing` and the `dropped` list, keeping `reasons` (which still distinguishes `is failure` from `is skipped`). You reach step 6 yourself only when green is already in hand at push time.
18
19
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@feigi/fleet-ctl",
3
- "version": "3.27.0",
3
+ "version": "3.28.1",
4
4
  "description": "Agent fleet: run-team controller, merge bot, PR reviewer, and the ticket pipeline they share",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
package/scripts/board.mjs CHANGED
@@ -31,22 +31,22 @@
31
31
  // <path>` is how an operator names the right one: it overrides the
32
32
  // heuristic outright.
33
33
 
34
- import { execFile, spawnSync } from "node:child_process";
34
+ import { execFile } from "node:child_process";
35
35
  import { readFileSync, writeFileSync, renameSync, existsSync, readdirSync, statSync, writeSync } from "node:fs";
36
36
  import { classifyRole, computeSpend, attributeTools, mergeTools } from "./compute-spend.mjs";
37
37
  import {
38
38
  encodeProjectDir, isOmpSessionDirName, ompSessionTranscripts, foldOmpTranscript, ompMemberRecord,
39
39
  } from "./member-record.mjs";
40
40
  import { makeDie, defineFlags } from "./arg.mjs";
41
- import { gitEnv, workspaceDirFromGitCommonDir } from "./git-env.mjs";
41
+ import { fleetFile, FleetDirUnresolvable } from "./fleet-dir.mjs";
42
42
  import { mergedReadPrs } from "./compute-board.mjs";
43
43
  // The heartbeat's liveness mark, read here and never written. The
44
44
  // cockpit is a READER of that key — the heartbeat is its only writer — and it
45
45
  // reaches the file through the module that owns the filename rather than
46
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, and a second probe could answer differently.
47
+ // file's own resolveCockpitInstance(), not from statePath(): the workspace is
48
+ // already resolved once per launch here, with the `canonicalise` opt-in only
49
+ // this caller takes, and a second resolution could answer differently.
50
50
  import { readState, stateFileIn } from "./fleet-state.mjs";
51
51
  import { fileURLToPath } from "node:url";
52
52
  import { isCLI } from "./is-cli.mjs";
@@ -1349,7 +1349,7 @@ async function main() {
1349
1349
  // writes no state directory, so the argument that moved serve()'s default
1350
1350
  // onto the workspace does not reach it, and changing it would change what
1351
1351
  // an existing `build` reads.
1352
- const instance = resolveCockpitInstance({ cwd: process.cwd(), gitCommonDir: gitCommonDir() });
1352
+ const instance = resolveCockpitInstance({ cwd: process.cwd(), ...cockpitWorkspace(process.cwd()) });
1353
1353
  const model = computeBoard(await gather({
1354
1354
  ledgerFile: ledgerFile || ".fleet/ledger.md", prevFile,
1355
1355
  // The heartbeat's file, from the SAME instance the identity
@@ -1460,11 +1460,12 @@ function workspaceHash(key) {
1460
1460
  //
1461
1461
  // A non-empty string, and nothing more: no trim(). A wholly-whitespace
1462
1462
  // answer to `--git-common-dir` is already refused one layer down, by
1463
- // git-env.mjs's workspaceDirFromGitCommonDir(), so no identity reaching
1464
- // either call site can be whitespace — the construction side gets that
1465
- // function's return value and the parsing side gets a payload some process
1466
- // wrote from it. A second whitespace rule here would be one more guard of
1467
- // exactly the kind this predicate exists to stop writing.
1463
+ // git-env.mjs's workspaceDirFromGitCommonDir() inside fleet-dir.mjs's
1464
+ // fleetFile(), so no identity reaching either call site can be whitespace —
1465
+ // the construction side gets the workspace fleetFile() resolved and the
1466
+ // parsing side gets a payload some process wrote from it. A second whitespace
1467
+ // rule here would be one more guard of exactly the kind this predicate exists
1468
+ // to stop writing.
1468
1469
  //
1469
1470
  // Not exported, for workspaceHash()'s reason above it: nothing outside this
1470
1471
  // file asks the question, and every widening of it is already pinned from
@@ -1482,53 +1483,41 @@ function isWorkspaceId(v) {
1482
1483
  }
1483
1484
 
1484
1485
  /**
1485
- * The cockpit's instance seam, and the only one. Given a cwd, the string
1486
- * `git rev-parse --git-common-dir` answered with — INJECTED, never read in
1487
- * here, which is what keeps the worktree case and the resolution-failed case
1488
- * both plain table rows — and an explicitly requested port if there was one,
1489
- * decide which state directory this cockpit serves and which port it binds.
1486
+ * The cockpit's instance seam, and the only one. Given a cwd, the workspace
1487
+ * this cockpit belongs to — INJECTED, already resolved, or null when it could
1488
+ * not be — and an explicitly requested port if there was one, decide which
1489
+ * state directory this cockpit serves and which port it binds.
1490
1490
  *
1491
- * Pure: it listens to nothing, spawns nothing and writes nothing, so every
1492
- * branch below is reachable from a test with no git repo and no socket. The
1493
- * one thing it reads is realpath — asked for by `canonicalise: true` below,
1494
- * and unable to fail the call either way.
1491
+ * Pure: it listens to nothing, spawns nothing, reads nothing and writes
1492
+ * nothing, so every branch below is reachable from a test with no git repo
1493
+ * and no socket.
1495
1494
  *
1496
- * `--git-common-dir` answers with the MAIN checkout's git dir from inside a
1497
- * linked worktree, so every worktree of one repo resolves to ONE state
1498
- * directory. That resolution is not spelled here: it is
1499
- * git-env.mjs's workspaceDirFromGitCommonDir(), the same function
1500
- * ledger.mjs's defaultLedgerPath() and fleet-state.mjs's statePath() resolve
1501
- * the run's single ledger and single heartbeat with — so the board, the
1502
- * ledger and the heartbeat cannot disagree about which run they belong to.
1503
- * The `canonicalise` opt-in is this caller's alone: it is what makes a
1504
- * symlinked route to one workspace derive that workspace's port instead of a
1505
- * second, private one, and neither of the other two takes it (canonicalising
1506
- * their answer would change the path each of them prints without changing
1507
- * which file it names).
1495
+ * The workspace comes from fleet-dir.mjs's fleetFile(), the same locator the
1496
+ * run's ledger and heartbeat are resolved with — so the board, the ledger and
1497
+ * the heartbeat cannot disagree about which run they belong to — asked with
1498
+ * the `canonicalise` opt-in only this caller takes: a symlinked route to one
1499
+ * workspace must derive that workspace's port instead of a second, private
1500
+ * one.
1501
+ *
1502
+ * `why` is fleetFile()'s message when it could not answer — it names what
1503
+ * failed, and the degrade warning below carries it, as the ledger's does.
1504
+ * Absent, the warning names the failure without a reason.
1508
1505
  */
1509
- export function resolveCockpitInstance({ cwd = process.cwd(), gitCommonDir, port } = {}) {
1506
+ export function resolveCockpitInstance({ cwd = process.cwd(), workspace, why, port } = {}) {
1510
1507
  // `port != null`, never truthiness: --port 0 is a real request (an
1511
1508
  // ephemeral bind) and reading it as "absent" would derive a port
1512
1509
  // straight over the top of one the caller explicitly asked for.
1513
1510
  const forced = port != null;
1514
- const workspace = workspaceDirFromGitCommonDir(gitCommonDir, cwd, { canonicalise: true });
1515
1511
  // Asked as `!isWorkspaceId(...)` rather than `=== null`: the question this
1516
1512
  // arm answers is "was an identity established", and what counts as one is
1517
1513
  // the predicate above — the same one the probe parses with, so the two
1518
- // sides cannot answer it differently. The behaviour is today's exactly:
1519
- // workspaceDirFromGitCommonDir() answers null for every unusable
1520
- // `--git-common-dir` and dirname() cannot answer "". It is the SHAPE of
1521
- // the question that stops being written out twice.
1514
+ // sides cannot answer it differently.
1522
1515
  if (!isWorkspaceId(workspace)) {
1523
1516
  // Degrade, never die: a non-git or otherwise unusual checkout still gets
1524
- // a board. The wording is defaultLedgerPath()'s rather than a second
1525
- // dialect for the same failure, trailing parenthetical included — that
1526
- // parenthetical names what is degraded HERE, which is not what is
1527
- // degraded there. No cause is interpolated where the ledger interpolates
1528
- // one: this function never ran the probe, so it has none to name, and the
1529
- // ledger's own template already emits exactly this arm when its cause is
1530
- // empty.
1531
- 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)`);
1517
+ // a board. The wording is the ledger's rather than a second dialect for
1518
+ // the same failure, trailing parenthetical included — that parenthetical
1519
+ // names what is degraded HERE, which is not what is degraded there.
1520
+ console.error(`${NAME}: WARNING ${why || "could not resolve --git-common-dir"}; using cwd-relative .fleet (a second cockpit in another workspace may collide on this port and this state directory)`);
1532
1521
  // Absolute, like the resolved arm, but anchored on the cwd — which is
1533
1522
  // what "cwd-relative" resolves to and what this script's fs calls did
1534
1523
  // with the bare `.fleet` they used before. No workspace was established,
@@ -1544,18 +1533,18 @@ export function resolveCockpitInstance({ cwd = process.cwd(), gitCommonDir, port
1544
1533
  };
1545
1534
  }
1546
1535
 
1547
- // The impure half, deliberately outside the seam above. Bounded for the
1548
- // reason the ledger's identical probe is bounded: an unbounded git that
1549
- // never returns hangs serve() before it binds anything, with nothing on
1550
- // stderr to say why. Ambient GIT_DIR/GIT_WORK_TREE scrubbed — either
1551
- // one answers `--git-common-dir` for a DIFFERENT repository, which would
1552
- // serve this cockpit out of someone else's workspace at exit 0, in silence.
1553
- // A non-zero exit, a stall and git missing entirely all land on "" and take
1554
- // the degrade arm above; the seam is total over whatever comes back.
1555
- const GIT_TIMEOUT_MS = 10_000;
1556
- function gitCommonDir() {
1557
- const r = spawnSync("git", ["rev-parse", "--git-common-dir"], { encoding: "utf8", timeout: GIT_TIMEOUT_MS, env: gitEnv() });
1558
- return r.status === 0 ? r.stdout : "";
1536
+ // The impure half, deliberately outside the seam above: the `{ workspace }`
1537
+ // fleetFile() resolves from `cwd`, or `{ workspace: null, why }` when it
1538
+ // cannot — which takes the degrade arm above, so a non-git checkout, a stalled
1539
+ // git and git missing entirely all still get a board, with the reason on its
1540
+ // warning. Spread into resolveCockpitInstance()'s arguments.
1541
+ function cockpitWorkspace(cwd) {
1542
+ try {
1543
+ return { workspace: dirname(fleetFile(null, { cwd, canonicalise: true })) };
1544
+ } catch (e) {
1545
+ if (!(e instanceof FleetDirUnresolvable)) throw e;
1546
+ return { workspace: null, why: e.message };
1547
+ }
1559
1548
  }
1560
1549
 
1561
1550
  // How many ports one launch may try before it gives up, and the whole cost
@@ -1773,7 +1762,7 @@ export async function serve({ ledgerFile, port, interval, open, spendDir } = {})
1773
1762
  // through `serve` at all was the real CLI — no test exercised it.
1774
1763
  const spendPin = spendDirPin(spendDir ?? argSpendDir());
1775
1764
  const { computeBoard } = await import("./compute-board.mjs");
1776
- const instance = resolveCockpitInstance({ cwd: process.cwd(), gitCommonDir: gitCommonDir(), port: portGiven });
1765
+ const instance = resolveCockpitInstance({ cwd: process.cwd(), ...cockpitWorkspace(process.cwd()), port: portGiven });
1777
1766
  const stateDir = instance.stateDir;
1778
1767
  const jsonPath = join(stateDir, "board.json");
1779
1768
  // The ledger's own default (ledger.mjs's defaultLedgerPath()) is
@@ -79,24 +79,28 @@
79
79
  // mismatch names the row the entry broke:
80
80
  //
81
81
  // row finding home
82
- // 1 survived, deferred for an allowed reason other open, ready-for-agent
83
- // than false-rationale
84
- // 2 survived, deferred false-rationale closed suggestion-band record
82
+ // 1 survived, in scope, deferred for an allowed open, ready-for-agent
83
+ // reason other than false-rationale
84
+ // 2 survived, in scope, deferred false-rationale closed suggestion-band record
85
85
  // 3 unverified, its refuters dispatched and crashed open, needs-triage
86
86
  // 4 in-scope suggestion, its refuter refuted it closed suggestion-band record
87
87
  // 5 in-scope suggestion, its refuter let it survive applied, or deferred as row 1
88
88
  // 6 out-of-scope suggestion alleging wrong behavior open, needs-triage
89
89
  // 7 claimKind shape, below the claim bar closed suggestion-band record
90
+ // 8 survived, out of scope, whatever its reason open, ready-for-agent
90
91
  //
91
92
  // Row 4 outranks row 7, and row 7 every other row. A row-5 deferral is
92
93
  // held to row 1's reasons: one of ALLOWED_DEFER other than
93
- // false-rationale, `remedy-outside-diff` under the rule above. An open
94
- // home carries its row's triage label and not the other one; the closed
95
- // suggestion-band record is the closed issue titled `PR #<pr> review: the
96
- // suggestion band, checked`, labelled `wontfix`. `claimKind` is trusted:
97
- // the script never judges whether a claim is about shape. A survived
98
- // finding out of scope has no row, and its deferral's filing is not
99
- // judged.
94
+ // false-rationale, `remedy-outside-diff` under the rule above. A row-8
95
+ // deferral is held to no reason and escalates nothing, whatever its
96
+ // severity. An open home carries exactly one triage label, its row's or
97
+ // a stronger one: `ready-for-agent` answers a `needs-triage` row, and
98
+ // `needs-triage` never answers a `ready-for-agent` one. The closed
99
+ // suggestion-band record is the closed issue titled `PR #<pr> review:
100
+ // the suggestion band, checked`, labelled `wontfix`. `claimKind` is
101
+ // trusted: the script never judges whether a claim is about shape. A
102
+ // deferral no row holds — a reversed refutation whose claim is about
103
+ // behavior — is a mismatch naming no filing-table row.
100
104
  //
101
105
  // Unchecked: `gh` unreachable, or a deferral's issue it cannot read, leaves
102
106
  // that entry's filing unjudged. With no rule broken and nothing escalated the
@@ -131,7 +135,8 @@ import { join, dirname, isAbsolute, relative, posix, sep } from "node:path";
131
135
  import { fileURLToPath } from "node:url";
132
136
  import { makeDie, defineFlags } from "./arg.mjs";
133
137
  import { isCLI } from "./is-cli.mjs";
134
- import { gitEnv, workspaceDirFromGitCommonDir } from "./git-env.mjs";
138
+ import { gitEnv } from "./git-env.mjs";
139
+ import { fleetFile, FleetDirUnresolvable } from "./fleet-dir.mjs";
135
140
  import { parseMember, memberTokens } from "./ledger-grammar.mjs";
136
141
  import { dispositionsToken, rowNums, sameHead } from "./fleet-tick.mjs";
137
142
  import { VERDICT_SCHEMA } from "./review-core.mjs";
@@ -151,29 +156,47 @@ const BUCKETS = [...COVERED, "refuted"];
151
156
  const ENUMS = { scope: ["in", "out"], claimKind: ["behavior", "shape"], disposition: ["apply", "defer"] };
152
157
 
153
158
  // The filing table: a deferral's home by its finding's state. `record` is the
154
- // closed suggestion-band record; `open` the triage label an open home carries.
159
+ // closed suggestion-band record; `open` the weakest triage label an open home may carry.
155
160
  export const FILING_ROWS = Object.freeze({
156
- 1: { finding: "a survived finding deferred for an allowed reason other than false-rationale", open: "ready-for-agent" },
157
- 2: { finding: "a survived finding deferred false-rationale", record: true },
161
+ 1: { finding: "an in-scope survived finding deferred for an allowed reason other than false-rationale", open: "ready-for-agent" },
162
+ 2: { finding: "an in-scope survived finding deferred false-rationale", record: true },
158
163
  3: { finding: "an unverified finding whose refuters crashed", open: "needs-triage" },
159
164
  4: { finding: "an in-scope suggestion its refuter refuted", record: true },
160
165
  5: { finding: "an in-scope suggestion its refuter let survive", open: "ready-for-agent" },
161
166
  6: { finding: "an out-of-scope suggestion alleging wrong behavior", open: "needs-triage" },
162
167
  7: { finding: "a finding whose claim is about shape, below the claim bar", record: true },
168
+ 8: { finding: "an out-of-scope survived finding, whatever its reason", open: "ready-for-agent" },
163
169
  });
170
+ // Strongest first: an open home may carry a label above its row's, never below.
164
171
  const TRIAGE_LABELS = ["ready-for-agent", "needs-triage"];
165
172
  // Row 1's reasons, which a row-5 deferral is held to.
166
173
  const ROW_1_DEFER = ALLOWED_DEFER.filter((r) => r !== "false-rationale");
167
174
  export const recordTitle = (pr) => `PR #${pr} review: the suggestion band, checked`;
168
175
 
169
176
  function homeText(row, pr) {
170
- return row.record ? `the closed "${recordTitle(pr)}" issue, labelled wontfix` : `an open issue labelled ${row.open}`;
177
+ if (row.record) return `the closed "${recordTitle(pr)}" issue, labelled wontfix`;
178
+ return `an open issue labelled ${TRIAGE_LABELS.slice(0, TRIAGE_LABELS.indexOf(row.open) + 1).reverse().join(" or ")}`;
171
179
  }
172
180
 
173
181
  // Whether an issue `{state, title, labels}` is `row`'s home on PR `pr`.
174
182
  function homeHolds(row, { state, title, labels }, pr) {
175
183
  if (row.record) return state === "CLOSED" && title.trim() === recordTitle(pr) && labels.includes("wontfix");
176
- return state === "OPEN" && labels.includes(row.open) && !labels.includes(TRIAGE_LABELS.find((l) => l !== row.open));
184
+ const triage = labels.filter((l) => TRIAGE_LABELS.includes(l));
185
+ return state === "OPEN" && triage.length === 1 && TRIAGE_LABELS.indexOf(triage[0]) <= TRIAGE_LABELS.indexOf(row.open);
186
+ }
187
+
188
+ // The row a deferral's finding state puts it on, by precedence, or null when
189
+ // no row holds it: only a reversed refutation (the refuted bucket) whose claim
190
+ // is not about shape. `refuted` is an in-scope suggestion's refuter verdict,
191
+ // null for any other finding.
192
+ function filingRow({ bucket, inScope, crashed, refuted, shape, reason }) {
193
+ if (refuted === true) return 4;
194
+ if (shape) return 7;
195
+ if (bucket === "refuted") return null;
196
+ if (crashed) return 3;
197
+ if (!inScope) return bucket === "survived" ? 8 : 6;
198
+ if (bucket === "unverified") return 5;
199
+ return reason === "false-rationale" ? 2 : 1;
177
200
  }
178
201
 
179
202
  function describeIssue({ state, title, labels }) {
@@ -402,15 +425,14 @@ export function checkDispositions({ review, record, recordProblem = null, touche
402
425
  at(bucket, index, `malformed entry — ${errors.join("; ")}`);
403
426
  return;
404
427
  }
405
- if (bucket === "refuted") {
406
- if (!e.reason?.trim()) at(bucket, index, "a reversed refutation names its evidence in reason, and this one names none");
428
+ if (bucket === "refuted" && !e.reason?.trim()) {
429
+ at(bucket, index, "a reversed refutation names its evidence in reason, and this one names none");
407
430
  return;
408
431
  }
409
- if (bucket === "survived" && e.disposition !== "defer") return;
432
+ if (bucket !== "unverified" && e.disposition !== "defer") return;
410
433
  const finding = review[bucket][index];
411
434
  const presumed = presumedInScope(finding, touched, roots);
412
435
  const inScope = presumed !== null || e.scope === "in";
413
- if (bucket === "survived" && !inScope) return;
414
436
  const why = presumed === null ? "its entry declares scope in" : `${presumed}, so it is in scope whatever its entry declares`;
415
437
  const crashed = bucket === "unverified" && finding.refutersDispatched > 0;
416
438
  // An in-scope suggestion's refuter verdict is the evidence a refuter ran.
@@ -435,8 +457,9 @@ export function checkDispositions({ review, record, recordProblem = null, touche
435
457
  const shape = e.claimKind === "shape";
436
458
  // A finding that stands defers only for a reason: an in-scope survivor
437
459
  // for one of ALLOWED_DEFER, a suggestion its refuter let through for one
438
- // of row 1's — unless row 7 takes it.
439
- if (bucket === "survived" || (refuted === false && !shape)) {
460
+ // of row 1's — unless row 7 takes it. An out-of-scope survivor defers for
461
+ // any reason, and escalates nothing.
462
+ if ((bucket === "survived" && inScope) || (refuted === false && !shape)) {
440
463
  const allowed = bucket === "survived" ? ALLOWED_DEFER : ROW_1_DEFER;
441
464
  if (!allowed.includes(e.reason)) {
442
465
  const reason = e.reason === undefined || e.reason === "" ? "no reason" : `reason ${JSON.stringify(e.reason)}`;
@@ -460,9 +483,11 @@ export function checkDispositions({ review, record, recordProblem = null, touche
460
483
  }
461
484
  }
462
485
  // Where the deferral must be filed. `claimKind` is trusted, never judged.
463
- const rowNo = refuted === true ? 4 : shape ? 7
464
- : bucket === "survived" ? (e.reason === "false-rationale" ? 2 : 1)
465
- : crashed ? 3 : inScope ? 5 : 6;
486
+ const rowNo = filingRow({ bucket, inScope, crashed, refuted, shape, reason: e.reason });
487
+ if (rowNo === null) {
488
+ at(bucket, index, `no filing-table row holds a deferred ${bucket} finding, scope ${inScope ? "in" : "out"}, claimKind ${e.claimKind} — the table names no home for it`);
489
+ return;
490
+ }
466
491
  const row = FILING_ROWS[rowNo];
467
492
  const { pr, issue: readIssue } = filingOf();
468
493
  if (e.issue === undefined) {
@@ -626,21 +651,26 @@ function verdictReader(scratch, pr) {
626
651
  }
627
652
 
628
653
  // The ledger file this run writes its verdict to, or null when there is none:
629
- // `--ledger`, else the run's `.fleet/ledger.md` under the git common dir of
630
- // `repo` — the workspace every worktree of one repository shares, which is
631
- // where `ledger.mjs dispatch` wrote the member's row. The path is handed to
632
- // `ledger.mjs` as `--file`, so the existence probe and the calls that follow
633
- // answer for one file. Only ENOENT means "there is none": any other failure
634
- // to look the path up is a fault, not a standalone run. An absent path named
635
- // by `--ledger` is announced on stderr; an absent default path is not.
654
+ // `--ledger`, else the run's `.fleet/ledger.md` resolved from `repo` by
655
+ // fleet-dir.mjs's fleetFile() — the workspace every worktree of one
656
+ // repository shares, which is where `ledger.mjs dispatch` wrote the member's
657
+ // row. The path is handed to `ledger.mjs` as `--file`, so the existence probe
658
+ // and the calls that follow answer for one file. Only ENOENT means "there is
659
+ // none": any other failure to look the path up is a fault, not a standalone
660
+ // run. An absent path named by `--ledger` is announced on stderr; an absent
661
+ // default path is not.
636
662
  // `lstat`, not `stat`, so a dangling symlink is a ledger that cannot be read
637
663
  // rather than an absent one.
638
664
  function ledgerInUse(explicit, repo) {
639
- const file = explicit ?? join(
640
- workspaceDirFromGitCommonDir(git(repo, ["rev-parse", "--git-common-dir"], "find the git common dir"), repo)
641
- ?? die("could not find the git common dir: git printed none"),
642
- ".fleet", "ledger.md",
643
- );
665
+ let file = explicit;
666
+ if (file == null) {
667
+ try {
668
+ file = fleetFile("ledger.md", { cwd: repo });
669
+ } catch (e) {
670
+ if (!(e instanceof FleetDirUnresolvable)) throw e;
671
+ die(e.message);
672
+ }
673
+ }
644
674
  try {
645
675
  lstatSync(file);
646
676
  return file;
@@ -0,0 +1,95 @@
1
+ // Where a run's `.fleet/` directory lives, answered once for every script
2
+ // that keeps a file in it. The ledger, the heartbeat's state, the shortlist,
3
+ // the cost guard and the cockpit's state directory are each ONE file per run,
4
+ // and they live in the main checkout: a member running from
5
+ // `.worktrees/<n>-slug` and the controller running from the checkout root
6
+ // have to name the same file, or each worktree quietly reads and writes a
7
+ // private copy of it.
8
+ //
9
+ // The answer is git's: `rev-parse --git-common-dir` names the common git dir
10
+ // every worktree of one repository shares, and git-env.mjs's
11
+ // workspaceDirFromGitCommonDir() turns that answer into the workspace
12
+ // holding it. This module is the spawn around that function — the scrubbed
13
+ // env, the bound, the join onto `.fleet/` — so a new `.fleet/`-rooted file is
14
+ // one `fleetFile("name")` call rather than another hand-spelled probe.
15
+ //
16
+ // One error policy: anything that leaves no workspace THROWS
17
+ // FleetDirUnresolvable, never a null or an empty path. What a caller does
18
+ // about it is the caller's own — the ledger and the heartbeat warn and fall
19
+ // back to a cwd-relative `.fleet/`, the shortlist refuses, the cockpit serves
20
+ // on its base port — and each says so in its own words around this error's
21
+ // message, which names what failed.
22
+ //
23
+ // Zero deps: node builtins and sibling scripts only.
24
+
25
+ import { spawnSync } from "node:child_process";
26
+ import { join } from "node:path";
27
+ import { gitEnv, workspaceDirFromGitCommonDir } from "./git-env.mjs";
28
+
29
+ // A `rev-parse` answers in milliseconds; this bound exists so a git that
30
+ // never answers cannot hang its caller, not to time a healthy one. A caller
31
+ // with an override of its own (ledger.mjs's LEDGER_GIT_TIMEOUT) passes the
32
+ // value it settled on as `timeoutMs`.
33
+ const DEFAULT_GIT_TIMEOUT_MS = 10_000;
34
+
35
+ // The cause reaches stderr inside a single warning line, so it is capped,
36
+ // keeping the END — the part of a child's stderr that says why it stopped.
37
+ const CAUSE_MAX = 500;
38
+
39
+ export class FleetDirUnresolvable extends Error {
40
+ constructor(message) {
41
+ super(message);
42
+ this.name = "FleetDirUnresolvable";
43
+ }
44
+ }
45
+
46
+ // The first non-empty of the fields a failed git can put its reason in:
47
+ // `error.message` for a git that never ran or was killed (`spawnSync git
48
+ // ENOENT`, `spawnSync git ETIMEDOUT`), its stderr for one that ran and
49
+ // refused (`fatal: not a git repository …`).
50
+ function cause(...candidates) {
51
+ const raw = candidates.map((c) => String(c ?? "").trim()).find(Boolean);
52
+ if (!raw) return "";
53
+ return raw.length > CAUSE_MAX ? `…${raw.slice(-(CAUSE_MAX - 1))}` : raw;
54
+ }
55
+
56
+ // A git that fails with nothing on stderr and no spawn error — a silent
57
+ // non-zero exit, a kill by a signal other than the bound's own — would
58
+ // otherwise leave the message naming no cause at all.
59
+ function ended(r) {
60
+ if (r.signal) return `killed by ${r.signal}`;
61
+ return r.status === null ? "" : `exit ${r.status}`;
62
+ }
63
+
64
+ /**
65
+ * The absolute path of `name` under the run's `.fleet/` directory, resolved
66
+ * from `cwd` — or the `.fleet/` directory itself when `name` is null.
67
+ *
68
+ * GIT_DIR/GIT_WORK_TREE are scrubbed from the probe (gitEnv()): either one
69
+ * makes `--git-common-dir` answer for a DIFFERENT repository, which would put
70
+ * the run's file in someone else's workspace, silently, at exit 0.
71
+ *
72
+ * `canonicalise` is workspaceDirFromGitCommonDir()'s opt-in, passed through:
73
+ * only a caller that keys something on the path (the cockpit's port) takes
74
+ * it. Everyone else prints the path it resolves, and realpath would change
75
+ * that spelling without changing which file it names.
76
+ *
77
+ * Throws FleetDirUnresolvable for every probe that leaves no workspace — no
78
+ * repository, an unreadable `.git`, git missing, a probe killed at
79
+ * `timeoutMs` — with git's own reason in the message.
80
+ */
81
+ export function fleetFile(name, { cwd = process.cwd(), timeoutMs, canonicalise = false } = {}) {
82
+ const r = spawnSync("git", ["rev-parse", "--git-common-dir"], {
83
+ cwd, encoding: "utf8", timeout: timeoutMs ?? DEFAULT_GIT_TIMEOUT_MS, env: gitEnv(),
84
+ });
85
+ // No separate `r.status === 0` gate: every failure mode (no repository, an
86
+ // unresolvable GIT_DIR, a permission-denied `.git`, a corrupt worktree
87
+ // pointer, a missing `git` binary, a timed-out probe) leaves `r.stdout`
88
+ // empty, which workspaceDirFromGitCommonDir() reads as `null` on its own.
89
+ const workspace = workspaceDirFromGitCommonDir(r.stdout, cwd, { canonicalise });
90
+ if (workspace === null) {
91
+ const why = cause(r.error && r.error.message, r.stderr) || ended(r);
92
+ throw new FleetDirUnresolvable(`could not resolve --git-common-dir${why ? `: ${why}` : ""}`);
93
+ }
94
+ return name === null ? join(workspace, ".fleet") : join(workspace, ".fleet", name);
95
+ }
@@ -33,15 +33,14 @@
33
33
  // correct, and neither script is in a position to hold one.
34
34
 
35
35
  import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
36
- import { spawnSync } from "node:child_process";
37
36
  import { dirname, join } from "node:path";
38
- import { workspaceDirFromGitCommonDir } from "./git-env.mjs";
37
+ import { fleetFile, FleetDirUnresolvable } from "./fleet-dir.mjs";
39
38
 
40
39
  // The filename, in one place, because the liveness mark gave this file a SECOND resolver.
41
40
  // board.mjs already resolves the run's workspace for itself — it has to, since
42
41
  // its own `canonicalise` opt-in is what keeps a symlinked route from deriving
43
42
  // a second port — so it reaches the state file by joining onto the
44
- // `.fleet` directory it already holds rather than re-running the probe below.
43
+ // `.fleet` directory it already holds rather than resolving it again.
45
44
  // What it must NOT do is spell `heartbeat.json` a second time: a filename in
46
45
  // two places is the drift this module's header exists to prevent, and a
47
46
  // cockpit reading a file the heartbeat does not write is a liveness panel
@@ -54,48 +53,20 @@ export function stateFileIn(fleetDir) {
54
53
  // Members run from their own worktrees, where a cwd-relative `.fleet/` does not
55
54
  // exist, so a cwd-relative path would give every worktree a private back-off
56
55
  // streak and a private elapsed total — the run's beat would be whichever
57
- // worktree happened to call last.
58
- //
59
- // This is ledger.mjs's defaultLedgerPath() resolution applied to a second file
60
- // for the same reason (there, a cwd-local ledger silently degraded the
61
- // duplicate-filing guard). The third file this comment used to predict arrived
62
- // as board.mjs's resolveCockpitInstance(), so the resolution itself
63
- // moved, as promised, though into git-env.mjs beside gitEnv() rather than into
64
- // this module: board.mjs and ledger.mjs both already import that one, and a
65
- // cockpit reaching into the heartbeat's state module for a path rule would be
66
- // a stranger dependency than either has now. Only the filename and the
67
- // warning below are this caller's own.
56
+ // worktree happened to call last. fleet-dir.mjs's fleetFile() resolves it the
57
+ // way it resolves the ledger, scrubbed and bounded: a `git` that never answers
58
+ // is killed rather than holding the beat. Only the warning and the fallback
59
+ // below are this caller's own.
68
60
  export function statePath(name) {
69
- // GIT_DIR and GIT_WORK_TREE scrubbed, never inherited: an ambient GIT_DIR
70
- // answers `--git-common-dir` for a DIFFERENT repository, which relocates the
71
- // ONE file this whole design rests on. It fails in exactly the direction the
72
- // common-dir resolution exists to close — a private streak and a private
73
- // elapsed total per environment — and it fails SILENTLY, because a resolved
74
- // path inside another repo looks like any other resolved path. Same scrub
75
- // run-merge-bot.md performs on the identical command in shell (`env -u
76
- // GIT_DIR -u GIT_WORK_TREE git rev-parse --git-common-dir`); spelled as an
77
- // env object here because there is no shell to spell it in.
78
- // Migrating this inline scrub to gitEnv() — imported in this file
79
- // for the path rule above, not for the env — stays out of scope: it is
80
- // recorded with its own measurement and its own behavioural fixture in
81
- // the test suite's MJS_LEGACY_INLINE list.
82
- const env = { ...process.env };
83
- delete env.GIT_DIR;
84
- delete env.GIT_WORK_TREE;
85
- const r = spawnSync("git", ["rev-parse", "--git-common-dir"], { encoding: "utf8", env });
86
- // No separate `r.status === 0` gate: every failure mode reproducible here
87
- // (no repository, an unresolvable GIT_DIR, a permission-denied `.git`, a
88
- // corrupt worktree pointer, a missing `git` binary) leaves `r.stdout`
89
- // empty, which workspaceDirFromGitCommonDir() already reads as `null` on
90
- // its own — see its own docstring for that contract.
91
- const workspace = workspaceDirFromGitCommonDir(r.stdout);
92
- if (workspace === null) {
61
+ try {
62
+ return stateFileIn(fleetFile(null));
63
+ } catch (e) {
64
+ if (!(e instanceof FleetDirUnresolvable)) throw e;
93
65
  // Announced, never silent: a cwd-relative fallback re-opens exactly the
94
66
  // per-worktree split this resolution exists to close.
95
- console.error(`${name}: WARNING could not resolve --git-common-dir; using cwd-relative .fleet/heartbeat.json`);
67
+ console.error(`${name}: WARNING ${e.message}; using cwd-relative .fleet/heartbeat.json`);
96
68
  return stateFileIn(".fleet");
97
69
  }
98
- return stateFileIn(join(workspace, ".fleet"));
99
70
  }
100
71
 
101
72
  // An unreadable or corrupt state file is NOT fatal, and the direction of the
@@ -899,7 +899,8 @@ import { fileURLToPath } from "node:url";
899
899
  import { isCLI } from "./is-cli.mjs";
900
900
  import { parseArgs } from "node:util";
901
901
  import { makeDie, isDigits } from "./arg.mjs";
902
- import { gitEnv, workspaceDirFromGitCommonDir } from "./git-env.mjs";
902
+ import { gitEnv } from "./git-env.mjs";
903
+ import { fleetFile, FleetDirUnresolvable } from "./fleet-dir.mjs";
903
904
  import { statePath, readState, writeState, assessBeat, isStalled, stallReport } from "./fleet-state.mjs";
904
905
  import { checkMainCheckout, describe } from "./main-checkout.mjs";
905
906
 
@@ -915,7 +916,6 @@ const PR_LIMIT = 200;
915
916
  // behind. So it discloses instead — the line says the count is a floor.
916
917
  const CLAIMED_LIMIT = 200;
917
918
  const MAX_BUFFER = 64 * 1024 * 1024;
918
- const GIT_TIMEOUT_MS = 10_000;
919
919
  // Every gh spawn below is killed at this bound, so a gh that never answers is
920
920
  // a failed read on that call's own failure path — the open-PR read refuses the
921
921
  // tick, a probe leaves standing what it could not confirm, the claimed count
@@ -1057,14 +1057,20 @@ function readLedger() {
1057
1057
  return d;
1058
1058
  }
1059
1059
 
1060
- // `.fleet/shortlist.json` beside the run's ledger: the workspace from `git
1061
- // rev-parse --git-common-dir`, GIT_DIR/GIT_WORK_TREE scrubbed so an
1062
- // ambient one cannot answer for another repository. null when unresolvable —
1063
- // read as a missing shortlist, and the refresh then says why it could not run.
1060
+ // `.fleet/shortlist.json` beside the run's ledger, through fleet-dir.mjs's
1061
+ // fleetFile(). null when unresolvable — read as a missing shortlist, and the
1062
+ // refresh then says why it could not run. Announced here first: a missing
1063
+ // shortlist is also what an empty queue looks like, and "outside a
1064
+ // repository" is not "no candidates yet". main() calls this once per tick,
1065
+ // so a workspace that stays unresolvable warns once per tick.
1064
1066
  function shortlistPath() {
1065
- const r = spawnSync("git", ["rev-parse", "--git-common-dir"], { encoding: "utf8", timeout: GIT_TIMEOUT_MS, env: gitEnv() });
1066
- const workspace = workspaceDirFromGitCommonDir(r.stdout);
1067
- return workspace === null ? null : join(workspace, ".fleet", "shortlist.json");
1067
+ try {
1068
+ return fleetFile("shortlist.json");
1069
+ } catch (e) {
1070
+ if (!(e instanceof FleetDirUnresolvable)) throw e;
1071
+ console.error(`${NAME}: WARNING ${e.message}; reading the shortlist as missing`);
1072
+ return null;
1073
+ }
1068
1074
  }
1069
1075
 
1070
1076
  function readShortlist(path) {
@@ -16,22 +16,18 @@
16
16
  // reach back into the caller's environment") do not transfer: a spawned
17
17
  // child's env object is already private to it, never the calling process's.
18
18
  //
19
- // `fleet-state.mjs`'s `statePath()` and `ledger.mjs`'s tracker-query probe
20
- // each spell the same three lines inline — `{ ...process.env }` then two
21
- // `delete`s — predating this module, and that duplication is exactly the
22
- // reason a THIRD hand-spelled copy (the hazard measured here, `ledger.mjs`'s
23
- // `defaultLedgerPath()`) should not become a fourth.
24
- // A shared helper also turns "does this call scrub the ambient vars" back
25
- // into a one-name grep, `gitEnv(`, the way `unset GIT_DIR GIT_WORK_TREE` is
26
- // one for shell.
19
+ // `ledger.mjs`'s tracker-query probe spells the same three lines inline —
20
+ // `{ ...process.env }` then two `delete`s — predating this module, and a
21
+ // hand-spelled copy per call site is exactly the duplication this module
22
+ // replaces. A shared helper also turns "does this call scrub the ambient
23
+ // vars" back into a one-name grep, `gitEnv(`, the way `unset GIT_DIR
24
+ // GIT_WORK_TREE` is one for shell.
27
25
  //
28
- // The two pre-existing inline sites are deliberately NOT migrated to call
29
- // this. Both are already fixed and covered by tests of their own —
30
- // `fleet-state.mjs`'s `statePath()`, and `ledger.mjs`'s tracker-query scrub
31
- // ("an inherited GIT_DIR or GH_REPO cannot retarget the query…") — and
32
- // touching either to satisfy a detector would be churn with no behavioural
33
- // change. The suite's census of ambient-var scrubs carries both of them by
34
- // name instead of by import.
26
+ // That pre-existing inline site is deliberately NOT migrated to call this. It
27
+ // is already fixed and covered by a test of its own ("an inherited GIT_DIR or
28
+ // GH_REPO cannot retarget the query…"), and touching it to satisfy a detector
29
+ // would be churn with no behavioural change. The suite's census of
30
+ // ambient-var scrubs carries it by name instead of by import.
35
31
 
36
32
  import { realpathSync } from "node:fs";
37
33
  import { dirname, resolve } from "node:path";
@@ -56,24 +52,20 @@ export function gitEnv(overrides = {}, base = process.env) {
56
52
 
57
53
  // Every fleet script that needs to know WHERE the run's files live asks git
58
54
  // the same question — `rev-parse --git-common-dir` — and then resolves the
59
- // answer the same way, because the answer is the same shape in all three:
60
- // the common dir is shared by every worktree of one repository (git answers
61
- // with the MAIN checkout's git dir from inside a linked worktree), so its
62
- // PARENT is the one workspace a run has, whichever worktree asked. That is
63
- // why a member running from `.worktrees/<n>-slug` and the controller running
64
- // from the checkout root agree about the run's single ledger, its single
65
- // heartbeat and its single board.
55
+ // answer the same way, because the answer is the same shape wherever it is
56
+ // asked: the common dir is shared by every worktree of one repository (git
57
+ // answers with the MAIN checkout's git dir from inside a linked worktree), so
58
+ // its PARENT is the one workspace a run has, whichever worktree asked. That
59
+ // is why a member running from `.worktrees/<n>-slug` and the controller
60
+ // running from the checkout root agree about the run's single ledger, its
61
+ // single heartbeat and its single board.
66
62
  //
67
- // Three callers hand-spelled that resolution, one apiece, before this function:
68
- // `ledger.mjs`'s `defaultLedgerPath()`, `fleet-state.mjs`'s `statePath()` and
69
- // `board.mjs`'s `resolveCockpitInstance()` — and `fleet-state.mjs`'s own
70
- // comment had already written down the trigger ("if a third file ever needs
71
- // this, the resolution itself should move"), which the third caller's arrival tripped.
72
- // What is NOT shared is the part each caller owns: the filename it joins on
73
- // (`ledger.md`, `heartbeat.json`, `.fleet`), the wording of the warning it
74
- // degrades with, and what its own degraded answer is. Hence the seam: this
75
- // function answers the directory or `null`, and every caller composes the
76
- // rest around it.
63
+ // For a run's `.fleet/` files the question is asked in one place,
64
+ // fleet-dir.mjs's fleetFile(), which spawns the probe and hands its answer to
65
+ // this function. What is NOT shared is the part each caller owns: the
66
+ // filename it joins on, the wording of the warning it degrades with, and what
67
+ // its own degraded answer is. Hence the seam: this function answers the
68
+ // directory or `null`, and every caller composes the rest around it.
77
69
 
78
70
  /**
79
71
  * The workspace directory a `git rev-parse --git-common-dir` answer names —
@@ -82,28 +74,28 @@ export function gitEnv(overrides = {}, base = process.env) {
82
74
  *
83
75
  * `null` is the signal every caller's degrade arm branches on, and the reason
84
76
  * this returns it rather than a cwd-relative fallback of its own: what a
85
- * degraded answer should be is the caller's to say (a cwd-relative filename
86
- * for the ledger, an absolute cwd-anchored `.fleet` for the board), and so is
87
- * the warning that must accompany it — a degrade nobody announces is the
88
- * failure class all three of those warnings exist to close.
77
+ * degraded answer should be is the caller's to say (fleet-dir.mjs turns it
78
+ * into a thrown error its own callers each degrade from in their own way),
79
+ * and so is the warning that must accompany it — a degrade nobody announces
80
+ * is the failure class those warnings exist to close.
89
81
  *
90
82
  * `resolve(cwd, …)` rather than resolve()'s implicit `process.cwd()`: git
91
83
  * answers this RELATIVE — a bare `.git` — when it runs from a checkout's top
92
84
  * level, and the cwd that was relative to is an argument here, not ambient,
93
- * so a caller that injects the answer (board.mjs, which takes it as a
94
- * parameter so its worktree and resolution-failed cases stay plain test rows)
95
- * can inject the cwd too. `cwd` defaults to `process.cwd()`, which is what
96
- * the callers that spawn git themselves already resolved against.
85
+ * so a caller that spawned git in a cwd of its choosing (fleet-dir.mjs's
86
+ * `cwd` option) resolves the answer against that same cwd. `cwd` defaults to
87
+ * `process.cwd()`, which is what a caller that spawns git without one
88
+ * resolved against.
97
89
  *
98
90
  * The `trim()` is what makes a newline-only answer the `null` case rather
99
91
  * than a path; a trailing newline riding on a real answer would be discarded
100
92
  * by `dirname()` anyway, together with the rest of the final segment.
101
93
  *
102
- * `canonicalise` is OPT-IN, and deliberately so. Only `board.mjs`
103
- * takes it: a symlinked route to one workspace derives a SECOND port and a
104
- * second state directory for a cockpit already being served, so the
105
- * cockpit's key has to be the canonical form. `ledger.mjs` and
106
- * `fleet-state.mjs` do not — both PRINT the path they resolve (the ledger in
94
+ * `canonicalise` is OPT-IN, and deliberately so. The cockpit takes it,
95
+ * through fleet-dir.mjs: a symlinked route to one workspace derives a SECOND
96
+ * port and a second state directory for a cockpit already being served, so
97
+ * the cockpit's key has to be the canonical form. The ledger and the
98
+ * heartbeat do not — both PRINT the path they resolve (the ledger in
107
99
  * `check`'s JSON, both in their degrade warnings), and realpath would change
108
100
  * that output without changing which file they reach, since the canonical and
109
101
  * symlinked spellings of one path are one file. Left off, this function reads
@@ -34,7 +34,7 @@ import { dirname, resolve, join, basename } from "node:path";
34
34
  import { fileURLToPath } from "node:url";
35
35
  import { spawnSync, execFileSync } from "node:child_process";
36
36
  import { makeDie, isFlagLike, hasEqualsForm, isDigits } from "./arg.mjs";
37
- import { gitEnv, workspaceDirFromGitCommonDir } from "./git-env.mjs";
37
+ import { fleetFile, FleetDirUnresolvable } from "./fleet-dir.mjs";
38
38
  import { parseMember, parseToken, memberTokens, nextMergeBot, agentDefinition, CELL, tierValues } from "./ledger-grammar.mjs";
39
39
  import { deriveRun, LedgerError, labelOffMember } from "./fleet-tick.mjs";
40
40
  import { stateFileIn, readState, assessBeat, stallsAt } from "./fleet-state.mjs";
@@ -132,45 +132,27 @@ const GIT_TIMEOUT_MS = gitBudget(10, process.env.LEDGER_GIT_TIMEOUT);
132
132
  // There is ONE ledger per run, and it lives in the main checkout. Members run
133
133
  // from their own worktrees, where a cwd-relative `.fleet/ledger.md` does not
134
134
  // exist — `check` then warns and reports every subject as safe to file, which
135
- // is precisely the duplicate-filing guard failing open. Resolve against the
136
- // git COMMON dir (shared by every worktree) rather than the cwd, via
137
- // git-env.mjs's workspaceDirFromGitCommonDir() — the resolution itself is
138
- // shared with fleet-state.mjs and board.mjs, and only the
139
- // filename and the warning below are this caller's own. No canonicalisation
135
+ // is precisely the duplicate-filing guard failing open. fleet-dir.mjs's
136
+ // fleetFile() resolves it against the git COMMON dir (shared by every
137
+ // worktree) instead, with GIT_DIR/GIT_WORK_TREE scrubbed so an ambient one
138
+ // cannot put the run's ledger under another repository; only the bound, the
139
+ // warning and the fallback below are this caller's own. No canonicalisation
140
140
  // is asked for: that is board.mjs's opt-in, and taking it here would change
141
- // the path this function RETURNS (and `check` prints) without changing which
142
- // file it names.
141
+ // the path `check` prints without changing which file it names.
143
142
  function defaultLedgerPath() {
144
- // GIT_DIR/GIT_WORK_TREE scrubbed (gitEnv()): unlike the tracker-query
145
- // probe below in this same file, this call used to pass no env at all.
146
- // An ambient GIT_DIR answers `--git-common-dir` for a DIFFERENT repository,
147
- // so the ONE ledger every run's duplicate-filing guard reads gets resolved
148
- // underneath THAT repository instead of the caller's own — measured
149
- // directly against a checkout of this repo: `GIT_DIR=/tmp/other/.git node
150
- // ledger.mjs row 357 "…"` wrote `/tmp/other/.fleet/ledger.md`, silently, at
151
- // exit 0, and `check` then reads whatever ledger (or absence of one) lives
152
- // there and reports every subject safe to file.
153
- const r = spawnSync("git", ["rev-parse", "--git-common-dir"], { encoding: "utf8", timeout: GIT_TIMEOUT_MS, env: gitEnv() });
154
- // No separate `r.status === 0` gate: every failure mode reproducible here
155
- // (no repository, an unresolvable GIT_DIR, a permission-denied `.git`, a
156
- // corrupt worktree pointer, a missing `git` binary, a timed-out probe)
157
- // leaves `r.stdout` empty, which workspaceDirFromGitCommonDir() already
158
- // reads as `null` on its own — see its own docstring for that contract.
159
- const workspace = workspaceDirFromGitCommonDir(r.stdout);
160
- if (workspace === null) {
143
+ try {
144
+ return fleetFile("ledger.md", { timeoutMs: GIT_TIMEOUT_MS });
145
+ } catch (e) {
146
+ if (!(e instanceof FleetDirUnresolvable)) throw e;
161
147
  // Could not resolve the shared git dir → fall back to a cwd-relative path.
162
148
  // That re-opens the worktree fail-open this resolution exists to close (a
163
149
  // member reads a cwd-local ledger, not the run's), so say so rather than
164
- // degrading the duplicate-filing guard in silence. This probe
165
- // is bounded too, and an ETIMEDOUT stall prints byte-identical stderr to
166
- // an instant "not a repository" failure without naming which — the
167
- // sibling probe in runCheck() already names it via cause(); match that
168
- // shape here rather than leaving this one generic.
169
- const why = cause(r.error && r.error.message, r.stderr);
170
- console.error(`${NAME}: WARNING could not resolve --git-common-dir${why ? `: ${why}` : ""}; using cwd-relative .fleet/ledger.md (duplicate-filing guard may be degraded)`);
150
+ // degrading the duplicate-filing guard in silence. The message names the
151
+ // cause, so an ETIMEDOUT stall does not read like an instant "not a
152
+ // repository" failure.
153
+ console.error(`${NAME}: WARNING ${e.message}; using cwd-relative .fleet/ledger.md (duplicate-filing guard may be degraded)`);
171
154
  return ".fleet/ledger.md";
172
155
  }
173
- return join(workspace, ".fleet", "ledger.md");
174
156
  }
175
157
 
176
158
  const argv = process.argv.slice(2);
@@ -62,12 +62,13 @@
62
62
  // bootstrap 95% interval on `mean_usd` minus the baseline's — printed to be
63
63
  // read, never judged on.
64
64
 
65
- import { execFileSync, spawnSync } from "node:child_process";
65
+ import { execFileSync } from "node:child_process";
66
66
  import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
67
67
  import { dirname, join } from "node:path";
68
68
  import { fileURLToPath } from "node:url";
69
69
  import { makeDie, defineFlags, isDigits } from "./arg.mjs";
70
- import { gitEnv, workspaceDirFromGitCommonDir } from "./git-env.mjs";
70
+ import { gitEnv } from "./git-env.mjs";
71
+ import { fleetFile, FleetDirUnresolvable } from "./fleet-dir.mjs";
71
72
  import { isCLI } from "./is-cli.mjs";
72
73
  import { CELL } from "./ledger-grammar.mjs";
73
74
  import { parseMemberName } from "./member-record.mjs";
@@ -428,12 +429,18 @@ export function guardFile(report, computedAt) {
428
429
  // CLI
429
430
  // ---------------------------------------------------------------------------
430
431
 
431
- // `.fleet/cost-guard.json` in the main workspace — the git common dir's parent,
432
+ // `.fleet/cost-guard.json` in the main workspace — fleet-dir.mjs's fleetFile(),
432
433
  // where fleet-tick reads it — not in the cwd, which from a linked worktree is a
433
- // different directory the tick never looks in. The cwd when git cannot answer.
434
+ // different directory the tick never looks in. The cwd when git cannot answer,
435
+ // announced on stderr rather than degraded to in silence, with git's reason.
434
436
  function defaultGuardPath() {
435
- const r = spawnSync("git", ["rev-parse", "--git-common-dir"], { encoding: "utf8", env: gitEnv() });
436
- return join(workspaceDirFromGitCommonDir(r.stdout) ?? ".", ".fleet", "cost-guard.json");
437
+ try {
438
+ return fleetFile("cost-guard.json");
439
+ } catch (e) {
440
+ if (!(e instanceof FleetDirUnresolvable)) throw e;
441
+ console.error(`${NAME}: WARNING ${e.message}; writing the guard to cwd-relative .fleet/cost-guard.json`);
442
+ return join(".", ".fleet", "cost-guard.json");
443
+ }
437
444
  }
438
445
 
439
446
  function main() {
@@ -44,10 +44,10 @@
44
44
  // written, an empty shortlist included — the empty queue is an answer. Never
45
45
  // exit 1: this script has no verdict to report, and 1 is also Node's own code for a crash.
46
46
  //
47
- // The file is `<workspace>/.fleet/shortlist.json`, the workspace resolved from
48
- // `git rev-parse --git-common-dir` through git-env.mjs, exactly as ledger.mjs's
49
- // defaultLedgerPath() resolves `.fleet/ledger.md` — so the controller, the tick
50
- // and a member in its own worktree all name one file. Unlike the ledger there
47
+ // The file is `<workspace>/.fleet/shortlist.json`, resolved by fleet-dir.mjs's
48
+ // fleetFile() exactly as ledger.mjs resolves `.fleet/ledger.md` — so the
49
+ // controller, the tick and a member in its own worktree all name one file.
50
+ // Unlike the ledger there
51
51
  // is no cwd-relative degrade: outside a repository inflight.sh cannot answer
52
52
  // for a single ticket either, so there is nothing honest to write. The payload
53
53
  // is `{scanned, shortlist: [{n, t}]}`, written to a sibling temp file and
@@ -65,7 +65,8 @@ import { mkdirSync, writeFileSync, renameSync, rmSync } from "node:fs";
65
65
  import { dirname, join } from "node:path";
66
66
  import { fileURLToPath } from "node:url";
67
67
  import { makeDie, writeAll, isDigits } from "./arg.mjs";
68
- import { gitEnv, workspaceDirFromGitCommonDir } from "./git-env.mjs";
68
+ import { gitEnv } from "./git-env.mjs";
69
+ import { fleetFile, FleetDirUnresolvable } from "./fleet-dir.mjs";
69
70
 
70
71
  const NAME = "shortlist";
71
72
  const die = makeDie(NAME);
@@ -81,10 +82,9 @@ const CLOSED = new Set(["MERGED", "CLOSED"]);
81
82
  // whatever order the probes finish in.
82
83
  const IN_FLIGHT = 4;
83
84
  // Bounds on children that could otherwise never return. None is a stopwatch:
84
- // each is far past the healthy case (a `rev-parse` answers in milliseconds, a
85
- // `gh … view` in under a second, inflight.sh in ~2.6 s), and each timeout
86
- // lands on the same fail-closed path as any other failed probe.
87
- const GIT_TIMEOUT_MS = 10_000;
85
+ // each is far past the healthy case (a `gh … view` in under a second,
86
+ // inflight.sh in ~2.6 s), and each timeout lands on the same fail-closed path
87
+ // as any other failed probe.
88
88
  const GH_TIMEOUT_MS = 20_000;
89
89
  const INFLIGHT_TIMEOUT_MS = 120_000;
90
90
  const MAX_BUFFER = 64 * 1024 * 1024;
@@ -140,14 +140,12 @@ async function eachLimited(items, fn) {
140
140
  }
141
141
 
142
142
  function shortlistPath() {
143
- const r = spawnSync("git", ["rev-parse", "--git-common-dir"], {
144
- encoding: "utf8", timeout: GIT_TIMEOUT_MS, env: gitEnv(),
145
- });
146
- const workspace = workspaceDirFromGitCommonDir(r.stdout);
147
- if (workspace === null) {
148
- die(`could not resolve the workspace — git rev-parse --git-common-dir: ${describe(r)}`);
143
+ try {
144
+ return fleetFile("shortlist.json");
145
+ } catch (e) {
146
+ if (!(e instanceof FleetDirUnresolvable)) throw e;
147
+ die(e.message);
149
148
  }
150
- return join(workspace, ".fleet", "shortlist.json");
151
149
  }
152
150
 
153
151
  function scan() {
@@ -217,7 +215,7 @@ const premiseLabel = ({ kind, target }) => `behind-${kind}:#${target}`;
217
215
  async function probeState(kind, target) {
218
216
  // gh's own remote resolution follows GIT_DIR/GIT_WORK_TREE exactly as git's
219
217
  // does, and GH_REPO outranks even that (ledger.mjs's tracker-query probe,
220
- // measured) — so this call needs the same scrub shortlistPath()'s git call
218
+ // measured) — so this call needs the same scrub fleetFile()'s git call
221
219
  // gets, or an ambient one of the three silently answers for a different
222
220
  // repository while `.fleet/shortlist.json` still lands in the right one.
223
221
  const r = await run("gh", [kind, "view", target, "--json", "state"], {
@@ -440,9 +440,10 @@ phase, or in any later one, asks the maintainer which tickets to take.
440
440
  free. Both drop the ticket, logged by number.
441
441
 
442
442
  It writes the survivors, in order, to `.fleet/shortlist.json` —
443
- `{scanned, shortlist: [{n, t}]}` — resolved against the git common dir
444
- exactly as `ledger.mjs` resolves `.fleet/ledger.md`, so you, the tick and a
445
- member in its own worktree all name one file. **Exit 0 is the file written,
443
+ `{scanned, shortlist: [{n, t}]}` — resolved against the git common dir by
444
+ `fleet-dir.mjs`, the one locator `ledger.mjs` resolves `.fleet/ledger.md`
445
+ with too, so you, the tick and a member in its own worktree all name one
446
+ file. **Exit 0 is the file written,
446
447
  an empty shortlist included** — the empty queue is an answer. **Exit 2 is a
447
448
  refusal**: the scan, the ledger read or the write did not answer, and the
448
449
  previous file stands untouched, because an empty file written then would