@feigi/fleet-ctl 3.156.2 → 3.158.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.
@@ -153,7 +153,7 @@
153
153
  // the ledger; main() does the I/O. Split so the guard table and the reading are
154
154
  // both unit-testable without a network.
155
155
 
156
- import { parseMember, parseToken, premisesOf, rowNums, nextRetry, readRetired, pullEnded, dispositionsToken, REVIEW, REVIEWED } from "./ledger-grammar.mjs";
156
+ import { parseMember, parseToken, premisesOf, rowNums, nextRetry, readRetired, pullEnded, dispositionsToken, failedReviewLaunches, REVIEW, REVIEWED } from "./ledger-grammar.mjs";
157
157
 
158
158
  // The implementer and reviewer rows' TARGET is the In-flight bound; the merge
159
159
  // bot's is 1. Availability of work belongs in the ACTION, not the target: a
@@ -970,7 +970,7 @@ export function foldLedger({ rows, dispatched }, open, { lenient = false } = {})
970
970
  }
971
971
  if (!m && REVIEWED_RUNLESS.test(tok)) {
972
972
  throw new LedgerError(`${where}: '${tok}' names no review run — reviewed= is now <head>:<survived>/<refuted>/<unverified>:<run>, `
973
- + "<run> the run-XXXXXXXX directory holding that review's review.json; drop the token with `ledger.mjs row` and record it again with `ledger.mjs review <pr>`");
973
+ + "<run> the run-XXXXXXXX directory holding that review's review.json; drop the token with `ledger.mjs row` and record it again with `ledger.mjs review <pr> --result <path>`");
974
974
  }
975
975
  if (!m) throw new LedgerError(`${where}: '${tok}' is not reviewed=<head>:<survived>/<refuted>/<unverified>:<run>`);
976
976
  latestFinisher = null;
@@ -1227,6 +1227,10 @@ export function deriveRun({ rows, dispatched, drain, retired = [] }, prs, queued
1227
1227
  // The number of every merge bot settled `done`: each is a merge pass
1228
1228
  // `--apply` reaps, reclaims and evicts after, once (reapDue).
1229
1229
  mergeBotDone: all.filter((m) => m.family === "merge-bot" && m.outcome === "done").map((m) => m.number).sort(asc),
1230
+ // The name of every fix-applier and finisher settled, whatever its outcome,
1231
+ // and of every review launch settled `=failed`: each is a settle
1232
+ // `--apply` runs the root sweep after, once (sweepDue).
1233
+ sweepAfter: [...all.filter((m) => (m.family === "fix-pr" || m.family === "finisher-pr") && m.outcome !== null).map((m) => m.name), ...failedReviewLaunches(rows)],
1230
1234
  reviewsLive: liveReviews.length,
1231
1235
  // The in-flight reviews of PRs the open list does not carry: the ones
1232
1236
  // the probe could retire, so the caller asks gh about these and no others.
@@ -1547,21 +1551,41 @@ export function ageChecks({ live, stems }) {
1547
1551
  ];
1548
1552
  }
1549
1553
 
1550
- // --apply's pure half. The merge-bot numbers `applied.reapAfter` names for
1551
- // THIS run: none when its `run` is not the controller record's `at`, since
1552
- // merge-bot numbering restarts with a run and the state file outlives it
1553
- // (fleet-state.mjs's `applied`). `controllerAt` is null with no record, and
1554
- // with no record nothing tells this run from the one before it: a list then
1555
- // names nothing, and the sweeps run again on the next tick.
1554
+ // --apply's pure half. `applied` when its `run` is THIS run's controller
1555
+ // record `at`, else null: merge-bot numbering restarts with a run, a name such
1556
+ // as `fix-pr-7` is reused by the next run's first member of its PR, and the
1557
+ // state file outlives both (fleet-state.mjs's `applied`). `controllerAt` is
1558
+ // null with no record, and with no record nothing tells this run from the one
1559
+ // before it: a list then names nothing, and the sweeps run again on the next
1560
+ // tick.
1561
+ const ofThisRun = (applied, controllerAt) => (applied !== null && controllerAt != null && applied.run === controllerAt ? applied : null);
1562
+
1563
+ // The entries of `names` that `ran` does not hold.
1564
+ const notIn = (names, ran) => {
1565
+ const done = new Set(ran);
1566
+ return names.filter((name) => !done.has(name));
1567
+ };
1568
+
1569
+ // The merge-bot numbers `applied.reapAfter` names for THIS run.
1556
1570
  export function reapedAfter(applied, controllerAt) {
1557
- return applied !== null && controllerAt != null && applied.run === controllerAt ? applied.reapAfter : [];
1571
+ return ofThisRun(applied, controllerAt)?.reapAfter ?? [];
1558
1572
  }
1559
1573
 
1560
1574
  // The merge passes owed their reap, reclaim and evict: every merge bot settled
1561
1575
  // `done` that reapedAfter() does not name.
1562
1576
  export function reapDue(done, applied, controllerAt) {
1563
- const ran = new Set(reapedAfter(applied, controllerAt));
1564
- return done.filter((n) => !ran.has(n));
1577
+ return notIn(done, reapedAfter(applied, controllerAt));
1578
+ }
1579
+
1580
+ // The members `applied.sweptAfter` names for THIS run.
1581
+ export function sweptAfter(applied, controllerAt) {
1582
+ return ofThisRun(applied, controllerAt)?.sweptAfter ?? [];
1583
+ }
1584
+
1585
+ // The settles owed the root sweep: every member in `settled` (run.sweepAfter)
1586
+ // that sweptAfter() does not name.
1587
+ export function sweepDue(settled, applied, controllerAt) {
1588
+ return notIn(settled, sweptAfter(applied, controllerAt));
1565
1589
  }
1566
1590
 
1567
1591
  // The implementers the tick would print `HOLD (tier unchecked …)` for: read
@@ -1594,13 +1618,13 @@ export function reapSummary(stdout) {
1594
1618
  + (warned.length ? `, warnings ${warned.length}${typeof first === "string" ? `: ${first}` : ""}` : "");
1595
1619
  }
1596
1620
 
1597
- // reclaim-scratch.mjs's receipt as `removed <k>, kept <m>, failed <f>`, or
1621
+ // reclaim-scratch.mjs's receipt as `removed <k>, [evicted <e>, ]kept <m>, failed <f>`, or
1598
1622
  // null. A removal that failed is in the receipt and exits 0: it is reported
1599
1623
  // here, and the pass still counts as reclaimed after.
1600
1624
  export function reclaimSummary(stdout) {
1601
1625
  const r = receiptOf(stdout);
1602
1626
  if (r === null || ![r.removed, r.kept, r.failed].every(Array.isArray)) return null;
1603
- return `removed ${r.removed.length}, kept ${r.kept.length}, failed ${r.failed.length}`;
1627
+ return `removed ${r.removed.length}, ${Array.isArray(r.evicted) ? `evicted ${r.evicted.length}, ` : ""}kept ${r.kept.length}, failed ${r.failed.length}`;
1604
1628
  }
1605
1629
 
1606
1630
  // evict.mjs's receipt as `evicted <k>, kept <m>, failed <f>`, or null. A tree
@@ -1697,7 +1721,9 @@ const OPTIONS = {
1697
1721
  "fold-unchanged": { type: "boolean", default: false },
1698
1722
  // `--apply` runs the idempotent follow-ups whose trigger the ledger and the
1699
1723
  // state file show, before the rows: reap.sh, reclaim-scratch.mjs and
1700
- // evict.mjs after every merge pass settled `done`, and tier-check.mjs on every implementer
1724
+ // evict.mjs after every merge pass settled `done`, reclaim-scratch.mjs
1725
+ // alone after every settle of a fix-applier, a finisher or a review launch
1726
+ // `=failed`, and tier-check.mjs on every implementer
1701
1727
  // the tick would hold as unchecked. It never dispatches, never settles a
1702
1728
  // member and writes no ledger row but through those scripts. Without it the
1703
1729
  // tick is read-only.
@@ -2057,11 +2083,24 @@ function reportDuty(r, { label, duty, what, summarise }) {
2057
2083
  // root or set of claim trees rather than one pass's share. Each runs whether
2058
2084
  // or not the one before it did: none reads another's result. True only when
2059
2085
  // all three applied, the one case `due` is recorded as reaped after; otherwise
2060
- // the next --apply tick runs them again.
2086
+ // the next --apply tick runs them again. `{all, reclaimed}`: the second is true
2087
+ // when the root sweep applied, which is also the sweep a settled member owes.
2061
2088
  function applyReap(due) {
2062
2089
  const label = `reap after ${due.map((n) => `merge-bot-${n}`).join(" ")}`;
2063
2090
  const reaped = reportDuty(runSibling("reap.sh", ["--apply"]), { label, duty: "reap", what: "reap.sh", summarise: reapSummary });
2064
- let reclaimed = false;
2091
+ const reclaimed = applySweep("reclaim");
2092
+ const evicted = reportDuty(runSibling("evict.mjs", ["--apply"]),
2093
+ { label: "evict", duty: "evict", what: "evict.mjs", summarise: evictSummary });
2094
+ return { all: reaped && reclaimed && evicted, reclaimed };
2095
+ }
2096
+
2097
+ // The root sweep, `reclaim-scratch.mjs --root <scratch> --apply`: after a merge
2098
+ // pass, and after the settle of a fix-applier, a finisher or a failed review
2099
+ // launch, each of which leaves trees nothing of their kind is left to use.
2100
+ // True when it applied: a receipt printed, failures listed in it included, the
2101
+ // next trigger retrying those. A non-zero exit or no receipt is not, and the
2102
+ // next --apply tick runs it again.
2103
+ function applySweep(label) {
2065
2104
  let root = null;
2066
2105
  try {
2067
2106
  root = scratchRoot();
@@ -2069,13 +2108,9 @@ function applyReap(due) {
2069
2108
  if (!(e instanceof FleetDirUnresolvable)) throw e;
2070
2109
  console.log(`APPLY FAILED reclaim: ${e.message}`);
2071
2110
  }
2072
- if (root !== null) {
2073
- reclaimed = reportDuty(runSibling("reclaim-scratch.mjs", ["--root", root, "--apply"]),
2074
- { label: "reclaim", duty: "reclaim", what: "reclaim-scratch.mjs", summarise: reclaimSummary });
2075
- }
2076
- const evicted = reportDuty(runSibling("evict.mjs", ["--apply"]),
2077
- { label: "evict", duty: "evict", what: "evict.mjs", summarise: evictSummary });
2078
- return reaped && reclaimed && evicted;
2111
+ if (root === null) return false;
2112
+ return reportDuty(runSibling("reclaim-scratch.mjs", ["--root", root, "--apply"]),
2113
+ { label, duty: "reclaim", what: "reclaim-scratch.mjs", summarise: reclaimSummary });
2079
2114
  }
2080
2115
 
2081
2116
  // tier-check.mjs's verdict by its exit status, each one a token the check
@@ -2372,16 +2407,26 @@ function main() {
2372
2407
 
2373
2408
  if (apply) {
2374
2409
  // Reap, reclaim and evict after every merge pass settled `done` since the
2375
- // last time they ran. Recorded only once all three applied, on a fresh read of the
2410
+ // last time they ran, and the root sweep after every settle `sweepAfter`
2411
+ // names that `sweptAfter` does not. A merge pass is recorded in `reapAfter`
2412
+ // only once all three applied, and a settle in `sweptAfter` once a root
2413
+ // sweep applied, the merge pass's own included; each on a fresh read of the
2376
2414
  // state file so nothing the heartbeat wrote meanwhile is reverted, never
2377
2415
  // onto a file that could not be read, and never with no controller
2378
2416
  // record: nothing could tell a list recorded then from the next run's.
2379
2417
  const run0 = controller?.at ?? null;
2380
2418
  const due = reapDue(run.mergeBotDone, priorState.applied, run0);
2381
- if (due.length && applyReap(due) && run0 !== null) {
2419
+ const owed = sweepDue(run.sweepAfter, priorState.applied, run0);
2420
+ const reap = due.length ? applyReap(due) : null;
2421
+ // The root sweep a merge pass ran is the one a settled member owes too.
2422
+ const swept = owed.length > 0 && (reap?.reclaimed || applySweep(`reclaim after ${owed.join(" ")}`));
2423
+ const reaped = reap?.all ? due : [];
2424
+ if (run0 !== null && (reaped.length > 0 || swept)) {
2382
2425
  const now = readState(path, NAME);
2383
2426
  if (!now.degraded) {
2384
- writeState(path, NAME, now, { applied: { run: run0, reapAfter: [...new Set([...reapedAfter(now.applied, run0), ...due])] } });
2427
+ const reapAfter = [...new Set([...reapedAfter(now.applied, run0), ...reaped])];
2428
+ const sweptNames = [...new Set([...sweptAfter(now.applied, run0), ...(swept ? owed : [])])];
2429
+ writeState(path, NAME, now, { applied: { run: run0, reapAfter, ...(sweptNames.length > 0 ? { sweptAfter: sweptNames } : {}) } });
2385
2430
  }
2386
2431
  }
2387
2432
  // The tier check, on exactly the members the implementer row would hold
@@ -15,9 +15,9 @@
15
15
  // claimed as a member here; everything else a row carries (`class=routine`,
16
16
  // `ports=`, `ci=`, `conflict-hold:#<pr>`, the
17
17
  // `review=`/`reviewed=` pair, the `→ PR#M` arrow) is not a member. The
18
- // review pair has a grammar of its own below, REVIEW and REVIEWED, which
19
- // `ledger.mjs review` writes and `ledger.mjs row` checks a write against
20
- // before it lands.
18
+ // review pair has a grammar of its own below, REVIEW and REVIEWED. A launch is
19
+ // written by `ledger.mjs review`, a result by `ledger.mjs review --result`,
20
+ // and `ledger.mjs row` checks a write against it before it lands.
21
21
 
22
22
  import { createHash } from "node:crypto";
23
23
 
@@ -427,7 +427,8 @@ export function nextReviewerName(rows, pr, retired = []) {
427
427
  const OPEN_WAYS_OUT = "wait for its reviewed=, or, once Member-killed confirms its runner dead, settle it =failed in the same `ledger.mjs review` call as the new launch";
428
428
 
429
429
  /** Whether a word of a row is a review token — `review=…` or `reviewed=…`,
430
- * parseable or not. `ledger.mjs review` writes these and nothing else. */
430
+ * parseable or not. `ledger.mjs review` writes these and nothing else: a
431
+ * launch from its arguments, a `reviewed=` only from a result file. */
431
432
  export const isReviewToken = (word) => word.startsWith("review=") || word.startsWith("reviewed=");
432
433
 
433
434
  /**
@@ -446,8 +447,9 @@ export function addedReviewToken(oldLine, line) {
446
447
  // an answer are written only by `ledger.mjs dispositions`, which derives them
447
448
  // from their evidence; the one input an argument supplies there is the
448
449
  // 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`.
450
+ // `reviewed=` is written by `ledger.mjs review <pr> --result <path>`, which
451
+ // derives it from the review result file; `fleet-event.mjs review-result`
452
+ // calls it.
451
453
 
452
454
  /** Whether `word` begins like a dispositions verdict or an Escalation answer,
453
455
  * parseable or not: the words `ledger.mjs token` refuses. The dispositions
@@ -758,6 +760,23 @@ function launchedRunners(text) {
758
760
  return out;
759
761
  }
760
762
 
763
+ /**
764
+ * The reviewer runner names every row's `review=member:<name>=failed` launch
765
+ * settled dead, once each, in row order: the launches whose review run root
766
+ * nothing is left to write to. A workflow launch is named by its runId, which
767
+ * no runner name matches, and a launch that is open or answered is not here.
768
+ */
769
+ export function failedReviewLaunches(rows) {
770
+ const out = [];
771
+ for (const text of rows) {
772
+ for (const word of text.split(/\s+/)) {
773
+ const m = REVIEW.exec(word);
774
+ if (m !== null && m.groups.failed !== undefined && m.groups.kind === "member" && REVIEWER.test(m.groups.name) && !out.includes(m.groups.name)) out.push(m.groups.name);
775
+ }
776
+ }
777
+ return out;
778
+ }
779
+
761
780
  /**
762
781
  * The names an `ancestor` rotate retires: every member the archive settled —
763
782
  * in `## Dispatched` or on any row, the same two places `ledger.mjs dispatch`
@@ -42,8 +42,8 @@
42
42
  // Writer policy: a Gate verdict — a dispositions verdict, an Escalation
43
43
  // answer, a `reviewed=` — is written only by its own verb, whoever calls it:
44
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`
45
+ // and `review --result` for the third, which it derives from the review's
46
+ // result file and refuses as an argument. `token`
47
47
  // refuses all three, and `row` carries every Gate verdict exactly as the row
48
48
  // holds it, so no other verb adds, changes or drops one. `filed` appends
49
49
  // filings, and all writes are serialized by `<file>.lock`; the other tokens
@@ -63,7 +63,7 @@
63
63
  // life, so the stall readers judge a busy run by them (fleet-state.mjs has
64
64
  // the rule).
65
65
 
66
- import { readFileSync, writeFileSync, mkdirSync, existsSync, renameSync, unlinkSync, linkSync } from "node:fs";
66
+ import { readFileSync, writeFileSync, mkdirSync, existsSync, renameSync, unlinkSync, linkSync, realpathSync } from "node:fs";
67
67
  import { createHash } from "node:crypto";
68
68
  import { dirname, resolve, join, basename, isAbsolute } from "node:path";
69
69
  import { fileURLToPath } from "node:url";
@@ -82,6 +82,7 @@ import { ownClosingIssues } from "./closing-refs.mjs";
82
82
  import { isTicketless } from "./ticketless.mjs";
83
83
  import { RELEASE_LABELS, LABEL_LIST_ARGS, LABEL_LIST_LIMIT, releaseLabelsIn, releaseLabelsDefined } from "./release-labels.mjs";
84
84
  import { LabelMapUnreadable, readLabelMap } from "./label-map.mjs";
85
+ import { REVIEWED, prTokens } from "./ledger-grammar.mjs";
85
86
 
86
87
  const NAME = "ledger";
87
88
  // The plugin's own agent definitions — the directory tier-check.mjs reads
@@ -804,7 +805,7 @@ if (cmd === "read") {
804
805
  // order, so `row` adds none; one the row already holds is carried.
805
806
  const reviewToken = addedReviewToken(oldRow, line);
806
807
  if (reviewToken !== undefined) {
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`);
808
+ die(`row ${key}: adds review token '${reviewToken}' — ${reviewTokenWriter(reviewToken)}`);
808
809
  }
809
810
  // Every Gate verdict is its own verb's to write, so a rewrite carries the
810
811
  // row's as they stand — none added, changed, dropped or reordered, which
@@ -3115,38 +3116,132 @@ function numberArg(arg, what, usage) {
3115
3116
  return Number(digits);
3116
3117
  }
3117
3118
 
3118
- // `review <pr> <token>…`: the only writer of a PR's `review=`/`reviewed=`
3119
- // tokens. Each lands on the PR's row — the ticket row once `settle
3119
+ // What a refusal names as the writer of review token `tok`: a `reviewed=` is a
3120
+ // Gate verdict `review` derives from a result file; a launch is an argument.
3121
+ function reviewTokenWriter(tok) {
3122
+ return tok.startsWith("reviewed=")
3123
+ ? "a reviewed= is written only with `ledger.mjs review <pr> --result <path>`, which derives it from the review's result file and puts it on the PR's row"
3124
+ : "review tokens are written only with `ledger.mjs review <pr> <token>…`, which puts them on the PR's row";
3125
+ }
3126
+
3127
+ // The `reviewed=` token a review result file at `path` derives, for PR `pr`.
3128
+ // `path` is `<scratch>/pr<pr>/<run>/<file>` with no `..` segment, `<run>` a
3129
+ // review run root (`run-` and eight characters); `scratch` is `--scratch`, else
3130
+ // the root `settle --from-report` falls back to. The token is the file's
3131
+ // `head` and `counts` with that run, and a `pr` the file carries must be
3132
+ // `pr`. Dies, writing nothing, naming the first check the file fails.
3133
+ function reviewResultToken(pr, path, scratchArg) {
3134
+ const where = `review #${pr} --result`;
3135
+ if (path.split("/").includes("..")) die(`${where}: ${path} has a ".." segment — pass the result file's path without one`);
3136
+ let scratch = scratchArg;
3137
+ if (scratch === null) {
3138
+ try {
3139
+ scratch = defaultScratch();
3140
+ } catch (e) {
3141
+ if (!(e instanceof FleetDirUnresolvable)) throw e;
3142
+ die(`${where}: no --scratch, and the scratch root could not be resolved — ${e.message}`);
3143
+ }
3144
+ }
3145
+ const real = (p) => {
3146
+ try {
3147
+ return realpathSync(p);
3148
+ } catch {
3149
+ return p;
3150
+ }
3151
+ };
3152
+ const file = resolve(path);
3153
+ const runRoot = dirname(file);
3154
+ const partition = join(resolve(scratch), `pr${pr}`);
3155
+ if (real(dirname(runRoot)) !== real(partition)) die(`${where}: ${file} is not under PR #${pr}'s partition ${partition}/ — nothing written`);
3156
+ const run = basename(runRoot);
3157
+ if (!/^run-[A-Za-z0-9]{8}$/.test(run)) die(`${where}: ${runRoot} is not a review run root (run- and eight characters) — nothing written`);
3158
+ let result;
3159
+ try {
3160
+ result = JSON.parse(readFileSync(file, "utf8"));
3161
+ } catch (e) {
3162
+ die(`${where}: cannot read ${file}: ${e.code ?? e.message} — nothing written`);
3163
+ }
3164
+ if (result?.pr !== undefined && Number(result.pr) !== pr) die(`${where}: ${file} is PR #${result.pr}'s review, not #${pr}'s — nothing written`);
3165
+ const { survived, refuted, unverified } = result?.counts ?? {};
3166
+ const token = `reviewed=${result?.head}:${survived}/${refuted}/${unverified}:${run}`;
3167
+ if (!REVIEWED.test(token)) die(`${where}: ${file} carries no head and counts a reviewed= token can name (${token}) — nothing written`);
3168
+ return token;
3169
+ }
3170
+
3171
+ // `review <pr> [--result <path> [--scratch <dir>]] [<review=…>…]`: the only
3172
+ // writer of a PR's `review=`/`reviewed=` tokens. A `reviewed=` is a Gate
3173
+ // verdict, so it is written only from `--result`, which derives it from the
3174
+ // review result file (reviewResultToken()); a `reviewed=` word among the
3175
+ // arguments is refused, parseable or not, since an argument is not evidence.
3176
+ // `--scratch` names the scratch root the file must sit under, as `settle
3177
+ // --from-report`'s `--reports` names its reports root, else the root
3178
+ // scratch-root.mjs prints. A launch token (`review=…`, `review=…=failed`) is an
3179
+ // argument token and may come in the same call, written before the result it
3180
+ // answers. Each token lands on the PR's row — the ticket row once `settle
3120
3181
  // impl-<N>=PR#M` has run, else `#M`, created when neither exists — so the
3121
3182
  // row's token order is write order, the order the tick folds the PR's review
3122
3183
  // record in. `review=X=failed` for a launch the row holds open as `review=X`
3123
3184
  // rewrites that token in place; every other token is appended as ` · <token>`.
3124
- // The whole ledger before and after is judged by rowWriteRefusal() under the
3125
- // lock, and a refusal writes nothing. The receipt's `next` is the runner name
3126
- // the PR's next launch takes as the ledger stands after the write, null with
3127
- // every letter taken.
3185
+ // A result token the PR's rows already carry is not written again: with no
3186
+ // launch in the call, exit 0 with nothing written. The whole ledger before
3187
+ // and after is judged by rowWriteRefusal() under the lock, and a refusal
3188
+ // writes nothing. The receipt names the derived token as `reviewed`, with
3189
+ // `written` saying whether this call put it on the row, and its `next` is the
3190
+ // runner name the PR's next launch takes as the ledger stands after the
3191
+ // write, null with every letter taken.
3128
3192
  function runReview() {
3129
- const usage = "usage: ledger.mjs review <pr> <review=…|reviewed=…>…";
3193
+ const usage = "usage: ledger.mjs review <pr> [--result <path> [--scratch <dir>]] [<review=…>…]";
3130
3194
  const [pr, ...parts] = rest;
3131
3195
  if (!pr || parts.length === 0) die(usage);
3132
3196
  const prNum = numberArg(pr, "a PR number", usage);
3133
- const tokens = parts.join(" ").split(/\s+/).filter(Boolean);
3197
+ const flags = new Map();
3198
+ const words = [];
3199
+ for (let k = 0; k < parts.length; k++) {
3200
+ const word = parts[k];
3201
+ const flag = word.split("=")[0];
3202
+ if (flag !== "--result" && flag !== "--scratch") {
3203
+ words.push(word);
3204
+ continue;
3205
+ }
3206
+ if (flag !== word) die(`review #${prNum}: ${flag} needs a space-separated value, not ${flag}= — ${usage}`);
3207
+ if (flags.has(word)) die(`review #${prNum}: ${word} is given twice — ${usage}`);
3208
+ const value = parts[++k];
3209
+ if (value === undefined || isFlagLike(value)) die(`review #${prNum}: ${word} needs a value — ${usage}`);
3210
+ flags.set(word, value);
3211
+ }
3212
+ if (flags.has("--scratch") && !flags.has("--result")) die(`review #${prNum}: --scratch is read only with --result — ${usage}`);
3213
+ const tokens = words.join(" ").split(/\s+/).filter(Boolean);
3214
+ const typed = tokens.find((tok) => tok.startsWith("reviewed="));
3215
+ if (typed !== undefined) {
3216
+ die(`review #${prNum}: '${typed}' is a reviewed= token — a reviewed= is a Gate verdict, written only with \`ledger.mjs review ${prNum} --result <path>\`, which derives it from the review's result file; no argument supplies one`);
3217
+ }
3134
3218
  const other = tokens.find((tok) => !isReviewToken(tok));
3135
3219
  if (other !== undefined) {
3136
- die(`review #${prNum}: '${other}' is not a review token — review writes only review=… and reviewed=…; every other token goes through row, dispatch or settle`);
3220
+ die(`review #${prNum}: '${other}' is not a review token — review writes only review=… launches and the reviewed= its --result derives; every other token goes through row, dispatch or settle`);
3137
3221
  }
3222
+ if (tokens.length === 0 && !flags.has("--result")) die(usage);
3138
3223
  const retired = retiredNames("review");
3224
+ let reviewed = null;
3225
+ if (flags.has("--result")) {
3226
+ reviewed = reviewResultToken(prNum, flags.get("--result"), flags.get("--scratch") ?? null);
3227
+ if (!prTokens(data.rows, prNum).includes(reviewed)) tokens.push(reviewed);
3228
+ }
3139
3229
  const i = prRowIndex(prNum);
3140
3230
  const created = i === -1;
3141
3231
  const oldLine = created ? null : data.rows[i];
3142
- const words = created ? [`#${prNum}`] : oldLine.split(/(\s+)/);
3232
+ if (tokens.length === 0) {
3233
+ console.error(` review on row ${rowKey(oldLine)}: already carries ${reviewed} — not written again`);
3234
+ console.log(JSON.stringify({ pr: prNum, row: rowKey(oldLine), line: oldLine, created: false, written: false, reviewed, next: nextReviewerName(data.rows, prNum, retired) }));
3235
+ return;
3236
+ }
3237
+ const cells = created ? [`#${prNum}`] : oldLine.split(/(\s+)/);
3143
3238
  const appended = [];
3144
3239
  for (const tok of tokens) {
3145
- const open = tok.endsWith("=failed") ? words.lastIndexOf(tok.slice(0, -"=failed".length)) : -1;
3146
- if (open > 0) words[open] = tok;
3240
+ const open = tok.endsWith("=failed") ? cells.lastIndexOf(tok.slice(0, -"=failed".length)) : -1;
3241
+ if (open > 0) cells[open] = tok;
3147
3242
  else appended.push(tok);
3148
3243
  }
3149
- const head = words.join("");
3244
+ const head = cells.join("");
3150
3245
  const line = appended.length === 0 ? head
3151
3246
  : created ? `${head} ${appended.join(" · ")}`
3152
3247
  : `${head} · ${appended.join(" · ")}`;
@@ -3157,7 +3252,7 @@ function runReview() {
3157
3252
  save(data);
3158
3253
  const key = rowKey(line);
3159
3254
  console.error(` review on row ${key}`);
3160
- console.log(JSON.stringify({ pr: prNum, row: key, line, created, next: nextReviewerName(data.rows, prNum, retired) }));
3255
+ console.log(JSON.stringify({ pr: prNum, row: key, line, created, ...(reviewed === null ? {} : { reviewed, written: tokens.includes(reviewed) }), next: nextReviewerName(data.rows, prNum, retired) }));
3161
3256
  }
3162
3257
 
3163
3258
  // `dispositions <member> --scratch <dir> [--repo <path>] [--uphold <list>]
@@ -3367,7 +3462,7 @@ function tokenRefusal(tok, earlier) {
3367
3462
  return "is a member token — members are written only with `ledger.mjs dispatch` and `ledger.mjs settle`";
3368
3463
  }
3369
3464
  if (isReviewToken(tok)) {
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";
3465
+ return `is a review token — ${reviewTokenWriter(tok)}`;
3371
3466
  }
3372
3467
  if (isDispositionsWord(tok)) {
3373
3468
  return tok.startsWith("escalation-answer=")