@feigi/fleet-ctl 3.35.6 → 3.35.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -12,7 +12,7 @@ argument-hint: [pr-number]
12
12
  **Write every ruling to `<scratch>/dispositions-<your name>.json`, `<your name>` the `fix-pr-<pr>[-x]` you were dispatched as (standalone, `fix-pr-<pr>`) — the disposition record `dispositions-check.mjs` judges against the review result file before any finisher is dispatched.** It is `{"head": "<the review file's head>", "run": "<the run root's name in the review path>", "entries": [ … ]}` — `run` the `<run>` of the review path your prompt names, which the check holds against the one the PR's latest `reviewed=` names, so a record written against an earlier review of the same PR, a same-head one included, is a mismatch (standalone, with no ledger naming a run, leave it out): one entry per `survived` finding and per `unverified` finding, plus one per `refuted` finding you reverse. Each entry carries `bucket` (`survived|unverified|refuted`), `index` (its position in that bucket of the review file — stable, since a round's file never changes), `scope` (`in|out`), `claimKind` (`behavior|shape`) and `disposition` (`apply|defer`), and where they apply `reason`, `issue` (the number you filed it to or commented on), `verdictPath` (an in-scope suggestion's refuter verdict file) and `remedyFiles` (the files its remedy names). A `refuted` entry carries `scope`, `claimKind` and `disposition` like every other entry, and a non-empty `reason` holding the evidence that reverses it; a missing or blank `reason` is a mismatch. The check reads scope off the diff before it reads your entry: a finding with no `line`, or on a line `git diff` touches from the PR's merge-base with `origin/main` to the review's `head`, is in scope whatever `scope` says, and only otherwise does the declared one stand. An in-scope `survived` finding deferred passes only with `reason` `false-rationale`, `mutual-exclusion`, `remedy-worse` or `remedy-outside-diff`. `remedy-outside-diff` — the remedy would edit a file the PR's diff does not touch — also needs `remedyFiles` to name at least one file absent from `git diff` from that merge-base to the review's `head`: none named, or every one in that diff, is a mismatch. A `critical` or `important` finding deferred for it goes to a human instead of passing: the script exits 1 with verdict `escalate`, `ledger.mjs dispatch` refuses the PR's finisher, and nothing retries it; a `suggestion` deferred for it passes. Any other reason, none, or a `survived` or `unverified` finding with no entry is a mismatch: the script exits 1 naming each violating entry's bucket, index and rule, and `ledger.mjs dispatch` refuses the PR's finisher. `disposition` has no `dismiss`: an in-scope `survived` finding verified correct, needing no change, is deferred with `reason` `false-rationale` and filed on the closed suggestion-band record — step 5's `PR #<pr> review: the suggestion band, checked`.
13
13
  3. **Run `testCmd` before you commit**, from the worktree, copied verbatim — not a runner you picked. `testCmd` is the command your dispatcher handed you; **standalone, with no dispatcher to hand you one, it is the repo's own test command**, the Test entrypoint in the repo's Recipe cache (`derive-testcmd.sh <repo> test` prints it). Read it off the repo, never invent one: "not a runner you picked" is what this step forbids, and on the standalone path nothing else defines the referent. With no usable Recipe cache (`derive-testcmd.sh` refuses), run the Recipe derivation step first — dispatch a `task` member, agent `fleet-recipe-deriver`, its prompt naming the main checkout's absolute path as `<repo>` and a scratch directory of its own; it proves both commands in a throwaway worktree and writes the cache only on proof, and its `RECIPE NOT PROVEN` is a stop, reported with its reason. Never fall back to a runner of your own choosing. `tests 0` is a FAILED run, not a pass: a glob matching nothing still exits 0. **Zero is not the only no-work count.** A run reporting **0 passes with no failures** skipped everything it collected, and a count **materially below the whole suite** means you ran a partial tree — this suite reported `tests 937` when this line was written, so compare what you get against a full run rather than against zero. The number drifts; that is the safe direction, because a stale one produces a loud false red while its absence produces a silent false green. Red, zero-test, or either no-work count → fix it or move the finding to defer; never commit over it. Then commit and push — `git push origin HEAD:<branch>`, the explicit refspec: this step also runs from a `--detach` worktree (`run-team/SKILL.md`'s worktree-recreation form), where a bare `git push` exits 128 (`fatal: You are not currently on a branch`) and any push whose destination is `HEAD` rather than a full or branch refname (`-u` or not, forced or not) exits 1 (`error: The destination you provided is not a full refname`) — and report the test result alongside the SHA. **Then reconcile the PR body with what you actually did.** It merges into the permanent record and nothing downstream re-derives it: your commit messages are yours to fix and usually get fixed, the body is neither. Removing a change, or reversing one, leaves the body asserting work the diff no longer contains. Measured twice in one run — one body kept asserting a calibration its own fix had just deleted as false, another kept claiming a hunk the fix had removed as "this diff owns it" — both caught by a finisher's reading rather than by any rule, and both would otherwise have merged intact. `gh pr edit <pr> --body-file <path>`, and re-read the body against the final diff rather than against your memory of it. **Never `--no-verify`.** The fleet runs in repos it knows nothing about: it must not assume a pre-commit hook exists, and must never bypass one that does — a hook that fails is a finding to report, not an obstacle. Nothing re-reviews what you commit here, so this run is the only gate between your edit and a merge.
14
14
  4. **Under the fleet, do not hold this wait.** The controller owns a persistent CI Monitor and dispatches a finisher once your report has arrived and CI is green — so push, then report to the controller a **final verdict** (every specialist you dispatched + its outcome + your apply/defer adjudication + the pushed SHA) and stop. A specialist that has neither reported nor been relayed to you is not a verdict line — ask the controller for it by name before ruling; see **Specialists**. The controller keys "review complete" on that verdict, **never on you merely going idle** — a slow specialist can still be running when your turn ends, and finishing off idle-alone ships a premature label (observed: a PR labelled while its contract-test specialist was still running and about to surface a vacuous pin). A turn-based reviewer re-reading `gh pr checks` each idle cycle rebuilds its whole context for nothing the Monitor lacks. **Standalone (no controller): watch** the run until the diff-validating jobs are green (bind via `ci-state.mjs` below); fix a **genuine** failure and repeat from 3. **Staleness is not a failure:** a `rebase-check` red or heavy jobs `skipped` **solely from a non-zero behind-count** never clears by waiting and must not be rebased away here — see **`skipped` is not `passed`** and **Do NOT rebase to label** below for what it looks like and why. Stop watching and go to 6. A turn-based reviewer that "waits for green" on a behind PR stalls forever and ends its turn without labelling. **`ci-state.mjs` returns `verdict: "no-ci"`** → there is no run to watch, so don't: go straight to 6 and let that step's `--declare-no-ci` branch decide.
15
- 5. File each deferred finding: `gh issue create --label <ready-for-agent|needs-triage>` with the finding, `file:line`, why deferred, `Deferred from PR #<pr> review`, and **the finding's `dimension` in the issue body** — the review returns it on every finding, and a backlog that does not carry it cannot be attributed to the specialist that generated it. **The label follows the finding's state, not this step** — but it is never omitted; an unlabelled issue is invisible to both `candidates.mjs --require-label` and the cockpit's pool query, reachable only by a human. **The bar here is whether the DEFECT is confirmed — never whether the remedy is settled.** Confirmed defect with the remedy still open → `ready-for-agent`, and say in the body that the remedy is open. Torn → `needs-triage`, narrowed: torn means **unsure anything is broken**, not unsure how to fix it. **A finding a refuter CHECKED and did not survive is neither** — it is not a confirmed defect, and you are not unsure whether anything is broken: you measured that nothing is. Refutations go as **one issue per review, titled `PR #<pr> review: the suggestion band, checked`, labelled `wontfix`, and CLOSED** — a run that files them open instead has to be corrected afterwards, as one was on 2026-08-27. Left open they read as queued agent work and rot into filing artifacts; a measured triage pass found a quarter of its `needs-triage` backlog was refuted records, bulk-closable by title shape. Closed is still a durable home — `check` reads the tracker at `--state all`, so a future run re-deriving the finding lands on the evidence rather than re-litigating it. Split the band only where an entry is **not** a refutation: a residual the refuter surfaced, or a finding refused as out of scope and never checked, is real deferred work — and real deferred work earns its own open issue only past a second bar. **Worth a claim: a finding whose own claim is that correct code could be shaped better — style, naming, layout, redundancy, a micro-simplification — never gets its own open issue.** Its only open question is "is this worth doing?", which answers itself under the repriced triage bar: measured 2026-08-15→31, 133 issues were triage-closed `wontfix` in sixteen days, 121 of them review deferrals, mostly this shape. Append it to the same closed record issue under a `Below the claim bar` heading — `file:line`, dimension, the claim, and a re-open trigger per entry. Closed is a durable home for these too: `check` reads `--state all`, so a run re-deriving the finding lands on the record instead of re-filing — and a later review returning the same finding as `survived`, or a maintainer hitting it, is the promotion signal: file it open then, citing the record. **An in-scope rediscovery step 2 applied is that same promotion signal, and it files nothing** — so the record carries no mark unless you write one: run `check` over each finding step 2 applied as well, and where its tracker rows put one on a `Below the claim bar` entry, comment on that record issue, opening `Promoted — applied, not filed`, and name the entry, that its refuter let it through, and the commit carrying the fix. That comment is the promotion mark this path leaves, and it is **not** a cross-reference — measured on this tracker, a comment mints `cross-referenced` on the issue its own text *names*, never on the issue it sits under (a comment citing a second issue landed on that issue's timeline and nowhere else), so the fixed opening is what carries the signal instead. **The bar reads the finding's claim, never its review band** — a finding that alleges wrong behavior, whatever band it sat in, `unverified`-with-crashed-refuters included, is above this bar and files open under the confirmed/torn split, which is why a band cannot carry this decision. Do **not** reach for phase 0's **decided?** test here. That is a *consumption* gate, priced for a seat where implementer divergence costs a claim, a worktree and a dispatch; at filing time divergence costs one PR review the maintainer already runs. Same test, two seats, opposite correct answers — and reading it in this seat took `needs-triage` from 11 to 135 before it was repriced (ruled 2026-08-18). **Dedupe through `~/.fleet/bin/fleet-run ledger.mjs check "<subject>"`, never a bare `gh issue list --search`** — the duplicate class that guard exists to catch was filed from *here*: the ledger row for the finding rediscovered five times in one measured run carries a reviewer's own source tag, `(review-pr-108)`. `check` reads this run's filed list *and* the tracker at `--state all`, so a closed duplicate still counts. Exit **1** is already filed in this run; exit **3** is a clean ledger with matching tracker rows that score against the subject — read the ones it prints and comment on the existing follow-up rather than filing a second issue. **Exit 0 is not automatically "safe to file"**: it covers `clean`, `soft-hit` and `unverified` alike, and an unreachable `gh` degrades to a ledger-only answer that says `TRACKER NOT CHECKED`, so read the stdout `verdict` to tell a tracker that was searched and clean from one nobody read — under `unverified`, search it yourself before filing — or, for the applied-promotion comment above, before treating a tracker nobody could read as a reason to skip it. **`soft-hit` is the answer that costs most to misread**: it means related rows were found and none of them was established as a duplicate — a near-miss above the floor, or tracker rows the scorer rates 0.00 — so read the rows it printed and decide, and never treat that exit 0 as permission. Exit **2** is a usage error, meaning nothing was checked at all: fix the invocation and re-run, never read it as a duplicate. Full exit-code and `verdict` semantics live in `$(~/.fleet/bin/fleet-run --root)/skills/run-team/SKILL.md`'s **Run ledger** section — read them there rather than restating them here. **The guard dedupes, it never drops:** a duplicate becomes a comment on the issue that already covers it, never a dropped finding. **Record every issue you create, at once:** immediately after each `gh issue create`, run `~/.fleet/bin/fleet-run ledger.mjs filed <N> "<subject>"` — `<N>` the number `gh issue create` printed, and **the same subject string you passed to `check`**, so the next `check` for that finding meets it in the filed list instead of scoring a rewording. Without it the guard's ledger half never holds a row, and its exit **1** can never fire. If `filed` fails, retry it once; if it fails again, leave the issue alone — it exists and is correct — and report it as `unrecorded: #N <subject>`, so the controller runs `filed` for it. Report `filed: #N <subject>` for every issue you created — under the fleet, in your report to the controller. **The one window the guard cannot see:** `check` → `gh issue create` → `filed` is three commands, and the ledger's lock covers each alone, so two filers can both read `clean` in the seconds before either records. That gap is accepted, never a reason to skip `filed`. Post the numbers as one PR comment.
15
+ 5. File each deferred finding: `gh issue create --label <ready-for-agent|needs-triage>` with the finding, `file:line`, why deferred, `Deferred from PR #<pr> review`, and **the finding's `dimension` in the issue body** — the review returns it on every finding, and a backlog that does not carry it cannot be attributed to the specialist that generated it. **The label follows the finding's state, not this step** — but it is never omitted; an unlabelled issue is invisible to both `candidates.mjs --require-label` and the cockpit's pool query, reachable only by a human. **The bar here is whether the DEFECT is confirmed — never whether the remedy is settled.** Confirmed defect with the remedy still open → `ready-for-agent`, and say in the body that the remedy is open. Torn → `needs-triage`, narrowed: torn means **unsure anything is broken**, not unsure how to fix it. **A finding a refuter CHECKED and did not survive is neither** — it is not a confirmed defect, and you are not unsure whether anything is broken: you measured that nothing is. Refutations go as **one issue per review, titled `PR #<pr> review: the suggestion band, checked`, labelled `wontfix`, and CLOSED** — a run that files them open instead has to be corrected afterwards, as one was on 2026-08-27. Left open they read as queued agent work and rot into filing artifacts; a measured triage pass found a quarter of its `needs-triage` backlog was refuted records, bulk-closable by title shape. Closed is still a durable home — `check` reads the tracker at `--state all`, so a future run re-deriving the finding lands on the evidence rather than re-litigating it. Split the band only where an entry is **not** a refutation: a residual the refuter surfaced, or a finding refused as out of scope and never checked, is real deferred work — and real deferred work earns its own open issue only past a second bar. **Worth a claim: a finding whose own claim is that correct code could be shaped better — style, naming, layout, redundancy, a micro-simplification — never gets its own open issue.** **Neither does a gap in a prose guard — a test holding prose to its wording — unless something acts on the guarded text: an agent follows it as an instruction (a skill, a command, an agent definition, a script's header or usage text, `AGENTS.md`), or a program other than its own guard reads it.** Whether anything does is your judgement, as `claimKind` is, and a gap below this bar is recorded `claimKind: shape`. A gap in a guard's own code — a slow pattern, a dead branch, an unchecked spawn result — takes the stakes of the prose it guards, and a helper several guards share takes the highest of theirs. A missed wording already in the tree is no guard gap — that prose is wrong — and neither is an input already in the tree that trips a guard's code; each files on its own merits. Once the prose is corrected, the observed wording may join the guard's literal ban, never a reader built to catch wordings nobody has written. A below-bar finding's only open question is "is this worth doing?", which answers itself under the repriced triage bar: measured 2026-08-15→31, 133 issues were triage-closed `wontfix` in sixteen days, 121 of them review deferrals, mostly this shape. Append it to the same closed record issue under a `Below the claim bar` heading — `file:line`, dimension, the claim, and a re-open trigger per entry. Closed is a durable home for these too: `check` reads `--state all`, so a run re-deriving the finding lands on the record instead of re-filing — and a later review returning the same finding as `survived`, or a maintainer hitting it, is the promotion signal: file it open then, citing the record. **An in-scope rediscovery step 2 applied is that same promotion signal, and it files nothing** — so the record carries no mark unless you write one: run `check` over each finding step 2 applied as well, and where its tracker rows put one on a `Below the claim bar` entry, comment on that record issue, opening `Promoted — applied, not filed`, and name the entry, that its refuter let it through, and the commit carrying the fix. That comment is the promotion mark this path leaves, and it is **not** a cross-reference — measured on this tracker, a comment mints `cross-referenced` on the issue its own text *names*, never on the issue it sits under (a comment citing a second issue landed on that issue's timeline and nowhere else), so the fixed opening is what carries the signal instead. **The bar reads the finding's claim, never its review band** — a finding that alleges wrong behavior, whatever band it sat in, `unverified`-with-crashed-refuters included, is above this bar and files open under the confirmed/torn split, which is why a band cannot carry this decision. Do **not** reach for phase 0's **decided?** test here. That is a *consumption* gate, priced for a seat where implementer divergence costs a claim, a worktree and a dispatch; at filing time divergence costs one PR review the maintainer already runs. Same test, two seats, opposite correct answers — and reading it in this seat took `needs-triage` from 11 to 135 before it was repriced (ruled 2026-08-18). **Dedupe through `~/.fleet/bin/fleet-run ledger.mjs check "<subject>"`, never a bare `gh issue list --search`** — the duplicate class that guard exists to catch was filed from *here*: the ledger row for the finding rediscovered five times in one measured run carries a reviewer's own source tag, `(review-pr-108)`. `check` reads this run's filed list *and* the tracker at `--state all`, so a closed duplicate still counts. Exit **1** is already filed in this run; exit **3** is a clean ledger with matching tracker rows that score against the subject — read the ones it prints and comment on the existing follow-up rather than filing a second issue. **Exit 0 is not automatically "safe to file"**: it covers `clean`, `soft-hit` and `unverified` alike, and an unreachable `gh` degrades to a ledger-only answer that says `TRACKER NOT CHECKED`, so read the stdout `verdict` to tell a tracker that was searched and clean from one nobody read — under `unverified`, search it yourself before filing — or, for the applied-promotion comment above, before treating a tracker nobody could read as a reason to skip it. **`soft-hit` is the answer that costs most to misread**: it means related rows were found and none of them was established as a duplicate — a near-miss above the floor, or tracker rows the scorer rates 0.00 — so read the rows it printed and decide, and never treat that exit 0 as permission. Exit **2** is a usage error, meaning nothing was checked at all: fix the invocation and re-run, never read it as a duplicate. Full exit-code and `verdict` semantics live in `$(~/.fleet/bin/fleet-run --root)/skills/run-team/SKILL.md`'s **Run ledger** section — read them there rather than restating them here. **The guard dedupes, it never drops:** a duplicate becomes a comment on the issue that already covers it, never a dropped finding. **Record every issue you create, at once:** immediately after each `gh issue create`, run `~/.fleet/bin/fleet-run ledger.mjs filed <N> "<subject>"` — `<N>` the number `gh issue create` printed, and **the same subject string you passed to `check`**, so the next `check` for that finding meets it in the filed list instead of scoring a rewording. Without it the guard's ledger half never holds a row, and its exit **1** can never fire. If `filed` fails, retry it once; if it fails again, leave the issue alone — it exists and is correct — and report it as `unrecorded: #N <subject>`, so the controller runs `filed` for it. Report `filed: #N <subject>` for every issue you created — under the fleet, in your report to the controller. **The one window the guard cannot see:** `check` → `gh issue create` → `filed` is three commands, and the ledger's lock covers each alone, so two filers can both read `clean` in the seconds before either records. That gap is accepted, never a reason to skip `filed`. Post the numbers as one PR comment.
16
16
  **A duplicate that should hold an open deferral is relabelled up, never down.** Where the guard lands a finding whose home is an open issue on an existing one that is open and labelled `needs-triage` while the finding's state calls for `ready-for-agent` — a defect its refuters confirmed — relabel it with `gh issue edit <N> --remove-label needs-triage --add-label ready-for-agent`, and cite the refuters' verdict in the comment you leave there. Never relabel `ready-for-agent` down to `needs-triage`: a `ready-for-agent` issue already holds a `needs-triage` finding, and a later run's crashed refuters are no reason to send a confirmed defect back to triage. A closed one cannot hold it: file a new open issue citing it, as the promotion rule above does for the closed record.
17
17
  **Name where each deferral went, in the disposition record.** Every entry you defer carries `issue`: the number of the issue you filed it to, commented it onto, or appended it to — the closed `PR #<pr> review: the suggestion band, checked` record included. An in-scope `suggestion`'s entry — an `unverified` finding with `refutersDispatched` of zero — also carries `verdictPath`, applied or deferred: the absolute path of a file holding its refuter's verdict as JSON, `{"refuted": <boolean>, "reason": "<string>"}`, under your own `<scratch>/pr<N>/fix-XXXXXXXX/<finding>/` run root. `dispositions-check.mjs` reads each named issue back through `gh issue view --json labels,state,title` and each verdict file off disk; a mismatch names the row of its filing table the entry broke, so move or relabel that filing to the home the row names and run the check again. With `gh` unreachable, or an issue it cannot read, that filing goes unchecked: with nothing else broken the verdict is `unchecked` — never `ok`, and it exits 1 — so run the check again once `gh` answers.
18
18
  6. Diff-check green (run-bound per `ci-state.mjs`; under staleness see **`skipped` is not `passed`** for what the label then rests on) **and** deferrals filed **and** the PR carrying exactly one release label (`patch`/`minor`/`major`, counting only those three; **required on every PR** — `release-label.yml` auto-adds `patch` when none is present and hard-fails on more than one, so this never needs to check whether the repo defines the gate at all, and `gh label list` settles nothing here any more) **and** `dispositions-check.mjs --member fix-pr-<pr> --scratch <scratch>` run over your own record exiting 0 (standalone that is yours to run, from the worktree, after step 2 writes `<scratch>/dispositions-fix-pr-<pr>.json`; `--review <path>` names the review file, which you write yourself from the findings step 1 collected, in the shape **The review result file** describes — `pr`, `head`, `snapshot`, `counts` and the `survived`, `refuted` and `unverified` buckets; standalone you pass `--no-ledger` with it, so it writes no token and the exit status is the verdict — a `.fleet/ledger.md` the repository already holds is a previous run's, and without the flag it exits 2 for a ledger with no row for you; under the fleet `ledger.mjs dispatch` has already refused a finisher without it) → `gh pr comment <pr> --body "ready-to-merge-head: <prHead>"`, `prHead` being the full SHA your green `ci-state.mjs` reading reported, which the merge bot reads as the head the label was applied to, then `gh pr edit <pr> --add-label ready-to-merge`. Do not merge. A non-zero dispositions exit halts you before the label, and you report the violations it printed. Zero or more than one release label halts you before the label, naming which you found — a timed-out `gh pr create` opens the PR with its `--label` unapplied and no exit status to react to, and nothing after this step re-derives the release label. **Under the fleet a finisher does this** — a fresh small agent the controller dispatches (after your final verdict, never on your bare idle). Gate it on the diff-validating **`check`** job, **not** on `ci-state --quiet` exit 0, which a behind PR — the normal case once any sibling merges — never reaches: a `rebase-check` red or heavy jobs `skipped` off the behind-count hold it short of full green, so an exit-0 gate strands every behind PR unlabelled. Label when `check` is present and green **and no heavy job (the diff-validating suites — *not* the `rebase-check` currency gate) is in `failure`** — a `skipped` heavy job is behind-count staleness and fine — **solely** off that count, which is a condition to establish rather than infer, see the five-condition note in `$(~/.fleet/bin/fleet-run --root)/skills/run-team/SKILL.md`'s fix-applier prompt block. A `failure` is the diff's own fault and blocks the label, else a genuinely broken PR gets labelled off a green `check` and burns a merge-bot rebase+CI cycle before the failure resurfaces. Read per-job state for this: run `ci-state.mjs` **without** `--quiet`, or read its `jobs` — the `--quiet` payload drops the per-job `jobs`/`missing` and the `dropped` list, keeping `reasons` (which still distinguishes `is failure` from `is skipped`). You reach step 6 yourself only when green is already in hand at push time.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@feigi/fleet-ctl",
3
- "version": "3.35.6",
3
+ "version": "3.35.8",
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": {
@@ -139,6 +139,9 @@ export function rowNums(text) {
139
139
  export const REVIEW = /^review=(?<kind>wf|member|fallback):(?<name>[^=\s]+)(?<failed>=failed)?$/;
140
140
  export const REVIEWED = /^reviewed=([0-9a-fA-F]{7,40}):(\d+)\/(\d+)\/(\d+):(run-[A-Za-z0-9]{8})$/;
141
141
 
142
+ // The stream a row belongs to: its PR, else its key.
143
+ const streamId = (text) => rowNums(text).pr ?? text.split(/\s/)[0];
144
+
142
145
  // Every PR's token stream: every row that maps to it under rowNums(), in
143
146
  // ledger row order, its tokens run end to end — the order fleet-tick.mjs's
144
147
  // fold reads a PR's review record in. A row naming no PR and keyed by no
@@ -146,7 +149,7 @@ export const REVIEWED = /^reviewed=([0-9a-fA-F]{7,40}):(\d+)\/(\d+)\/(\d+):(run-
146
149
  function streams(rows) {
147
150
  const out = new Map();
148
151
  for (const text of rows) {
149
- const id = rowNums(text).pr ?? text.split(/\s/)[0];
152
+ const id = streamId(text);
150
153
  if (!out.has(id)) out.set(id, []);
151
154
  out.get(id).push(...text.split(/\s+/).filter(Boolean));
152
155
  }
@@ -297,6 +300,82 @@ export function rowWriteRefusal(before, after, oldLine, line) {
297
300
  return null;
298
301
  }
299
302
 
303
+ /**
304
+ * What a ledger still holds live, and what must travel with it. `tokens` is
305
+ * every unsettled member token and every open review launch, once each, in
306
+ * ledger order, as `{name, token, row}` — the member or runner name (a
307
+ * workflow launch's runId), the token as written, and the key of the first
308
+ * row carrying it, null for a member `## Dispatched` alone names. `rows` is
309
+ * the indices of every row of a stream — the rows one PR's record spans, or
310
+ * a row's own key when it names none — in which any row carries one of those
311
+ * tokens: a stream's rows are read together, so a live row carried without
312
+ * its siblings would lose the PR's review record and the settled copies that
313
+ * keep a bare token from reading live again. `dispatched` is every
314
+ * `## Dispatched` entry whose member is unsettled, plus every settled entry
315
+ * naming a member a kept row carries, for the same reason. A member is
316
+ * settled by a settled copy in `## Dispatched` or on a row, except that a
317
+ * PR-bound member's settled copy counts only on its own PR's row — the reading
318
+ * fleet-tick.mjs folds liveness by, so nothing that fold calls live is left
319
+ * out. A launch is open while unanswered and not `=failed`, paired across its
320
+ * PR's rows as `rowWriteRefusal` pairs them. Malformed tokens are the caller's
321
+ * to have refused: one here is read as nothing.
322
+ */
323
+ export function liveOnLedger(rows, dispatched) {
324
+ const settled = new Set();
325
+ for (const e of dispatched) {
326
+ const t = parseToken(e);
327
+ if (t !== null && t.error === null && t.outcome !== null) settled.add(t.name);
328
+ }
329
+ for (const text of rows) {
330
+ const { pr } = rowNums(text);
331
+ for (const t of memberTokens(text)) {
332
+ if (t.error === null && t.outcome !== null && (t.bound !== "pr" || t.number === pr)) settled.add(t.name);
333
+ }
334
+ }
335
+ const live = (t) => t !== null && t.error === null && t.outcome === null && !settled.has(t.name);
336
+ const open = new Map();
337
+ for (const [id, tokens] of streams(rows)) {
338
+ const r = readReviews(tokens);
339
+ open.set(id, r.launches.filter((l) => r.open.includes(l.id)));
340
+ }
341
+ const out = { rows: [], dispatched: [], tokens: [] };
342
+ const seen = new Set();
343
+ const add = (name, token, row) => {
344
+ if (seen.has(token)) return;
345
+ seen.add(token);
346
+ out.tokens.push({ name, token, row });
347
+ };
348
+ const streamOf = rows.map(streamId);
349
+ const liveStreams = new Set();
350
+ rows.forEach((text, i) => {
351
+ const key = text.split(/\s/)[0];
352
+ const words = text.split(/\s+/).filter(Boolean);
353
+ const members = memberTokens(text).filter(live);
354
+ const launches = (open.get(streamOf[i]) ?? []).filter((l) => words.includes(l.id));
355
+ if (members.length === 0 && launches.length === 0) return;
356
+ liveStreams.add(streamOf[i]);
357
+ for (const t of members) add(t.name, t.name, key);
358
+ for (const l of launches) add(l.name, l.id, key);
359
+ });
360
+ const carried = new Set();
361
+ rows.forEach((text, i) => {
362
+ if (!liveStreams.has(streamOf[i])) return;
363
+ out.rows.push(i);
364
+ for (const t of memberTokens(text)) if (t.error === null) carried.add(t.name);
365
+ });
366
+ for (const e of dispatched) {
367
+ const t = parseToken(e);
368
+ if (t === null || t.error !== null) continue;
369
+ if (live(t)) {
370
+ out.dispatched.push(e);
371
+ add(t.name, t.name, null);
372
+ } else if (carried.has(t.name)) {
373
+ out.dispatched.push(e);
374
+ }
375
+ }
376
+ return out;
377
+ }
378
+
300
379
  // A ticket row is `#N <text>`; it is an Exclusion when `excluded` is the
301
380
  // text's first word — `impl-N · … excluded …` is a row about something else.
302
381
  // `#N excluded · behind-pr:#M` / `behind-issue:#M`: `#M` is an issue or PR
@@ -340,11 +419,14 @@ export function unescapeText(s) {
340
419
  return s.replace(/\\(\\|n)/g, (_, c) => (c === "n" ? "\n" : "\\"));
341
420
  }
342
421
 
343
- /** The name the next merge bot takes: 1 + the `merge-bot-` entries in
344
- * `## Dispatched`, settled ones included. One ledger per run, so n restarts
345
- * at 1 with every run. */
422
+ /** The name the next merge bot takes: 1 + the highest `merge-bot-<n>` in
423
+ * `## Dispatched`, settled ones included — the highest, not the count, since
424
+ * a rotate that carries a live bot forward carries a settled predecessor
425
+ * only when a carried row names it. n restarts at 1 with every run that
426
+ * carries no bot. */
346
427
  export function nextMergeBot(dispatched) {
347
- return `merge-bot-${dispatched.map(parseToken).filter((t) => t?.family === "merge-bot").length + 1}`;
428
+ const ns = dispatched.map(parseToken).filter((t) => t?.family === "merge-bot").map((t) => t.number);
429
+ return `merge-bot-${Math.max(0, ...ns) + 1}`;
348
430
  }
349
431
 
350
432
  // An implementer cell is `<role>-<level>` — an omp role and a thinking
@@ -15,9 +15,11 @@
15
15
  // `<member>=<outcome>` in both places (an implementer's settle to `PR#M` also
16
16
  // folds the PR's own `#M` row into its ticket's), and `drain` writes the
17
17
  // one marker that stops supply. The token grammar is
18
- // ledger-grammar.mjs's. `## Dispatched` gains an entry per dispatch and never
19
- // loses or reorders one — settling annotates an entry in place — which is what
20
- // lets `merge-bot-<n>` be counted from it.
18
+ // ledger-grammar.mjs's. Within a run `## Dispatched` gains an entry per
19
+ // dispatch and never loses or reorders one — settling annotates an entry in
20
+ // place — which is what lets `merge-bot-<n>` be numbered from it; a rotate
21
+ // that carries a run's live entries forward carries a settled one only for a
22
+ // member a carried row names.
21
23
  //
22
24
  // Writer policy: the controller owns run
23
25
  // state (`row`/`settle`/`dispatch`/`drain`/`ruled`/`rotate`); filers append
@@ -35,7 +37,7 @@ import { fileURLToPath } from "node:url";
35
37
  import { spawnSync, execFileSync } from "node:child_process";
36
38
  import { makeDie, isFlagLike, hasEqualsForm, isDigits } from "./arg.mjs";
37
39
  import { fleetFile, FleetDirUnresolvable } from "./fleet-dir.mjs";
38
- import { parseMember, parseToken, memberTokens, nextMergeBot, agentDefinition, CELL, tierValues, rowPr, rowWriteRefusal, ROWS, DISPATCHED, FILED, RULED, DRAIN, headerRe, escapeText, unescapeText } from "./ledger-grammar.mjs";
40
+ import { parseMember, parseToken, memberTokens, nextMergeBot, liveOnLedger, agentDefinition, CELL, tierValues, rowPr, rowWriteRefusal, ROWS, DISPATCHED, FILED, RULED, DRAIN, headerRe, escapeText, unescapeText } from "./ledger-grammar.mjs";
39
41
  import { deriveRun, LedgerError, labelOffMember } from "./fleet-tick.mjs";
40
42
  import { stateFileIn, readState, writeState, assessBeat, stallsAt } from "./fleet-state.mjs";
41
43
  import { isDead, processSource, ancestry, controllerOf, judgeController, ProcUnreadable } from "./proc.mjs";
@@ -434,6 +436,20 @@ function refuseStrayInId(value, what) {
434
436
  // report what the parse saw rather than what a later stat() guesses.
435
437
  let ledgerParsed = false;
436
438
 
439
+ // A section's entries, unescaped, in file order — none when the header is
440
+ // absent. Lenient by design: it refuses nothing, so rotate reads a ledger
441
+ // load() refuses through the same slicing.
442
+ function sectionOf(text, name) {
443
+ const m = headerRe(name).exec(text);
444
+ if (!m) return [];
445
+ const start = m.index + m[1].length + name.length;
446
+ const after = text.slice(start);
447
+ const end = after.search(/\n## /);
448
+ return (end === -1 ? after : after.slice(0, end))
449
+ .split("\n").map((l) => l.trim()).filter((l) => l.startsWith("- "))
450
+ .map((l) => unescapeText(l.slice(2)));
451
+ }
452
+
437
453
  function load() {
438
454
  if (!existsSync(file)) return { rows: [], filed: [], ruled: [], dispatched: [], drain: null };
439
455
  let text;
@@ -442,16 +458,7 @@ function load() {
442
458
  } catch (e) {
443
459
  die(`cannot read ${file}: ${e.message}`);
444
460
  }
445
- const section = (name) => {
446
- const m = headerRe(name).exec(text);
447
- if (!m) return [];
448
- const start = m.index + m[1].length + name.length;
449
- const after = text.slice(start);
450
- const end = after.search(/\n## /);
451
- return (end === -1 ? after : after.slice(0, end))
452
- .split("\n").map((l) => l.trim()).filter((l) => l.startsWith("- "))
453
- .map((l) => unescapeText(l.slice(2)));
454
- };
461
+ const section = (name) => sectionOf(text, name);
455
462
  // Set here, past the read and the early return, so it can only be true of a
456
463
  // file this function actually opened and recognised as a ledger.
457
464
  ledgerParsed = headerRe(FILED).test(text);
@@ -734,9 +741,9 @@ if (requireFile && !existsSync(file)) die(`--require-file given but ledger file
734
741
 
735
742
  const WRITE_COMMANDS = new Set(["row", "filed", "ruled", "dispatch", "settle", "drain", "rotate"]);
736
743
  if (WRITE_COMMANDS.has(cmd)) await acquireLock();
737
- // `rotate` moves the file whole and never parses it: a ledger load() would
738
- // refuse is still the previous run's record, and archiving it as-is is the
739
- // whole job.
744
+ // `rotate` never load()s: a ledger load() would refuse is still the previous
745
+ // run's record, and it is archived as-is — and read line by line when it
746
+ // carries live members forward, see carryOf().
740
747
  const data = cmd === "rotate" ? null : load();
741
748
 
742
749
  // The payload subcommands end by falling out of this chain, never by calling
@@ -1493,12 +1500,26 @@ function runCheck() {
1493
1500
  // ── rotate ───────────────────────────────────────────────────────────────────
1494
1501
  //
1495
1502
  // One ledger per run. Phase 0 of every run moves the previous run's file aside
1496
- // before anything reads it, so no row, exclusion, filing, ruling or drain
1497
- // marker outlives the run that wrote it: the next write subcommand finds no
1498
- // file and starts the empty skeleton, exactly as on a first run. The archive
1499
- // is the file itself — hard-linked to its stamped name, then unlinked — so its
1500
- // bytes are untouched, and the link refuses atomically when that name is
1501
- // already taken rather than overwriting an older archive.
1503
+ // before anything reads it, so no exclusion, filing, ruling or drain marker
1504
+ // outlives the run that wrote it. The archive is the file itself —
1505
+ // hard-linked to its stamped name, then unlinked or, when a successor is
1506
+ // carried, replaced by it — so its bytes are untouched, and the link refuses
1507
+ // atomically when that name is already taken rather than overwriting an older
1508
+ // archive.
1509
+ //
1510
+ // What follows depends on the verdict below. After a `dead` or `none` one
1511
+ // nothing is carried: the next write subcommand finds no file and starts the
1512
+ // empty skeleton, exactly as on a first run. After an `ancestor` one — this
1513
+ // session's own earlier run, whose members run inside the omp process that
1514
+ // is still this run's — rotate writes a new ledger holding what is still
1515
+ // live in the archive: every row of a stream that holds an unsettled member
1516
+ // token or an open review launch, whole, and every unsettled `## Dispatched`
1517
+ // entry plus the settled ones naming a carried member (see carryOf()). The
1518
+ // members those name may still be running, and dropping their tokens would
1519
+ // let the next tick dispatch onto their work and leave their
1520
+ // results nothing to settle. Phase 0 then reconciles each carried token
1521
+ // against the session's job list; rotate cannot, since that list is the
1522
+ // controller's to read and no script's.
1502
1523
  //
1503
1524
  // Under the write lock like every other write subcommand, so a concurrent
1504
1525
  // writer either lands before the move (in the archive, whole) or after it (in
@@ -1560,6 +1581,19 @@ function runRotate() {
1560
1581
  if (prior === "none" && exists && assessBeat({ beat, ticked, now: Date.now() }).kind === "beating") {
1561
1582
  die(`refusing to rotate ${file}: the controller that owns it is still beating — last beat ${new Date(beat.at).toISOString()} in ${beatFile}; it counts as stalled after ${new Date(stallsAt({ beat, ticked })).toISOString()}`);
1562
1583
  }
1584
+ // Read before anything moves: a ledger whose live tokens cannot be read is
1585
+ // refused with nothing moved, never archived with those tokens dropped.
1586
+ let carry = { rows: [], dispatched: [], skipped: [] };
1587
+ if (prior === "ancestor" && exists) {
1588
+ let text;
1589
+ try {
1590
+ text = readFileSync(file, "utf8");
1591
+ } catch (e) {
1592
+ die(`refusing to rotate ${file}: cannot read it to carry this session's live members forward: ${e.message}`);
1593
+ }
1594
+ carry = carryOf(text);
1595
+ }
1596
+ const carrying = carry.rows.length > 0 || carry.dispatched.length > 0;
1563
1597
  let archive = null;
1564
1598
  if (exists) {
1565
1599
  const stamp = new Date().toISOString().replace(/\.\d{3}Z$/, "Z").replaceAll(":", "");
@@ -1569,15 +1603,33 @@ function runRotate() {
1569
1603
  } catch (e) {
1570
1604
  die(e.code === "EEXIST" ? `refusing to rotate ${file}: ${archive} already exists` : `cannot rotate ${file} to ${archive}: ${e.message}`);
1571
1605
  }
1572
- try {
1573
- unlinkSync(file);
1574
- } catch (e) {
1575
- die(`archived ${file} as ${archive} but could not remove it: ${e.message} — remove it by hand before the next write`);
1606
+ // Carrying, the new ledger is renamed over the old file by save(), so the
1607
+ // file is never absent while its live tokens exist only in memory: a write
1608
+ // that fails leaves the ledger where it was, the archive a second name for
1609
+ // the same bytes, and a retry carries from the unmoved file. Carrying
1610
+ // nothing, the file has no successor to wait for.
1611
+ if (!carrying) {
1612
+ try {
1613
+ unlinkSync(file);
1614
+ } catch (e) {
1615
+ die(`archived ${file} as ${archive} but could not remove it: ${e.message} — remove it by hand before the next write`);
1616
+ }
1576
1617
  }
1577
- console.error(` rotated ${file} -> ${archive}`);
1578
1618
  } else {
1579
1619
  console.error(` nothing to rotate: ${file} does not exist`);
1580
1620
  }
1621
+ // Nothing to carry writes nothing, so the next write starts the skeleton
1622
+ // exactly as after any other verdict.
1623
+ if (carrying) {
1624
+ save({ rows: carry.rows, dispatched: carry.dispatched, filed: [], ruled: [], drain: null });
1625
+ }
1626
+ if (archive !== null) console.error(` rotated ${file} -> ${archive}`);
1627
+ for (const { line, why } of carry.skipped) {
1628
+ console.error(` skipped unparseable line '${line}' — not carried: ${why}`);
1629
+ }
1630
+ if (carrying) {
1631
+ console.error(` carried ${carry.rows.length} row(s) and ${carry.dispatched.length} ## Dispatched entr${carry.dispatched.length === 1 ? "y" : "ies"} from ${archive}`);
1632
+ }
1581
1633
  // Re-read rather than reuse the read above: the heartbeat file has other
1582
1634
  // writers, and a patch built from an older view would undo what they wrote
1583
1635
  // since.
@@ -1585,7 +1637,47 @@ function runRotate() {
1585
1637
  if (!writeState(beatFile, NAME, readState(beatFile, NAME), { controller: record })) {
1586
1638
  die(`${archive === null ? "found no ledger" : `rotated ${file} -> ${archive}`} but could not record this run's controller in ${beatFile} — the next run judges whatever record that file still holds, and none if it cannot be read`);
1587
1639
  }
1588
- console.log(JSON.stringify({ rotated: archive !== null, archive }));
1640
+ console.log(JSON.stringify({
1641
+ rotated: archive !== null, archive,
1642
+ carried: { rows: carry.rows, dispatched: carry.dispatched },
1643
+ skipped: carry.skipped.map((s) => s.line),
1644
+ }));
1645
+ }
1646
+
1647
+ // What an `ancestor` rotate carries out of the archived text, read line by
1648
+ // line so one bad line costs only itself: the whole point is to keep live
1649
+ // members' tokens, and a ledger load() refuses (a second drain marker, say)
1650
+ // still holds them. A row is read the way the tick reads it — a row the tick
1651
+ // would refuse is skipped rather than carried into a ledger the next tick
1652
+ // refuses whole — and a `## Dispatched` entry must be a well-formed member
1653
+ // token. Every skipped line is returned with its reason; a skipped row's
1654
+ // member can still be carried by its `## Dispatched` entry, which keeps its
1655
+ // name taken. Of what parses, liveOnLedger() picks what travels: every row
1656
+ // of a stream that holds a live token, whole, so a carried row's settled
1657
+ // tokens, `reviewed=` and every other record on it come along, and its
1658
+ // siblings' with them, and the tick's per-PR reading of the PR is unchanged;
1659
+ // and the `## Dispatched` entries, settled ones among them, that keep a
1660
+ // carried member from reading live again.
1661
+ function carryOf(text) {
1662
+ const skipped = [];
1663
+ const rows = sectionOf(text, ROWS).filter((r) => {
1664
+ try {
1665
+ deriveRun({ rows: [r], dispatched: [], drain: null }, []);
1666
+ return true;
1667
+ } catch (e) {
1668
+ if (!(e instanceof LedgerError)) throw e;
1669
+ skipped.push({ line: r, why: e.message });
1670
+ return false;
1671
+ }
1672
+ });
1673
+ const dispatched = sectionOf(text, DISPATCHED).filter((e) => {
1674
+ const t = parseToken(e);
1675
+ if (t !== null && t.error === null) return true;
1676
+ skipped.push({ line: e, why: t === null ? "not a member token" : `${t.name}: ${t.error}` });
1677
+ return false;
1678
+ });
1679
+ const live = liveOnLedger(rows, dispatched);
1680
+ return { rows: live.rows.map((i) => rows[i]), dispatched: live.dispatched, skipped };
1589
1681
  }
1590
1682
 
1591
1683
  // ── dispatch / settle ────────────────────────────────────────────────────────
@@ -4,12 +4,12 @@
4
4
  // classifies; it acts on nothing — no dispatch, no label, no release. The
5
5
  // controller dispatches off its answer.
6
6
  //
7
- // A claim's label and worktree exist before its first push. Rotation carries
8
- // no ledger row forward, the candidate scan excludes `in-progress`, and the
9
- // in-flight check reads the worktree as taken — so a claim a dead run left
10
- // without a PR is held by nobody until this step names it. One with an open
11
- // PR is not stranded: phase 0's fold-in queues every open PR, so it is never
12
- // listed here.
7
+ // A claim's label and worktree exist before its first push. Rotation after a
8
+ // dead or unknown run carries no ledger row forward, the candidate scan
9
+ // excludes `in-progress`, and the in-flight check reads the worktree as
10
+ // taken — so a claim a dead run left without a PR is held by nobody until
11
+ // this step names it. One with an open PR is not stranded: phase 0's fold-in
12
+ // queues every open PR, so it is never listed here.
13
13
  //
14
14
  // THE VERDICT is `prior` in the controller record, the one `ledger.mjs
15
15
  // rotate` reached on the record it replaced — never a fresh judgement of the
@@ -19,8 +19,10 @@
19
19
  // dead every open in-progress issue with no open PR: `resume` when
20
20
  // exactly one worktree for it sits under this checkout's
21
21
  // `.worktrees/` and its directory is there, `report` otherwise
22
- // ancestor this session's earlier run: nothing listed — its members may
23
- // still be live, and the in-run liveness check covers them
22
+ // ancestor this session's earlier run: no claim listed — its members may
23
+ // still be live, and rotate carried their tokens forward;
24
+ // `carried` lists them instead, for the controller to reconcile
25
+ // against the session's job list
24
26
  // none nothing proves the previous run dead: every claim `report`
25
27
  //
26
28
  // "An open PR about the issue" is the in-flight check's reading, its branch rule
@@ -33,18 +35,27 @@
33
35
  // the number as a whole segment, so a worktree named for issue 129 is never
34
36
  // issue 12's.
35
37
  //
36
- // Prints `{prior, claims: [{n, t, action, worktree, branch, why}]}` on stdout.
38
+ // Prints `{prior, claims: [{n, t, action, worktree, branch, why}], carried:
39
+ // [{name, token, row}]}` on stdout. `carried` is empty unless prior is
40
+ // `ancestor`; each entry is the member or runner name (a workflow launch's
41
+ // runId), the token as the ledger holds it, and the key of the first row
42
+ // carrying it — null for a member only `## Dispatched` names. It is every
43
+ // live token on the ledger: at phase 0 this run has dispatched nothing yet,
44
+ // so each is one rotate carried.
37
45
  // Exit 0 answered; 2 a list that did not answer — a gh or git failure, a
38
- // list at its cap, which may hold more than it showed, or a worktree path
39
- // whose presence cannot be told. Never read 2 as nothing stranded.
46
+ // list at its cap, which may hold more than it showed, a worktree path
47
+ // whose presence cannot be told, or a ledger that cannot be read. Never read
48
+ // 2 as nothing stranded.
40
49
 
41
50
  import { spawnSync } from "node:child_process";
42
51
  import { realpathSync, statSync } from "node:fs";
43
52
  import { basename, dirname, join } from "node:path";
53
+ import { fileURLToPath } from "node:url";
44
54
  import { makeDie, writeAll } from "./arg.mjs";
45
55
  import { gitEnv } from "./git-env.mjs";
46
56
  import { fleetFile, FleetDirUnresolvable } from "./fleet-dir.mjs";
47
57
  import { readState, stateFileIn } from "./fleet-state.mjs";
58
+ import { liveOnLedger } from "./ledger-grammar.mjs";
48
59
 
49
60
  const NAME = "stranded";
50
61
  const die = makeDie(NAME);
@@ -149,8 +160,8 @@ function main() {
149
160
  const { controller } = readState(stateFileIn(fleetDir), NAME);
150
161
  const prior = controller?.prior ?? "none";
151
162
  if (prior === "ancestor") {
152
- log(`${NAME}: the previous run is this session's own earlier run — its claims are left alone`);
153
- console.log(JSON.stringify({ prior, claims: [] }));
163
+ log(`${NAME}: the previous run is this session's own earlier run — its claims are left alone, and the live tokens rotate carried are listed`);
164
+ console.log(JSON.stringify({ prior, claims: [], carried: carriedTokens(join(fleetDir, "ledger.md")) }));
154
165
  return;
155
166
  }
156
167
 
@@ -206,7 +217,26 @@ function main() {
206
217
  claims.push({ n: issue.number, t: issue.title, action, worktree: one?.path ?? null, branch: one?.branch ?? null, why });
207
218
  log(` #${issue.number} ${action} — ${why}`);
208
219
  }
209
- console.log(JSON.stringify({ prior, claims }));
220
+ console.log(JSON.stringify({ prior, claims, carried: [] }));
221
+ }
222
+
223
+ // Every live token on the ledger, read through `ledger.mjs read` so the
224
+ // ledger keeps one parser. A read that fails is a list that did not answer.
225
+ function carriedTokens(file) {
226
+ const script = join(dirname(fileURLToPath(import.meta.url)), "ledger.mjs");
227
+ // `--file` names the ledger outright, so the read resolves no workspace
228
+ // and runs no git.
229
+ const r = spawnSync(process.execPath, [script, "--file", file, "read"], { encoding: "utf8", maxBuffer: MAX_BUFFER });
230
+ if (r.error || r.status !== 0) die(`ledger.mjs read failed (${how(r)}) — which tokens rotate carried is unknown`);
231
+ let d;
232
+ try {
233
+ d = JSON.parse(r.stdout);
234
+ } catch (e) {
235
+ die(`could not parse ledger.mjs read output: ${e.message}`);
236
+ }
237
+ const strings = (xs) => Array.isArray(xs) && xs.every((x) => typeof x === "string");
238
+ if (!d || !strings(d.rows) || !strings(d.dispatched)) die("ledger.mjs read returned no {rows, dispatched}");
239
+ return liveOnLedger(d.rows, d.dispatched).tokens;
210
240
  }
211
241
 
212
242
  main();
@@ -374,18 +374,31 @@ phase, or in any later one, asks the maintainer which tickets to take.
374
374
  every run, whatever way the previous one ended.** One ledger per run:
375
375
  `~/.fleet/bin/fleet-run ledger.mjs rotate` moves the previous run's
376
376
  `.fleet/ledger.md` byte-for-byte to `.fleet/ledger.<UTC
377
- YYYY-MM-DDTHHMMSSZ>.md` and leaves none behind, so this run's first write
378
- starts the empty skeleton. Nothing is carried forward — no row, exclusion,
379
- `## Filed` or `## Ruled` entry — so an unchecked `impl-` row a prior run
380
- left behind can no longer hold this run's tick. What an unclean end left in
377
+ YYYY-MM-DDTHHMMSSZ>.md` and leaves none behind. What it carries forward
378
+ turns on the verdict it reaches below. After `dead` or `none` nothing is
379
+ carried — no row, exclusion, `## Filed` or `## Ruled` entry — so this
380
+ run's first write starts the empty skeleton, and an unchecked `impl-` row
381
+ a prior run left behind can no longer hold this run's tick: a dead
382
+ controller took its in-process members with it. After `ancestor` — this
383
+ session's own earlier run, whose members run inside the same omp process
384
+ and may still be live — it writes a new ledger holding every row of a
385
+ stream (one PR's rows) in which a row carries an unsettled member token
386
+ or an open `review=` launch, whole and with every other token on it, plus
387
+ every unsettled `## Dispatched` entry and the settled entry of each
388
+ member a carried row names; exclusions, `## Filed`, `## Ruled` and the
389
+ drain marker are never carried.
390
+ A line it cannot parse is skipped with a warning naming it, and the
391
+ rotation still succeeds. It prints `{rotated, archive, carried: {rows,
392
+ dispatched}, skipped}`. The carried tokens keep the tick from dispatching
393
+ onto those members' work, keep their names taken, and give their late
394
+ results a token to settle; the stranded-claim step below reconciles them.
395
+ What an unclean end left in
381
396
  flight comes back through the ordinary per-run path: open PRs through the
382
397
  fold-in below, `behind-pr:`/`behind-issue:` exclusions through phase 1's
383
398
  collision and sequence checks, and a claim a dead run left without a PR
384
399
  through the stranded-claim step below — resumed by a new member under a
385
400
  new name when its worktree is in this checkout, reported to the
386
- maintainer otherwise. A claim this session's own earlier run left stays
387
- with it: its member may still be live, and the Member-killed row's check
388
- covers it. An exclusion that expires with the run that wrote
401
+ maintainer otherwise. An exclusion that expires with the run that wrote
389
402
  it (`deferred-to-session-end` and its like) must be restated if it still
390
403
  holds. **The guard is the
391
404
  controller record**, `controller` in `.fleet/heartbeat.json`: the omp
@@ -476,8 +489,12 @@ phase, or in any later one, asks the maintainer which tickets to take.
476
489
  that run's own metrics — it is reviewable work no member otherwise picks up,
477
490
  because the Shortlist holds ISSUES and nothing looks at inherited PRs. Queue
478
491
  each for review exactly as ticket work: same review workflow, same
479
- fix-applier, same finisher. Measured 2026-09-03 — a prior run's ticket PR
480
- arrived this way and its review found a defect its own PR body called
492
+ fix-applier, same finisher. **Skip a PR a row rotate carried already
493
+ holds** — its `#<pr>` key, or the PR of its `impl-<N>=PR#<pr>` token: that
494
+ row already queues it, and a `ledger.mjs row` write replaces the whole
495
+ line, wiping the live tokens carried on it. Measured 2026-09-03 — a prior
496
+ run's ticket PR arrived this way and its review found a defect its own PR
497
+ body called
481
498
  unreviewed, and a metrics PR's review then caught two metrics rows the
482
499
  controller had missed in its own close-out, so no PR is exempt from being
483
500
  wrong. Reviewing them next run is also what stops one pinning
@@ -486,20 +503,39 @@ phase, or in any later one, asks the maintainer which tickets to take.
486
503
 
487
504
  **Resume the claims a dead run left without a PR — after the fold-in,
488
505
  before shortlisting.** A claim's label and worktree exist before its first
489
- push, and rotation carries no row forward, the candidate scan excludes
490
- `in-progress`, and the in-flight check reads the worktree as taken — so a
506
+ push, and rotation after a dead run carries no row forward, the candidate
507
+ scan excludes `in-progress`, and the in-flight check reads the worktree as
508
+ taken — so a
491
509
  claim the previous run left without a PR is held by nobody until this step
492
510
  names it. `~/.fleet/bin/fleet-run stranded.mjs` lists and classifies; you
493
511
  dispatch. It reads the `prior` rotate just recorded, never the record
494
512
  itself, which names this run's own live controller, and prints
495
- `{prior, claims: [{n, t, action, worktree, branch, why}]}`:
513
+ `{prior, claims: [{n, t, action, worktree, branch, why}], carried: [{name,
514
+ token, row}]}`:
496
515
 
497
516
  - `prior: dead` — every open `in-progress` issue with no open PR (one with
498
517
  an open PR is the fold-in's): `resume` when exactly one worktree for it
499
518
  sits under this checkout's `.worktrees/`, `report` otherwise.
500
- - `prior: ancestor` — this session's own earlier run: nothing is listed.
501
- Its members may still be live, and the Member-killed row's check covers
502
- them.
519
+ - `prior: ancestor` — this session's own earlier run: no claim is listed.
520
+ `carried` lists every live token rotate carried — its member or runner
521
+ `name` (a `review=wf:` launch's runId), the `token` as the ledger holds
522
+ it, and the `row` carrying it, null for a member only `## Dispatched`
523
+ names. Reconcile them before shortlisting: read `proc://` once, find
524
+ each `name` among this session's jobs, and act on its state.
525
+ `running` → keep the token. `completed` or `failed` → record its
526
+ result from `agent://<id>` as the **Record, then tick** table records
527
+ that member's report; an output you cannot read is a death the
528
+ Member-killed row confirms. `cancelled` → record it dead. Absent, or a
529
+ state you cannot read → keep the token live and let the Member-killed
530
+ row clear it: a token nothing confirms dead counts as live. Recording a
531
+ death has two forms, here and on the Member-killed row alike. An
532
+ `impl-`, `fix-pr-`, `finisher-pr-` or `merge-bot-` member is settled:
533
+ `ledger.mjs settle <name> killed`. A reviewer is no member `settle`
534
+ takes — `settle review-pr-<n> killed` exits 2 — so its launch is
535
+ settled `=failed` where it stands: a `ledger.mjs row` rewrite of its row
536
+ that turns `review=member:<name>` into `review=member:<name>=failed`
537
+ (`fallback:` and `wf:` launches alike), after which the tick owes the PR
538
+ a review again under the next free reviewer name.
503
539
  - `prior: none` — no record proves the previous run dead (no record yet, or
504
540
  no `omp` process found above the rotation): every claim is `report`, and
505
541
  nothing is resumed.
@@ -517,8 +553,9 @@ phase, or in any later one, asks the maintainer which tickets to take.
517
553
  `claim-ticket.sh`: the claim already stands. A `report` goes to the
518
554
  maintainer as `#<N> — <why>` and nothing else: no dispatch, no label change,
519
555
  no release. Exit 2 is a list that did not answer — a `gh` or `git`
520
- failure, a list at its cap, or a worktree whose presence cannot be told —
521
- and is never nothing stranded.
556
+ failure, a list at its cap, a worktree whose presence cannot be told, or,
557
+ after `ancestor`, a ledger that cannot be read — and is never nothing
558
+ stranded.
522
559
 
523
560
  1. **Build the Shortlist** — `~/.fleet/bin/fleet-run shortlist.mjs`, then read
524
561
  `.fleet/shortlist.json`. The script runs the cheap filters and nothing else
@@ -1156,6 +1193,18 @@ or `released`, and exit 2 naming the wrong session for any other. Clear a
1156
1193
  mismatch by fixing the definition or the dispatch and dispatching the
1157
1194
  replacement at the right tier.
1158
1195
 
1196
+ **After `/resume`, a carried implementer can hold the whole tick.** A live
1197
+ implementer rotate carried forward with no verdict on its row is unchecked,
1198
+ and once this session has been reopened with `/resume` its transcript sits
1199
+ under the earlier session's directory: the check given this run's `session`
1200
+ finds no `<member>.jsonl` and exits 2, writing nothing. `HOLD (tier unchecked
1201
+ impl-<N>)` then stops the whole tick, not only that member's ticket. It
1202
+ clears once the member settles: one settled `killed` or `released` gets
1203
+ `tier-unverifiable=` from the same check, and one settled any other way ran,
1204
+ so pass the directory that dispatched it, as above. Until it settles,
1205
+ follow the carried token's reconciliation in phase 0: `proc://` reads
1206
+ `running` → wait; dead → the Member-killed row.
1207
+
1159
1208
  **Run the check right after the dispatch, and never reinstall the plugin or
1160
1209
  change `modelRoles` while any member is unchecked.** The check reads the
1161
1210
  installed definition and the live `modelRoles` at check time, not at
@@ -3975,8 +4024,11 @@ map or the filed list redoes finished work. Two duplicate tickets shipped in one
3975
4024
  run from exactly that.
3976
4025
 
3977
4026
  **The file lives one run.** Phase 0 rotates it before anything reads it, so
3978
- no row, exclusion, filing, ruling or drain marker outlives the run that
3979
- wrote it. Never rotate mid-run: it is phase 0's step alone.
4027
+ no exclusion, filing, ruling or drain marker outlives the run that wrote it,
4028
+ and no row does either — except, when the previous run was this session's
4029
+ own, a row still carrying a live token, which rotate carries forward with
4030
+ its live `## Dispatched` entries (phase 0). Never rotate mid-run: it is
4031
+ phase 0's step alone.
3980
4032
 
3981
4033
  One line per ticket, rewritten in place (`ledger.mjs row <ticket> <text>`):
3982
4034
 
@@ -4023,7 +4075,9 @@ live count from it, so nobody states one. Write neither by hand:
4023
4075
  ledger, so the next run's rotation retires it with everything else.
4024
4076
  - **`ledger.mjs rotate`** — phase 0's first ledger write, every run: moves
4025
4077
  the file as-is to `ledger.<UTC YYYY-MM-DDTHHMMSSZ>.md` beside it under the
4026
- same `<file>.lock`, and the next write starts the empty skeleton. Refused
4078
+ same `<file>.lock`, and the next write starts the empty skeleton — unless
4079
+ the previous run was this session's own, when it first writes the rows and
4080
+ `## Dispatched` entries still live into a new ledger (phase 0 says which). Refused
4027
4081
  while the recorded controller is alive and not this run's ancestor, ledger
4028
4082
  or none — or, with no record and a ledger to move, while the heartbeat mark
4029
4083
  is still beating — or when the archive name already exists, the process