@feigi/fleet-ctl 3.155.0 → 3.156.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.
@@ -72,7 +72,7 @@ every other, not a spelling for you to correct.
72
72
  the merge.** A deferral of a finding in the review's result is not yours to
73
73
  re-judge when the PR's latest review counted a survived or unverified finding:
74
74
  `ledger.mjs dispatch` then dispatched you only once the PR's ledger row held a
75
- `dispositions-ok` verdict from `dispositions-check.mjs` on that review
75
+ `dispositions-ok` verdict from `ledger.mjs dispositions` on that review
76
76
  (`dispositionsRefusal`), and that check had already read back where the
77
77
  fix-applier's disposition record says each deferral was filed. That verdict is
78
78
  the judgement of those homes: do not halt on a home the script accepted, and
@@ -25,7 +25,7 @@ Label names in this file are roles; the Label map gives the string to type; a me
25
25
  5. File each deferred finding: `gh issue create --label "<needs-triage string>"` 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 body also carries the evidence triage needs: the refuter's verdict — the `verdictPath` reason, or the review's votes — and the candidate remedy.** **Every issue you create is labelled `needs-triage`; only triage sets `ready-for-agent`** — and the label 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. **A confirmed defect does not settle its remedy**, so confirming one earns it no other label: a confirmed defect with the remedy still open files `needs-triage`, and so does a finding you are unsure is broken at all. **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`, filed with `gh issue create --label "<wontfix string>"` and then CLOSED** — left open they read as queued agent work. Closed is still a durable home — `check` reads the tracker at `--state all`, so a later run re-deriving the finding lands on the evidence. Split the band only where an entry is **not** a refutation: a residual the refuter surfaced, or an out-of-scope finding its refuter let survive or never decided, 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. 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, 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, `needs-triage`, which is why a band cannot carry this decision. Do **not** reach for phase 0's **decided?** test here. That is a *consumption* gate, and whether a filed issue is decided enough to reach it is triage's call, never the filer's. **The cost of this rule is watched:** open `needs-triage` issues citing `Deferred from PR` above 40 on 3 consecutive run dates send the filing rule back to the maintainer — batch triage, a fleet triage role, or a different bar. **Dedupe through `~/.omp/plugins/node_modules/@feigi/fleet-ctl/scripts/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*. `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 `~/.omp/plugins/node_modules/@feigi/fleet-ctl/skills/run-team/references/ledger.md`, which `SKILL.md`'s wake section points at — 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 `~/.omp/plugins/node_modules/@feigi/fleet-ctl/scripts/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.
26
26
  **A duplicate that should hold an open deferral is a comment, never a relabel.** Where the guard lands a finding whose home is an open issue on an existing one that is open, cite the refuters' verdict — or the review's votes — in the comment you leave there, and change no label. Never relabel `ready-for-agent` down to `needs-triage`: a `ready-for-agent` issue already holds a `needs-triage` finding, because triage already promoted it, and a later run's crashed refuters are no reason to send it back. A closed one cannot hold it: file a new open issue citing it, as the promotion rule above does for the closed record.
27
27
  **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 `PR #<pr> review: the suggestion band, checked` record included. A `suggestion`'s entry — an `unverified` finding with `refutersDispatched` of zero — also carries `verdictPath`, applied or deferred, in scope and, above the claim bar, out of scope: 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. An out-of-scope one whose refuter crashed before any verdict reached you still names the path its verdict would have taken there; out of scope, that file missing or holding no decision files the finding open `needs-triage`, while in scope it is a mismatch. `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.
28
- 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` only to a dependabot or renovate PR that has none, and hard-fails any PR with none or 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. The prefix `ready-to-merge-head:` is not a label: type it as written, whatever string the Label map gives `ready-to-merge`. Then `gh pr edit <pr> --add-label "<ready-to-merge string>"`. 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 `~/.omp/plugins/node_modules/@feigi/fleet-ctl/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.
28
+ 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` only to a dependabot or renovate PR that has none, and hard-fails any PR with none or 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 whenever a ledger exists; under the fleet the verdict is `ledger.mjs dispositions`'s, and `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. The prefix `ready-to-merge-head:` is not a label: type it as written, whatever string the Label map gives `ready-to-merge`. Then `gh pr edit <pr> --add-label "<ready-to-merge string>"`. 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 `~/.omp/plugins/node_modules/@feigi/fleet-ctl/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.
29
29
 
30
30
  **`verdict: "no-ci"` — this repo has no `check` job to gate on at all**, and that is a different state from red or unknown, not a third way to skip the wait. Label off step 3's own green `testCmd` run instead of a `check` job that will never exist — and only once `ci-state.mjs` reads `no-ci` **without** the flag, since a repo whose CI is merely misconfigured exits 2 there rather than reading no-ci. `--declare-no-ci` is your caller-side declaration that step 3's run **is** this repo's gate: it flips the exit code and echoes itself into `reasons`, so finding it in the payload confirms only that you passed it, never that anyone verified anything. **No green `testCmd` run on record → do not label.** Say in your verdict that the repo has no CI configured and no declaration, and stop — inferring a pass from silence here is exactly the misconfigured-CI case the declaration exists to rule out.
31
31
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@feigi/fleet-ctl",
3
- "version": "3.155.0",
3
+ "version": "3.156.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": {
@@ -4,10 +4,10 @@
4
4
  // fix-applier writes its record to `<scratch>/dispositions-fix-pr-<M>[-x].json`,
5
5
  // one file per fix-applier; the review result file it answers is
6
6
  // `<scratch>/pr<M>/<run>/review.json`, `<run>` the run root the PR's latest
7
- // `reviewed=<head>:<survived>/<refuted>/<unverified>:<run>` names. This
8
- // script reads the two together, judges the record, and writes its verdict
9
- // onto the PR's ledger row as a token `ledger.mjs dispatch` gates the PR's
10
- // finisher on:
7
+ // `reviewed=<head>:<survived>/<refuted>/<unverified>:<run>` names. This module
8
+ // reads the two together and judges the record; `ledger.mjs dispositions`
9
+ // runs that judgement and writes its verdict onto the PR's ledger row as a
10
+ // token `ledger.mjs dispatch` gates the PR's finisher on:
11
11
  //
12
12
  // dispositions-ok=fix-pr-<M>[-x]:<run> every rule below held
13
13
  // dispositions-mismatch=fix-pr-<M>[-x]:<run> at least one entry broke one
@@ -21,8 +21,8 @@
21
21
  // filed could not be read
22
22
  // escalation-answer=<run>:<bucket>[<index>]:upheld|sent-back
23
23
  // the maintainer's answer to one escalated
24
- // finding, written by --uphold and
25
- // --send-back and by nothing else
24
+ // finding, written by the verb's --uphold
25
+ // and --send-back and by nothing else
26
26
  //
27
27
  // `<run>` is the review's own run, so a verdict on one review never answers
28
28
  // a later one — a second review at the same head included.
@@ -159,13 +159,14 @@
159
159
  // that entry's filing unjudged. With no rule broken and nothing escalated the
160
160
  // verdict is `unchecked`, which `ledger.mjs dispatch` refuses a finisher on —
161
161
  // never ok, and never a mismatch, since the record broke nothing. Run the
162
- // check again once `gh` answers.
162
+ // verb again once `gh` answers.
163
163
  //
164
164
  // Escalation answers: the maintainer answers an escalated finding `upheld` —
165
165
  // the deferral stands — or `sent-back` — the finding is applied in this PR.
166
- // `--uphold <list>` and `--send-back <list>`, each a comma-separated list of
167
- // `<bucket>[<index>]` as the output prints it, record the answers for the
168
- // escalated member, `--member fix-pr-<M>[-x]`, in one write that adds
166
+ // `ledger.mjs dispositions <member> --scratch <dir>` takes `--uphold <list>`
167
+ // and `--send-back <list>`, each a comma-separated list of `<bucket>[<index>]`
168
+ // as the output prints it, and records the answers for the escalated member,
169
+ // `fix-pr-<M>[-x]`, in one write that adds
169
170
  // `escalation-answer=<run>:<bucket>[<index>]:upheld|sent-back` per finding to
170
171
  // the PR's row and replaces the escalate with the verdict the record then
171
172
  // earns: `ok` — `unchecked` when a filing could not be read — with every
@@ -177,11 +178,11 @@
177
178
  // Every record judged against a review reads that review's answers off the
178
179
  // PR's rows, whether or not the run records any: an upheld finding is no
179
180
  // escalation, and an entry that defers a sent-back finding is a violation
180
- // whatever its reason. Running the check again with no answer flags therefore
181
+ // whatever its reason. Running the verb again with no answer flags therefore
181
182
  // reproduces the verdict and its violations.
182
183
  //
183
- // A run that records answers refuses — exit 2, the cause named, the ledger
184
- // byte-identical — unless: a ledger is in use; the PR's current dispositions
184
+ // A run that records answers refuses — nothing judged, the ledger
185
+ // byte-identical — unless: the PR's current dispositions
185
186
  // verdict on its latest review is an escalate naming the member; no
186
187
  // fix-applier on the PR is live; the record, judged with the answers already
187
188
  // on the row, breaks no rule; every listed finding is one the record escalates,
@@ -189,35 +190,32 @@
189
190
  // answer. A record that breaks a rule has no outside-diff escalate to answer:
190
191
  // a second failure on one review clears only with a new review.
191
192
  //
192
- // Exit status: 0 ok; 1 mismatch, escalate or unchecked; 2 nothing judged and
193
- // nothing written — a bad flag, an answer the run refuses to record, no valid
194
- // Label map (the message names `label-map.mjs ensure`), an unreadable or
195
- // malformed review file, a record file that exists but cannot be read, a git
196
- // or ledger failure. A missing or unparseable RECORD is judged, not refused:
197
- // the fix-applier wrote nothing a reader can use, so every finding it had to
198
- // cover is dropped.
193
+ // Who writes what. This module is the judgement, and writes nothing.
194
+ // `ledger.mjs dispositions` runs judgeMember() in-process over the ledger it
195
+ // loaded and is the only writer of a dispositions verdict and of an
196
+ // escalation answer: its exit status is 0 for `ok`, 1 for `mismatch`,
197
+ // `escalate` or `unchecked` — a verdict, written — and 2 for nothing judged
198
+ // and nothing written, which is a bad flag, an answer the run refuses to
199
+ // record, no valid Label map (the message names `label-map.mjs ensure`), an
200
+ // unreadable or malformed review file, a record file that exists but cannot
201
+ // be read, a git or ledger failure. A missing or unparseable RECORD is judged,
202
+ // not refused: the fix-applier wrote nothing a reader can use, so every
203
+ // finding it had to cover is dropped.
199
204
  //
200
- // Without a ledger the record is judged all the same and the exit status is
201
- // the whole verdict: no token is written, no row is read, and `token` in the
202
- // stdout payload is null. That is the shape of a standalone `/review-and-fix`
203
- // with no controller, chosen by `--no-ledger` or by a ledger path that does
204
- // not exist. With no `reviewed=` to name the review, `--review <path>` names
205
- // its file, and is required; with a ledger it is refused, since the ledger
206
- // already names one.
207
- // A repository's `.fleet/ledger.md` outlives the fleet run that wrote it, so a
208
- // standalone member in a worktree of such a repository would otherwise find
209
- // the previous run's ledger, and a ledger that exists is never skipped: one
210
- // holding no row for the member is a fault (exit 2), as is a ledger path that
211
- // cannot be looked up (a parent that is a file, no permission, a symlink loop).
212
- // Only a path that does not exist is "no ledger": the default path, or one
213
- // `--ledger` names, which also prints a note on stderr that no token was
214
- // written. `--no-ledger` names that state outright: no ledger is looked for,
215
- // whatever the repository holds, and it contradicts `--ledger`.
205
+ // This script is the standalone check, a `/review-and-fix` with no
206
+ // controller: `--no-ledger --review <path>` names the review's file, and the
207
+ // record is judged all the same, the exit status the whole verdict — 0 ok,
208
+ // 1 anything else, 2 nothing judged — with no token written and `token` in the
209
+ // stdout payload null. A repository's `.fleet/ledger.md` outlives the fleet
210
+ // run that wrote it, so a ledger at the default path that exists is never
211
+ // skipped: without `--no-ledger` it is a refusal (exit 2) naming the verb.
212
+ // Only a path that does not exist is "no ledger", and `--no-ledger` names
213
+ // that state outright: no ledger is looked for, whatever the repository
214
+ // holds. `--ledger`, `--uphold` and `--send-back` are the verb's and refused.
216
215
 
217
216
  import { readFileSync, existsSync, lstatSync, realpathSync, statSync } from "node:fs";
218
217
  import { execFileSync } from "node:child_process";
219
218
  import { join, dirname, basename, isAbsolute, relative, posix, sep } from "node:path";
220
- import { fileURLToPath } from "node:url";
221
219
  import { makeDie, defineFlags } from "./arg.mjs";
222
220
  import { isCLI } from "./is-cli.mjs";
223
221
  import { gitEnv } from "./git-env.mjs";
@@ -228,8 +226,6 @@ import { deriveRun, LedgerError } from "./fleet-tick.mjs";
228
226
  import { VERDICT_SCHEMA } from "./review-core.mjs";
229
227
 
230
228
  const NAME = "dispositions-check";
231
- const SCRIPT_DIR = dirname(fileURLToPath(import.meta.url));
232
- const LEDGER_SCRIPT = join(SCRIPT_DIR, "ledger.mjs");
233
229
 
234
230
  // Two spellings of one commit: either head a prefix of the other, the way a
235
231
  // record's head (7-40 hex) is matched against its review's full head.
@@ -731,13 +727,21 @@ export function failedBefore(rows, pr, member, run) {
731
727
  }
732
728
 
733
729
  // ---------------------------------------------------------------------------
734
- // CLI
730
+ // the judgement over a ledger snapshot, and the standalone CLI
735
731
  // ---------------------------------------------------------------------------
736
732
 
737
- const die = makeDie(NAME);
738
- const { arg, has, sweep, stray } = defineFlags(die, {
739
- flags: { member: "value", scratch: "value", repo: "value", ledger: "value", "no-ledger": "bool", review: "value", uphold: "value", "send-back": "value" },
740
- });
733
+ /** Nothing judged and nothing written: the cause is the message. */
734
+ export class CheckRefusal extends Error {}
735
+ const refuse = (message) => {
736
+ throw new CheckRefusal(message);
737
+ };
738
+
739
+ /** The parsed fix-applier `name` names, or a CheckRefusal. */
740
+ function parseFixApplier(name) {
741
+ const member = parseMember(name);
742
+ if (member === null || member.family !== "fix-pr") refuse(`'${name}' is not a fix-applier — expected fix-pr-<M>, a -b, -c … suffix allowed`);
743
+ return member;
744
+ }
741
745
 
742
746
  // The one git primitive. An ambient GIT_DIR or GIT_WORK_TREE — a hook, a
743
747
  // `rebase --exec` — would answer for another repository and judge the record
@@ -748,15 +752,7 @@ function git(repo, args, what) {
748
752
  encoding: "utf8", env: gitEnv({ LC_ALL: "C" }), maxBuffer: 256 * 1024 * 1024, stdio: ["ignore", "pipe", "pipe"],
749
753
  });
750
754
  } catch (e) {
751
- die(`could not ${what}: ${e.stderr?.toString().trim() || e.message}`);
752
- }
753
- }
754
-
755
- function runLedger(ledgerFile, args, what) {
756
- try {
757
- return execFileSync(process.execPath, [LEDGER_SCRIPT, "--file", ledgerFile, ...args], { encoding: "utf8" });
758
- } catch (e) {
759
- die(`could not ${what}: ${e.stderr?.trim() || e.message}`);
755
+ refuse(`could not ${what}: ${e.stderr?.toString().trim() || e.message}`);
760
756
  }
761
757
  }
762
758
 
@@ -845,36 +841,27 @@ function verdictReader(scratch, pr) {
845
841
  };
846
842
  }
847
843
 
848
- // The ledger file this run writes its verdict to, or null when there is none:
849
- // `--ledger`, else the run's `.fleet/ledger.md` resolved from `repo` by
850
- // fleet-dir.mjs's fleetFile() — the workspace every worktree of one
851
- // repository shares, which is where `ledger.mjs dispatch` wrote the member's
852
- // row. The path is handed to `ledger.mjs` as `--file`, so the existence probe
853
- // and the calls that follow answer for one file. Only ENOENT means "there is
854
- // none": any other failure to look the path up is a fault, not a standalone
855
- // run. An absent path named by `--ledger` is announced on stderr; an absent
856
- // default path is not.
857
- // `lstat`, not `stat`, so a dangling symlink is a ledger that cannot be read
858
- // rather than an absent one.
859
- function ledgerInUse(explicit, repo) {
860
- let file = explicit;
861
- if (file == null) {
862
- try {
863
- file = fleetFile("ledger.md", { cwd: repo });
864
- } catch (e) {
865
- if (!(e instanceof FleetDirUnresolvable)) throw e;
866
- die(e.message);
867
- }
844
+ // The ledger file the repository's default path names, or null when there is
845
+ // none: the run's `.fleet/ledger.md` resolved from `repo` by fleet-dir.mjs's
846
+ // fleetFile() — the workspace every worktree of one repository shares, which
847
+ // is where `ledger.mjs dispatch` wrote the member's row. Only ENOENT means
848
+ // "there is none": any other failure to look the path up is a fault, not a
849
+ // standalone run. `lstat`, not `stat`, so a dangling symlink is a ledger that
850
+ // cannot be read rather than an absent one.
851
+ function defaultLedger(repo) {
852
+ let file;
853
+ try {
854
+ file = fleetFile("ledger.md", { cwd: repo });
855
+ } catch (e) {
856
+ if (!(e instanceof FleetDirUnresolvable)) throw e;
857
+ refuse(e.message);
868
858
  }
869
859
  try {
870
860
  lstatSync(file);
871
861
  return file;
872
862
  } catch (e) {
873
- if (e.code === "ENOENT") {
874
- if (explicit !== null) console.error(`${NAME}: no ledger at ${file} (named by --ledger) — judged with no ledger, so no token was written; pass --no-ledger to choose that`);
875
- return null;
876
- }
877
- die(`could not look for the ledger ${file}: ${e.message}`);
863
+ if (e.code === "ENOENT") return null;
864
+ refuse(`could not look for the ledger ${file}: ${e.message}`);
878
865
  }
879
866
  }
880
867
 
@@ -886,111 +873,124 @@ function readJson(path) {
886
873
  // that bucket of the review file.
887
874
  const ADDRESS = new RegExp(`^(${BUCKETS.join("|")})\\[(0|[1-9][0-9]*)\\]$`);
888
875
 
889
- // The findings a `--uphold` or `--send-back` list names, each `<bucket>[<index>]`
890
- // — or null when the flag is absent. A second occurrence of the flag would be
891
- // read by nothing, so it is refused rather than dropped.
892
- function addressList(flag) {
893
- const raw = arg(flag);
876
+ /** The findings a `--uphold` or `--send-back` list `raw` names, each
877
+ * `<bucket>[<index>]`, or null when the flag is absent. */
878
+ function addressList(flag, raw) {
894
879
  if (raw === null) return null;
895
- if (process.argv.filter((a) => a === `--${flag}`).length > 1) die(`--${flag} is given twice — name every finding in one comma-separated list`);
896
880
  const list = raw.split(",").map((a) => a.trim());
897
881
  const bad = list.find((a) => !ADDRESS.test(a));
898
- if (bad !== undefined) die(`--${flag} names ${JSON.stringify(bad)}, which is no <bucket>[<index>] — a bucket is ${BUCKETS.join(", ")}, an index a whole number from 0`);
882
+ if (bad !== undefined) refuse(`--${flag} names ${JSON.stringify(bad)}, which is no <bucket>[<index>] — a bucket is ${BUCKETS.join(", ")}, an index a whole number from 0`);
899
883
  return list;
900
884
  }
901
885
 
886
+ /** The maintainer's answers the raw `--uphold` and `--send-back` lists give
887
+ * (null for an absent flag), a Map from a finding's address to `upheld` or
888
+ * `sent-back`; an address that is none, or a finding listed twice or both
889
+ * ways, is refused. Told before anything is read, since a list that cannot
890
+ * be one is a usage error. */
891
+ export function answerMap(upholdRaw, sendBackRaw) {
892
+ const [uphold, sendBack] = [addressList("uphold", upholdRaw), addressList("send-back", sendBackRaw)];
893
+ const listed = new Map();
894
+ for (const [flag, list, answer] of [["--uphold", uphold, "upheld"], ["--send-back", sendBack, "sent-back"]]) {
895
+ for (const a of list ?? []) {
896
+ if (listed.has(a)) refuse(listed.get(a) === answer ? `${flag} lists ${a} twice` : `${a} is listed in both --uphold and --send-back — a finding is answered one way`);
897
+ listed.set(a, answer);
898
+ }
899
+ }
900
+ return listed;
901
+ }
902
+
902
903
  // Addresses in the record's own order: by bucket, then by index.
903
904
  const byAddress = (a, b) => {
904
905
  const [x, y] = [a, b].map((s) => ADDRESS.exec(s));
905
906
  return BUCKETS.indexOf(x[1]) - BUCKETS.indexOf(y[1]) || Number(x[2]) - Number(y[2]);
906
907
  };
907
908
 
908
- function main() {
909
- const usage = "usage: dispositions-check.mjs --member fix-pr-<M>[-x] --scratch <dir> [--repo <path>] [--ledger <path> | --no-ledger --review <path>] [--uphold <list>] [--send-back <list>]";
910
- const name = arg("member");
911
- const scratch = arg("scratch");
912
- if (!name || !scratch) die(usage);
913
- sweep();
914
- stray();
915
- const member = parseMember(name);
916
- if (member === null || member.family !== "fix-pr") die(`'${name}' is not a fix-applier — expected fix-pr-<M>, a -b, -c … suffix allowed`);
917
- const pr = member.number;
918
- const repo = arg("repo") ?? process.cwd();
919
- // The maintainer's answers, when this run records them: `--uphold` and
920
- // `--send-back`, each a list of the escalated findings answered that way.
921
- // Told before anything is read, since a list that cannot be one is a usage error.
922
- const uphold = addressList("uphold");
923
- const sendBack = addressList("send-back");
924
- const listed = new Map();
925
- for (const [flag, list, answer] of [["--uphold", uphold, "upheld"], ["--send-back", sendBack, "sent-back"]]) {
926
- for (const a of list ?? []) {
927
- if (listed.has(a)) die(listed.get(a) === answer ? `${flag} lists ${a} twice` : `${a} is listed in both --uphold and --send-back — a finding is answered one way`);
928
- listed.set(a, answer);
909
+ /**
910
+ * PR `pr`'s latest review on `ledger` (`{rows, dispatched, drain}`), as
911
+ * fleet-tick.mjs's deriveRun folds it — the fold `ledger.mjs dispatch` gates
912
+ * the finisher by. With `answering`, it also holds what recording the
913
+ * maintainer's answers needs: the PR's current verdict on that review is an
914
+ * escalate from fix-applier `memberName`, and no fix-applier on the PR is
915
+ * live. `ledger.mjs dispositions` asks again under its lock, against the
916
+ * ledger as it stands then, so two answer runs that read the same escalate
917
+ * cannot both write. Throws a CheckRefusal otherwise.
918
+ */
919
+ export function latestReview(ledger, pr, memberName, answering) {
920
+ let latest;
921
+ try {
922
+ latest = deriveRun({ rows: ledger.rows, dispatched: ledger.dispatched, drain: ledger.drain }, []).reviewed.find((r) => r.pr === pr);
923
+ } catch (e) {
924
+ if (!(e instanceof LedgerError)) throw e;
925
+ refuse(`${e.message} — fleet-tick.mjs refuses this ledger, so PR #${pr}'s latest review cannot be read off it`);
926
+ }
927
+ if (latest === undefined) refuse(`PR #${pr} has no reviewed= on the ledger — no review for ${memberName}'s record to answer`);
928
+ // Answers clear the escalate they answer and nothing else: the PR's current
929
+ // verdict on this review must be that escalate, and no fix-applier on the PR
930
+ // may be working — its landing would answer the review in its own right.
931
+ if (answering) {
932
+ const current = latest.dispositions;
933
+ if (current === null || current.verdict !== "escalate" || current.member !== memberName) {
934
+ refuse(`PR #${pr}'s current dispositions verdict on review ${latest.run} is ${current === null ? "none" : `${current.verdict} from ${current.member}`}, not an escalate from ${memberName} — escalation answers clear the escalate they answer, and nothing else`);
935
+ }
936
+ if (latest.fixLive.length > 0) {
937
+ refuse(`${latest.fixLive.join(", ")} still live on PR #${pr} — a fix-applier answering review ${latest.run} has not settled, so the answers wait: settle it, then record them`);
929
938
  }
930
939
  }
940
+ return latest;
941
+ }
942
+
943
+ /**
944
+ * Fix-applier `name`'s record judged against the review it answers.
945
+ * `ledger` is the snapshot to judge against, `{rows, dispatched, drain}` as
946
+ * `ledger.mjs read` prints them, or null for a standalone check, which names
947
+ * its review with `reviewPath`. `listed` is the maintainer's answers to
948
+ * record (answerMap()), empty when this run records none, and non-empty only
949
+ * with a `ledger`, the row they are recorded on. Never writes a
950
+ * ledger: the caller does, and learns what to write from the result,
951
+ * `{member, pr, head, verdict, token, violations, escalations, unchecked,
952
+ * run, recorded, secondMismatch}` — `token` null with no ledger, `recorded`
953
+ * the `[address, answer]` pairs this run records.
954
+ *
955
+ * A CheckRefusal is nothing judged: a bad flag, an answer the run refuses to
956
+ * record, no valid Label map (the message names `label-map.mjs ensure`), an
957
+ * unreadable or malformed review file, a record file that exists but cannot
958
+ * be read, a git or ledger failure. A missing or unparseable RECORD is judged,
959
+ * not refused: the fix-applier wrote nothing a reader can use, so every
960
+ * finding it had to cover is dropped.
961
+ */
962
+ export function judgeMember({ name, scratch, repo, ledger = null, reviewPath = null, listed = new Map() }) {
963
+ const member = parseFixApplier(name);
964
+ const pr = member.number;
931
965
  const recording = listed.size > 0;
932
- const standalone = has("no-ledger");
933
- if (standalone && arg("ledger") !== null) die("--no-ledger and --ledger contradict: name one");
934
- const ledgerFile = standalone ? null : ledgerInUse(arg("ledger"), repo);
935
- if (recording && ledgerFile === null) {
936
- die(`${uphold !== null ? "--uphold" : "--send-back"} records the maintainer's answer on the ledger row, and no ledger is in use — run it for the escalated member where the run's ledger is`);
937
- }
938
- // Without a ledger nothing names the review the record answers, so `--review`
939
- // must; with one, the latest `reviewed=` already does. Both are usage errors,
940
- // so they are told before the Label map, the ledger or the tracker is read.
941
- if (ledgerFile === null && arg("review") === null) die(`no ledger names PR #${pr}'s review — pass --review <path> for the review file ${member.name}'s record answers`);
942
- if (ledgerFile !== null && arg("review") !== null) die(`--review and a ledger contradict: with a ledger the review is the one PR #${pr}'s latest reviewed= names`);
943
- // The Label map, read once, here at the I/O boundary — after the flags and the
944
- // ledger's location are settled, before the ledger or the tracker is read: a
945
- // home's labels are compared and worded in the tracker's own spelling. No
946
- // valid map is "nothing judged" (exit 2), never a verdict; the reader's
947
- // message names `ensure`.
966
+ // The Label map, read once, here at the I/O boundary — before the ledger or
967
+ // the tracker is read: a home's labels are compared and worded in the
968
+ // tracker's own spelling. No valid map is "nothing judged", never a verdict;
969
+ // the reader's message names `ensure`.
948
970
  let roles;
949
971
  try {
950
972
  roles = readLabelMap({ cwd: repo });
951
973
  } catch (e) {
952
- die(e.message);
974
+ refuse(e.message);
953
975
  }
954
976
 
955
977
  // The review the record answers. With a ledger it is the one PR M's latest
956
978
  // `reviewed=` names — `<scratch>/pr<M>/<run>/review.json`, read off the
957
979
  // same per-PR fold `ledger.mjs dispatch` gates the finisher by, so the check
958
980
  // and the gate never judge two different reviews. Without one it is the
959
- // `--review` path the checks above required.
960
- let data = null, row = null, run = null, charges = false, reviewPath, answers = new Map();
961
- if (ledgerFile === null) {
962
- reviewPath = arg("review");
963
- } else {
964
- data = JSON.parse(runLedger(ledgerFile, ["read"], "read the ledger"));
981
+ // `reviewPath` the caller named.
982
+ let run = null, charges = false, answers = new Map();
983
+ if (ledger !== null) {
965
984
  // The verdict lands on the row carrying the member on its own PR's row —
966
985
  // where `ledger.mjs dispatch` wrote it, and where the gate reads PR M's
967
986
  // tokens from.
968
- row = data.rows.find((r) => rowNums(r).pr === pr && memberTokens(r).some((t) => t.name === member.name));
969
- if (row === undefined) die(`${member.name} is on no row of PR #${pr} — \`ledger.mjs dispatch\` records a fix-applier before its record can be checked; with no controller, pass --no-ledger`);
970
- let latest;
971
- try {
972
- latest = deriveRun({ rows: data.rows, dispatched: data.dispatched, drain: data.drain }, []).reviewed.find((r) => r.pr === pr);
973
- } catch (e) {
974
- if (!(e instanceof LedgerError)) throw e;
975
- die(`${e.message} — fleet-tick.mjs refuses this ledger, so PR #${pr}'s latest review cannot be read off it`);
976
- }
977
- if (latest === undefined) die(`PR #${pr} has no reviewed= on the ledger — no review for ${member.name}'s record to answer`);
978
- run = latest.run;
979
- // Answers clear the escalate they answer and nothing else: the PR's current
980
- // verdict on this review must be that escalate, and no fix-applier on the PR
981
- // may be working — its landing would answer the review in its own right.
982
- if (recording) {
983
- const current = latest.dispositions;
984
- if (current === null || current.verdict !== "escalate" || current.member !== member.name) {
985
- die(`PR #${pr}'s current dispositions verdict on review ${run} is ${current === null ? "none" : `${current.verdict} from ${current.member}`}, not an escalate from ${member.name} — escalation answers clear the escalate they answer, and nothing else`);
986
- }
987
- if (latest.fixLive.length > 0) {
988
- die(`${latest.fixLive.join(", ")} still live on PR #${pr} — a fix-applier answering review ${run} has not settled, so the answers wait: settle it, then record them`);
989
- }
987
+ if (!ledger.rows.some((r) => rowNums(r).pr === pr && memberTokens(r).some((t) => t.name === member.name))) {
988
+ refuse(`${member.name} is on no row of PR #${pr} — \`ledger.mjs dispatch\` records a fix-applier before its record can be checked; with no controller, run dispositions-check.mjs with --no-ledger --review <path>`);
990
989
  }
990
+ run = latestReview(ledger, pr, member.name, recording).run;
991
991
  // Every record judged against this review reads the answers recorded for it.
992
992
  // A token that only looks like one answers nothing, and says so.
993
- const tokens = prTokens(data.rows, pr);
993
+ const tokens = prTokens(ledger.rows, pr);
994
994
  answers = escalationAnswers(tokens, run);
995
995
  for (const t of tokens) {
996
996
  if (t.startsWith("escalation-answer=") && escalationAnswerToken(t) === null) {
@@ -1006,10 +1006,10 @@ function main() {
1006
1006
  try {
1007
1007
  review = readJson(reviewPath);
1008
1008
  } catch (e) {
1009
- die(`could not read the review file ${reviewPath}: ${e.message}`);
1009
+ refuse(`could not read the review file ${reviewPath}: ${e.message}`);
1010
1010
  }
1011
1011
  const problem = reviewProblem(review);
1012
- if (problem !== null) die(`${reviewPath} ${problem}`);
1012
+ if (problem !== null) refuse(`${reviewPath} ${problem}`);
1013
1013
  const head = String(review.head).toLowerCase();
1014
1014
 
1015
1015
  // One record per fix-applier: a retry, or a fix-applier answering a later
@@ -1027,7 +1027,7 @@ function main() {
1027
1027
  try {
1028
1028
  text = readFileSync(recordPath, "utf8");
1029
1029
  } catch (e) {
1030
- die(`could not read the disposition record ${recordPath}: ${e.message}`);
1030
+ refuse(`could not read the disposition record ${recordPath}: ${e.message}`);
1031
1031
  }
1032
1032
  try {
1033
1033
  record = JSON.parse(text);
@@ -1059,62 +1059,94 @@ function main() {
1059
1059
  // escalate, or an escalated one left unanswered, makes an answer that
1060
1060
  // settles nothing.
1061
1061
  if (judged.violations.length > 0) {
1062
- die(`${member.name}'s record breaks a rule, so its escalate is no outside-diff one: the maintainer's answers clear an escalate whose record breaks none. A broken rule is a mismatch, and after an earlier failure on review ${run} a second failure, which only a new review of the PR clears — run the check without --uphold and --send-back to judge it. It breaks:\n`
1062
+ refuse(`${member.name}'s record breaks a rule, so its escalate is no outside-diff one: the maintainer's answers clear an escalate whose record breaks none. A broken rule is a mismatch, and after an earlier failure on review ${run} a second failure, which only a new review of the PR clears — run \`ledger.mjs dispositions ${member.name} --scratch <scratch>\` without --uphold and --send-back to judge it. It breaks:\n`
1063
1063
  + judged.violations.map((v) => ` ${member.name}: ${formatViolation(v)}`).join("\n"));
1064
1064
  }
1065
1065
  const open = judged.escalations.map((x) => `${x.bucket}[${x.index}]`).sort(byAddress);
1066
1066
  for (const a of [...listed.keys()].sort(byAddress)) {
1067
- if (!open.includes(a)) die(`${a} is not one of ${member.name}'s escalated findings${open.length > 0 ? ` (${open.join(", ")})` : " — its record escalates none"}`);
1067
+ if (!open.includes(a)) refuse(`${a} is not one of ${member.name}'s escalated findings${open.length > 0 ? ` (${open.join(", ")})` : " — its record escalates none"}`);
1068
1068
  }
1069
1069
  const unanswered = open.filter((a) => !listed.has(a));
1070
1070
  if (unanswered.length > 0) {
1071
- die(`${member.name}'s record escalates ${open.join(", ")}, and ${unanswered.join(", ")} ${unanswered.length === 1 ? "has" : "have"} no answer — every escalated finding is answered in one run, with --uphold or --send-back`);
1071
+ refuse(`${member.name}'s record escalates ${open.join(", ")}, and ${unanswered.join(", ")} ${unanswered.length === 1 ? "has" : "have"} no answer — every escalated finding is answered in one run, with --uphold or --send-back`);
1072
1072
  }
1073
1073
  answers = new Map([...answers, ...listed]);
1074
1074
  judged = judge(answers);
1075
1075
  recorded = open.map((a) => [a, listed.get(a)]);
1076
1076
  }
1077
1077
  const { violations, escalations, unchecked } = judged;
1078
- // No ledger, no row: the exit status below is the verdict, and with no
1079
- // earlier fix-applier's verdict to count, a broken rule is always a
1080
- // mismatch.
1078
+ // No ledger, no row: the exit status is the verdict, and with no earlier
1079
+ // fix-applier's verdict to count, a broken rule is always a mismatch.
1081
1080
  // A mismatch an earlier fix-applier already drew on this review makes this
1082
1081
  // one the second: it is written as an escalate, which only a new review of
1083
1082
  // the PR clears. A finding the maintainer sent back counts as a broken rule
1084
1083
  // like any other, here and in failedBefore(). A broken rule outranks an
1085
1084
  // escalation, and an escalation a filing the tracker could not answer.
1086
- const secondMismatch = violations.length > 0 && data !== null && failedBefore(data.rows, pr, member, run);
1085
+ const secondMismatch = violations.length > 0 && ledger !== null && failedBefore(ledger.rows, pr, member, run);
1087
1086
  const verdict = violations.length > 0 ? (secondMismatch ? "escalate" : "mismatch")
1088
1087
  : escalations.length > 0 ? "escalate" : unchecked.length > 0 ? "unchecked" : "ok";
1089
- const token = data === null ? null : `dispositions-${verdict}=${member.name}:${run}`;
1088
+ const token = ledger === null ? null : `dispositions-${verdict}=${member.name}:${run}`;
1089
+ return { member: member.name, pr, head, verdict, token, violations, escalations, unchecked, run, recorded, secondMismatch };
1090
+ }
1090
1091
 
1091
- if (data !== null) {
1092
- const key = row.split(/\s/)[0];
1093
- if (!/^#[0-9]+$/.test(key)) die(`the row carrying ${member.name} has no #<n> key for \`ledger.mjs row\` to rewrite it by: ${row}`);
1094
- const text = row.slice(key.length).trim();
1095
- const answerTokens = recorded.map(([a, answer]) => `escalation-answer=${run}:${a}:${answer}`);
1096
- const updated = withVerdict([text, ...answerTokens].join(" · "), token);
1097
- if (updated === text) console.error(` ${member.name}: row ${key} already carries ${token} — not written again`);
1098
- else runLedger(ledgerFile, ["row", key, updated], `write ${recorded.length > 0 ? `the escalation answers and ${token}` : token} onto row ${key}`);
1099
- }
1092
+ /** What a judgement prints: the stderr lines a reader acts on, then the
1093
+ * stdout payload `{member, pr, head, verdict, token, violations, escalations,
1094
+ * unchecked}`. The exit status is the verdict's: 0 ok, 1 anything else. */
1095
+ export function printVerdict({ member, pr, head, verdict, token, violations, escalations, unchecked, run, recorded, secondMismatch }) {
1100
1096
  if (recorded.length > 0) {
1101
- console.error(`${member.name}: recorded the maintainer's escalation answers on review ${run} — ${recorded.map(([a, answer]) => `${a} ${answer === "sent-back" ? "sent back" : answer}`).join(", ")}`);
1097
+ console.error(`${member}: recorded the maintainer's escalation answers on review ${run} — ${recorded.map(([a, answer]) => `${a} ${answer === "sent-back" ? "sent back" : answer}`).join(", ")}`);
1102
1098
  }
1103
-
1104
- for (const v of violations) console.error(`${member.name}: ${formatViolation(v)}`);
1105
- for (const x of escalations) console.error(`${member.name}: ${formatEscalation(x)}`);
1099
+ for (const v of violations) console.error(`${member}: ${formatViolation(v)}`);
1100
+ for (const x of escalations) console.error(`${member}: ${formatEscalation(x)}`);
1106
1101
  for (const u of unchecked) {
1107
- console.error(`${member.name}: ${u.bucket}[${u.index}]: where it was filed is unchecked — #${u.issue} could not be read through gh: ${u.problem}`);
1102
+ console.error(`${member}: ${u.bucket}[${u.index}]: where it was filed is unchecked — #${u.issue} could not be read through gh: ${u.problem}`);
1108
1103
  }
1109
1104
  if (secondMismatch) {
1110
- console.error(`${member.name}: escalate — an earlier fix-applier's record on review ${run} already failed this check; no further fix-applier answers PR #${pr}, a human does`);
1105
+ console.error(`${member}: escalate — an earlier fix-applier's record on review ${run} already failed this check; no further fix-applier answers PR #${pr}, a human does`);
1111
1106
  }
1112
- console.log(JSON.stringify({ member: member.name, pr, head, verdict, token, violations, escalations, unchecked }));
1107
+ console.log(JSON.stringify({ member, pr, head, verdict, token, violations, escalations, unchecked }));
1113
1108
  // exitCode, not exit(): stdout to a pipe is written asynchronously, and an
1114
1109
  // exit() here could cut the payload off.
1115
1110
  process.exitCode = verdict === "ok" ? 0 : 1;
1116
1111
  }
1117
1112
 
1113
+ const die = makeDie(NAME);
1114
+ const { arg, has, sweep, stray } = defineFlags(die, {
1115
+ flags: { member: "value", scratch: "value", repo: "value", ledger: "value", "no-ledger": "bool", review: "value", uphold: "value", "send-back": "value" },
1116
+ });
1117
+
1118
+ // The standalone check. A fleet run's verdict is `ledger.mjs dispositions`'s,
1119
+ // so this script writes nothing and refuses a ledger outside `--no-ledger`.
1120
+ function main() {
1121
+ const usage = "usage: dispositions-check.mjs --member fix-pr-<M>[-x] --scratch <dir> [--repo <path>] --no-ledger --review <path>";
1122
+ const name = arg("member");
1123
+ const scratch = arg("scratch");
1124
+ if (!name || !scratch) die(usage);
1125
+ sweep();
1126
+ stray();
1127
+ const verb = `ledger.mjs dispositions ${name} --scratch ${scratch}`;
1128
+ for (const flag of ["ledger", "uphold", "send-back"]) {
1129
+ if (arg(flag) !== null) {
1130
+ die(`--${flag} belongs to the ledger verb: run \`${verb}${flag === "ledger" ? "" : " --uphold '<list>' --send-back '<list>'"}\` — this script writes no ledger`);
1131
+ }
1132
+ }
1133
+ const repo = arg("repo") ?? process.cwd();
1134
+ try {
1135
+ const member = parseFixApplier(name);
1136
+ if (!has("no-ledger")) {
1137
+ const ledgerFile = defaultLedger(repo);
1138
+ if (ledgerFile !== null) {
1139
+ die(`a ledger is in use at ${ledgerFile}, and a fleet run's verdict is the ledger verb's: run \`${verb}\`; to judge a record with no controller, pass --no-ledger --review <path>`);
1140
+ }
1141
+ }
1142
+ if (arg("review") === null) die(`no ledger names PR #${member.number}'s review — pass --review <path> for the review file ${member.name}'s record answers`);
1143
+ printVerdict(judgeMember({ name, scratch, repo, reviewPath: arg("review") }));
1144
+ } catch (e) {
1145
+ if (e instanceof CheckRefusal) die(e.message);
1146
+ throw e;
1147
+ }
1148
+ }
1149
+
1118
1150
  // Only run main() as a CLI, never when imported (see is-cli.mjs): a string
1119
1151
  // comparison skipped main() through a symlinked path and exited 0 — the code
1120
1152
  // that means ok — having judged and written nothing.
@@ -58,9 +58,9 @@
58
58
  // (`.fleet/briefs/<member>.json`) is kind `review` or
59
59
  // `dispositions-retry` — a review fix-applier, not one that cleared a
60
60
  // conflict hold or a red check — and with no `dispositions-*=<member>:`
61
- // token on the PR's rows yet: `dispositions-check.mjs --member <member>
62
- // --scratch <scratch>`, its stdout printed. That script writes its own
63
- // verdict token; its exit 1 is a verdict, its exit 2 a NEED.
61
+ // token on the PR's rows yet: `ledger.mjs dispositions <member> --scratch
62
+ // <scratch>`, its stdout printed. That verb writes the verdict token
63
+ // itself; its exit 1 is a verdict, any other nonzero exit a NEED.
64
64
  // A `failed` outcome takes no dispositions check and runs the Recipe read, below.
65
65
  // The Recipe read, after an `impl-report` settled `blocked` or a `fix-report` settled `failed`, whatever the member's cause: `derive-testcmd.sh . install`, `. check` and `. test`, each `--at origin/main`, from the main checkout, the three reads phase0.mjs's `recipe` step makes (recipe-read.mjs is the one reader of both). All three exit 0: nothing printed, the cache is valid. One refused (exit 1): the refused reads, then `NEED derive-recipe`, which is phase 0's mid-run trigger; a refusal naming `--at` is no cache fault, and the controller fetches and reads again. Exit 3 or any other failure of a read: a `NEED recipe-read …` line carrying the environment fault, since the cache's state is unknown and deriving would not help. A cause local to the member's worktree reads valid from the main checkout and prints nothing. No other outcome runs the reads.
66
66
  // finisher-report <finisher-pr-M[-x]>
@@ -655,23 +655,23 @@ function fixReport(ev, member) {
655
655
  ev.note(`dispositions already checked for ${member}`);
656
656
  return;
657
657
  }
658
- const by = `dispositions-check.mjs --member ${member} --scratch ${ev.scratch}`;
658
+ const by = `ledger.mjs dispositions ${member} --scratch ${ev.scratch}`;
659
659
  const sidecar = join(ev.fleetDir, BRIEFS, `${member}.json`);
660
660
  let kind;
661
661
  try {
662
662
  ({ kind } = JSON.parse(readFileSync(sidecar, "utf8")));
663
663
  } catch (e) {
664
- ev.need(`dispositions-check ${member} — its brief ${sidecar} is unreadable (${e.code ?? e.message}), so whether it answered a review is unknown: run ${by} if it did`);
664
+ ev.need(`dispositions ${member} — its brief ${sidecar} is unreadable (${e.code ?? e.message}), so whether it answered a review is unknown: run ${by} if it did`);
665
665
  return;
666
666
  }
667
667
  if (!REVIEW_FIX_KINDS.has(kind)) {
668
668
  ev.note(`no dispositions check: ${member} was a ${kind} fix-applier`);
669
669
  return;
670
670
  }
671
- const r = node("dispositions-check.mjs", ["--member", member, "--scratch", ev.scratch]);
671
+ const r = node("ledger.mjs", ["dispositions", member, "--scratch", ev.scratch]);
672
672
  ev.print(r.stdout);
673
673
  if (r.status === 0 || r.status === 1) ev.note(`dispositions checked (exit ${r.status})`);
674
- else ev.need(`dispositions-check ${member} — nothing judged (${r.how}): ${said(r)}; run ${by} again`);
674
+ else ev.need(`dispositions ${member} — nothing judged (${r.how}): ${said(r)}; run ${by} again`);
675
675
  }
676
676
 
677
677
  const listed = (labels) => (labels.length === 0 ? "(none)" : labels.join(", "));
@@ -1291,7 +1291,7 @@ export function deriveRun({ rows, dispatched, drain, retired = [] }, prs, queued
1291
1291
  // `ledger.mjs dispatch` gates a finisher off this, read from the same
1292
1292
  // per-PR fold as everything above, `ledger.mjs settle --from-report`
1293
1293
  // checks a fix-applier's `no-op` against `fleetHead`, and
1294
- // dispositions-check.mjs reads the review file it judges against off
1294
+ // `ledger.mjs dispositions` reads the review file it judges against off
1295
1295
  // `run`. Nothing in this tick acts on it.
1296
1296
  reviewed: [...byPr.entries()].filter(([, st]) => st.reviewedHead !== null)
1297
1297
  .map(([n, st]) => ({
@@ -265,8 +265,8 @@ function streams(rows) {
265
265
  /** Every token of PR `pr`'s stream, in ledger row order: the tokens firstReview() reads. */
266
266
  export const prTokens = (rows, pr) => streams(rows).get(pr) ?? [];
267
267
 
268
- // dispositions-check.mjs's verdict on a review fix-applier's disposition
269
- // record: `dispositions-ok=fix-pr-<M>[-x]:<run>`,
268
+ // The verdict `ledger.mjs dispositions` derives from a review fix-applier's
269
+ // disposition record: `dispositions-ok=fix-pr-<M>[-x]:<run>`,
270
270
  // `dispositions-mismatch=…`, `dispositions-escalate=…` (a critical or
271
271
  // important deferral, or a second mismatch on one review, that the
272
272
  // maintainer answers) or `dispositions-unchecked=…` (no rule broke, but where
@@ -274,10 +274,10 @@ export const prTokens = (rows, pr) => streams(rows).get(pr) ?? [];
274
274
  // record answers, as its `reviewed=` names it. `ledger.mjs dispatch` refuses a
275
275
  // finisher on anything but an ok. A mismatch returns the PR to fixDue for one
276
276
  // retry. An escalate clears one of two ways: the maintainer's escalation
277
- // answers, recorded through dispositions-check.mjs, replace an escalate over
277
+ // answers, recorded through `ledger.mjs dispositions`, replace an escalate over
278
278
  // a deferral outside the PR's diff with the verdict they give, and a second
279
279
  // mismatch on one review clears only when a new review of the PR counts again
280
- // from none. An unchecked is answered by running the check again, so the tick
280
+ // from none. An unchecked is answered by running the verb again, so the tick
281
281
  // offers no fix-applier for it. A token outside this shape is no verdict at
282
282
  // all, which the gate reads as unchecked: fail closed.
283
283
  export function dispositionsToken(tok) {
@@ -289,7 +289,8 @@ export function dispositionsToken(tok) {
289
289
  }
290
290
 
291
291
  // The maintainer's answer to one finding a fix-applier's record escalated, as
292
- // dispositions-check.mjs writes it onto the PR's row, and the only writer:
292
+ // `ledger.mjs dispositions` writes it onto the PR's row with `--uphold` or
293
+ // `--send-back`, and the only writer:
293
294
  // `escalation-answer=<run>:<bucket>[<index>]:upheld` (the deferral stands) or
294
295
  // `…:sent-back` (the finding is applied in this PR). `<run>` is the run of the
295
296
  // review whose escalation it answers, as its `reviewed=` names it, and
@@ -327,8 +328,8 @@ export function escalationAnswers(tokens, run) {
327
328
  * verdict anywhere on the stream names its run. A review with findings no
328
329
  * fix-applier answered was superseded, and is skipped; a failed review wrote
329
330
  * no `reviewed=`, and is no review. `answered` names runs answered on top of
330
- * the ledger's: dispositions-check.mjs passes the run of the record it is
331
- * checking, whose verdict is not written yet. `{head, survived, refuted,
331
+ * the ledger's: `ledger.mjs dispositions` passes the run of the record it is
332
+ * judging, whose verdict is not written yet. `{head, survived, refuted,
332
333
  * unverified, run}`, or null when no review qualifies.
333
334
  */
334
335
  export function firstReview(tokens, answered = []) {
@@ -440,6 +441,74 @@ export function addedReviewToken(oldLine, line) {
440
441
  return added(words(oldLine), words(line))[0];
441
442
  }
442
443
 
444
+ // A Gate verdict is a ledger token a dispatch gate reads: a dispositions
445
+ // verdict, an Escalation answer or a `reviewed=`. A dispositions verdict and
446
+ // an answer are written only by `ledger.mjs dispositions`, which derives them
447
+ // from their evidence; the one input an argument supplies there is the
448
+ // maintainer's answer to an escalate, as `--uphold`/`--send-back` flags. A
449
+ // `reviewed=` is written by `ledger.mjs review`, off `fleet-event.mjs
450
+ // review-result`.
451
+
452
+ /** Whether `word` begins like a dispositions verdict or an Escalation answer,
453
+ * parseable or not: the words `ledger.mjs token` refuses. The dispositions
454
+ * prefixes are matched case-insensitively, as dispositionsToken() parses them. */
455
+ export const isDispositionsWord = (word) => /^dispositions-(?:ok|mismatch|escalate|unchecked)=/i.test(word) || word.startsWith("escalation-answer=");
456
+
457
+ /** Whether `word` is a Gate verdict: one dispositionsToken(),
458
+ * escalationAnswerToken() or REVIEWED parses. */
459
+ export const isGateVerdict = (word) => dispositionsToken(word) !== null || escalationAnswerToken(word) !== null || REVIEWED.test(word);
460
+
461
+ // A word shaped like a Gate verdict that none of the three parses.
462
+ const malformedGateWord = (word) => (isDispositionsWord(word) || word.startsWith("reviewed=")) && !isGateVerdict(word);
463
+
464
+ /** The command that writes the Gate verdict `word` is shaped like, for a
465
+ * refusal to name. */
466
+ export function gateVerdictWriter(word) {
467
+ if (word.startsWith("reviewed=")) return "`fleet-event.mjs review-result <pr> <path>`";
468
+ if (word.startsWith("escalation-answer=")) return "`ledger.mjs dispositions <member> --scratch <scratch> --uphold '<list>' --send-back '<list>'`";
469
+ const member = dispositionsToken(word)?.member.name ?? "<member>";
470
+ return `\`ledger.mjs dispositions ${member} --scratch <scratch>\``;
471
+ }
472
+
473
+ /**
474
+ * Why `ledger.mjs row` must not write `line` over `oldLine` (null for a new
475
+ * row), or null when it may: the row's Gate verdicts, in row order, must
476
+ * equal the rewrite's. That refuses adding, changing, dropping or reordering
477
+ * one, and a whole-row wipe of a row that holds one. A row holding a Gate
478
+ * verdict keeps its PR, as rowNums() reads it: a rewrite that carries every
479
+ * verdict but maps the row to another PR moves them off their own PR's
480
+ * stream, so it is refused too. A verdict-shaped word no grammar parses is
481
+ * held to the one-way half: adding one is refused, dropping one is allowed,
482
+ * so a runless `reviewed=` and a legacy head-named verdict can still be
483
+ * cleaned off a row.
484
+ */
485
+ export function gateVerdictRefusal(oldLine, line) {
486
+ const words = (text) => (text === null ? [] : text.split(/\s+/).filter(Boolean));
487
+ const [was, now] = [words(oldLine), words(line)];
488
+ const [before, after] = [was.filter(isGateVerdict), now.filter(isGateVerdict)];
489
+ const carried = "a rewrite carries every Gate verdict exactly as the row holds it";
490
+ const badWord = added(was.filter(malformedGateWord), now.filter(malformedGateWord))[0];
491
+ if (badWord !== undefined) {
492
+ return `adds '${badWord}', a word shaped like a Gate verdict that no grammar parses — ${carried}; ${gateVerdictWriter(badWord)} writes the verdict`;
493
+ }
494
+ if (before.length === after.length && before.every((w, i) => w === after[i])) {
495
+ if (before.length === 0) return null;
496
+ const [from, to] = [rowNums(oldLine).pr, rowNums(line).pr];
497
+ if (from === to) return null;
498
+ const name = (pr) => (pr === null ? "no PR" : `PR #${pr}`);
499
+ return `moves its Gate verdicts from ${name(from)} to ${name(to)} — ${carried}, on the PR it maps to`;
500
+ }
501
+ const gained = added(before, after)[0];
502
+ if (gained !== undefined) {
503
+ return `adds or changes Gate verdict '${gained}' — ${carried}; ${gateVerdictWriter(gained)} writes it`;
504
+ }
505
+ const lost = added(after, before)[0];
506
+ if (lost !== undefined) {
507
+ return `drops Gate verdict '${lost}' — ${carried}; ${gateVerdictWriter(lost)} writes it again`;
508
+ }
509
+ return `reorders its Gate verdicts — ${carried}`;
510
+ }
511
+
443
512
  // Every row key a ledger's rows map to each PR number under rowNums(), in
444
513
  // ledger order.
445
514
  function prRowKeys(rows) {
@@ -39,11 +39,19 @@
39
39
  // name whose outcome is outside its family's vocabulary — into
40
40
  // `## Retired`, where `dispatch` and that numbering still read it.
41
41
  //
42
- // Writer policy: the controller owns run state
43
- // (`row`/`token`/`settle`/`dispatch`/`review`/`drain`/`ruled`/`rotate`); filers append
44
- // filings with `filed`; all writes are serialized by `<file>.lock`. Every
45
- // write subcommand except `rotate` — which moves the file whole and never
46
- // loads it, see runRotate() — rewrites the WHOLE file from what it loaded,
42
+ // Writer policy: a Gate verdict — a dispositions verdict, an Escalation
43
+ // answer, a `reviewed=` — is written only by its own verb, whoever calls it:
44
+ // `dispositions` for the first two, which it derives from their evidence,
45
+ // and `review` for the third, which still takes its `reviewed=` as an
46
+ // argument, not yet deriving it from the review's result file. `token`
47
+ // refuses all three, and `row` carries every Gate verdict exactly as the row
48
+ // holds it, so no other verb adds, changes or drops one. `filed` appends
49
+ // filings, and all writes are serialized by `<file>.lock`; the other tokens
50
+ // of a row are freeform to the writers that have them (`row`/`token`/
51
+ // `settle`/`dispatch`/`drain`/`ruled`/`rotate`). Every write subcommand
52
+ // except `rotate` — which moves the file whole and never loads it, see
53
+ // runRotate() — rewrites the WHOLE file
54
+ // from what it loaded,
47
55
  // so two unlocked writers are last-writer-wins — measured, 8 concurrent
48
56
  // `filed` kept 2-5 of 8 rows — and the lock is what lets a second kind of
49
57
  // writer exist at all. The reasoning for each part of the lock lives at
@@ -63,7 +71,7 @@ import { spawnSync, execFileSync } from "node:child_process";
63
71
  import { makeDie, isFlagLike, hasEqualsForm, isDigits, writeAll } from "./arg.mjs";
64
72
  import { fleetFile, FleetDirUnresolvable } from "./fleet-dir.mjs";
65
73
  import { readReceipt } from "./phase0-receipt.mjs";
66
- import { parseMember, parseToken, memberTokens, nextMergeBot, nextRetry, liveOnLedger, settledOnLedger, retiredOnLedger, retiredName, readRetired, agentDefinition, expectedDefinition, CELL, POLICY_CELL, tierValues, cellValues, decidingCell, rowPr, rowWriteRefusal, isReviewToken, addedReviewToken, newSplitRow, splitRowClause, added, premisesOf, MEMBER_FAMILIES, HALT_CAUSES, ROWS, DISPATCHED, ROUTED, FILED, RULED, DRAIN, RETIRED, RECEIPT, archiveStamp, receiptArchiveName, CLOSEOUT_RECEIPT, closeoutArchiveName, BRIEFS, briefsArchiveName, memberRole, parseDispatchedEntry, dispatchedEntry, parseRouting, parseRoutedEntry, routedEntry, headerRe, escapeText, ledgerSection, nextReviewerName, isOmpSessionDirName } from "./ledger-grammar.mjs";
74
+ import { parseMember, parseToken, memberTokens, nextMergeBot, nextRetry, liveOnLedger, settledOnLedger, retiredOnLedger, retiredName, readRetired, agentDefinition, expectedDefinition, CELL, POLICY_CELL, tierValues, cellValues, decidingCell, rowPr, rowNums, rowWriteRefusal, isReviewToken, addedReviewToken, isDispositionsWord, gateVerdictWriter, gateVerdictRefusal, newSplitRow, splitRowClause, added, premisesOf, MEMBER_FAMILIES, HALT_CAUSES, ROWS, DISPATCHED, ROUTED, FILED, RULED, DRAIN, RETIRED, RECEIPT, archiveStamp, receiptArchiveName, CLOSEOUT_RECEIPT, closeoutArchiveName, BRIEFS, briefsArchiveName, memberRole, parseDispatchedEntry, dispatchedEntry, parseRouting, parseRoutedEntry, routedEntry, headerRe, escapeText, ledgerSection, nextReviewerName, isOmpSessionDirName } from "./ledger-grammar.mjs";
67
75
  import { deriveRun, LedgerError, labelOffMember, CONFLICT_HOLD, PARKED } from "./fleet-tick.mjs";
68
76
  import { stateFileIn, readState, writeState, assessBeat, stallsAt } from "./fleet-state.mjs";
69
77
  import { processSource, ancestry, controllerOf, judgeController, ProcUnreadable } from "./proc.mjs";
@@ -284,7 +292,7 @@ const requireFile = requireFileIdx !== -1;
284
292
  if (requireFileIdx !== -1) argv.splice(requireFileIdx, 1);
285
293
 
286
294
  const [cmd, ...rest] = argv;
287
- if (!cmd) die("usage: ledger.mjs [--file <path>] [--require-file] row|token|filed|ruled|check|read|dispatch|settle|review|drain|undrain|rotate [args]");
295
+ if (!cmd) die("usage: ledger.mjs [--file <path>] [--require-file] row|token|filed|ruled|check|read|dispatch|settle|review|dispositions|drain|undrain|rotate [args]");
288
296
 
289
297
  // A `--`-prefixed token in `check`'s free-text tail used to fold
290
298
  // straight into the duplicate-filing subject, so a misspelled flag searched
@@ -700,14 +708,16 @@ async function acquireLock() {
700
708
  // so a caller gating on the exit code reads the same failure either way.
701
709
  if (requireFile && !existsSync(file)) die(`--require-file given but ledger file does not exist: ${file}`);
702
710
 
703
- const WRITE_COMMANDS = new Set(["row", "token", "filed", "ruled", "dispatch", "settle", "review", "drain", "undrain", "rotate"]);
711
+ const WRITE_COMMANDS = new Set(["row", "token", "filed", "ruled", "dispatch", "settle", "review", "dispositions", "drain", "undrain", "rotate"]);
704
712
  // `settle --from-report` takes the lock itself, once its checks have run —
705
- // see runSettleFromReport().
713
+ // see runSettleFromReport(). So does `dispositions`, once every git, gh and
714
+ // file read has run — see runDispositions().
706
715
  const FROM_REPORT = cmd === "settle" && rest.includes("--from-report");
716
+ const LATE_LOCK = FROM_REPORT || cmd === "dispositions";
707
717
  // A merge bot's dispatch reads the queue it records before the lock, for the
708
718
  // same reason: a gh call held under the lock stalls every other writer.
709
719
  const QUEUED = cmd === "dispatch" && rest.length === 1 && /^merge-bot(-[0-9]+)?$/.test(rest[0]) ? queueSnapshot() : null;
710
- if (WRITE_COMMANDS.has(cmd) && !FROM_REPORT) await acquireLock();
720
+ if (WRITE_COMMANDS.has(cmd) && !LATE_LOCK) await acquireLock();
711
721
  // `rotate` never load()s: a ledger load() would refuse is still the previous
712
722
  // run's record, and it is archived as-is — and read line by line when it
713
723
  // carries live members forward, see carryOf().
@@ -796,6 +806,11 @@ if (cmd === "read") {
796
806
  if (reviewToken !== undefined) {
797
807
  die(`row ${key}: adds review token '${reviewToken}' — review tokens are written only with \`ledger.mjs review <pr> <token>…\`, which puts them on the PR's row`);
798
808
  }
809
+ // Every Gate verdict is its own verb's to write, so a rewrite carries the
810
+ // row's as they stand — none added, changed, dropped or reordered, which
811
+ // also refuses a whole-row wipe of a row that holds one.
812
+ const gateWhy = gateVerdictRefusal(oldRow, line);
813
+ if (gateWhy !== null) die(`row ${key}: ${gateWhy}`);
799
814
  // Every token about a PR lives on the PR's row, so a write that makes a PR
800
815
  // map to a second row splits its history across two rows the tick reads in
801
816
  // row order, not write order. Added only: a split already on disk is
@@ -901,6 +916,8 @@ if (cmd === "read") {
901
916
  runToken();
902
917
  } else if (cmd === "review") {
903
918
  runReview();
919
+ } else if (cmd === "dispositions") {
920
+ await runDispositions();
904
921
  } else if (cmd === "drain") {
905
922
  // One marker per run. A second `drain` — a replacement controller that
906
923
  // cannot tell whether its predecessor got this far — is answered with the
@@ -932,7 +949,7 @@ if (cmd === "read") {
932
949
  if (rest.length) die("usage: ledger.mjs rotate");
933
950
  runRotate();
934
951
  } else {
935
- die(`unknown subcommand '${cmd}' — expected row, token, filed, ruled, check, read, dispatch, settle, review, drain, undrain or rotate`);
952
+ die(`unknown subcommand '${cmd}' — expected row, token, filed, ruled, check, read, dispatch, settle, review, dispositions, drain, undrain or rotate`);
936
953
  }
937
954
 
938
955
  // Reached only by an arm that did not die, so every write subcommand that did
@@ -1965,32 +1982,32 @@ function dispositionsRefusal(pr, review) {
1965
1982
  if (review === undefined) return null;
1966
1983
  if (review.fixLive.length > 0) {
1967
1984
  return `${review.fixLive.join(", ")} still live on PR #${pr} — a fix-applier answering review ${review.run} has not settled, `
1968
- + "so no dispositions verdict answers its work yet; settle it, run dispositions-check.mjs for it, then dispatch the finisher again";
1985
+ + "so no dispositions verdict answers its work yet; settle it, run `ledger.mjs dispositions` for it, then dispatch the finisher again";
1969
1986
  }
1970
1987
  if (review.survived === 0 && review.unverified === 0) return null;
1971
1988
  const v = review.dispositions;
1972
1989
  if (v === null) {
1973
1990
  return `dispositions unchecked — no dispositions-ok=/dispositions-mismatch=/dispositions-escalate=/dispositions-unchecked= token answers PR #${pr}'s latest review, `
1974
- + `${review.run} at ${review.head}; run dispositions-check.mjs --member fix-pr-${pr}[-<x>] --scratch <scratch> for the fix-applier `
1991
+ + `${review.run} at ${review.head}; run ledger.mjs dispositions fix-pr-${pr}[-<x>] --scratch <scratch> for the fix-applier `
1975
1992
  + "that answered that review, then dispatch the finisher again";
1976
1993
  }
1977
1994
  if (v.verdict === "unchecked") {
1978
1995
  return `dispositions unchecked — ${v.member}'s check of review ${review.run} could not read where a deferral was filed (gh unreachable, `
1979
1996
  + "or an issue unreadable — an issue that does not exist is unreadable too, and no re-run answers that one: the check's stderr names "
1980
- + `it, and the record's issue number needs correcting); run dispositions-check.mjs --member ${v.member} --scratch <scratch> again once gh answers, `
1997
+ + `it, and the record's issue number needs correcting); run ledger.mjs dispositions ${v.member} --scratch <scratch> again once gh answers, `
1981
1998
  + "then dispatch the finisher again";
1982
1999
  }
1983
2000
  if (v.verdict === "mismatch") {
1984
2001
  return `dispositions mismatch — ${v.member}'s disposition record fails the check against review ${review.run}; `
1985
- + `dispositions-check.mjs --member ${v.member} --scratch <scratch> names each violating entry by bucket, index and rule`;
2002
+ + `ledger.mjs dispositions ${v.member} --scratch <scratch> names each violating entry by bucket, index and rule`;
1986
2003
  }
1987
2004
  if (v.verdict === "escalate") {
1988
2005
  return `dispositions escalate — ${v.member} deferred a finding above suggestion severity because its remedy lies outside the PR's diff, `
1989
2006
  + `or its record drew a second mismatch on this review: review ${review.run} gets no finisher until the escalate clears. `
1990
2007
  + "An outside-diff deferral clears when the maintainer's escalation answers are recorded with "
1991
- + `dispositions-check.mjs --member ${v.member} --scratch <scratch> --uphold '<list>' --send-back '<list>'; `
2008
+ + `ledger.mjs dispositions ${v.member} --scratch <scratch> --uphold '<list>' --send-back '<list>'; `
1992
2009
  + "a second mismatch clears only with a new review of the PR. "
1993
- + `dispositions-check.mjs --member ${v.member} --scratch <scratch> alone names each escalated finding or violating entry by bucket and index, `
2010
+ + `ledger.mjs dispositions ${v.member} --scratch <scratch> alone names each escalated finding or violating entry by bucket and index, `
1994
2011
  + "for the PR comment that hands it to the maintainer";
1995
2012
  }
1996
2013
  return null;
@@ -3143,6 +3160,103 @@ function runReview() {
3143
3160
  console.log(JSON.stringify({ pr: prNum, row: key, line, created, next: nextReviewerName(data.rows, prNum, retired) }));
3144
3161
  }
3145
3162
 
3163
+ // `dispositions <member> --scratch <dir> [--repo <path>] [--uphold <list>]
3164
+ // [--send-back <list>]`: the only writer of a PR's `dispositions-*=` verdict
3165
+ // and `escalation-answer=` tokens. It judges the fix-applier's disposition
3166
+ // record in-process, through the module dispositions-check.mjs exports,
3167
+ // against the ledger this call loaded — every git, gh and file read happens
3168
+ // first, with no lock held, since a gh call under the lock stalls every other
3169
+ // writer. Only then does it take the lock, load the ledger again and write
3170
+ // onto the row that carries the member as it stands now, every other token
3171
+ // kept: a token another writer put on that row while the tracker was read is
3172
+ // carried, never dropped. The verdict is judged against the review that was
3173
+ // the latest when it was read; one written for a review that has since been
3174
+ // superseded does nothing, since the gate and the tick read only verdicts
3175
+ // naming the latest run. A run recording answers is the exception: under the
3176
+ // lock it asks again that the escalate they answer is still the PR's current
3177
+ // verdict on that same review and that no fix-applier is live, and exits 2
3178
+ // with nothing written when either has changed, so two answer runs that read
3179
+ // one escalate cannot both write. A verdict the row already carries is not
3180
+ // written again, and its findings are printed all the same. The write passes
3181
+ // rowWriteRefusal() like any other. Its payload, stderr lines and exit status
3182
+ // are printVerdict()'s: 0 ok, 1 mismatch, escalate or unchecked, 2 nothing
3183
+ // judged and nothing written.
3184
+ async function runDispositions() {
3185
+ const usage = "usage: ledger.mjs dispositions <fix-pr-M[-x]> --scratch <dir> [--repo <path>] [--uphold <list>] [--send-back <list>]";
3186
+ const flags = new Map();
3187
+ let member = null;
3188
+ for (let i = 0; i < rest.length; i++) {
3189
+ const word = rest[i];
3190
+ if (!word.startsWith("--")) {
3191
+ if (member !== null) die(`dispositions: unexpected argument '${word}' — ${usage}`);
3192
+ member = word;
3193
+ continue;
3194
+ }
3195
+ const name = word.slice(2).split("=")[0];
3196
+ if (!["scratch", "repo", "uphold", "send-back"].includes(name)) die(`dispositions: unknown flag ${word} — ${usage}`);
3197
+ if (hasEqualsForm(name, rest)) die(`dispositions: --${name} needs a space-separated value, not --${name}=`);
3198
+ if (flags.has(name)) die(`dispositions: --${name} is given twice${name === "uphold" || name === "send-back" ? " — name every finding in one comma-separated list" : ""}`);
3199
+ const value = rest[++i];
3200
+ if (isFlagLike(value)) die(`dispositions: --${name} needs a value — ${usage}`);
3201
+ flags.set(name, value);
3202
+ }
3203
+ if (member === null || !flags.has("scratch")) die(usage);
3204
+ const { judgeMember, latestReview, answerMap, printVerdict, withVerdict, CheckRefusal } = await import("./dispositions-check.mjs");
3205
+ const refusing = (fn) => {
3206
+ try {
3207
+ return fn();
3208
+ } catch (e) {
3209
+ if (e instanceof CheckRefusal) die(e.message);
3210
+ throw e;
3211
+ }
3212
+ };
3213
+ const listed = refusing(() => answerMap(flags.get("uphold") ?? null, flags.get("send-back") ?? null));
3214
+ const result = refusing(() => judgeMember({
3215
+ name: member, scratch: flags.get("scratch"), repo: flags.get("repo") ?? process.cwd(), ledger: data, listed,
3216
+ }));
3217
+
3218
+ await acquireLock();
3219
+ data = load();
3220
+ const { pr, run, token } = result;
3221
+ // Answers clear the escalate they answer, so what recording them needs is
3222
+ // asked again on the ledger as it stands under the lock: two answer runs
3223
+ // that both read the same escalate would otherwise both write.
3224
+ if (result.recorded.length > 0) {
3225
+ let why = null;
3226
+ try {
3227
+ const latest = latestReview(data, pr, result.member, true);
3228
+ if (latest.run !== run) why = `PR #${pr}'s latest review is ${latest.run} now, not ${run}`;
3229
+ } catch (e) {
3230
+ if (!(e instanceof CheckRefusal)) throw e;
3231
+ why = e.message;
3232
+ }
3233
+ if (why !== null) {
3234
+ die(`dispositions: the ledger changed while ${result.member}'s record was judged — ${why}; nothing written, run \`ledger.mjs dispositions ${result.member} --scratch ${flags.get("scratch")}\` again to judge it as it stands`);
3235
+ }
3236
+ }
3237
+ const i = data.rows.findIndex((r) => rowNums(r).pr === pr && memberTokens(r).some((t) => t.name === result.member));
3238
+ if (i === -1) {
3239
+ die(`dispositions: ${result.member} is on no row of PR #${pr} now — the ledger changed while its record was judged; nothing written, run \`ledger.mjs dispositions ${result.member} --scratch ${flags.get("scratch")}\` again`);
3240
+ }
3241
+ const oldRow = data.rows[i];
3242
+ const key = rowKey(oldRow);
3243
+ if (!/^#[0-9]+$/.test(key)) die(`dispositions: the row carrying ${result.member} has no #<n> key to be rewritten by: ${oldRow}`);
3244
+ const text = oldRow.slice(key.length).trim();
3245
+ const answerTokens = result.recorded.map(([a, answer]) => `escalation-answer=${run}:${a}:${answer}`);
3246
+ const updated = withVerdict([text, ...answerTokens].join(" · "), token);
3247
+ if (updated === text) {
3248
+ console.error(` ${result.member}: row ${key} already carries ${token} — not written again`);
3249
+ } else {
3250
+ const line = `${key} ${updated}`;
3251
+ const after = data.rows.with(i, line);
3252
+ const refusal = rowWriteRefusal(data.rows, after, oldRow, line, readRetired(data.retired).names);
3253
+ if (refusal !== null) die(`dispositions: row ${key}: ${refusal}`);
3254
+ data.rows = after;
3255
+ save(data);
3256
+ }
3257
+ printVerdict(result);
3258
+ }
3259
+
3146
3260
  // A row's tokens: its words after the key, bar the ` · ` separators between
3147
3261
  // them.
3148
3262
  function rowTokens(text) {
@@ -3235,7 +3349,9 @@ function withTier(line, tok) {
3235
3349
  // call's tokens before it. A token is one word: an empty argument, one with
3236
3350
  // a space in it (prose, which would split into words the row's own words
3237
3351
  // then dedupe against), and the row's ` · ` separator are no token. A member
3238
- // token is `dispatch`'s or `settle`'s, a review token `review`'s. A word
3352
+ // token is `dispatch`'s or `settle`'s, a review token `review`'s, and a
3353
+ // dispositions verdict or an Escalation answer `dispositions`' — any word
3354
+ // beginning like one, parseable or not. A word
3239
3355
  // shaped like a member that the grammar cannot parse, a `tier=` that is not
3240
3356
  // a cell, a `tier=` naming a second tier in one call, any `cell=` (the row
3241
3357
  // step's, never a token), a `conflict-hold` or `parked` token the tick cannot
@@ -3253,6 +3369,11 @@ function tokenRefusal(tok, earlier) {
3253
3369
  if (isReviewToken(tok)) {
3254
3370
  return "is a review token — review tokens are written only with `ledger.mjs review <pr> <token>…`, which puts them on the PR's row";
3255
3371
  }
3372
+ if (isDispositionsWord(tok)) {
3373
+ return tok.startsWith("escalation-answer=")
3374
+ ? `is an Escalation answer — a Gate verdict is written only by ${gateVerdictWriter(tok)}, which takes the maintainer's answer only against an escalate its own check raised; running that again is how a verdict is restored`
3375
+ : `is a dispositions verdict — a Gate verdict is written only by ${gateVerdictWriter(tok)}, which derives it from the disposition record and the review; running that again is how a verdict is restored`;
3376
+ }
3256
3377
  const name = tok.split("=")[0];
3257
3378
  if (MEMBER_FAMILIES.some((family) => name.startsWith(`${family}-`))) {
3258
3379
  return "is shaped like a member token this grammar cannot parse — a member is impl-<N>, fix-pr-<M>, finisher-pr-<M> or merge-bot-<n>, a retry suffix allowed";
@@ -788,7 +788,7 @@ function nextStep(pr, state) {
788
788
  if (state === "MERGED") {
789
789
  return `the PR is merged and its evidence is not there to read — give the verdicts by hand: append ${pr} --closed-own-ticket yes|no --minted-false-claim yes|no --note "<the evidence>"`;
790
790
  }
791
- return `check the record again (\`dispositions-check.mjs --member fix-pr-${pr} --scratch <scratch>\`), or dispatch the fix-applier again as a dispositions retry (\`--kind dispositions-retry\`), then run append ${pr} again`;
791
+ return `check the record again (\`ledger.mjs dispositions fix-pr-${pr} --scratch <scratch>\`), or dispatch the fix-applier again as a dispositions retry (\`--kind dispositions-retry\`), then run append ${pr} again`;
792
792
  }
793
793
 
794
794
  // The PR's state as GitHub gives it: OPEN, CLOSED (never merged) or MERGED.
@@ -603,13 +603,14 @@ answered by none of the first one's verdicts. A PR whose latest review counts
603
603
  gated like survivors, and the tick prints `DISPATCH fix-pr PR#<M>` for it: that
604
604
  fix-applier's `no-op` and its `ok` verdict are what open the finisher. The
605
605
  refusal names its cause. `dispositions
606
- unchecked` — no verdict answers that review: run `dispositions-check.mjs` for
607
- the fix-applier that answered the review, as `fleet-event.mjs`'s `fix-report`
608
- entry states, then dispatch again. It names a `dispositions-unchecked=` verdict too —
609
- no rule broke, but the check could not read where a deferral was filed, `gh`
610
- unreachable or an issue unreadable: run the check again for that fix-applier
606
+ unchecked` — no verdict answers that review: run `ledger.mjs dispositions`
607
+ for the fix-applier that answered the review, as
608
+ `fleet-event.mjs`'s `fix-report` entry states, then dispatch again. It names a
609
+ `dispositions-unchecked=` verdict too —
610
+ no rule broke, but the verb could not read where a deferral was filed, `gh`
611
+ unreachable or an issue unreadable: run the verb again for that fix-applier
611
612
  once `gh` answers (an issue that does not exist is unreadable too, and no re-run
612
- answers that one: the check's stderr names it, and the record's issue number
613
+ answers that one: the verb's stderr names it, and the record's issue number
613
614
  needs correcting); the tick offers no fix-applier for it. `dispositions
614
615
  mismatch` — no finisher: the tick prints `DISPATCH fix-pr PR#<M>` for it, and
615
616
  the next-suffix fix-applier answers it (**Then dispatch a fix-applier**).
@@ -618,7 +619,7 @@ the next-suffix fix-applier answers it (**Then dispatch a fix-applier**).
618
619
  a second mismatch only with a new review (**Dispositions escalation**). **On any PR with a
619
620
  returned review, `0/<n>/0` included, it refuses too while a fix-applier on the
620
621
  PR is still live, verdict or not** —
621
- `fix-pr-<M>[-x] still live`: settle it, run the check for it, then dispatch
622
+ `fix-pr-<M>[-x] still live`: settle it, run `ledger.mjs dispositions` for it, then dispatch
622
623
  again.
623
624
 
624
625
  **It refuses a finisher, too, while the PR sits on a conflict hold no
@@ -774,18 +775,18 @@ next suffix (`fix-pr-<M>-b`) and dispatched like the first, its brief rendered w
774
775
  first one's with the retry paragraph added: `--mismatched-record`, the mismatched member's record
775
776
  `<scratch>/dispositions-<member>.json` it starts from, and `--violations`, the check's
776
777
  violation list as printed — the lines
777
- `dispositions-check.mjs` printed, each naming a bucket, an index and a rule;
778
- re-run the check for the mismatched member to reprint them. It writes its own
779
- record, and when it reports you run the check for it exactly as for the first
780
- one. `ok` ends it. A second failure on the same review is written as
778
+ `ledger.mjs dispositions` printed, each naming a bucket, an index and a rule;
779
+ run it again for the mismatched member to reprint them. It writes its own
780
+ record, and you run it for that one as for the first. `ok` ends it. A second
781
+ failure on the same review is written as
781
782
  `dispositions-escalate=fix-pr-<M>-b:<run>` in place of a mismatch: the tick
782
- prints no `DISPATCH fix-pr` for it. Post the check's output with
783
+ prints no `DISPATCH fix-pr` for it. Post the verb's output with
783
784
  `gh pr comment <M>`. A second failure is flagged for a human. A new review of
784
- the PR counts again from none. An escalate whose check printed no violations is
785
+ the PR counts again from none. An escalate whose verb printed no violations is
785
786
  the maintainer's to answer instead, one yes/no per escalated finding: yes upholds
786
787
  the deferral, no sends it back to be applied in this PR. With every finding
787
- explicitly answered this session, record them with `dispositions-check.mjs`
788
- `--uphold` and `--send-back`: `ok` gets the finisher, `mismatch` the tick's
788
+ explicitly answered this session, record them with `ledger.mjs dispositions`
789
+ and its `--uphold` and `--send-back`: `ok` gets the finisher, `mismatch` the tick's
789
790
  retry, `escalate` is a second failure. See references/dispositions-escalation.md.
790
791
 
791
792
  ### The main-gain hit
@@ -78,7 +78,7 @@ claim, never your patch.
78
78
 
79
79
  **Before you report, write every ruling to `<scratch>/dispositions-<your name>.json`**,
80
80
  `<your name>` the `fix-pr-<pr>[-x]` you were dispatched as — the record the controller checks with
81
- `dispositions-check.mjs` before it dispatches any finisher.
81
+ `ledger.mjs dispositions` before it dispatches any finisher.
82
82
 
83
83
  **Charge every standing entry of that record:** which entries stand, and the
84
84
  `charge` and `chargeReason` fields, are in `review-and-fix.md`'s step 2. Read
@@ -1,10 +1,10 @@
1
1
  # Dispositions escalation: what you do with an escalate
2
2
 
3
- What SKILL.md's **Dispositions escalation** points at: the message, the records and the comment that clear a `dispositions escalate` whose check printed no violations — a `critical`, `important` or severity-less finding a fix-applier deferred `remedy-outside-diff`, its record breaking no rule. An escalate whose check printed violations is a second mismatch on one review: no answer clears it, you comment and flag the PR for a human, and a new review of the PR counts again from none.
3
+ What SKILL.md's **Dispositions escalation** points at: the message, the records and the comment that clear a `dispositions escalate` whose verb printed no violations — a `critical`, `important` or severity-less finding a fix-applier deferred `remedy-outside-diff`, its record breaking no rule. An escalate whose verb printed violations is a second mismatch on one review: no answer clears it, you comment and flag the PR for a human, and a new review of the PR counts again from none.
4
4
 
5
5
  ## Ask the maintainer
6
6
 
7
- Post the check's output with `gh pr comment <M>`: it names each escalated finding, and re-running the check for the escalated member reprints it. Then put one message to the maintainer, with one yes/no for each escalated finding. Each finding is named by:
7
+ Post the verb's output with `gh pr comment <M>`: it names each escalated finding, and running `ledger.mjs dispositions <member> --scratch <scratch>` again for the escalated member reprints it. Then put one message to the maintainer, with one yes/no for each escalated finding. Each finding is named by:
8
8
 
9
9
  - its address, `<bucket>[<index>]` as the check printed it, its severity and its claim, read from `<scratch>/pr<M>/<run>/review.json`;
10
10
  - its remedy files, as the check printed them;
@@ -18,16 +18,16 @@ Record nothing until every finding has an answer, and nothing without the mainta
18
18
 
19
19
  On the answers, in this order:
20
20
 
21
- 1. Run `dispositions-check.mjs --member <member> --scratch <scratch> --uphold '<list>' --send-back '<list>'`, `<member>` the escalated fix-applier and each list the findings answered that way, `<bucket>[<index>]` separated by commas. Quote each list — `[` opens a glob under zsh — and pass a flag only for a list that has a finding in it. One write puts an `escalation-answer=<run>:<bucket>[<index>]:upheld|sent-back` token per finding on the PR's row and replaces the escalate with the verdict the answers earn. It refuses instead, exit 2 and the ledger untouched, naming the cause: the PR's current verdict on its latest review is not an escalate from that member, a fix-applier on the PR is live, the record breaks a rule, a finding is not one the record escalates or is listed twice or both ways, or an escalated finding has no answer.
21
+ 1. Run `ledger.mjs dispositions <member> --scratch <scratch> --uphold '<list>' --send-back '<list>'`, `<member>` the escalated fix-applier and each list the findings answered that way, `<bucket>[<index>]` separated by commas. Quote each list — `[` opens a glob under zsh — and pass a flag only for a list that has a finding in it. One write puts an `escalation-answer=<run>:<bucket>[<index>]:upheld|sent-back` token per finding on the PR's row and replaces the escalate with the verdict the answers earn. It refuses instead, exit 2 and the ledger untouched, naming the cause: the PR's current verdict on its latest review is not an escalate from that member, a fix-applier on the PR is live, the record breaks a rule, a finding is not one the record escalates or is listed twice or both ways, or an escalated finding has no answer. No other command writes an answer: `ledger.mjs token` and `ledger.mjs row` refuse one.
22
22
  2. Record one line per finding: `ledger.mjs ruled <M> "escalation answer <bucket>[<index>]: upheld|sent back — <reason>"`, the maintainer's reason.
23
23
  3. Post one PR comment under the escalate comment, quoting the answers.
24
24
 
25
25
  The verdict then decides what follows:
26
26
 
27
27
  - `ok`: dispatch the finisher, as for any `ok`. An upheld finding passes; its deferral is judged by every other rule as before.
28
- - `mismatch`: a sent-back finding is a broken rule, so the tick prints `DISPATCH fix-pr PR#<M>` and the retry runs as any mismatch's does. The retry's `--violations` are the check's lines as printed, the sent-back ones included; re-run the check for the member to reprint them. The retry's record is judged with the answers: deferring a sent-back finding again, for any reason, is a second failure, and applying it while deferring an upheld one `remedy-outside-diff` passes.
28
+ - `mismatch`: a sent-back finding is a broken rule, so the tick prints `DISPATCH fix-pr PR#<M>` and the retry runs as any mismatch's does. The retry's `--violations` are the verb's lines as printed, the sent-back ones included; run the verb again for the member to reprint them. The retry's record is judged with the answers: deferring a sent-back finding again, for any reason, is a second failure, and applying it while deferring an upheld one `remedy-outside-diff` passes.
29
29
  - `escalate`: an earlier fix-applier on the review had already failed, so the send-back is the second failure. Comment, flag the PR for a human, and a new review of the PR counts again from none.
30
- - `unchecked`: the answers are recorded, but a filing could not be read. Run the check again once `gh` answers; it reads the answers already on the row.
30
+ - `unchecked`: the answers are recorded, but a filing could not be read. Run the verb again once `gh` answers; it reads the answers already on the row.
31
31
 
32
32
  An answer belongs to one review. A new review counts from none, so the same finding deferred again on it escalates again.
33
33
 
@@ -170,7 +170,7 @@ What does not empty it is noticing the question and dispatching anyway.
170
170
  the merge.** A deferral of a finding in the review's result is not yours to
171
171
  re-judge when the PR's latest review counted a survived or unverified finding:
172
172
  `ledger.mjs dispatch` then dispatched you only once the PR's ledger row held a
173
- `dispositions-ok` verdict from `dispositions-check.mjs` on that review
173
+ `dispositions-ok` verdict from `ledger.mjs dispositions` on that review
174
174
  (`dispositionsRefusal`), and that check had already read back where the
175
175
  fix-applier's disposition record says each deferral was filed. That verdict is
176
176
  the judgement of those homes: do not halt on a home the script accepted, and