@feigi/fleet-ctl 3.58.0 → 3.59.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.
@@ -15,7 +15,9 @@
15
15
  // row and appends it to `## Dispatched` with `brief=<hash>`, the brief it
16
16
  // refuses to dispatch without, `settle` rewrites that token to
17
17
  // `<member>=<outcome>` in both places (an implementer's settle to `PR#M` also
18
- // folds the PR's own `#M` row into its ticket's), `review` appends a PR's
18
+ // folds the PR's own `#M` row into its ticket's) — with `--from-report`, the
19
+ // outcome derived from the member's report file and checked against git and
20
+ // GitHub first, see runSettleFromReport() — `review` appends a PR's
19
21
  // `review=`/`reviewed=` tokens to the PR's row, and `drain` writes the
20
22
  // one marker that stops supply. The token grammar is
21
23
  // ledger-grammar.mjs's. Within a run `## Dispatched` gains an entry per
@@ -47,13 +49,14 @@ import { createHash } from "node:crypto";
47
49
  import { dirname, resolve, join, basename } from "node:path";
48
50
  import { fileURLToPath } from "node:url";
49
51
  import { spawnSync, execFileSync } from "node:child_process";
50
- import { makeDie, isFlagLike, hasEqualsForm, isDigits } from "./arg.mjs";
52
+ import { makeDie, isFlagLike, hasEqualsForm, isDigits, writeAll } from "./arg.mjs";
51
53
  import { fleetFile, FleetDirUnresolvable } from "./fleet-dir.mjs";
52
- import { parseMember, parseToken, memberTokens, nextMergeBot, nextRetry, liveOnLedger, retiredOnLedger, isRetirable, agentDefinition, CELL, tierValues, rowPr, rowWriteRefusal, isReviewToken, addedReviewToken, newSplitRow, splitRowClause, added, premisesOf, MEMBER_FAMILIES, ROWS, DISPATCHED, FILED, RULED, DRAIN, RETIRED, RECEIPT, archiveStamp, receiptArchiveName, CLOSEOUT_RECEIPT, closeoutArchiveName, BRIEFS, briefsArchiveName, memberRole, parseDispatchedEntry, dispatchedEntry, headerRe, escapeText, unescapeText } from "./ledger-grammar.mjs";
54
+ import { parseMember, parseToken, memberTokens, nextMergeBot, nextRetry, liveOnLedger, retiredOnLedger, isRetirable, agentDefinition, CELL, tierValues, rowPr, rowWriteRefusal, isReviewToken, addedReviewToken, newSplitRow, splitRowClause, added, premisesOf, MEMBER_FAMILIES, HALT_CAUSES, ROWS, DISPATCHED, FILED, RULED, DRAIN, RETIRED, RECEIPT, archiveStamp, receiptArchiveName, CLOSEOUT_RECEIPT, closeoutArchiveName, BRIEFS, briefsArchiveName, memberRole, parseDispatchedEntry, dispatchedEntry, headerRe, escapeText, unescapeText } from "./ledger-grammar.mjs";
53
55
  import { deriveRun, LedgerError, labelOffMember, HELD, CONFLICT_HOLD } from "./fleet-tick.mjs";
54
56
  import { stateFileIn, readState, writeState, assessBeat, stallsAt } from "./fleet-state.mjs";
55
57
  import { processSource, ancestry, controllerOf, judgeController, ProcUnreadable } from "./proc.mjs";
56
58
  import { attemptLock, releaseLockFile, reapPathOf } from "./pid-lock.mjs";
59
+ import { readReportIn, reportsDir, reportFamily, defaultScratch } from "./report-files.mjs";
57
60
 
58
61
  const NAME = "ledger";
59
62
  // The plugin's own agent definitions — the directory tier-check.mjs reads
@@ -664,11 +667,14 @@ async function acquireLock() {
664
667
  if (requireFile && !existsSync(file)) die(`--require-file given but ledger file does not exist: ${file}`);
665
668
 
666
669
  const WRITE_COMMANDS = new Set(["row", "token", "filed", "ruled", "dispatch", "settle", "review", "drain", "rotate"]);
667
- if (WRITE_COMMANDS.has(cmd)) await acquireLock();
670
+ // `settle --from-report` takes the lock itself, once its checks have run —
671
+ // see runSettleFromReport().
672
+ const FROM_REPORT = cmd === "settle" && rest.includes("--from-report");
673
+ if (WRITE_COMMANDS.has(cmd) && !FROM_REPORT) await acquireLock();
668
674
  // `rotate` never load()s: a ledger load() would refuse is still the previous
669
675
  // run's record, and it is archived as-is — and read line by line when it
670
676
  // carries live members forward, see carryOf().
671
- const data = cmd === "rotate" ? null : load();
677
+ let data = cmd === "rotate" ? null : load();
672
678
 
673
679
  // The payload subcommands end by falling out of this chain, never by calling
674
680
  // process.exit(). On a pipe, process.stdout.write is async and process.exit()
@@ -784,21 +790,11 @@ if (cmd === "read") {
784
790
  // `check` against that row silently degrades from the hard "already
785
791
  // filed" block to a soft near-miss suggestion instead.
786
792
  if (!isDigits(id)) die(`'${issue}' is not an issue number`);
787
- // Both callers retry once on a failure they observed, and an observed
788
- // failure is not proof the write failed — a timeout after the row landed
789
- // reads as one — so a repeat filing of an issue already on file is a no-op.
790
- // Identity is the issue number alone, matched NUMERICALLY — so a
791
- // non-canonical spelling (`08`) still dedupes against `8` — as the token
792
- // between `#` and the first whitespace: never `check`'s fuzzy subject
793
- // matcher, and never a prefix test, which would dedupe issue 8 against issue 80.
794
- // The existing row wins, subject and all — a retry reworded is still the
795
- // same filing.
796
- const existing = data.filed.find((row) => Number(row.match(/^#(\S+)/)?.[1]) === Number(id));
797
- if (existing !== undefined) {
798
- console.error(` already recorded: ${existing}`);
799
- console.log(JSON.stringify({ issue, subject, total: data.filed.length, alreadyRecorded: true, row: existing }));
793
+ const { row, alreadyRecorded } = recordFiled(id, subject);
794
+ if (alreadyRecorded) {
795
+ console.error(` already recorded: ${row}`);
796
+ console.log(JSON.stringify({ issue, subject, total: data.filed.length, alreadyRecorded: true, row }));
800
797
  } else {
801
- data.filed.push(`#${id} ${subject}`);
802
798
  save(data);
803
799
  console.log(JSON.stringify({ issue, subject, total: data.filed.length }));
804
800
  }
@@ -819,7 +815,8 @@ if (cmd === "read") {
819
815
  } else if (cmd === "dispatch") {
820
816
  runDispatch();
821
817
  } else if (cmd === "settle") {
822
- runSettle();
818
+ if (FROM_REPORT) await runSettleFromReport();
819
+ else runSettle();
823
820
  } else if (cmd === "token") {
824
821
  runToken();
825
822
  } else if (cmd === "review") {
@@ -2022,8 +2019,18 @@ function renderedBrief(name, role) {
2022
2019
  return { path, sha256: s.sha256 };
2023
2020
  }
2024
2021
 
2022
+ // Whether `outcome` is one whose claim a member's report carries and `settle
2023
+ // --from-report` checks against git or GitHub before writing. Settled with
2024
+ // the bare form, the claim goes unchecked, so that form says so on stderr.
2025
+ function reportedOutcome(outcome) {
2026
+ return /^(?:PR#|applied:|halted:)|^(?:bailed|no-op|labelled|done)$/.test(outcome);
2027
+ }
2028
+
2025
2029
  function runSettle() {
2026
- const usage = "usage: ledger.mjs settle <member> <outcome>";
2030
+ const usage = "usage: ledger.mjs settle <member> <outcome> | settle <member> --from-report [--reports <dir>]";
2031
+ // `--reports` names where `--from-report` reads; alone it would land here
2032
+ // as an outcome.
2033
+ if (rest.includes("--reports")) die(`--reports is read only with --from-report — ${usage}`);
2027
2034
  // `settle impl-<N> PR#<n>`, or the one token it writes — `settle
2028
2035
  // impl-<N>=PR#<n>` — which is how the spec's record-before-tick table
2029
2036
  // spells every settlement.
@@ -2032,6 +2039,27 @@ function runSettle() {
2032
2039
  const parsed = parseToken(rest.length === 2 ? `${rest[0]}=${rest[1]}` : rest[0]);
2033
2040
  if (!parsed) die(unknownMember(rest[0].split("=")[0]));
2034
2041
  if (parsed.error) die(`${parsed.name}: ${parsed.error}`);
2042
+ const { name, outcome } = parsed;
2043
+ const token = `${name}=${outcome}`;
2044
+ const { i, changed } = settleMember(parsed);
2045
+ if (changed) {
2046
+ save(data);
2047
+ console.error(` settled ${token}`);
2048
+ }
2049
+ if (reportedOutcome(outcome)) {
2050
+ console.error(`${NAME}: WARNING ${token} settled without --from-report — the member's claim was not checked`);
2051
+ }
2052
+ console.log(JSON.stringify({
2053
+ member: name, outcome, ticket: i === -1 ? null : rowKey(data.rows[i]), line: i === -1 ? null : data.rows[i], changed,
2054
+ }));
2055
+ }
2056
+
2057
+ // The settle both forms share: rewrites `parsed`'s live token to
2058
+ // `<member>=<outcome>` in `data`, saving nothing. `{i, changed}`: `i` the row
2059
+ // the token sits on (-1 for none), `changed` false when the same outcome was
2060
+ // already on record and nothing was rewritten. Every refusal is die(), exit 2,
2061
+ // before anything in `data` changes.
2062
+ function settleMember(parsed) {
2035
2063
  const { name, outcome } = parsed;
2036
2064
  const token = `${name}=${outcome}`;
2037
2065
  // Same guard as runDispatch(): a `## Dispatched` entry this grammar cannot
@@ -2048,14 +2076,10 @@ function runSettle() {
2048
2076
 
2049
2077
  const liveRows = data.rows.flatMap((r, i) => (carries(r, name, true) ? [i] : []));
2050
2078
  const liveEntry = entry !== null && entry.outcome === null;
2051
- const payload = (i, changed) => ({
2052
- member: name, outcome, ticket: i === -1 ? null : rowKey(data.rows[i]), line: i === -1 ? null : data.rows[i], changed,
2053
- });
2054
2079
  if (!liveEntry && liveRows.length === 0) {
2055
2080
  if (settled.length === 0) die(`no live ${name} in the ledger — \`dispatch\` it first`);
2056
2081
  // The same outcome again: already on record, so nothing is written.
2057
- console.log(JSON.stringify(payload(data.rows.findIndex((r) => carries(r, name)), false)));
2058
- return;
2082
+ return { i: data.rows.findIndex((r) => carries(r, name)), changed: false };
2059
2083
  }
2060
2084
 
2061
2085
  // The rows before any write below: the fold's guard reads the row this
@@ -2112,9 +2136,299 @@ function runSettle() {
2112
2136
  // carried. The refused member settles `=bailed` or to a PR of its own.
2113
2137
  const split = newSplitRow(before, data.rows);
2114
2138
  if (split !== null) die(`settle ${token}: ${splitRowClause(split)}; settle ${name} =bailed or to a PR of its own`);
2115
- save(data);
2116
- console.error(` settled ${token}`);
2117
- console.log(JSON.stringify(payload(i, true)));
2139
+ return { i, changed: true };
2140
+ }
2141
+
2142
+ // One filing into `## Filed`, unsaved: `{row, alreadyRecorded}`. A repeat
2143
+ // filing of an issue already on file is a no-op — both callers of `filed`
2144
+ // retry once on a failure they observed, and an observed failure is not
2145
+ // proof the write failed (a timeout after the row landed reads as one), and
2146
+ // `settle --from-report` run twice records the same report twice. Identity
2147
+ // is the issue number alone, matched NUMERICALLY — so a non-canonical
2148
+ // spelling (`08`) still dedupes against `8` — as the token between `#` and
2149
+ // the first whitespace: never `check`'s fuzzy subject matcher, and never a
2150
+ // prefix test, which would dedupe issue 8 against issue 80. The existing row
2151
+ // wins, subject and all — a retry reworded is still the same filing.
2152
+ function recordFiled(id, subject) {
2153
+ const existing = data.filed.find((row) => Number(row.match(/^#(\S+)/)?.[1]) === Number(id));
2154
+ if (existing !== undefined) return { row: existing, alreadyRecorded: true };
2155
+ const row = `#${id} ${subject}`;
2156
+ data.filed.push(row);
2157
+ return { row, alreadyRecorded: false };
2158
+ }
2159
+
2160
+ // -- settle --from-report -----------------------------------------------------
2161
+ //
2162
+ // `settle <member> --from-report [--reports <dir>]`: the member's outcome read
2163
+ // off the report file it wrote, `<dir>/<member>.json` — `<dir>` by default
2164
+ // `<scratch>/reports`, `<scratch>` the root scratch-root.mjs prints — rather
2165
+ // than typed by hand. The file must check against its family's schema
2166
+ // (report-schema.mjs) and name this member in `member`. The token is derived
2167
+ // from it, and an outcome that asserts a git or GitHub state has that state
2168
+ // checked before anything is written:
2169
+ //
2170
+ // impl-N=PR#M verify-sha.sh <branch> <head> exits 0; PR M
2171
+ // reads OPEN and its closingIssuesReferences name N
2172
+ // impl-N=bailed bailCause is not null; the receipt names it
2173
+ // fix-pr-M=applied:<head> origin's refs/heads/<branch> is <head>
2174
+ // fix-pr-M=no-op origin's refs/heads/<branch> is the head PR M's
2175
+ // latest reviewed= names, as the tick folds it
2176
+ // finisher-pr-M=labelled PR M's labels carry ready-to-merge, and so does
2177
+ // the report's labelsReadBack
2178
+ // finisher-pr-M=halted:<c> cause is in the halted:<cause> vocabulary and
2179
+ // evidence is not empty
2180
+ // merge-bot-n=done every merged[].pr reads MERGED
2181
+ //
2182
+ // A `failed` report claims no state, so it settles `=failed` unchecked. A
2183
+ // fix-applier's `refuted` deferral claims one more thing: that its disposition
2184
+ // record gives the reversal a reason, which is the text `## Ruled` gets.
2185
+ //
2186
+ // Exit 3: a check failed — the member's claim and the world disagree — and
2187
+ // stderr names each failed check; nothing written. Exit 2: the report is
2188
+ // absent, unreadable or invalid, a check could not look (a `gh`, `git` or
2189
+ // verify-sha.sh call that failed, printed what it was not asked for, or never
2190
+ // finished), or a refusal the bare form makes; nothing written either.
2191
+ //
2192
+ // After the settle, in the same write: every `unrecorded` entry goes to `##
2193
+ // Filed` the way `filed` records one, and for a fix-applier every `deferred`
2194
+ // entry in the `refuted` bucket goes to `## Ruled` as `#M reversed refutation
2195
+ // <index>: <reason>`. A line already there is not written again, so a second
2196
+ // run of the same settle writes nothing. The receipt on stdout is `{member,
2197
+ // outcome, checks: [{name, ok}], filed, ruled}`, `filed` and `ruled` the
2198
+ // lines this call added.
2199
+ //
2200
+ // The checks run before the write lock is taken, against the ledger as read
2201
+ // without it, because they are network calls and every other writer waits
2202
+ // for the lock 10 s at most. The settle itself is judged again under the
2203
+ // lock, on the ledger reloaded there.
2204
+
2205
+ // A failed check: die()'s refusal shape, on stderr with nothing on stdout,
2206
+ // at exit 3.
2207
+ function mismatch(msg) {
2208
+ try {
2209
+ writeAll(2, `\n${NAME}: ${msg}\n`);
2210
+ } catch {
2211
+ // The message may be lost; the exit code may not.
2212
+ }
2213
+ process.exit(3);
2214
+ }
2215
+
2216
+ async function runSettleFromReport() {
2217
+ const usage = "usage: ledger.mjs settle <member> --from-report [--reports <dir>]";
2218
+ const verifySha = join(dirname(fileURLToPath(import.meta.url)), "verify-sha.sh");
2219
+ const ready = "ready-to-merge";
2220
+ // The bound on each child a check runs: generous, because verify-sha.sh
2221
+ // fetches, and still a bound, because the child may never answer at all.
2222
+ const checkTimeoutMs = 60_000;
2223
+ let member;
2224
+ let reports = null;
2225
+ for (let k = 0; k < rest.length; k++) {
2226
+ const a = rest[k];
2227
+ if (a === "--from-report") continue;
2228
+ if (a === "--reports") {
2229
+ const v = rest[++k];
2230
+ if (isFlagLike(v)) die(`--reports needs a directory — ${usage}`);
2231
+ if (reports !== null) die(`--reports given twice — ${usage}`);
2232
+ reports = v;
2233
+ } else if (a.startsWith("-")) {
2234
+ die(`unknown flag '${a}' — ${usage}`);
2235
+ } else if (member === undefined) {
2236
+ member = a;
2237
+ } else {
2238
+ die(usage);
2239
+ }
2240
+ }
2241
+ if (member === undefined) die(usage);
2242
+ if (member.includes("=")) die(`settle --from-report takes a member name, not '${member}': the outcome is the report's — ${usage}`);
2243
+ const live = parseToken(member);
2244
+ if (!live) die(unknownMember(member));
2245
+ const where = `settle ${member} --from-report`;
2246
+
2247
+ if (reports === null) {
2248
+ try {
2249
+ reports = reportsDir(defaultScratch());
2250
+ } catch (e) {
2251
+ if (!(e instanceof FleetDirUnresolvable)) throw e;
2252
+ die(`${where}: no --reports, and the scratch root could not be resolved — ${e.message}`);
2253
+ }
2254
+ }
2255
+ const read = readReportIn(reports, member);
2256
+ if (read.state === "absent") die(`${where}: no report at ${read.path}; nothing written`);
2257
+ if (read.state === "invalid") die(`${where}: ${read.path} is not a ${reportFamily(member)} report — ${read.violation}; nothing written`);
2258
+ const report = read.report;
2259
+ const invalid = (violation) => die(`${where}: ${read.path} is not a ${reportFamily(member)} report — ${violation}; nothing written`);
2260
+ if (report.member !== member) invalid(`$.member: ${JSON.stringify(report.member)} is not ${member}`);
2261
+ // An issue number is a positive integer. A negative id writes a row `#-3 …`
2262
+ // that `filed` refuses and `check`'s subjectOf() cannot strip.
2263
+ for (const [k, { issue }] of (report.unrecorded ?? []).entries()) {
2264
+ if (!Number.isInteger(issue) || issue < 1) invalid(`$.unrecorded[${k}].issue: ${JSON.stringify(issue)} is not an issue number`);
2265
+ }
2266
+
2267
+ // Every child runs from the ledger's repository with runCheck()'s
2268
+ // environment, for runCheck()'s reasons: GH_REPO would point gh at another
2269
+ // tracker whatever the cwd, and GIT_DIR/GIT_WORK_TREE git at another repo.
2270
+ const env = { ...process.env, GH_REPO: "" };
2271
+ delete env.GIT_DIR;
2272
+ delete env.GIT_WORK_TREE;
2273
+ let repo = null;
2274
+ const repoDir = () => {
2275
+ if (repo !== null) return repo;
2276
+ let dir = dirname(resolve(file));
2277
+ while (!existsSync(dir) && dirname(dir) !== dir) dir = dirname(dir);
2278
+ const r = spawnSync("git", ["-C", dir, "rev-parse", "--show-toplevel"], { encoding: "utf8", env, timeout: GIT_TIMEOUT_MS });
2279
+ if (r.status !== 0) {
2280
+ const why = cause(r.error && r.error.message, r.stderr);
2281
+ die(`${where}: could not look — cannot resolve the ledger's repository (${dir})${why ? `: ${why}` : ""}; nothing written`);
2282
+ }
2283
+ repo = r.stdout.trim();
2284
+ return repo;
2285
+ };
2286
+ // A child that must answer with one of `answers`; anything else — another
2287
+ // status, a spawn failure, a timeout — could not look.
2288
+ const look = (what, cmd, args, answers = [0]) => {
2289
+ const r = spawnSync(cmd, args, { encoding: "utf8", cwd: repoDir(), env, timeout: checkTimeoutMs, stdio: ["ignore", "pipe", "pipe"] });
2290
+ if (r.status === null || !answers.includes(r.status)) {
2291
+ const why = cause(r.error && r.error.message, r.stderr);
2292
+ die(`${where}: could not look — ${what}${r.status === null ? "" : ` exited ${r.status}`}${why ? `: ${why}` : ""}; nothing written`);
2293
+ }
2294
+ return r;
2295
+ };
2296
+ // A `gh pr view --json <fields>` answer: an object whose every requested
2297
+ // field has the type that field has. Anything else was not what was asked
2298
+ // for, so it could not look.
2299
+ const prFieldOk = { state: (v) => typeof v === "string", labels: Array.isArray, closingIssuesReferences: Array.isArray };
2300
+ const prView = (pr, fields) => {
2301
+ const what = `gh pr view ${pr} --json ${fields}`;
2302
+ const r = look(what, "gh", ["pr", "view", String(pr), "--json", fields]);
2303
+ let v = null;
2304
+ try {
2305
+ v = JSON.parse(r.stdout);
2306
+ } catch {
2307
+ // Falls through to the refusal below.
2308
+ }
2309
+ if (v === null || typeof v !== "object") {
2310
+ die(`${where}: could not look — ${what} printed no JSON object: ${cause(r.stdout)}; nothing written`);
2311
+ }
2312
+ const missing = fields.split(",").filter((f) => !prFieldOk[f](v[f]));
2313
+ if (missing.length > 0) {
2314
+ die(`${where}: could not look — ${what} answered without a usable ${missing.join(", ")}: ${cause(r.stdout)}; nothing written`);
2315
+ }
2316
+ return v;
2317
+ };
2318
+ // origin's head of `branch`, or null when origin has no such branch.
2319
+ const remoteHead = (branch) => {
2320
+ const ref = `refs/heads/${branch}`;
2321
+ const r = look(`git ls-remote origin ${ref}`, "git", ["ls-remote", "origin", ref]);
2322
+ const line = r.stdout.split("\n").find((l) => l.endsWith(`\t${ref}`));
2323
+ return line === undefined ? null : line.split("\t")[0];
2324
+ };
2325
+
2326
+ const checks = [];
2327
+ const check = (name, ok) => {
2328
+ checks.push({ name, ok });
2329
+ return ok;
2330
+ };
2331
+ const ruledLines = [];
2332
+ let outcome;
2333
+ if (live.family === "impl") {
2334
+ if (report.outcome === "pr") {
2335
+ if (report.pr === null || report.pr < 1) invalid(`$.pr: ${JSON.stringify(report.pr)} is not a PR number, with outcome "pr"`);
2336
+ if (report.head === null) invalid('$.head: null, with outcome "pr"');
2337
+ outcome = `PR#${report.pr}`;
2338
+ const sha = look(`verify-sha.sh ${report.branch} ${report.head}`, "sh", [verifySha, report.branch, report.head], [0, 1]);
2339
+ check(`verify-sha.sh ${report.branch} ${report.head} exits 0`, sha.status === 0);
2340
+ const pr = prView(report.pr, "state,closingIssuesReferences");
2341
+ check(`PR #${report.pr} reads OPEN`, pr.state === "OPEN");
2342
+ check(`PR #${report.pr} closes #${live.number}`, pr.closingIssuesReferences.some((c) => c?.number === live.number));
2343
+ } else {
2344
+ outcome = "bailed";
2345
+ check(`bailCause: ${report.bailCause}`, report.bailCause !== null);
2346
+ }
2347
+ } else if (live.family === "fix-pr") {
2348
+ if (report.outcome === "applied") {
2349
+ outcome = `applied:${report.head}`;
2350
+ const head = remoteHead(report.branch);
2351
+ check(`origin refs/heads/${report.branch} is ${report.head}`, head === report.head);
2352
+ } else if (report.outcome === "no-op") {
2353
+ outcome = "no-op";
2354
+ let fold;
2355
+ try {
2356
+ fold = deriveRun({ rows: data.rows, dispatched: data.dispatched, drain: data.drain }, []);
2357
+ } catch (e) {
2358
+ if (!(e instanceof LedgerError)) throw e;
2359
+ die(`${where}: ${e.message} — fleet-tick.mjs refuses this ledger, so PR #${live.number}'s latest reviewed= cannot be read off it; nothing written`);
2360
+ }
2361
+ const reviewed = fold.reviewed.find((r) => r.pr === live.number)?.head ?? null;
2362
+ if (reviewed === null) {
2363
+ check(`PR #${live.number}'s row names a reviewed= head`, false);
2364
+ } else {
2365
+ const head = remoteHead(report.branch);
2366
+ check(`origin refs/heads/${report.branch} is ${reviewed}, the head PR #${live.number}'s latest reviewed= names`,
2367
+ head !== null && head.toLowerCase().startsWith(reviewed.toLowerCase()));
2368
+ }
2369
+ } else {
2370
+ outcome = "failed";
2371
+ }
2372
+ const refuted = report.deferred.filter((d) => d.bucket === "refuted");
2373
+ if (refuted.length > 0) {
2374
+ const path = report.dispositionsRecord;
2375
+ let record;
2376
+ try {
2377
+ record = JSON.parse(readFileSync(path, "utf8"));
2378
+ } catch (e) {
2379
+ die(`${where}: could not look — the disposition record ${path} could not be read as JSON: ${e.code ?? e.message}; nothing written`);
2380
+ }
2381
+ const entries = Array.isArray(record?.entries) ? record.entries : [];
2382
+ for (const d of refuted) {
2383
+ const entry = entries.find((e) => e?.bucket === "refuted" && e?.index === d.index);
2384
+ const reason = typeof entry?.reason === "string" ? entry.reason.trim() : "";
2385
+ if (check(`${path} gives refuted[${d.index}] a reason`, reason !== "")) {
2386
+ ruledLines.push(`#${live.number} reversed refutation ${d.index}: ${reason}`);
2387
+ }
2388
+ }
2389
+ }
2390
+ } else if (live.family === "finisher-pr") {
2391
+ if (report.outcome === "labelled") {
2392
+ outcome = "labelled";
2393
+ const pr = prView(live.number, "labels");
2394
+ check(`PR #${live.number} carries ${ready}`, pr.labels.some((l) => l?.name === ready));
2395
+ check(`labelsReadBack carries ${ready}`, report.labelsReadBack.includes(ready));
2396
+ } else if (report.outcome === "halted") {
2397
+ outcome = `halted:${report.cause}`;
2398
+ check(`cause ${report.cause} is in the halted:<cause> vocabulary`, HALT_CAUSES.includes(report.cause));
2399
+ check("evidence is not empty", (report.evidence ?? "").trim() !== "");
2400
+ } else {
2401
+ outcome = "failed";
2402
+ }
2403
+ } else {
2404
+ outcome = "done";
2405
+ for (const { pr } of report.merged) check(`PR #${pr} reads MERGED`, prView(pr, "state").state === "MERGED");
2406
+ }
2407
+
2408
+ const failed = checks.filter((c) => !c.ok);
2409
+ if (failed.length > 0) {
2410
+ mismatch(`${where}: the report's claim and the world disagree — ${failed.map((c) => `failed: ${c.name}`).join("; ")}; nothing written`);
2411
+ }
2412
+ const parsed = parseToken(`${member}=${outcome}`);
2413
+ if (parsed.error) invalid(`${parsed.name}: ${parsed.error}`);
2414
+
2415
+ await acquireLock();
2416
+ data = load();
2417
+ const { changed } = settleMember(parsed);
2418
+ const filed = [];
2419
+ for (const { issue, subject } of report.unrecorded ?? []) {
2420
+ const { row, alreadyRecorded } = recordFiled(String(issue), subject);
2421
+ if (!alreadyRecorded) filed.push(row);
2422
+ }
2423
+ const ruled = [];
2424
+ for (const line of ruledLines) {
2425
+ if (data.ruled.includes(line)) continue;
2426
+ data.ruled.push(line);
2427
+ ruled.push(line);
2428
+ }
2429
+ if (changed || filed.length > 0 || ruled.length > 0) save(data);
2430
+ if (changed) console.error(` settled ${member}=${outcome}`);
2431
+ console.log(JSON.stringify({ member, outcome, checks, filed, ruled }));
2118
2432
  }
2119
2433
 
2120
2434
  // A ticket or PR number argument as a number: a leading `#` is allowed, a
@@ -38,9 +38,14 @@ export const reportPath = (scratch, member) => join(reportsDir(scratch), `${memb
38
38
  * wrong shape, or `{state: "absent", path}`. Throws on a member no schema
39
39
  * covers: ask reportFamily() first. */
40
40
  export function readReport(scratch, member) {
41
+ return readReportIn(reportsDir(scratch), member);
42
+ }
43
+
44
+ /** readReport() for a reports directory named directly, `<dir>/<member>.json`. */
45
+ export function readReportIn(dir, member) {
41
46
  const family = reportFamily(member);
42
47
  if (family === null) throw new Error(`no report schema for '${member}'`);
43
- const path = reportPath(scratch, member);
48
+ const path = join(dir, `${member}.json`);
44
49
  let text;
45
50
  try {
46
51
  text = readFileSync(path, "utf8");