@feigi/fleet-ctl 3.128.2 → 3.129.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -22,7 +22,7 @@ Label names in this file are roles; the Label map gives the string to type; a me
22
22
  3. **Run `checkCmd` and `testCmd` before you commit**, from the worktree, each copied verbatim — not a runner you picked. `checkCmd` is the Recipe's Check step and `testCmd` is the command your dispatcher handed you; **standalone, with no dispatcher to hand you them, they are the repo's own Check step and Test entrypoint**, read off the repo's Recipe cache (`derive-testcmd.sh <repo> check` prints the first, `derive-testcmd.sh <repo> test` the second). Read them off the repo, never invent one: "not a runner you picked" is what this step forbids, and on the standalone path nothing else defines the referent. With no usable Recipe cache (`derive-testcmd.sh` refuses), run the Recipe derivation step first — dispatch a `task` member, agent `fleet-recipe-deriver`, its prompt naming the main checkout's absolute path as `<repo>` and a scratch directory of its own; it proves all three commands in a throwaway worktree and writes the cache only on proof, and its `RECIPE NOT PROVEN` is a stop, reported with its reason. Never fall back to a runner of your own choosing. `tests 0` is a FAILED run, not a pass: a glob matching nothing still exits 0. **Zero is not the only no-work count.** A run reporting **0 passes with no failures** skipped everything it collected, and a count **materially below the whole suite** means you ran a partial tree — this suite reported `tests 937` when this line was written, so compare what you get against a full run rather than against zero. The number drifts; that is the safe direction, because a stale one produces a loud false red while its absence produces a silent false green. Red, zero-test, or either no-work count → fix it or move the finding to defer; never commit over it. Then commit and push — `~/.fleet/bin/fleet-run push-sync.mjs --branch <branch>`, which pushes the explicit refspec `HEAD:refs/heads/<branch>` and then moves the worktree holding `<branch>` to the pushed SHA, or names why it did not and exits 3 with the push landed: this step also runs from a `--detach` worktree (`run-team/SKILL.md`'s worktree-recreation form), where a bare `git push` exits 128 (`fatal: You are not currently on a branch`), any push whose destination is `HEAD` rather than a full or branch refname (`-u` or not, forced or not) exits 1 (`error: The destination you provided is not a full refname`), and a refspec push alone leaves the claim worktree's `refs/heads/<branch>` at its old tip — and report the test result alongside the SHA. **Then reconcile the PR body with what you actually did.** It merges into the permanent record and nothing downstream re-derives it: your commit messages are yours to fix and usually get fixed, the body is neither. Removing a change, or reversing one, leaves the body asserting work the diff no longer contains. Seen twice in one run, and caught only by a finisher's reading. `gh pr edit <pr> --body-file <path>`, and re-read the body against the final diff rather than against your memory of it. **Never `--no-verify` on a commit you push, or on the push itself.** The fleet runs in repos it knows nothing about: it must not assume a pre-commit hook exists, and must never bypass one that does on what reaches the branch — a hook that fails is a finding to report, not an obstacle. Nothing re-reviews what you commit here, so this run is the only gate between your edit and a merge.
23
23
  **Under the fleet, run the two through `recipe-check.mjs`, not one by one:** from the worktree, after `git add` and before the commit, `~/.fleet/bin/fleet-run recipe-check.mjs --member <your name> --testCmd "<testCmd>" --reports <scratch>/reports` — `<your name>` the `fix-pr-<pr>[-x]` you were dispatched as, and `<testCmd>` the whole command you were handed, one quoted argument. It runs the Recipe's Check step, which is `checkCmd`, then `<testCmd>` exactly as handed, against the staged tree, and records both results beside your report. The record is keyed to the tree, so run it again after any content change or rebase — a message-only amend keeps it valid — and the controller refuses an `applied` report whose head's tree has no green record. After the commit, and before you push or report, compare `git rev-parse 'HEAD^{tree}'` with the `tree` field of your record, `<scratch>/reports/<your name>.check.json`. A commit hook that rewrote and re-staged files after the record was written makes the two differ. When they do, list the paths it changed, `git diff --name-only "$(jq -r .tree <scratch>/reports/<your name>.check.json)" HEAD`. If the PR changes every listed path anyway, run `recipe-check.mjs` again with the same arguments: right after the commit the index holds the committed tree, so the re-run runs both commands on that tree and records it, leaving the head's sha as it is. A listed path the PR does not otherwise change is a stale base the hook staged rather than left unstaged, and a re-run would record it green: `git fetch origin && git rebase origin/main`, take the commit back with `git reset --soft HEAD^`, put each such path alone back with `git restore --source=HEAD --staged --worktree -- <that path>`, run `recipe-check.mjs`, then `git commit -C ORIG_HEAD` and compare again. A hook that stages such a path again on the rebased base → push nothing and report that cause. Equal trees need no re-run. Exit 1 is red; exit 2 and 4 are refusals that record nothing: your brief says how each ends; exit 75 (no slot free) and exit 143, 130 or 129 (a SIGTERM, SIGINT or SIGHUP, nothing recorded) are no test result: run it again, with `timeout: 0` on the call for a signal. **Standalone, with no report to settle against,** run `checkCmd` and `testCmd` yourself, each copied verbatim.
24
24
  4. **Under the fleet, do not hold this wait.** The controller owns a persistent CI Monitor and dispatches a finisher once your report has arrived and CI is green — so push, then report to the controller a **final verdict** (every specialist you dispatched + its outcome + your apply/defer adjudication + how many refuters you dispatched against out-of-scope suggestions + the pushed SHA) and stop. A specialist that has not reported to you is not a verdict line — `hub send` it by name for its report, then ask the controller, before ruling; see **Specialists**. The controller keys "review complete" on that verdict, **never on you merely going idle** — a slow specialist can still be running when your turn ends, and finishing off idle-alone ships a premature label. A turn-based reviewer re-reading `gh pr checks` each idle cycle rebuilds its whole context for nothing the Monitor lacks. **Standalone (no controller): watch** the run until the diff-validating jobs are green (bind via `ci-state.mjs` below); fix a **genuine** failure and repeat from 3. **Staleness is not a failure:** a `rebase-check` red or heavy jobs `skipped` **solely from a non-zero behind-count** never clears by waiting and must not be rebased away here — see **`skipped` is not `passed`** and **Do NOT rebase to label** below for what it looks like and why. Stop watching and go to 6. A turn-based reviewer that "waits for green" on a behind PR stalls forever and ends its turn without labelling. **`ci-state.mjs` returns `verdict: "no-ci"`** → there is no run to watch, so don't: go straight to 6 and let that step's `--declare-no-ci` branch decide.
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`, labelled `<wontfix string>`, and CLOSED** — left open they read as queued agent work. Closed is still a durable home — `check` reads the tracker at `--state all`, so a future run re-deriving the finding lands on the evidence rather than re-litigating it. Split the band only where an entry is **not** a refutation: a residual the refuter surfaced, or 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 `~/.fleet/bin/fleet-run ledger.mjs check "<subject>"`, never a bare `gh issue list --search`** — the duplicate class that guard exists to catch was filed from *here*. `check` reads this run's filed list *and* the tracker at `--state all`, so a closed duplicate still counts. Exit **1** is already filed in this run; exit **3** is a clean ledger with matching tracker rows that score against the subject — read the ones it prints and comment on the existing follow-up rather than filing a second issue. **Exit 0 is not automatically "safe to file"**: it covers `clean`, `soft-hit` and `unverified` alike, and an unreachable `gh` degrades to a ledger-only answer that says `TRACKER NOT CHECKED`, so read the stdout `verdict` to tell a tracker that was searched and clean from one nobody read — under `unverified`, search it yourself before filing — or, for the applied-promotion comment above, before treating a tracker nobody could read as a reason to skip it. **`soft-hit` is the answer that costs most to misread**: it means related rows were found and none of them was established as a duplicate — a near-miss above the floor, or tracker rows the scorer rates 0.00 — so read the rows it printed and decide, and never treat that exit 0 as permission. Exit **2** is a usage error, meaning nothing was checked at all: fix the invocation and re-run, never read it as a duplicate. Full exit-code and `verdict` semantics live in `$(~/.fleet/bin/fleet-run --root)/skills/run-team/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 `~/.fleet/bin/fleet-run ledger.mjs filed <N> "<subject>"` — `<N>` the number `gh issue create` printed, and **the same subject string you passed to `check`**, so the next `check` for that finding meets it in the filed list instead of scoring a rewording. Without it the guard's ledger half never holds a row, and its exit **1** can never fire. If `filed` fails, retry it once; if it fails again, leave the issue alone — it exists and is correct — and report it as `unrecorded: #N <subject>`, so the controller runs `filed` for it. Report `filed: #N <subject>` for every issue you created — under the fleet, in your report to the controller. **The one window the guard cannot see:** `check` → `gh issue create` → `filed` is three commands, and the ledger's lock covers each alone, so two filers can both read `clean` in the seconds before either records. That gap is accepted, never a reason to skip `filed`. Post the numbers as one PR comment.
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 `~/.fleet/bin/fleet-run ledger.mjs check "<subject>"`, never a bare `gh issue list --search`** — the duplicate class that guard exists to catch was filed from *here*. `check` reads this run's filed list *and* the tracker at `--state all`, so a closed duplicate still counts. Exit **1** is already filed in this run; exit **3** is a clean ledger with matching tracker rows that score against the subject — read the ones it prints and comment on the existing follow-up rather than filing a second issue. **Exit 0 is not automatically "safe to file"**: it covers `clean`, `soft-hit` and `unverified` alike, and an unreachable `gh` degrades to a ledger-only answer that says `TRACKER NOT CHECKED`, so read the stdout `verdict` to tell a tracker that was searched and clean from one nobody read — under `unverified`, search it yourself before filing — or, for the applied-promotion comment above, before treating a tracker nobody could read as a reason to skip it. **`soft-hit` is the answer that costs most to misread**: it means related rows were found and none of them was established as a duplicate — a near-miss above the floor, or tracker rows the scorer rates 0.00 — so read the rows it printed and decide, and never treat that exit 0 as permission. Exit **2** is a usage error, meaning nothing was checked at all: fix the invocation and re-run, never read it as a duplicate. Full exit-code and `verdict` semantics live in `$(~/.fleet/bin/fleet-run --root)/skills/run-team/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 `~/.fleet/bin/fleet-run ledger.mjs filed <N> "<subject>"` — `<N>` the number `gh issue create` printed, and **the same subject string you passed to `check`**, so the next `check` for that finding meets it in the filed list instead of scoring a rewording. Without it the guard's ledger half never holds a row, and its exit **1** can never fire. If `filed` fails, retry it once; if it fails again, leave the issue alone — it exists and is correct — and report it as `unrecorded: #N <subject>`, so the controller runs `filed` for it. Report `filed: #N <subject>` for every issue you created — under the fleet, in your report to the controller. **The one window the guard cannot see:** `check` → `gh issue create` → `filed` is three commands, and the ledger's lock covers each alone, so two filers can both read `clean` in the seconds before either records. That gap is accepted, never a reason to skip `filed`. Post the numbers as one PR comment.
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
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 `$(~/.fleet/bin/fleet-run --root)/skills/run-team/SKILL.md`'s fix-applier prompt block. A `failure` is the diff's own fault and blocks the label, else a genuinely broken PR gets labelled off a green `check` and burns a merge-bot rebase+CI cycle before the failure resurfaces. Read per-job state for this: run `ci-state.mjs` **without** `--quiet`, or read its `jobs` — the `--quiet` payload drops the per-job `jobs`/`missing` and the `dropped` list, keeping `reasons` (which still distinguishes `is failure` from `is skipped`). You reach step 6 yourself only when green is already in hand at push time.
@@ -80,8 +80,8 @@ Nothing else names that head. A commit's dates are when it was made, not when it
80
80
  **No record — a hand-added label, or one applied before its labeller recorded a head — falls back to the timeline, which can refuse a moved head but never name the labelled one.** Read it before `gh pr update-branch` too: your own rebase lands commits after the label by construction, so once you have rebased this read can no longer tell your commits from someone else's:
81
81
 
82
82
  ```bash
83
- gh api "repos/{owner}/{repo}/issues/<pr>/timeline?per_page=100" --paginate \
84
- -q '.[] | select((.event == "labeled" and .label.name == "<ready-to-merge string>")
83
+ label="<ready-to-merge string>" gh api "repos/{owner}/{repo}/issues/<pr>/timeline?per_page=100" --paginate \
84
+ -q '.[] | select((.event == "labeled" and .label.name == env.label)
85
85
  or .event == "committed" or .event == "head_ref_force_pushed")
86
86
  | .event + " " + (.sha // .label.name // "")'
87
87
  ```
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@feigi/fleet-ctl",
3
- "version": "3.128.2",
3
+ "version": "3.129.0",
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": {
@@ -41,12 +41,22 @@
41
41
  // commit-and-pr `git switch -c <branch>` (`--branch`, default
42
42
  // `chore/run-artifacts-<UTC date>`, suffixed `b`, `c`… while
43
43
  // that name exists locally or on origin), commit exactly the
44
- // three `docs/metrics/*.tsv` files, push `-u`, `gh pr create
45
- // --label patch` with a body naming the reason and the rows
46
- // each file gained and lost, `git switch main`. The branch, and
47
- // the PR once it exists, are kept in the receipt: a re-run
48
- // after a failed push or PR resumes on that branch and never
49
- // opens a second PR.
44
+ // three `docs/metrics/*.tsv` files, `git fetch origin`, `git
45
+ // rebase origin/main`, push `-u` with a lease, `gh pr
46
+ // create --label patch` with a body naming the reason and the
47
+ // rows each file gained and lost, `git switch main`. The
48
+ // rebase is three-way, so rows `main` gained during the run
49
+ // stay; one that conflicts or that git refuses is aborted, the
50
+ // branch is pushed as it was, and the PR is opened all the
51
+ // same, for the merge step to leave open. The lease expects
52
+ // origin's branch at the head the receipt last recorded as
53
+ // pushed, or absent before the first push, so a re-run
54
+ // pushes its rebased branch over the one it pushed before,
55
+ // and over nothing else: a branch someone else pushed to
56
+ // fails the step. The branch, the pushed head
57
+ // (the merge step's pin) and the PR once it exists are kept
58
+ // in the receipt: a re-run after a failed push or PR resumes
59
+ // on that branch and never opens a second PR.
50
60
  // phase0-receipt moves `.fleet/phase0.json` to `.fleet/phase0.previous.json`,
51
61
  // the name `phase0.mjs` holds a previous run's receipt under,
52
62
  // so a run that ended here leaves no phase-0 receipt for the
@@ -56,8 +66,46 @@
56
66
  // before the stop. No `phase0.json` is nothing to move and is
57
67
  // `ok`; a held receipt already there that is not this one is
58
68
  // a failed step.
59
- // heartbeat-stop `fleet-heartbeat.mjs --stop "<reason>"`, last, because
60
- // every reader takes a recorded stop as the end of the run.
69
+ // heartbeat-stop `fleet-heartbeat.mjs --stop "<reason>"`. Every reader takes
70
+ // a recorded stop as the end of the run, and it comes before
71
+ // the merge step because a stopped beat starts no alarm
72
+ // turn: before the stop, every wake ends in a tick, which
73
+ // lists the open Close-out PR as a review to dispatch and
74
+ // holds the run open. A `finish` call omp has moved to the
75
+ // background still delivers its result as a turn of its own.
76
+ // merge merges the Close-out PR the step before opened. A rebase
77
+ // that conflicted or was refused leaves it open at once.
78
+ // Otherwise `inertVerdict()` (finisher-scope.mjs) at the
79
+ // pin; anything but `inert` leaves it open. Then, every 30 s,
80
+ // `gh pr view <n> --json state,headRefOid,mergeStateStatus`
81
+ // and `ci-state.mjs --pr <n> --declare-no-ci`: green CI, the
82
+ // head at the pin and `mergeStateStatus` CLEAN or HAS_HOOKS
83
+ // is one `gh pr merge <n> --merge --match-head-commit <pin>`,
84
+ // then a read that confirms MERGED: `merged PR #<n> at <sha>`.
85
+ // A PR already MERGED is that line too; one CLOSED is
86
+ // `closed: PR #<n>`. A failed check (UNSTABLE included), a
87
+ // head off the pin, BEHIND or DIRTY is `left open: PR #<n> —
88
+ // <reason>`, ok, with nothing armed or retried: the next
89
+ // run's phase 0 folds it in. Every other state keeps the
90
+ // step pending, `NEED merge-wait PR #<n>` over the last state
91
+ // read: CI pending, gh or CI unreadable, green CI with
92
+ // `mergeStateStatus` neither CLEAN nor HAS_HOOKS, or a `gh pr
93
+ // merge` that failed or has not landed. 30 minutes after the
94
+ // step first ran, that state leaves the PR open the same way:
95
+ // `the 30-min bound: <state>`, or `gh unreadable until the
96
+ // bound` / `CI unreadable until the bound`. The step stops
97
+ // waiting within 4 minutes of the `finish` call's start; the
98
+ // steps before it are not held to that. The next call resumes
99
+ // from the receipt without pushing, opening or merging again,
100
+ // and one call asks `gh pr merge` at most once. A receipt
101
+ // whose `mergeStarted` is not a past time, or whose `rebase`
102
+ // is neither null nor a reason, fails the step. The step runs
103
+ // gh and read-only git only, and never moves HEAD, the index
104
+ // or a ref. It never arms auto-merge: GitHub keeps
105
+ // auto-merge armed across pushes by anyone with write
106
+ // access, and every member pushes with the maintainer's
107
+ // credentials. It never passes `--delete-branch`, which also
108
+ // deletes the local branch and switches the checkout.
61
109
  //
62
110
  // `reopen` undoes `begin` for a run that must drain again: refused (exit 2)
63
111
  // once any `finish` step is ok, since the tick and what follows it have already
@@ -68,15 +116,19 @@
68
116
  // THE RECEIPT is `.fleet/closeout.json` (resolved through fleet-dir.mjs, so a
69
117
  // worktree and the main checkout name one file), shared by all three commands:
70
118
  //
71
- // { reason, begun, branch, pr, steps: { <name>: { status, at, output } } }
119
+ // { reason, begun, branch, pr, pin, rebase, mergeStarted, mergeOutcome,
120
+ // steps: { <name>: { status, at, output } } }
72
121
  //
73
122
  // `status` is ok, pending or failed; `at` an ISO time; `output` the step's own
74
123
  // words. Every step name of both commands is always present: one not yet run
75
124
  // is `pending`. `begun` is the time `begin` finished its steps, ok or pending,
76
- // null until then; `branch` and `pr` belong to the commit-and-pr step. A re-run
77
- // skips every `ok` step and runs the rest, stopping at the first that is not
78
- // `ok`, so the steps after it stay `pending`. `ledger.mjs rotate` archives the
79
- // receipt beside the ledger as `closeout.<UTC stamp>.json`.
125
+ // null until then; `branch`, `pr`, `pin` (the head pushed) and `rebase` (null,
126
+ // or why the rebase was aborted) belong to the commit-and-pr step;
127
+ // `mergeStarted` (the merge step's first run, an ISO time) and `mergeOutcome`
128
+ // (its final line) to the merge step. A re-run skips every `ok` step and runs
129
+ // the rest, stopping at the first that is not `ok`, so the steps after it stay
130
+ // `pending`. `ledger.mjs rotate` archives the receipt beside the ledger as
131
+ // `closeout.<UTC stamp>.json`.
80
132
  //
81
133
  // One `closeout: <step>: <status>` line per step on stdout, its output under
82
134
  // it, indented, with the `NEED` lines at the left margin. Exit 0 every step
@@ -95,6 +147,7 @@ import { dirname, join } from "node:path";
95
147
  import { fileURLToPath } from "node:url";
96
148
  import { makeDie, defineFlags } from "./arg.mjs";
97
149
  import { FleetDirUnresolvable, fleetFile } from "./fleet-dir.mjs";
150
+ import { inertVerdict } from "./finisher-scope.mjs";
98
151
  import { gitEnv } from "./git-env.mjs";
99
152
  import { isCLI } from "./is-cli.mjs";
100
153
  import { CLOSEOUT_RECEIPT, RECEIPT, RECEIPT_HELD, memberTokens, rowPr, isOmpSessionDirName } from "./ledger-grammar.mjs";
@@ -148,6 +201,8 @@ function fatal(message) {
148
201
  // ── the receipt ──────────────────────────────────────────────────────────────
149
202
 
150
203
  const blank = () => ({ status: "pending", at: null, output: "" });
204
+ // The receipt's own fields, in the order it is written; each null until set.
205
+ const RECEIPT_FIELDS = ["reason", "begun", "branch", "pr", "pin", "rebase", "mergeStarted", "mergeOutcome"];
151
206
 
152
207
  function readReceipt(path, stepNames) {
153
208
  let prior = null;
@@ -157,7 +212,7 @@ function readReceipt(path, stepNames) {
157
212
  if (e.code !== "ENOENT") fatal(`cannot read receipt ${path}: ${e.message}`);
158
213
  }
159
214
  const steps = Object.fromEntries(stepNames.map((n) => [n, { ...blank(), ...prior?.steps?.[n] }]));
160
- return { reason: prior?.reason ?? null, begun: prior?.begun ?? null, branch: prior?.branch ?? null, pr: prior?.pr ?? null, steps };
215
+ return { ...Object.fromEntries(RECEIPT_FIELDS.map((k) => [k, prior?.[k] ?? null])), steps };
161
216
  }
162
217
 
163
218
  function writeReceipt(path, receipt) {
@@ -303,6 +358,33 @@ function rowCounts(git) {
303
358
  return { lines: r.stdout.split("\n").filter(Boolean).map((l) => l.split("\t")).map(([added, removed, file]) => `- ${file}: +${added} -${removed}`) };
304
359
  }
305
360
 
361
+ // Replays the branch's commit onto the `origin/main` just fetched, three-way,
362
+ // so rows `main` gained during the run stay. A replay that stops on a
363
+ // conflict, or that git refuses to start, is aborted and the branch stays as
364
+ // it was: `{ leftOpen }` names why, and the step goes on to push and open the
365
+ // PR. `{ error }` is a fetch, or an abort, that failed.
366
+ function rebaseOntoMain(git) {
367
+ const fetch = git(["fetch", "origin"], NETWORK_TIMEOUT_MS);
368
+ if (fetch.status !== 0) return { error: `git fetch origin failed: ${detail(fetch)}` };
369
+ const rebase = git(["rebase", "origin/main"]);
370
+ if (rebase.status === 0) return { leftOpen: null };
371
+ const unmerged = git(["diff", "--name-only", "--diff-filter=U"]);
372
+ const stopped = git(["rev-parse", "--verify", "--quiet", "REBASE_HEAD"]);
373
+ if (stopped.status === 0) {
374
+ const abort = git(["rebase", "--abort"]);
375
+ if (abort.status !== 0) return { error: `git rebase origin/main stopped and git rebase --abort failed: ${detail(abort)}` };
376
+ }
377
+ // git's first line, then the paths it lists indented under it, such as the
378
+ // untracked files a replay would overwrite.
379
+ const [said, ...rest] = detail(rebase).split("\n");
380
+ const named = rest.filter((l) => /^\s/.test(l)).map((l) => l.trim());
381
+ const refused = [said, named.join(", ")].filter(Boolean).join(" ");
382
+ if (unmerged.status !== 0) return { leftOpen: `rebase failed: ${refused}; git diff --diff-filter=U failed: ${detail(unmerged)}` };
383
+ const files = unmerged.stdout.split("\n").filter(Boolean);
384
+ if (files.length > 0) return { leftOpen: `rebase conflict: ${files.join(", ")}` };
385
+ return { leftOpen: `rebase refused: ${refused}` };
386
+ }
387
+
306
388
  // Everything the step does while the checkout is on the metrics branch; the
307
389
  // caller switches back to main whatever this returns.
308
390
  function onBranch({ git, cwd, reason, receipt, save }) {
@@ -312,14 +394,25 @@ function onBranch({ git, cwd, reason, receipt, save }) {
312
394
  const commit = git(["commit", "-m", `Closeout: ${reason}`, "--", ...METRICS]);
313
395
  if (commit.status !== 0) return failed(`git commit failed: ${detail(commit)}`);
314
396
  }
397
+ const rebased = rebaseOntoMain(git);
398
+ if (rebased.error) return failed(rebased.error);
315
399
  const ahead = git(["rev-list", "--count", "origin/main..HEAD"]);
316
400
  if (ahead.status !== 0) return failed(`git rev-list --count origin/main..HEAD failed: ${detail(ahead)}`);
317
401
  if (ahead.stdout === "0") return failed(`nothing to commit: ${METRICS.join(", ")} are unchanged`);
402
+ const head = git(["rev-parse", "HEAD"]);
403
+ if (head.status !== 0) return failed(`git rev-parse HEAD failed: ${detail(head)}`);
318
404
 
319
- const push = git(["push", "-u", "origin", receipt.branch], NETWORK_TIMEOUT_MS);
405
+ // The lease is the head this step last pushed, never what the fetch above
406
+ // just read: an empty one expects the branch absent from origin.
407
+ const lease = `--force-with-lease=refs/heads/${receipt.branch}:${receipt.pin ?? ""}`;
408
+ const push = git(["push", "-u", lease, "origin", receipt.branch], NETWORK_TIMEOUT_MS);
320
409
  if (push.status !== 0) return failed(`git push failed: ${detail(push)}`);
410
+ receipt.pin = head.stdout;
411
+ receipt.rebase = rebased.leftOpen;
412
+ save();
413
+ const lines = [`pushed ${receipt.pin}`, ...(rebased.leftOpen === null ? [] : [rebased.leftOpen])];
321
414
 
322
- if (receipt.pr !== null) return ok(`PR ${receipt.pr} already opened for ${receipt.branch}`);
415
+ if (receipt.pr !== null) return ok([...lines, `PR ${receipt.pr} already opened for ${receipt.branch}`].join("\n"));
323
416
  const counts = rowCounts(git);
324
417
  if (counts.error) return failed(counts.error);
325
418
  const body = `Closeout: ${reason}\n\nRows changed:\n${counts.lines.join("\n")}\n`;
@@ -327,13 +420,19 @@ function onBranch({ git, cwd, reason, receipt, save }) {
327
420
  if (pr.status !== 0) return failed(`gh pr create failed: ${detail(pr)}`);
328
421
  receipt.pr = pr.stdout.split("\n").at(-1);
329
422
  save();
330
- return ok(`PR ${receipt.pr} opened on ${receipt.branch}`);
423
+ return ok([...lines, `PR ${receipt.pr} opened on ${receipt.branch}`].join("\n"));
331
424
  }
332
425
 
333
- function stepCommitAndPR({ reason, branch, receipt, save }) {
426
+ // The work tree the command runs in, as `{ cwd }`, or `{ error }`.
427
+ function workTree() {
334
428
  const top = run("git", ["rev-parse", "--show-toplevel"], { cwd: process.cwd() });
335
- if (top.status !== 0) return failed(`not inside a git work tree: ${detail(top)}`);
336
- const cwd = top.stdout;
429
+ return top.status === 0 ? { cwd: top.stdout } : { error: `not inside a git work tree: ${detail(top)}` };
430
+ }
431
+
432
+ function stepCommitAndPR({ reason, branch, receipt, save }) {
433
+ const wt = workTree();
434
+ if (wt.error) return failed(wt.error);
435
+ const { cwd } = wt;
337
436
  const git = (args, timeoutMs) => run("git", args, { cwd, timeoutMs });
338
437
 
339
438
  if (receipt.branch === null) {
@@ -383,6 +482,135 @@ function stepHeartbeatStop({ cwd, reason }) {
383
482
  return r.status === 0 ? ok(r.stdout) : failed(`fleet-heartbeat.mjs --stop failed: ${detail(r)}`);
384
483
  }
385
484
 
485
+ // One read of the PR: `{ state, headRefOid, mergeStateStatus }`, or
486
+ // `{ unreadable }` naming what gh answered instead.
487
+ function readPr(n, cwd, timeoutMs) {
488
+ const r = run("gh", ["pr", "view", n, "--json", "state,headRefOid,mergeStateStatus"], { cwd, env: { GH_REPO: "" }, timeoutMs });
489
+ if (r.status !== 0) return { unreadable: `gh pr view failed: ${detail(r)}` };
490
+ let v = null;
491
+ try {
492
+ v = JSON.parse(r.stdout);
493
+ } catch {
494
+ // Not JSON: named below with what gh printed.
495
+ }
496
+ if (typeof v?.state === "string" && typeof v.headRefOid === "string" && typeof v.mergeStateStatus === "string") return v;
497
+ return { unreadable: `gh pr view answered ${r.stdout || "nothing"}` };
498
+ }
499
+
500
+ // CI as the merge gate reads it, `ci-state.mjs --pr <n> --declare-no-ci`, with
501
+ // the payload and the exit status agreeing. A not-green answer whose run has
502
+ // not completed, or that found no run on the head yet, is still pending; one
503
+ // whose run completed is a failed check.
504
+ function readCi(n, cwd, timeoutMs) {
505
+ const r = node("ci-state.mjs", ["--pr", n, "--declare-no-ci"], { cwd, env: { GH_REPO: "" }, timeoutMs });
506
+ let ci = null;
507
+ try {
508
+ ci = JSON.parse(r.stdout);
509
+ } catch {
510
+ // Not JSON: unreadable below.
511
+ }
512
+ if (ci === null || typeof ci !== "object") return { unreadable: `ci-state.mjs answered nothing readable: ${detail(r)}` };
513
+ if (r.status === 0 && (ci.verdict === "green" || ci.verdict === "no-ci")) return { green: true, prHead: ci.prHead };
514
+ if (r.status === 1 && ci.verdict === "not-green" && Array.isArray(ci.reasons)) {
515
+ const why = ci.reasons.join("; ") || "not green";
516
+ return ci.status === "completed" ? { failed: why } : { pending: why };
517
+ }
518
+ return { unreadable: `ci-state.mjs ${r.how}, verdict ${ci.verdict ?? "absent"}` };
519
+ }
520
+
521
+ // The merge step's clocks: it stops waiting within CALL_MS of the `finish`
522
+ // call's start, reads the PR every POLL_MS, sleeps only while READ_MS is left
523
+ // after the sleep for the reads that follow it, and stops waiting BOUND_MS
524
+ // after its first run. CLOSEOUT_CALL_MS and CLOSEOUT_POLL_MS can only shorten
525
+ // theirs.
526
+ const shorter = (name, ms) => {
527
+ const v = Number(process.env[name]);
528
+ return Number.isInteger(v) && v > 0 && v < ms ? v : ms;
529
+ };
530
+ const CALL_MS = shorter("CLOSEOUT_CALL_MS", 4 * 60_000);
531
+ const POLL_MS = shorter("CLOSEOUT_POLL_MS", 30_000);
532
+ const READ_MS = CALL_MS / 8;
533
+ const BOUND_MS = 30 * 60_000;
534
+ const BOUND = "the 30-min bound";
535
+ const PR_NUMBER = /\/pull\/(\d+)$/;
536
+ const FULL_SHA = /^[0-9a-f]{40}$/;
537
+ const MERGEABLE = new Set(["CLEAN", "HAS_HOOKS"]);
538
+ // Atomics.wait never blocks on a value nothing writes, so it is a plain sleep.
539
+ const IDLE = new Int32Array(new SharedArrayBuffer(4));
540
+
541
+ function stepMerge({ receipt, save, started }) {
542
+ const n = PR_NUMBER.exec(receipt.pr ?? "")?.[1];
543
+ if (n === undefined) return failed(`no PR number in the receipt's pr: ${receipt.pr}`);
544
+ const done = (line) => {
545
+ receipt.mergeOutcome = line;
546
+ save();
547
+ return ok(line);
548
+ };
549
+ const leftOpen = (why) => done(`left open: PR #${n} — ${why}`);
550
+ const merged = (oid) => done(`merged PR #${n} at ${oid}`);
551
+ const { rebase } = receipt;
552
+ if (rebase !== null && (typeof rebase !== "string" || rebase === "")) return failed(`the receipt's rebase is neither null nor a reason: ${JSON.stringify(rebase)}`);
553
+ if (rebase !== null) return leftOpen(rebase);
554
+ if (!FULL_SHA.test(receipt.pin ?? "")) return failed(`no pushed head in the receipt to pin the merge to: ${receipt.pin}`);
555
+ const wt = workTree();
556
+ if (wt.error) return failed(wt.error);
557
+ const { cwd } = wt;
558
+ if (receipt.mergeStarted === null) {
559
+ receipt.mergeStarted = new Date().toISOString();
560
+ save();
561
+ }
562
+ // NaN, from anything but a time string, fails the comparison too.
563
+ const begun = typeof receipt.mergeStarted === "string" ? Date.parse(receipt.mergeStarted) : NaN;
564
+ if (!(begun <= Date.now())) return failed(`the receipt's mergeStarted is not a past time: ${JSON.stringify(receipt.mergeStarted)}`);
565
+
566
+ const v = inertVerdict({ worktree: cwd, pin: receipt.pin });
567
+ if (v.verdict !== "inert") {
568
+ const why = v.reason ?? v.paths.filter((p) => p.class === null).map((p) => `${p.path} (${p.why})`).join(", ");
569
+ return leftOpen(`verdict ${v.verdict}: ${why}`);
570
+ }
571
+
572
+ const bound = begun + BOUND_MS;
573
+ const deadline = started + CALL_MS - CALL_MS / 8;
574
+ const budget = () => Math.min(NETWORK_TIMEOUT_MS, Math.max(1, Math.floor(deadline - Date.now())));
575
+ // `at` is how the bound names the state if it is the last one read.
576
+ const atBound = (last) => leftOpen(`${last.at}: ${last.why}`);
577
+ const NOT_YET = { at: BOUND, why: "gh pr merge answered and the PR is not MERGED yet" };
578
+ let last = { at: BOUND, why: "not read yet" };
579
+ // What the call's one `gh pr merge` answered, kept for every later poll so a
580
+ // failed merge's own words reach the NEED line and the bound.
581
+ let asked = null;
582
+ while (Date.now() < deadline) {
583
+ const pr = readPr(n, cwd, budget());
584
+ if (pr.unreadable) last = { at: "gh unreadable until the bound", why: pr.unreadable };
585
+ else if (pr.state === "MERGED") return merged(pr.headRefOid);
586
+ else if (pr.state === "CLOSED") return done(`closed: PR #${n}`);
587
+ else if (pr.headRefOid !== receipt.pin) return leftOpen(`head moved off the pin ${receipt.pin}: ${pr.headRefOid}`);
588
+ else if (pr.mergeStateStatus === "BEHIND" || pr.mergeStateStatus === "DIRTY") return leftOpen(pr.mergeStateStatus);
589
+ else {
590
+ const ci = readCi(n, cwd, budget());
591
+ if (ci.failed) return leftOpen(`a check failed: ${ci.failed}`);
592
+ if (ci.unreadable) last = { at: "CI unreadable until the bound", why: ci.unreadable };
593
+ else if (ci.pending) last = { at: BOUND, why: `CI pending: ${ci.pending}` };
594
+ else if (ci.prHead !== receipt.pin) return leftOpen(`head moved off the pin ${receipt.pin}: ${ci.prHead}`);
595
+ else if (pr.mergeStateStatus === "UNSTABLE") return leftOpen("a check failed: UNSTABLE");
596
+ else if (!MERGEABLE.has(pr.mergeStateStatus)) last = { at: BOUND, why: `CI green, mergeStateStatus ${pr.mergeStateStatus}` };
597
+ else if (asked !== null) last = asked;
598
+ else {
599
+ const merge = run("gh", ["pr", "merge", n, "--merge", "--match-head-commit", receipt.pin], { cwd, env: { GH_REPO: "" }, timeoutMs: budget() });
600
+ const after = readPr(n, cwd, budget());
601
+ if (after.state === "MERGED") return merged(after.headRefOid);
602
+ asked = merge.status === 0 ? NOT_YET : { at: BOUND, why: `gh pr merge failed: ${detail(merge)}` };
603
+ last = asked;
604
+ }
605
+ }
606
+ if (Date.now() >= bound) return atBound(last);
607
+ if (Date.now() + POLL_MS + READ_MS >= deadline) break;
608
+ Atomics.wait(IDLE, 0, 0, POLL_MS);
609
+ }
610
+ if (Date.now() >= bound) return atBound(last);
611
+ return pending(`NEED merge-wait PR #${n}\n${last.why}`);
612
+ }
613
+
386
614
  // ── the steps, in order ──────────────────────────────────────────────────────
387
615
 
388
616
  const BEGIN = { drain: stepDrain, release: stepRelease };
@@ -394,6 +622,7 @@ const FINISH = {
394
622
  "commit-and-pr": stepCommitAndPR,
395
623
  "phase0-receipt": stepPhase0Receipt,
396
624
  "heartbeat-stop": stepHeartbeatStop,
625
+ merge: stepMerge,
397
626
  };
398
627
  const STEP_NAMES = [...Object.keys(BEGIN), ...Object.keys(FINISH)];
399
628
 
@@ -470,7 +699,7 @@ function main() {
470
699
  const receiptPath = join(fleetDir, CLOSEOUT_RECEIPT);
471
700
  const receipt = readReceipt(receiptPath, STEP_NAMES);
472
701
  receipt.reason = reason;
473
- const ctx = { cwd: process.cwd(), fleetDir, reason, branch };
702
+ const ctx = { cwd: process.cwd(), fleetDir, reason, branch, started: performance.timeOrigin };
474
703
  if (cmd === "reopen") {
475
704
  process.exitCode = reopen(ctx, receipt, receiptPath);
476
705
  } else if (cmd === "begin") {
@@ -18,8 +18,8 @@
18
18
  // origin every Label role -> "table" | "default" | "maintainer"
19
19
  //
20
20
  // VALID STRINGS (labelStringFaults): non-empty after trimming, at most 50
21
- // code points, no `"` and no `\`, and no two roles mapping to one string,
22
- // compared ignoring case.
21
+ // code points, none of `"`, `\`, `$`, a backtick and `,`, and no two roles
22
+ // mapping to one string, compared ignoring case.
23
23
  //
24
24
  // THE READER (readLabelMap) returns `roles` when the cache parses, holds every
25
25
  // Label role and passes the string rules; anything else throws
@@ -137,6 +137,9 @@ function stringFault(value) {
137
137
  if (length > MAX_LENGTH) return `longer than ${MAX_LENGTH} code points (${length})`;
138
138
  if (value.includes('"')) return 'contains `"`';
139
139
  if (value.includes("\\")) return "contains `\\`";
140
+ if (value.includes("$")) return "contains `$`";
141
+ if (value.includes("`")) return "contains a backtick";
142
+ if (value.includes(",")) return "contains `,`";
140
143
  return null;
141
144
  }
142
145
 
@@ -93,7 +93,7 @@ Infer branch/worktree convention from `git worktree list` / `git branch -r` —
93
93
 
94
94
  **Run the Install step with `CI` removed**, from the new worktree's root: `env -u CI sh -c "<install>"`, `<install>` the output of `derive-testcmd.sh . install`. A setup script that skips under `CI` installs no git hooks there, and you would then commit with the repository's commit-time checks silently absent. Only the Install step loses `CI`; the Check step and the Test entrypoint baseline run in your shell's own environment.
95
95
 
96
- Abandoned before PR opens → remove the `<in-progress string>` label.
96
+ Abandoned before PR opens → `gh issue edit <N> --remove-label "<in-progress string>"`.
97
97
 
98
98
  ## 6. Size the ticket, then pick a path
99
99
 
@@ -24,7 +24,7 @@ These hold in every phase: check each wake against them, and report evidence tha
24
24
  - A grandchild surfaces as its own task-notification; an unrecognized task-id is not a member reporting done.
25
25
  - A reviewer never reviews a PR it implemented.
26
26
  - The merge bot only touches PRs whose implementer reported done; rebasing a worktree someone is working in destroys uncommitted work.
27
- - `ready-to-merge` is added by a reviewer only — never an implementer, never you — but for the run's own artifact PR, which this line does not reach: label and merge that one yourself.
27
+ - `ready-to-merge` is added by a reviewer only — never an implementer, never you.
28
28
  - Every member acts through the maintainer's `gh` credentials, so no write is attributable: when a label moves unexpectedly, ask members directly, rule out automation with `grep -rn '<label>' .github/workflows/`, and do not re-add it.
29
29
  - Phase 1 is serial; everything else may run concurrently.
30
30
 
@@ -193,9 +193,9 @@ owes beyond its call:
193
193
  `ACTION: run over → fleet-heartbeat.mjs --stop "<reason>"`, which it does
194
194
  once the run is draining with no open PR and no live implementer.
195
195
  3. `~/.fleet/bin/fleet-run closeout.mjs finish --reason "<reason>"`, which
196
- then records `fleet-heartbeat.mjs --stop` last, because every reader takes
197
- a recorded stop as the end of the run. A `NEED tier-outcomes append <pr>`
198
- is a reviewed PR with no verdict row — for an implementer's, one that never
196
+ records `fleet-heartbeat.mjs --stop` and then merges the Close-out PR. On `NEED merge-wait PR #<n>`,
197
+ run `finish` again at once. A PR it names `left open` is the next run's: you never label or merge it.
198
+ A `NEED tier-outcomes append <pr>` is a reviewed PR with no verdict row — for an implementer's, one that never
199
199
  reached its finisher: run `append <pr>` (**Guard: accumulate per PR**) and run `finish` again.
200
200
  A PR closing none or several: a NEED if a settled `impl-<N>=PR#<pr>` token
201
201
  names it, else a note. A step it fails is explained in
@@ -623,9 +623,7 @@ again.
623
623
 
624
624
  **It refuses a finisher, too, while the PR sits on a conflict hold no
625
625
  fix-applier has cleared** — the same per-PR fold the tick prints `DISPATCH
626
- fix-pr` off, ahead of the dispositions verdict. A PR known to conflict cannot
627
- merge, and a finisher on it would race the conflict fix-applier rebasing it.
628
- Dispatch that fix-applier, let it settle `applied:`/`no-op`, then dispatch the
626
+ fix-pr` off, ahead of the dispositions verdict. Dispatch that fix-applier, let it settle `applied:`/`no-op`, then dispatch the
629
627
  finisher again.
630
628
 
631
629
  **An unanswered question from the member is an outbox item, and it blocks dispatch with the same weight as a reply you have already decided on.** See references/finisher.md.
@@ -636,7 +634,7 @@ in the fix-applier body, not in per-event messages.**
636
634
  **Once the label is on, take it off before you approve any push.** Write `label-off=<latest finisher attempt>` onto the PR's row first
637
635
  (`ledger.mjs token <PR number> label-off=<latest finisher attempt>`, which keeps
638
636
  every token the row already has, see references/ledger.md), then
639
- remove `ready-to-merge`, then approve. Then
637
+ remove the label (`gh pr edit <pr> --remove-label "<ready-to-merge string>"`, the string `show ready-to-merge` prints), then approve. Then
640
638
  dispatch a **fresh** finisher against the new head; the first audit does not
641
639
  transfer, since it verified a different tree. See references/finisher.md.
642
640
 
@@ -20,9 +20,11 @@
20
20
  3. `~/.fleet/bin/fleet-run closeout.mjs finish --reason "<reason>"` — scrapes
21
21
  the run's member facts, checks the tier-outcomes rows, refreshes the
22
22
  metrics, commits the three metrics files and opens their PR, sets the
23
- phase-0 receipt aside as `.fleet/phase0.previous.json`, then records
24
- `fleet-heartbeat.mjs --stop` last, because every reader takes a recorded
25
- stop as the end of the run. A `NEED tier-outcomes append <pr>` is a
23
+ phase-0 receipt aside as `.fleet/phase0.previous.json`, records
24
+ `fleet-heartbeat.mjs --stop`, because every reader takes a recorded stop
25
+ as the end of the run, and then merges the Close-out PR. On `NEED
26
+ merge-wait PR #<n>`, run `finish` again at once. A PR it names `left open`
27
+ is the next run's: you never label or merge it. A `NEED tier-outcomes append <pr>` is a
26
28
  reviewed PR with no verdict row — for an implementer's PR, one that never
27
29
  reached its finisher, since `ledger.mjs dispatch` refuses that finisher
28
30
  until the row exists: run `append <pr>` (**Guard: accumulate per PR**) and run `finish` again. A reviewed
@@ -122,6 +122,8 @@ and will act on it. Relay everything — reversals too — then dispatch.
122
122
  - **The PR's closing references match its ruling and exclude its own suggestion-band record** → `ledger.mjs dispatch` reads the PR's `closingIssuesReferences` from `gh pr view <M>` before it dispatches any finisher, counting only those in the PR's own repository: a reference into another repository closes none of this repository's tickets, whatever its number. When the ruled row says `closed_own_ticket=yes`, each ticket a settled `impl-<N>=PR#<M>` token names must be closed by the body (`Closes #<N>`); when it says `no`, none may be, and no reference may be the PR's own suggestion-band record. A blank verdict is refused until it is set. A refusal names the PR and the ticket. The controller repairs the body itself with `gh pr edit <M> --body-file <file>`, then dispatches the finisher again. A `gh` read that fails refuses the dispatch and writes nothing.
123
123
  - **The PR carries exactly one release label** → `ledger.mjs dispatch` reads the PR's labels from `gh pr view <M>` before it dispatches any finisher, and refuses unless exactly one of `patch`, `minor` and `major` is among them — the count `finisher-label.mjs` makes before it labels. A repository whose label list defines none of the three is not gated. A Ticketless PR with none is not refused: `finisher-label.mjs` adds `patch` to it before its count. Any other PR with none is refused naming the tickets it closes, and any PR with several naming the labels found — the bump, or which label stays, is not picked for the controller. The controller adds or removes the label itself, then dispatches the finisher again. A `gh` read that fails or answers malformed refuses the dispatch, saying the labels could not be read, and writes nothing.
124
124
 
125
+ A PR known to conflict cannot merge, and a finisher on it would race the conflict fix-applier rebasing it. That is why the conflict-hold refusal SKILL.md describes exists.
126
+
125
127
  Gate on the `check` job, **not** on `ci-state --quiet` exit 0: a behind PR never
126
128
  reaches full green, so an exit-0 gate strands it unlabelled. The finisher reads
127
129
  per-job state (`ci-state.mjs` without `--quiet`, or its `jobs`), since `--quiet`
@@ -74,9 +74,9 @@ and never re-pin.
74
74
  **File it where the plugin is developed.** When this main checkout's `origin`
75
75
  is the repository that `repository.url` in the Install root's `package.json`
76
76
  names — the same host and `owner/repo` — file it the way `review-and-fix.md`
77
- step 5 files a deferral: `ledger.mjs check "<subject>"`, then `gh issue create`
78
- labelled with the string `~/.fleet/bin/fleet-run label-map.mjs show needs-triage`
79
- prints, then `ledger.mjs filed <N> "<subject>"` with the same subject. A
77
+ step 5 files a deferral: `ledger.mjs check "<subject>"`, then
78
+ `gh issue create --label "<needs-triage string>"`, `<needs-triage string>` being what
79
+ `~/.fleet/bin/fleet-run label-map.mjs show needs-triage` prints, then `ledger.mjs filed <N> "<subject>"` with the same subject. A
80
80
  tracker hit is handled the way step 5 handles one. The subject is `<path>: <the
81
81
  defect in one line>`; the body carries the evidence — the members, the text
82
82
  they followed, the transcript and ledger lines — the trigger it met, the
@@ -13,16 +13,6 @@ The invariants SKILL.md states one line each, as they read before they were tigh
13
13
  - The merge bot only touches PRs whose implementer reported done. Rebasing a
14
14
  worktree someone is working in destroys uncommitted work.
15
15
  - `ready-to-merge` is added by a reviewer only — never an implementer, never you.
16
- **The run's own artifact PR is exempt, and it is exempt because this invariant
17
- does not reach it:** what the line forbids is a fleet member signing off its own
18
- ticket work, which presupposes an issue, an implementer, a `review-pr` run and a
19
- finisher, and the metrics PR you author has none of them. Label and
20
- merge that one yourself instead of re-deriving a blocker from this line and
21
- stranding the rows behind it. The exemption belongs to the run that authors the
22
- PR and does not outlive it: one still open when the run ends is a PR a prior run
23
- left open, which phase 0 folds into the next run's review queue as ticket work —
24
- and a PR is not exempt from being wrong, only from waiting on a reviewer
25
- no phase of this run will ever dispatch against it.
26
16
  - **Every member acts through the maintainer's `gh` credentials, so no write is
27
17
  attributable.** Any invariant about *who* did something is unenforceable after
28
18
  the fact: when a label moves unexpectedly, ask members directly, rule out