rungate 0.8.2 → 0.8.3

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.
Files changed (63) hide show
  1. package/bin/rungate.ts +11 -6
  2. package/config/prove-evidence.schema.json +21 -3
  3. package/gates/.gate-salt +1 -1
  4. package/gates/gate-executor.ts +153 -1
  5. package/gates/prove.test.ts +12 -6
  6. package/gates/schema.ts +69 -6
  7. package/gates/workflow.test.ts +12 -5
  8. package/hooks/DocHygiene.hook.ts +2 -1
  9. package/hooks/GateResultProtection.hook.ts +28 -7
  10. package/hooks/HookCurrency.hook.ts +48 -1
  11. package/hooks/VerifyPhaseLock.hook.ts +25 -8
  12. package/hooks/WorkflowStateGuard.hook.ts +24 -7
  13. package/lib/ai-review-jury.ts +725 -0
  14. package/lib/ai-review-rounds.ts +791 -4
  15. package/lib/ai-review-unmeasured.ts +361 -0
  16. package/lib/bash-write-guard.ts +1235 -102
  17. package/lib/cli-commands.ts +252 -11
  18. package/lib/closing-reference-audit.ts +163 -0
  19. package/lib/conformity.ts +12 -0
  20. package/lib/create-sc.ts +45 -12
  21. package/lib/derived-spec.ts +206 -0
  22. package/lib/file-claims.ts +335 -0
  23. package/lib/finding-arbiter.ts +502 -28
  24. package/lib/finding-jury.ts +48 -1
  25. package/lib/finding-pr-routing.ts +333 -0
  26. package/lib/frontmatter.ts +16 -0
  27. package/lib/gate-check-audit.ts +259 -0
  28. package/lib/generators/agents-md.ts +29 -0
  29. package/lib/github.ts +112 -7
  30. package/lib/hook-tree-currency.ts +494 -0
  31. package/lib/issue-closure-audit.ts +161 -14
  32. package/lib/issue-create-override.ts +53 -3
  33. package/lib/issue-filing-gate.ts +1073 -76
  34. package/lib/local-review-rounds.ts +523 -0
  35. package/lib/organize.ts +10 -0
  36. package/lib/project-state-shape.ts +56 -5
  37. package/lib/repo-path.ts +94 -0
  38. package/lib/report-provenance.ts +65 -3
  39. package/lib/risk-tier.ts +302 -0
  40. package/lib/rounds-to-pass.ts +274 -0
  41. package/lib/rule-row-drift.ts +199 -0
  42. package/lib/sc-claim-forms.ts +33 -5
  43. package/lib/sc-guard.ts +11 -1
  44. package/lib/sc-id-cross-tree.ts +17 -2
  45. package/lib/sc-ids.ts +71 -6
  46. package/lib/sc-reservations.ts +158 -14
  47. package/lib/scaffold/ai-review-findings.ts +1157 -18
  48. package/lib/scaffold/ai-review-step.ts +3798 -76
  49. package/lib/scaffold/ai-review-unmeasured-workflow.ts +243 -0
  50. package/lib/scaffold/owned-files.ts +14 -0
  51. package/lib/scaffold/steps.ts +83 -9
  52. package/lib/scratch-roots.ts +93 -3
  53. package/lib/spec-updater.ts +16 -0
  54. package/lib/validators/spec-validators.ts +28 -2
  55. package/package.json +2 -1
  56. package/scripts/ai-review-findings.ts +41 -1
  57. package/scripts/arbitrate-finding.ts +330 -12
  58. package/scripts/audit-specs.ts +225 -23
  59. package/scripts/create-sc.ts +11 -0
  60. package/scripts/detect-sc-drift.ts +10 -2
  61. package/scripts/record-ai-review-unmeasured.ts +370 -0
  62. package/scripts/split-spec.ts +12 -0
  63. package/scripts/sync-sc-status.ts +11 -0
@@ -95,12 +95,18 @@
95
95
  * that join and nothing more, exactly as `CandidateRecord` says of itself.
96
96
  */
97
97
 
98
- import { appendFileSync, mkdirSync, readFileSync, statSync } from "fs";
98
+ import { appendFileSync, existsSync, mkdirSync, readFileSync, statSync } from "fs";
99
99
  import { homedir } from "os";
100
100
  import { dirname, join } from "path";
101
101
 
102
- import { resolveRepoSlug } from "./branch-cleanup";
103
- import { createGitHubClient, listOpenIssues } from "./github";
102
+ import { githubSlugFromRemoteUrl, resolveRepoSlug } from "./branch-cleanup";
103
+ import {
104
+ createGitHubClient,
105
+ listOpenIssues,
106
+ parseOwnerRepo,
107
+ TRUSTED_ASSOCIATIONS,
108
+ type OpenIssuePage,
109
+ } from "./github";
104
110
  import {
105
111
  duplicateCollisions,
106
112
  symptomHash,
@@ -115,6 +121,8 @@ import {
115
121
  DROPPED_CATEGORIES,
116
122
  type Disposition,
117
123
  type FindingCategory,
124
+ type JuryReading,
125
+ type Severity,
118
126
  } from "./finding-jury";
119
127
  import { clauses, createsIssue, flagValues, labelValues } from "./issue-create-override";
120
128
 
@@ -129,6 +137,45 @@ import { clauses, createsIssue, flagValues, labelValues } from "./issue-create-o
129
137
  */
130
138
  export const FILING_OVERRIDE_LABEL = "arbiter-override";
131
139
 
140
+ /**
141
+ * How many claims `SUCCESS.md` states under "Done, for the harness".
142
+ *
143
+ * A constant and not a read, because this decision runs inside a hook from an
144
+ * arbitrary working directory and a gate that needs I/O to decide is a gate
145
+ * that fails open when the I/O does. `test/issue-filing-gate.test.ts` binds it
146
+ * to the file — add a claim to `SUCCESS.md` and the suite goes red until this
147
+ * number follows.
148
+ */
149
+ export const SUCCESS_CLAIM_COUNT = 6;
150
+
151
+ /**
152
+ * Which `SUCCESS.md` claim a filing says it moves, or `null` for none.
153
+ *
154
+ * `CLAUDE.md` has required this since the file was written — *"before filing
155
+ * an issue … say which claim it moves. Something that moves none of them is
156
+ * cleanup and should say so rather than borrowing urgency."* It was prose, so
157
+ * nothing executed it, and the tracker grew faster than it drained: measured
158
+ * across 2026-10-23, open issues went 53 → 52 → 55 while the close rate fell
159
+ * from 11/h to 7/h. A backlog that is an output of the review loop cannot be
160
+ * drained by closing faster.
161
+ *
162
+ * The number is BOUNDED rather than merely shaped. `Claim 99` would otherwise
163
+ * satisfy a gate whose whole content is "name one", which is the hole any
164
+ * format-only check has — see `.claude/rules/checks-must-be-able-to-fail.md`
165
+ * on assertions that hold vacuously.
166
+ *
167
+ * Deliberately NOT accepted: a bare `#4`, which is an issue number far more
168
+ * often than a claim, and `SC-4`, which is a success criterion and a different
169
+ * register entirely. The word has to be there.
170
+ */
171
+ export function namedClaim(text: string): number | null {
172
+ for (const m of text.matchAll(/\bclaims?\s*#?\s*(\d+)/gi)) {
173
+ const n = Number(m[1]);
174
+ if (n >= 1 && n <= SUCCESS_CLAIM_COUNT) return n;
175
+ }
176
+ return null;
177
+ }
178
+
132
179
  /** How many open issues the dedupe compares against. */
133
180
  export const OPEN_ISSUE_LIMIT = 100;
134
181
 
@@ -143,7 +190,62 @@ export const OPEN_ISSUE_LIMIT = 100;
143
190
  */
144
191
  export const MAX_BODY_FILE_BYTES = 256 * 1024;
145
192
 
146
- /** One `gh issue create` clause, as much of it as the two stages read. */
193
+ /**
194
+ * How long the tracker read gets before the reading is UNMEASURED.
195
+ *
196
+ * Restored after the `gh` → Octokit move deleted it: the CLI call carried a
197
+ * `spawnSync` timeout and Octokit has none by default, so a hung API call
198
+ * hung the agent's Bash tool with no ceiling. A hook has no retry and no
199
+ * patience to spend.
200
+ */
201
+ export const OPEN_ISSUE_TIMEOUT_MS = 20_000;
202
+
203
+ /**
204
+ * The most symptom keys one open issue may contribute to the corpus.
205
+ *
206
+ * A single issue that names a hundred symbols, files and readings matches
207
+ * almost anything, so it suppresses almost anything. On a public repo that is
208
+ * a one-issue denial of service against our own quality mechanism, and it
209
+ * needs no write access to this repository at all.
210
+ *
211
+ * Forty is above every real issue on this tracker — the largest measured,
212
+ * #1261 itself, is well under it — and an issue over the cap is dropped from
213
+ * the comparison set rather than truncated. Truncating would silently keep
214
+ * whichever keys sorted first, which is a reading nobody chose.
215
+ */
216
+ export const MAX_KEYS_PER_EXISTING_ISSUE = 40;
217
+
218
+ /** The most colliding keys a refusal message will quote back. */
219
+ const MAX_QUOTED_KEYS = 6;
220
+
221
+ /** Resolve, or reject, after `ms`. One ceiling for any tracker read. */
222
+ export async function withTimeout<T>(work: Promise<T>, ms: number): Promise<T> {
223
+ let timer: ReturnType<typeof setTimeout> | undefined;
224
+ try {
225
+ return await Promise.race([
226
+ work,
227
+ new Promise<never>((_, reject) => {
228
+ timer = setTimeout(() => reject(new Error(`timed out after ${ms}ms`)), ms);
229
+ }),
230
+ ]);
231
+ } finally {
232
+ if (timer !== undefined) clearTimeout(timer);
233
+ }
234
+ }
235
+
236
+ /**
237
+ * One `gh issue create` clause, resolved the way `gh` itself would resolve it.
238
+ *
239
+ * **Every field here is what the consumer will act on, not what the command
240
+ * mentions.** That is the whole contract of this type, and it exists because
241
+ * the first version did not have it: the gate adjudicated `flagValues(...)`
242
+ * joined together while `gh` uses pflag, which is LAST-WINS — so
243
+ * `--title <benign> --title <real finding>` was adjudicated on both and filed
244
+ * as the second. Five rounds of review produced four separate reports of that
245
+ * one shape (first-vs-last title, the body read, the `--repo` target, the
246
+ * page cap), which is the signature of a class rather than four defects.
247
+ * `resolveFiling` is the single binding, so a fifth cannot be written.
248
+ */
147
249
  export interface FilingAttempt {
148
250
  title: string;
149
251
  body: string;
@@ -158,6 +260,22 @@ export interface FilingAttempt {
158
260
  * deduplicating.
159
261
  */
160
262
  bodyFile: string | null;
263
+ /**
264
+ * The tracker this filing targets, from `--repo`/`-R`, or `null` for the
265
+ * working directory's own. Read because deduplicating a filing aimed at
266
+ * one repository against a different repository's open issues is not a
267
+ * weaker reading, it is the wrong one.
268
+ */
269
+ repo: string | null;
270
+ /**
271
+ * A title, body or body-file flag appeared more than once.
272
+ *
273
+ * Recorded rather than refused. Last-wins already resolves it to what `gh`
274
+ * will post, so there is no differential left to guard against — but the
275
+ * shape is not one anybody types by accident, and a column that can be
276
+ * counted later is worth more than a refusal nobody can audit.
277
+ */
278
+ repeatedValueFlag: boolean;
161
279
  }
162
280
 
163
281
  /**
@@ -187,26 +305,86 @@ export interface FilingAdjudication {
187
305
  * A second set of names for `category` / `refusal` / `withheldBy` would make
188
306
  * that union a join nobody can write.
189
307
  *
190
- * `severity` and `jury` are always `null` here and are present anyway, so the
191
- * two row shapes parse under one reader. A chokepoint has no verifier group,
192
- * and an absent vote is not a severity of `Important`.
308
+ * `severity` and `jury` are always `null` **when this file writes the row**,
309
+ * and are present anyway, so the two row shapes parse under one reader. A
310
+ * chokepoint has no verifier group, and an absent vote is not a severity of
311
+ * `Important`.
312
+ *
313
+ * They are typed `| null` rather than `null` since #1467. They were the bare
314
+ * literal, which made the row shape unable to *hold* a vote rather than merely
315
+ * not carrying one here — and `scripts/arbitrate-finding.ts`, the one path in
316
+ * the tree that takes a ballot, writes to this same ledger. CRC-B4 asks that
317
+ * the ledger record every verifier's individual vote and whether the verifiers
318
+ * disagreed; a field typed `null` cannot, whatever is wired to it. The
319
+ * chokepoint's own rows are unchanged and still write `null` for both.
193
320
  */
194
321
  export interface FilingLedgerRow {
195
322
  at: string;
323
+ /**
324
+ * This row, told apart from every other row on a shared ledger (#1318).
325
+ *
326
+ * **The same field, the same composition and the same `null` as
327
+ * `CandidateRecord.key`** — `${batch}/${index}` — because the value of the
328
+ * two row shapes is the population they form together, and two schemes
329
+ * answering "which row is this" is one decider with a spare
330
+ * (`.claude/rules/checks-must-be-able-to-fail.md`, the fourth shape).
331
+ * Neither of the fields that look as though they could do this job can:
332
+ * `id` is `UNFILED_ID` for every row this writer emits, and `symptomHash`
333
+ * is a similarity identity, not a row identity — 6 of the 8 rows on the
334
+ * live ledger share one value.
335
+ *
336
+ * `null` when the session identity is absent, and that is a reading rather
337
+ * than a gap: `summariseFindingOutcomes` already refuses a corpus of
338
+ * repeated ids and names this field in the refusal. A plausible-looking key
339
+ * would be the Silent Default Substitution `.claude/rules/config-access.md`
340
+ * forbids, and the one failure mode that silently shrinks a corpus.
341
+ */
342
+ key: string | null;
196
343
  id: string;
197
344
  title: string;
198
345
  symptomHash: string;
199
346
  category: FindingCategory;
200
- severity: null;
347
+ severity: Severity | null;
201
348
  disposition: Disposition;
202
349
  refusal: ArbiterRefusal | null;
203
350
  /** Did it reach the tracker? */
204
351
  emitted: boolean;
205
352
  withheldBy: WithheldBy | null;
206
- jury: null;
353
+ /** The vote, when one was taken. `null` when no group was convened. */
354
+ jury: JuryReading | null;
207
355
  duplicateOf: string[];
208
356
  /** The refusal was overridden with `--label arbiter-override`. */
209
357
  overridden: boolean;
358
+ /**
359
+ * The `at` of a prior REFUSE row for this same title, when one exists.
360
+ *
361
+ * **The field that makes an override survive a re-drafted body (#1536).**
362
+ * `overridden` used to read `verdict.outcome === "REFUSE" && labelled`,
363
+ * which is correct about this adjudication and blind to the one that came
364
+ * before it: the body feeds `symptomHash`, so writing down *why* you are
365
+ * overriding changes the keys, the duplicate stops matching, the verdict
366
+ * is no longer a refusal and the label is never exercised. Measured on the
367
+ * live ledger — the #1520 filing, same title, 37 seconds apart:
368
+ *
369
+ * 10:55:08.109Z DROP refusal=DUPLICATE emitted=false overridden=false
370
+ * 10:55:45.786Z ISSUE refusal=null emitted=true overridden=false
371
+ *
372
+ * One `overridden: true` row had ever been written, against two overrides
373
+ * performed that day. The countability `refusalMessage` promises was 50%
374
+ * in the only sample there was.
375
+ *
376
+ * The join is the **title**, not the hash, and that is the whole point: an
377
+ * override is a claim about a specific prior refusal, so it has to be
378
+ * recognised by something the re-draft does not touch. `duplicateOf` on
379
+ * this row then carries that refusal's targets, so the row names what was
380
+ * waived rather than implying it.
381
+ *
382
+ * `null` also when the ledger could not be read — `priorRefusalFor`
383
+ * returns `null` for "nothing matched" and the gate pushes
384
+ * `unreadableLedgerNote` for "could not look", because those are different
385
+ * states and only one of them is a reading.
386
+ */
387
+ refiledAfter: string | null;
210
388
  }
211
389
 
212
390
  /**
@@ -217,6 +395,99 @@ export interface FilingLedgerRow {
217
395
  const TITLE_FLAG = { long: "--title", short: "-t" };
218
396
  const BODY_FLAG = { long: "--body", short: "-b" };
219
397
  const BODY_FILE_FLAG = { long: "--body-file", short: "-F" };
398
+ const REPO_FLAG = { long: "--repo", short: "-R" };
399
+
400
+ /**
401
+ * The value `gh` will act on when a flag is given more than once.
402
+ *
403
+ * **pflag is last-wins, and this one line is the whole parser-differential
404
+ * class.** The first version joined the values, so
405
+ * `--title <benign> --title <real finding>` was adjudicated on the pair and
406
+ * filed as the second — a complete bypass for anyone who knew it, and
407
+ * reachable by accident. Joining is the intuitive reading and it is wrong
408
+ * about every repeated flag; `at(-1)` is what the consumer does.
409
+ */
410
+ const asGhWould = (values: string[]): string => values.at(-1) ?? "";
411
+
412
+ /**
413
+ * The repository `gh` will file against, as `owner/repo` — or `null` because
414
+ * this gate cannot read that tracker (#1318 PR, the `--repo` differential).
415
+ *
416
+ * **`asGhWould` above is last-wins; this is the other half of the same
417
+ * class.** `gh` resolves `--repo` through `ghrepo.FromFullName`, which accepts
418
+ * a bare `OWNER/REPO`, a `HOST/OWNER/REPO`, a full `https://` URL and an
419
+ * scp-style `git@github.com:owner/repo.git`. `parseOwnerRepo` accepts only
420
+ * the first of those and **throws** on the rest, inside the `catch` in
421
+ * `openFindings` — so for three spellings `gh` files perfectly well against,
422
+ * the corpus read came back `null`, the dedupe never ran, and the filing was
423
+ * ALLOWED as UNMEASURED. Measured against this tracker: `gh issue list --repo`
424
+ * returned the same first issue for `hornjason/pai-harness`,
425
+ * `https://github.com/hornjason/pai-harness` and `github.com/hornjason/pai-harness`,
426
+ * while `parseOwnerRepo` threw `Invalid repo format` for the last two.
427
+ *
428
+ * `githubSlugFromRemoteUrl` already parses every host-bearing form — it is
429
+ * what `resolveRepoSlug` runs the `origin` remote through — so this is a
430
+ * composition and not a second parser. **`parseOwnerRepo` remains the only
431
+ * validator**: whatever this returns, it returned because that function
432
+ * accepted it, so no second opinion about what a slug is can drift from the
433
+ * one the API client holds (the fourth shape in
434
+ * `.claude/rules/checks-must-be-able-to-fail.md`).
435
+ *
436
+ * The `catch` is fail-CLOSED and that is the difference from the one it
437
+ * replaces: `null` here routes to a refusal, not to an allow.
438
+ *
439
+ * **A non-github.com host is `null` on purpose.** `gh` accepts
440
+ * `HOST/OWNER/REPO` for an enterprise instance; `createGitHubClient` talks to
441
+ * github.com and nothing else. A tracker this process genuinely cannot read
442
+ * must not resolve to a slug that names a different one.
443
+ */
444
+ export function ghRepoTarget(value: string): string | null {
445
+ const trimmed = value.trim();
446
+ if (trimmed === "") return null;
447
+ const candidate = githubSlugFromRemoteUrl(trimmed) ?? trimmed.replace(/\.git$/i, "");
448
+ try {
449
+ const { owner, repo } = parseOwnerRepo(candidate);
450
+ return `${owner}/${repo}`;
451
+ } catch {
452
+ return null;
453
+ }
454
+ }
455
+
456
+ /**
457
+ * One clause, resolved to what `gh` would resolve it to.
458
+ *
459
+ * The single binding for "what will actually be filed". Four of the sixteen
460
+ * review findings on this subsystem were one instance each of the gate
461
+ * reading a different value than the consumer acts on; they are answered
462
+ * here, together, so a fifth cannot be written against a second parser.
463
+ *
464
+ * ## What this deliberately does not resolve
465
+ *
466
+ * **A `cd` in an earlier clause.** `cd /other/repo && gh issue create …`
467
+ * targets another tracker and this reads the session's directory. Resolving
468
+ * it means tracking directory state across clauses, which is the shell
469
+ * interpreter `lib/issue-create-override.ts` explicitly declines to be, and
470
+ * the failure is in the safe direction: the dedupe runs against the wrong
471
+ * corpus, finds nothing, and the filing is allowed. `--repo` IS read,
472
+ * because it is in the clause and costs one more query.
473
+ */
474
+ export function resolveFiling(tokens: string[]): FilingAttempt {
475
+ const titles = flagValues(tokens, TITLE_FLAG);
476
+ const bodies = flagValues(tokens, BODY_FLAG);
477
+ const bodyFiles = flagValues(tokens, BODY_FILE_FLAG);
478
+ const repos = flagValues(tokens, REPO_FLAG);
479
+ return {
480
+ title: asGhWould(titles),
481
+ body: asGhWould(bodies),
482
+ labels: labelValues(tokens),
483
+ // The PATH, last-wins, or `null` when the body is inline (#1300). The
484
+ // same `asGhWould` reading as the title and the body — a repeated
485
+ // `--body-file` overrides rather than accumulating.
486
+ bodyFile: bodyFiles.length > 0 ? asGhWould(bodyFiles) : null,
487
+ repo: repos.length > 0 ? asGhWould(repos) : null,
488
+ repeatedValueFlag: titles.length > 1 || bodies.length > 1 || bodyFiles.length > 1,
489
+ };
490
+ }
220
491
 
221
492
  /**
222
493
  * Every `gh issue create` in this command, one entry per clause.
@@ -226,18 +497,7 @@ const BODY_FILE_FLAG = { long: "--body-file", short: "-F" };
226
497
  * the whole string lets the first half excuse the second.
227
498
  */
228
499
  export function filingAttempts(cmd: string): FilingAttempt[] {
229
- return clauses(cmd)
230
- .filter(createsIssue)
231
- .map(tokens => {
232
- const bodyFile = flagValues(tokens, BODY_FILE_FLAG);
233
- return {
234
- title: flagValues(tokens, TITLE_FLAG).join(" "),
235
- body: flagValues(tokens, BODY_FLAG).join("\n"),
236
- labels: labelValues(tokens),
237
- // The LAST one, matching `gh`: a repeated flag overrides.
238
- bodyFile: bodyFile.at(-1) ?? null,
239
- };
240
- });
500
+ return clauses(cmd).filter(createsIssue).map(resolveFiling);
241
501
  }
242
502
 
243
503
  /**
@@ -270,14 +530,15 @@ export function readBodyFile(path: string, limit: number = MAX_BODY_FILE_BYTES):
270
530
  * The single place that decides whether a filing may proceed.
271
531
  *
272
532
  * `readExisting` is a thunk and not a value so the `gh issue list` is never
273
- * paid for a finding the category stage already drops. It returns `null` for
274
- * "could not be read", which is a different fact from an empty tracker — the
533
+ * paid for a finding the category stage already drops. It returns a
534
+ * `CorpusReading`, whose `UNMEASURED` arm is "could not be read" and carries
535
+ * its own `why` — a different fact from an empty tracker, which is the
275
536
  * distinction `.claude/rules/config-access.md` makes about a corrupt config,
276
537
  * applied to the one input this gate cannot produce itself.
277
538
  */
278
539
  export async function adjudicateFiling(
279
540
  attempt: FilingAttempt,
280
- readExisting: () => Promise<readonly Finding[] | null>,
541
+ readExisting: () => Promise<CorpusReading>,
281
542
  readBody: (path: string) => string | null = readBodyFile,
282
543
  ): Promise<FilingAdjudication> {
283
544
  // ── where is the body? ──
@@ -354,17 +615,46 @@ export async function adjudicateFiling(
354
615
  };
355
616
  }
356
617
 
357
- // ── is this new? ──
358
- const existing = await readExisting();
359
- if (existing === null) {
618
+ // ── which tracker is this going to? ──
619
+ //
620
+ // **The one UNMEASURED in this file that REFUSES, and the reason it is not
621
+ // an exception to the policy above.** Every other unreadable input here is
622
+ // a fact about the environment — no token, a 403, a rate limit, an
623
+ // unreachable API — which the agent cannot fix and must not be gagged by.
624
+ // This one is a fact about the COMMAND: the agent wrote a `--repo` value,
625
+ // it is in the clause, and re-spelling it as `owner/repo` is a one-token
626
+ // edit. A refusal somebody can act on in the same turn is not a gag.
627
+ //
628
+ // `outcome` and `refusal` are separate fields precisely so the policy can
629
+ // differ from the reading. Every other site sets them in lockstep, which is
630
+ // what makes the lockstep look like an invariant; it never was one.
631
+ //
632
+ // Fail-closed here because the alternative is the fail-open that made the
633
+ // differential exploitable in the first place: `gh` accepts more spellings
634
+ // of `--repo` than this process can read, and a spelling we cannot read
635
+ // must not be the cheapest way past the dedupe.
636
+ if (attempt.repo !== null && ghRepoTarget(attempt.repo) === null) {
360
637
  return {
361
638
  ...base,
362
- outcome: "UNMEASURED",
639
+ outcome: "REFUSE",
363
640
  refusal: "UNMEASURED",
364
- reason: "the open-issue set could not be read, so whether this symptom is already filed was never asked",
641
+ reason:
642
+ `\`--repo ${attempt.repo}\` does not resolve to a github.com \`owner/repo\`, so the ` +
643
+ `open issues of the tracker this would file against were never read. Re-run with ` +
644
+ `\`--repo owner/repo\`; an enterprise host is not readable from here at all`,
365
645
  };
366
646
  }
367
- const collisions = duplicateCollisions(finding, existing);
647
+
648
+ // ── is this new? ──
649
+ const existing = await readExisting();
650
+ if (existing.reading === "UNMEASURED") {
651
+ // The reason is the READING's own, never composed here. A sentence
652
+ // written at this distance from the failure can be false for the input
653
+ // it is emitted on, which this file already paid for once in the
654
+ // `--body-file` arm above.
655
+ return { ...base, outcome: "UNMEASURED", refusal: "UNMEASURED", reason: existing.why };
656
+ }
657
+ const collisions = duplicateCollisions(finding, existing.findings);
368
658
  if (collisions.length > 0) {
369
659
  return {
370
660
  ...base,
@@ -378,22 +668,123 @@ export async function adjudicateFiling(
378
668
  };
379
669
  }
380
670
 
671
+ // ── it is novel and postable. does it say what it MOVES? ──
672
+ //
673
+ // **Last, and the ordering is the design.** A regex over a string already in
674
+ // hand is the cheapest test in this function, so the cost doctrine every
675
+ // other stage follows would put it first — and first is wrong here, twice
676
+ // over. A duplicate must be refused as DUPLICATE, because "already filed as
677
+ // #1173" is actionable and "name a claim" is not; and an UNMEASURED tracker
678
+ // must stay UNMEASURED, because a policy refusal that outranks a reading
679
+ // failure is a reading failure nobody ever sees. This stage only ever
680
+ // converts an ALLOW, so it can mask nothing.
681
+ //
682
+ // Measured when it was briefly placed first: 34 of 78 cases in this file's
683
+ // own suite went red, every one a dedupe or UNMEASURED case short-circuited
684
+ // before it could run. That is the mask, observed rather than reasoned
685
+ // about.
686
+ //
687
+ // This REFUSES rather than noting, and the difference is the whole point.
688
+ // `CLAUDE.md` has carried the rule as prose for the life of this repository
689
+ // — *"say which claim it moves"* — and nothing executed it, so the tracker
690
+ // grew faster than it drained: open issues went 53 → 52 → 55 across
691
+ // 2026-10-23 while the close rate fell from 11/h to 7/h. A rule nothing
692
+ // executes is not a rule; `.claude/rules/config-access.md` says that about
693
+ // ADRs and it was true of this line too.
694
+ //
695
+ // The escape hatch is the label that already exists. Cleanup is still
696
+ // postable — say so with `--label arbiter-override`, and it is counted. An
697
+ // override nobody can count is the thing this gate is not.
698
+ if (namedClaim(`${attempt.title}\n${body}`) === null) {
699
+ return {
700
+ ...base,
701
+ outcome: "REFUSE",
702
+ refusal: "NO_CLAIM",
703
+ reason:
704
+ `the filing is novel, and names no SUCCESS.md claim — nothing says what it moves. ` +
705
+ `Name one as "Claim <1-${SUCCESS_CLAIM_COUNT}>" in the title or body, or post it as ` +
706
+ `cleanup with \`--label ${FILING_OVERRIDE_LABEL}\``,
707
+ };
708
+ }
709
+
381
710
  return {
382
711
  ...base,
383
712
  outcome: "ALLOW",
384
713
  refusal: null,
385
- reason: `no open issue shares this symptom, and ${category} is not a dropped category`,
714
+ reason:
715
+ `no open issue shares this symptom, ${category} is not a dropped category, ` +
716
+ `and it names SUCCESS.md claim ${namedClaim(`${attempt.title}\n${body}`)}`,
386
717
  };
387
718
  }
388
719
 
389
720
  /**
390
- * The open issues, as findings — or `null` when the set could not be read.
721
+ * Why one existing issue was kept out of the comparison set.
722
+ *
723
+ * **Five reasons across two modules, and that is the point of #1374.** The
724
+ * first two are this file's own filters. The last three happen in
725
+ * `lib/github.ts`, before this file sees a row at all, and they used to
726
+ * happen silently — the count this file took was already post-filter, so a
727
+ * page holding 100 pull requests and no issues reached `corpusReading` as
728
+ * `considered === 0` and was reported as a clean tracker. A drop nobody
729
+ * records is a drop nobody can reason about, wherever it happens.
730
+ */
731
+ export interface CorpusDrop {
732
+ /**
733
+ * The issue number as a string, or `null` for a drop that is not about one
734
+ * issue — a malformed row that carried no number, or the page cap, which
735
+ * is a fact about the request rather than about any row in the answer.
736
+ */
737
+ id: string | null;
738
+ reason:
739
+ | "untrusted-author"
740
+ | "over-key-cap"
741
+ | "pull-request"
742
+ | "malformed-row"
743
+ | "page-cap";
744
+ /** The producing filter's own sentence, so the report is not re-derived. */
745
+ detail: string;
746
+ }
747
+
748
+ /**
749
+ * What a corpus read yielded, and what it had to drop to get there.
391
750
  *
392
- * `null` and `[]` are different facts and the caller treats them differently:
393
- * an empty tracker means nothing is a duplicate, an unreadable one means
394
- * nobody asked. Every failure path here returns `null` rather than `[]`, so a
395
- * `gh` that is missing, unauthenticated, rate-limited, slow or returning
396
- * something unexpected cannot be mistaken for a clean tracker.
751
+ * **One discriminator.** `reading` is the whole answer — there is no `null`
752
+ * beside it meaning the same thing, because two spellings of UNMEASURED are
753
+ * two deciders for one question and the second one always agrees with the
754
+ * first (`.claude/rules/checks-must-be-able-to-fail.md`, the fourth shape).
755
+ * Every path that could not take a reading returns `UNMEASURED` **with its
756
+ * own `why`**, because a reason composed downstream is a reason that can be
757
+ * false for the input it was emitted on, which this file already paid for
758
+ * once in the `--body-file` arm above.
759
+ *
760
+ * `dropped` is carried on BOTH arms. A read that succeeded after dropping
761
+ * three issues is a different fact from one that dropped none, and the caller
762
+ * cannot ask afterwards.
763
+ */
764
+ export type CorpusReading =
765
+ | { reading: "MEASURED"; findings: readonly Finding[]; dropped: readonly CorpusDrop[] }
766
+ | { reading: "UNMEASURED"; why: string; dropped: readonly CorpusDrop[] };
767
+
768
+ /** A reading that was taken. */
769
+ export function measuredCorpus(
770
+ findings: readonly Finding[],
771
+ dropped: readonly CorpusDrop[] = [],
772
+ ): CorpusReading {
773
+ return { reading: "MEASURED", findings, dropped };
774
+ }
775
+
776
+ /** A reading that was not taken, and why. */
777
+ export function unmeasuredCorpus(why: string, dropped: readonly CorpusDrop[] = []): CorpusReading {
778
+ return { reading: "UNMEASURED", why, dropped };
779
+ }
780
+
781
+ /**
782
+ * The open issues, as findings, or an UNMEASURED reading naming why not.
783
+ *
784
+ * An empty tracker means nothing is a duplicate; an unreadable one means
785
+ * nobody asked. Every failure path here is `UNMEASURED` rather than an empty
786
+ * list, so a `gh` that is missing, unauthenticated, rate-limited, slow or
787
+ * returning something unexpected cannot be mistaken for a clean tracker.
397
788
  *
398
789
  * **Through Octokit and never the GitHub CLI.** `lib/`, `hooks/` and `gates/`
399
790
  * may not reach `gh` as a subprocess — GITHUB-API-MIGRATION-SPEC.md's SC-893,
@@ -406,7 +797,7 @@ export async function adjudicateFiling(
406
797
  * **The cost, stated because it decides what this gate does on a dev box:**
407
798
  * `createGitHubClient` needs `GITHUB_TOKEN` or `GH_TOKEN`, and a developer's
408
799
  * GitHub credential usually lives in the CLI's keyring and not in the
409
- * environment. With no token this returns `null`, the dedupe is UNMEASURED,
800
+ * environment. With no token the dedupe is UNMEASURED,
410
801
  * and only the category stage runs. That is visible rather than silent — the
411
802
  * ledger row says `UNMEASURED` and the agent is told — and it is the honest
412
803
  * reading: nobody asked the tracker. Export a token, or supply the set below.
@@ -419,41 +810,282 @@ export async function adjudicateFiling(
419
810
  * allowed to be wrong in: the result is a duplicate reaching the tracker,
420
811
  * never a real finding silenced.
421
812
  */
422
- export async function openFindings(projectRoot: string): Promise<readonly Finding[] | null> {
813
+ /**
814
+ * Which tracker the dedupe asks about. One binding, so there is one answer.
815
+ *
816
+ * **An explicit `--repo` that does not resolve is `null`, never the working
817
+ * directory's slug.** Falling back is the tempting repair and it is the worse
818
+ * one: this gate would then adjudicate a filing bound for one tracker against
819
+ * another tracker's issues, which is not a weaker reading — it is the wrong
820
+ * one, and it is wrong in both directions at once (a real duplicate on the
821
+ * target is invisible, an unrelated issue here can refuse it). The same
822
+ * argument `filingGate` makes for caching per target rather than per command.
823
+ *
824
+ * `null` from here is UNMEASURED to `openFindings`, and the POLICY over an
825
+ * unparseable explicit target is decided in `adjudicateFiling`, from
826
+ * `attempt.repo`, before this is ever called. Both read `ghRepoTarget`; one
827
+ * decides what to query, the other decides what to do about not being able
828
+ * to — two questions, one predicate.
829
+ */
830
+ export function corpusSlug(projectRoot: string, repo: string | null): string | null {
831
+ if (repo !== null) return ghRepoTarget(repo);
832
+ return resolveRepoSlug({ projectRoot }).slug;
833
+ }
834
+
835
+ export async function openFindings(
836
+ projectRoot: string,
837
+ repo: string | null = null,
838
+ ): Promise<CorpusReading> {
423
839
  const override = process.env.RUNGATE_OPEN_FINDINGS;
424
840
  if (override !== undefined && override !== "") {
425
841
  try {
426
842
  return asFindings(JSON.parse(readFileSync(override, "utf-8")));
427
843
  } catch {
428
- return null;
844
+ return unmeasuredCorpus(
845
+ `the supplied comparison set \`${override}\` could not be read or parsed, so whether ` +
846
+ "this symptom is already filed was never asked",
847
+ );
429
848
  }
430
849
  }
431
850
  try {
432
- const { slug } = resolveRepoSlug({ projectRoot });
433
- if (slug === null) return null;
434
- const issues = await listOpenIssues(createGitHubClient(), slug, OPEN_ISSUE_LIMIT);
435
- return issues.map(i => ({ id: String(i.number), title: i.title, body: i.body }));
851
+ const slug = corpusSlug(projectRoot, repo);
852
+ if (slug === null) {
853
+ return unmeasuredCorpus(
854
+ repo === null
855
+ ? "no repository slug could be resolved, so there was no tracker to compare against"
856
+ : `\`--repo ${repo}\` does not resolve to a github.com \`owner/repo\`, so there ` +
857
+ "was no tracker to compare against",
858
+ );
859
+ }
860
+ const page = await withTimeout(
861
+ listOpenIssues(createGitHubClient(), slug, OPEN_ISSUE_LIMIT),
862
+ OPEN_ISSUE_TIMEOUT_MS,
863
+ );
864
+ return trustedCorpus(page);
436
865
  } catch {
437
- // Every failure lands here as `null`, which is "nobody asked" and not
866
+ // Every failure lands here as UNMEASURED, which is "nobody asked" and not
438
867
  // "nothing matched" — a missing token, a 403, a rate limit and an
439
868
  // unreachable API are all states this must not report as a clean tracker.
440
- return null;
869
+ return unmeasuredCorpus(
870
+ "the open-issue set could not be read, so whether this symptom is already filed was never asked",
871
+ );
872
+ }
873
+ }
874
+
875
+ /**
876
+ * The open issues that may be used to suppress a filing.
877
+ *
878
+ * Two filters, and both exist because **this repository is public, so the
879
+ * corpus is attacker-controlled input**. An open issue here is not evidence
880
+ * that something was already reported; it is text somebody on the internet
881
+ * wrote, and this gate turns it into a refusal.
882
+ *
883
+ * - **Author trust.** Only `OWNER`/`MEMBER`/`COLLABORATOR`; see
884
+ * `TRUSTED_ASSOCIATIONS`.
885
+ * - **A key cap per issue.** One issue stuffed with symptom keys matches
886
+ * everything, so it is dropped rather than allowed to.
887
+ *
888
+ * Both fail in the direction of a duplicate reaching the tracker, never a
889
+ * real finding silenced. That asymmetry is the whole design and it is why
890
+ * neither of these is a refusal.
891
+ */
892
+ /**
893
+ * Whether one existing issue may join the comparison set.
894
+ *
895
+ * One binding, because both corpus readers below apply it and the mutation
896
+ * battery could not mutate either on its own while the predicate was spelled
897
+ * twice — an anchor matching two sites is a mutation nobody chose, and a
898
+ * battery that reports `ANCHOR x2` is telling you about its own range rather
899
+ * than about the guard (`.claude/rules/checks-must-be-able-to-fail.md`, the
900
+ * seventh shape). Dropped whole rather than truncated: truncating keeps
901
+ * whichever keys sorted first, which is a reading nobody picked.
902
+ */
903
+ function withinKeyCap(finding: Finding): boolean {
904
+ return symptomKeys(finding).length <= MAX_KEYS_PER_EXISTING_ISSUE;
905
+ }
906
+
907
+ /**
908
+ * A corpus that filtered to nothing is UNMEASURED, not a clean tracker.
909
+ *
910
+ * **One binding, because both readers below reach it and because this is the
911
+ * fail-open the filters create.** Each filter is individually argued to fail
912
+ * in the safe direction — a duplicate reaches the tracker, never a real
913
+ * finding silenced — and that argument is about ONE issue being dropped. It
914
+ * does not survive composition: a non-empty issue list that filters down to
915
+ * an empty one is byte-indistinguishable from a tracker with nothing on it,
916
+ * and the gate then ALLOWs on the strength of a comparison it never made.
917
+ * That is not the safe direction; it is no direction at all, and a filter
918
+ * with a bug in it would read exactly the same.
919
+ *
920
+ * `dropped` travels either way, so a read that succeeded after dropping three
921
+ * issues can be told from one that dropped none.
922
+ */
923
+ function corpusReading(
924
+ considered: number,
925
+ findings: readonly Finding[],
926
+ dropped: readonly CorpusDrop[],
927
+ source: string,
928
+ ): CorpusReading {
929
+ if (considered === 0 || findings.length > 0) return measuredCorpus(findings, dropped);
930
+ return unmeasuredCorpus(
931
+ `the ${source} held ${considered} issue(s) and every one of them was filtered out of the ` +
932
+ "comparison set, so whether this symptom is already filed was never asked — an empty " +
933
+ `corpus that was emptied BY US is not a clean tracker. Dropped: ${describeDrops(dropped)}`,
934
+ dropped,
935
+ );
936
+ }
937
+
938
+ /** The drops as one sentence, each with the filter's own reason. */
939
+ export function describeDrops(dropped: readonly CorpusDrop[]): string {
940
+ if (dropped.length === 0) return "nothing — the list was non-empty and the filters took none of it, which should be impossible here";
941
+ return dropped
942
+ .map(d => (d.id === null ? `(${d.reason}: ${d.detail})` : `#${d.id} (${d.reason}: ${d.detail})`))
943
+ .join("; ");
944
+ }
945
+
946
+ /**
947
+ * The open-issue page as a comparison set, or the reading that says why not.
948
+ *
949
+ * **It takes the PAGE and not the issues** (#1374). The count that decides
950
+ * MEASURED from UNMEASURED has to be the population the tracker returned, and
951
+ * the only place that number exists is beside the rows `lib/github.ts`
952
+ * dropped. Taking `issues.length` here — which is what this did — asks "did
953
+ * OUR filters empty it?" of a list somebody else had already emptied.
954
+ */
955
+ export function trustedCorpus(page: OpenIssuePage): CorpusReading {
956
+ const { issues } = page;
957
+ const out: Finding[] = [];
958
+ const dropped: CorpusDrop[] = [];
959
+ for (const row of page.droppedRows) {
960
+ dropped.push({
961
+ id: row.number === null ? null : String(row.number),
962
+ reason: row.reason,
963
+ detail:
964
+ row.reason === "pull-request"
965
+ ? "the REST issues endpoint returns pull requests as issues, and a PR body quotes the symptom of the issue it fixes"
966
+ : "the row carried no usable number or title, so there was nothing to compare against",
967
+ });
968
+ }
969
+ if (page.truncated) {
970
+ // Not an UNMEASURED on its own: a full page IS a reading, of a narrower
971
+ // question than the one asked. It travels as a drop so the agent is told
972
+ // the comparison could not see the whole tracker, which is the fact a
973
+ // bare "no duplicate found" hides.
974
+ dropped.push({
975
+ id: null,
976
+ reason: "page-cap",
977
+ detail:
978
+ `the tracker returned a full page of ${page.perPage} and this gate does not paginate, ` +
979
+ "so any issue past that position was never compared against",
980
+ });
441
981
  }
982
+ for (const issue of issues) {
983
+ const id = String(issue.number);
984
+ if (!TRUSTED_ASSOCIATIONS.has(issue.authorAssociation)) {
985
+ dropped.push({
986
+ id,
987
+ reason: "untrusted-author",
988
+ detail:
989
+ `author association ${issue.authorAssociation === "" ? "(absent)" : issue.authorAssociation}` +
990
+ ` is not one of ${[...TRUSTED_ASSOCIATIONS].join("/")}`,
991
+ });
992
+ continue;
993
+ }
994
+ const finding: Finding = { id, title: issue.title, body: issue.body };
995
+ if (!withinKeyCap(finding)) {
996
+ dropped.push({
997
+ id,
998
+ reason: "over-key-cap",
999
+ detail: `names ${symptomKeys(finding).length} symptom keys, over the cap of ${MAX_KEYS_PER_EXISTING_ISSUE}`,
1000
+ });
1001
+ continue;
1002
+ }
1003
+ out.push(finding);
1004
+ }
1005
+ // `page.considered`, never `issues.length`. That one substitution is #1374.
1006
+ return corpusReading(page.considered, out, dropped, "tracker");
442
1007
  }
443
1008
 
444
- /** Supplied rows as `Finding`s, or `null` if the shape is not what we asked for. */
445
- function asFindings(parsed: unknown): readonly Finding[] | null {
446
- if (!Array.isArray(parsed)) return null;
1009
+ /** Supplied rows as `Finding`s, or UNMEASURED if the shape is not what we asked for. */
1010
+ function asFindings(parsed: unknown): CorpusReading {
1011
+ const malformed = (what: string) =>
1012
+ unmeasuredCorpus(
1013
+ `the supplied comparison set is ${what}, so whether this symptom is already filed was never asked`,
1014
+ );
1015
+ if (!Array.isArray(parsed)) return malformed("not an array");
447
1016
  const out: Finding[] = [];
1017
+ const dropped: CorpusDrop[] = [];
448
1018
  for (const row of parsed) {
449
- if (row === null || typeof row !== "object") return null;
1019
+ if (row === null || typeof row !== "object") return malformed("not a list of objects");
450
1020
  const r = row as Record<string, unknown>;
451
1021
  const id = r.number ?? r.id;
452
- if (typeof id !== "number" && typeof id !== "string") return null;
453
- if (typeof r.title !== "string") return null;
454
- out.push({ id: String(id), title: r.title, body: typeof r.body === "string" ? r.body : "" });
1022
+ if (typeof id !== "number" && typeof id !== "string") return malformed("missing a row id");
1023
+ if (typeof r.title !== "string") return malformed("missing a row title");
1024
+ const finding: Finding = {
1025
+ id: String(id),
1026
+ title: r.title,
1027
+ body: typeof r.body === "string" ? r.body : "",
1028
+ };
1029
+ // The key cap applies here too, through the SAME predicate. This file is
1030
+ // operator-supplied rather than attacker-supplied, so the AUTHOR filter
1031
+ // does not, but one row naming everything suppresses everything whoever
1032
+ // wrote it.
1033
+ if (!withinKeyCap(finding)) {
1034
+ dropped.push({
1035
+ id: finding.id,
1036
+ reason: "over-key-cap",
1037
+ detail: `names ${symptomKeys(finding).length} symptom keys, over the cap of ${MAX_KEYS_PER_EXISTING_ISSUE}`,
1038
+ });
1039
+ continue;
1040
+ }
1041
+ out.push(finding);
455
1042
  }
456
- return out;
1043
+ return corpusReading(parsed.length, out, dropped, "supplied comparison set");
1044
+ }
1045
+
1046
+ /**
1047
+ * The environment variable the session identity comes from.
1048
+ *
1049
+ * One exported constant because it is named in the UNMEASURED note an agent
1050
+ * reads, and a variable named in prose and read in code from two places is
1051
+ * two spellings of one fact.
1052
+ */
1053
+ export const LEDGER_SESSION_ENV = "CLAUDE_CODE_SESSION_ID";
1054
+
1055
+ /**
1056
+ * The batch every row of one command shares, or `null` when there is no
1057
+ * session identity to build one from (#1318).
1058
+ *
1059
+ * **`${at}/${index}` is the cheapest wrong fix and it does not hold.**
1060
+ * `ledgerPath()` defaults to `~/.rungate/finding-ledger.jsonl` — one file for
1061
+ * every agent on the machine, not one per worktree — and `at` is a single
1062
+ * `new Date().toISOString()` hoisted outside the row loop. So `${at}/${index}`
1063
+ * is unique *within* one command and only probabilistically across concurrent
1064
+ * writers, and the live ledger already carries two rows identical in every
1065
+ * field including `at`. #1263 asks for unique **by construction**, and a
1066
+ * coin-toss you only have to lose once silently reintroduces the defect.
1067
+ *
1068
+ * Three components, and each closes a case the others leave open:
1069
+ *
1070
+ * - **the session**, first 8 chars of `CLAUDE_CODE_SESSION_ID` — the same cut
1071
+ * `hooks/TeamInit.hook.ts` takes, so a ledger row joins to that session's
1072
+ * `teams/session-<8>` directory rather than needing a second identity;
1073
+ * - **the pid**, because one session runs parallel subagents and each Bash
1074
+ * call spawns its own hook PROCESS. Two of them can append in the same
1075
+ * millisecond with the same session and the same clause index, which is
1076
+ * every other component held fixed. A pid is unique among live processes,
1077
+ * and a process that is appending is live;
1078
+ * - **`at` and the clause index**, which separate one process's own rows.
1079
+ *
1080
+ * `null`, loudly, when the variable is absent — never a fallback that merely
1081
+ * looks unique. `.claude/rules/config-access.md`, *Silent Default
1082
+ * Substitution*: `0`, `{}` and a plausible key are indistinguishable from
1083
+ * success; UNMEASURED is not.
1084
+ */
1085
+ export function filingBatch(at: string, pid: number = process.pid): string | null {
1086
+ const session = (process.env[LEDGER_SESSION_ENV] ?? "").trim();
1087
+ if (session === "") return null;
1088
+ return `${session.slice(0, 8)}.${pid}/${at}`;
457
1089
  }
458
1090
 
459
1091
  /** Where the adjudications land. One line of JSON per decision. */
@@ -485,6 +1117,91 @@ export function recordAdjudication(row: FilingLedgerRow, path: string = ledgerPa
485
1117
  }
486
1118
  }
487
1119
 
1120
+ /**
1121
+ * Every row on the ledger, or `null` when the file is there and unreadable.
1122
+ *
1123
+ * **An absent ledger is an empty one; a corrupt ledger is neither.** That is
1124
+ * `.claude/rules/config-access.md`'s distinction, applied to the one file
1125
+ * this gate now reads as well as writes: a machine that has never adjudicated
1126
+ * a filing genuinely has no prior refusals, and saying UNMEASURED there would
1127
+ * put a note on the first `gh issue create` anybody ever runs.
1128
+ *
1129
+ * A single malformed line is skipped rather than refusing the file. The
1130
+ * ledger is append-only from several processes and a torn final write is the
1131
+ * expected failure, not a corrupted store — but a file that cannot be opened
1132
+ * at all is `null`, because that one cannot be told apart from a lookup
1133
+ * nobody performed.
1134
+ */
1135
+ export function readLedgerRows(path: string = ledgerPath()): FilingLedgerRow[] | null {
1136
+ if (!existsSync(path)) return [];
1137
+ let text: string;
1138
+ try {
1139
+ text = readFileSync(path, "utf-8");
1140
+ } catch {
1141
+ return null;
1142
+ }
1143
+ const rows: FilingLedgerRow[] = [];
1144
+ for (const line of text.split("\n")) {
1145
+ if (line.trim() === "") continue;
1146
+ try {
1147
+ rows.push(JSON.parse(line) as FilingLedgerRow);
1148
+ } catch {
1149
+ // A torn append, not a corrupt store.
1150
+ }
1151
+ }
1152
+ return rows;
1153
+ }
1154
+
1155
+ /**
1156
+ * The most recent refusal of a filing under this exact title, if any.
1157
+ *
1158
+ * Exported so the gate has ONE binding for "has this been refused before?"
1159
+ * and a test can read the same answer the gate acts on — two spellings of
1160
+ * this question would be the fourth shape in
1161
+ * `.claude/rules/checks-must-be-able-to-fail.md`.
1162
+ *
1163
+ * **Exact title, and no time bound.** A title is what the issue's own
1164
+ * evidence shows surviving a re-draft, and loosening it to a similarity
1165
+ * would re-introduce exactly the thing #1536 is about: a judgement over
1166
+ * prose, defeated by changing the prose. A window would be a second
1167
+ * threshold with no corpus behind it, and the cost of attributing an
1168
+ * override to a refusal from last month is a row that says so — visible,
1169
+ * and nothing is withheld by it.
1170
+ *
1171
+ * ## THREE ROWS THAT ARE NOT A REFUSAL, AND LOOK LIKE ONE
1172
+ *
1173
+ * The first spelling of this was `refusal !== null && !emitted`, and
1174
+ * `FG-48 CONTROL` turned it red inside the hour — a filing that had nothing
1175
+ * to do with #1536 started carrying `refiledNote` because an earlier row on
1176
+ * the shared ledger had the same title.
1177
+ *
1178
+ * - **`UNMEASURED` is not a refusal.** It is this file's whole doctrine
1179
+ * that a filing nobody could adjudicate and a filing somebody refused are
1180
+ * different states, and the first predicate collapsed them.
1181
+ * - **A clean clause blocked by a sibling** carries `withheldBy: BLOCKED`
1182
+ * and `refusal: null` — withheld by the command, never adjudicated down.
1183
+ * - **A refusal that was overridden** reached the tracker. The next filing
1184
+ * of that title is a second finding, not a re-draft of a waived one.
1185
+ *
1186
+ * So the test is that the row's OWN adjudication withheld it:
1187
+ * `withheldBy === refusal` is what distinguishes a refusal the row earned
1188
+ * from one it inherited, and it is the field `markBlockedCommand` moves.
1189
+ */
1190
+ export function priorRefusalFor(
1191
+ title: string,
1192
+ rows: readonly FilingLedgerRow[],
1193
+ ): FilingLedgerRow | null {
1194
+ let best: FilingLedgerRow | null = null;
1195
+ for (const row of rows) {
1196
+ if (row.title !== title) continue;
1197
+ if (row.refusal === null || row.refusal === "UNMEASURED") continue;
1198
+ if (row.emitted || row.overridden) continue;
1199
+ if (row.withheldBy !== row.refusal) continue;
1200
+ if (best === null || row.at >= best.at) best = row;
1201
+ }
1202
+ return best;
1203
+ }
1204
+
488
1205
  export interface FilingGateReading {
489
1206
  /** The block reason, or `null` to allow. */
490
1207
  refusal: string | null;
@@ -508,7 +1225,9 @@ export async function filingGate(
508
1225
  options: {
509
1226
  projectRoot: string;
510
1227
  now?: string;
511
- readExisting?: (projectRoot: string) => Promise<readonly Finding[] | null>;
1228
+ readExisting?: (projectRoot: string, repo: string | null) => Promise<CorpusReading>;
1229
+ /** The adjudications already on the ledger. `null` means unreadable. */
1230
+ readLedger?: () => FilingLedgerRow[] | null;
512
1231
  },
513
1232
  ): Promise<FilingGateReading> {
514
1233
  const attempts = filingAttempts(cmd);
@@ -516,50 +1235,221 @@ export async function filingGate(
516
1235
 
517
1236
  const at = options.now ?? new Date().toISOString();
518
1237
  const read = options.readExisting ?? openFindings;
519
- // Read once per command, not once per clause: two creates in one command
520
- // adjudicated against two different snapshots is a reading nobody can act
521
- // on. The PROMISE is cached rather than its value, so two clauses cannot
522
- // both start a request before either has resolved.
523
- let cached: Promise<readonly Finding[] | null> | undefined;
524
- const readExisting = () => (cached ??= read(options.projectRoot));
1238
+ // Read once per TARGET TRACKER, not once per command and not once per
1239
+ // clause. Once per clause would adjudicate two creates against two
1240
+ // different snapshots; once per command would adjudicate a `--repo other/x`
1241
+ // filing against THIS repository's issues, which is not a weaker reading,
1242
+ // it is the wrong one. The PROMISE is cached rather than its value, so two
1243
+ // clauses on one tracker cannot both start a request before either resolves.
1244
+ const cached = new Map<string, Promise<CorpusReading>>();
1245
+ const readFor = (repo: string | null) => {
1246
+ const key = repo ?? "";
1247
+ const hit = cached.get(key);
1248
+ if (hit !== undefined) return hit;
1249
+ const started = read(options.projectRoot, repo);
1250
+ cached.set(key, started);
1251
+ return started;
1252
+ };
525
1253
 
526
1254
  const rows: FilingLedgerRow[] = [];
527
1255
  const refusals: string[] = [];
528
1256
  const notes: string[] = [];
529
1257
 
530
- for (const attempt of attempts) {
531
- const verdict = await adjudicateFiling(attempt, readExisting);
532
- const overridden = verdict.outcome === "REFUSE" && attempt.labels.includes(FILING_OVERRIDE_LABEL);
533
- const emitted = verdict.outcome !== "REFUSE" || overridden;
1258
+ // One batch per command, so every row of one adjudication shares it and the
1259
+ // clause index separates them — `CandidateRecord.key`'s scheme exactly.
1260
+ const batch = filingBatch(at);
1261
+ if (batch === null) notes.push(unkeyedLedgerNote());
1262
+
1263
+ // Read ONCE per command, before any clause, for the same reason the
1264
+ // corpus is: two clauses adjudicated against two snapshots of the same
1265
+ // store are two readings nobody can compare. `null` is a failed read and
1266
+ // is said out loud rather than standing in for "no prior refusal".
1267
+ const priorRows = (options.readLedger ?? (() => readLedgerRows()))();
1268
+ if (priorRows === null) notes.push(unreadableLedgerNote());
1269
+
1270
+ for (const [index, attempt] of attempts.entries()) {
1271
+ const verdict = await adjudicateFiling(attempt, () => readFor(attempt.repo));
1272
+ const labelled = attempt.labels.includes(FILING_OVERRIDE_LABEL);
1273
+ const prior = priorRows === null ? null : priorRefusalFor(attempt.title, priorRows);
1274
+ // **An override waives A REFUSAL, and the refusal need not be this
1275
+ // adjudication's** (#1536). `verdict.outcome === "REFUSE" && labelled`
1276
+ // is blind to the re-drafted body that stopped colliding — see
1277
+ // `FilingLedgerRow.refiledAfter` for the two live rows 37 seconds apart
1278
+ // that measured it. Nothing here is stricter: `prior` cannot cause a
1279
+ // refusal, only name one that already happened.
1280
+ const overridden = labelled && (verdict.outcome === "REFUSE" || prior !== null);
1281
+ // **This clause's own reading, and nothing about the command.** The
1282
+ // command-level decision is not available yet — it needs every clause —
1283
+ // so `emitted` here is provisional and `markBlockedCommand` below applies
1284
+ // the second half. #1344 is what happens when it is not applied: a clause
1285
+ // that cleared on its own merits inside a command the hook went on to
1286
+ // refuse was recorded as having reached the tracker.
1287
+ const cleared = verdict.outcome !== "REFUSE" || overridden;
534
1288
 
535
1289
  rows.push({
536
1290
  at,
1291
+ key: batch === null ? null : `${batch}/${index}`,
537
1292
  id: UNFILED_ID,
538
1293
  title: attempt.title,
539
1294
  symptomHash: verdict.symptomHash,
540
1295
  category: verdict.category,
541
1296
  severity: null,
542
- disposition: emitted ? "ISSUE" : "DROP",
1297
+ // The adjudication's ROUTING decision, which is a different question
1298
+ // from whether anything was filed and stays answered on a blocked
1299
+ // command. `arbitrateBatch` does the same: a candidate withheld
1300
+ // `BATCH_UNMEASURED` keeps the disposition its verdict gave it.
1301
+ disposition: cleared ? "ISSUE" : "DROP",
543
1302
  refusal: verdict.refusal,
544
- emitted,
545
- withheldBy: emitted ? null : verdict.refusal,
1303
+ emitted: cleared,
1304
+ withheldBy: cleared ? null : verdict.refusal,
546
1305
  jury: null,
547
- duplicateOf: verdict.duplicateOf,
1306
+ // This adjudication's collisions when it had any; otherwise the ones
1307
+ // the refusal being waived named, so the row NAMES the refusal rather
1308
+ // than leaving a reader to infer it from a timestamp. #1536 asks for
1309
+ // exactly this and points at the field.
1310
+ duplicateOf: verdict.duplicateOf.length > 0 ? verdict.duplicateOf : (prior?.duplicateOf ?? []),
548
1311
  overridden,
1312
+ refiledAfter: prior?.at ?? null,
549
1313
  });
550
1314
 
551
1315
  if (verdict.outcome === "REFUSE" && !overridden) refusals.push(refusalMessage(verdict));
552
1316
  if (verdict.outcome === "UNMEASURED") notes.push(unmeasuredNote(verdict));
553
- if (overridden) notes.push(overrideNote(verdict));
1317
+ if (overridden) notes.push(overrideNote(verdict, prior));
1318
+ // A re-draft that cleared the gate on its own is not refused and not
1319
+ // blocked — the gate does not get stricter here (#1536). It is SAID, so
1320
+ // the honest filer who labels the override and the filer who reworded
1321
+ // until it passed stop producing the same ledger.
1322
+ else if (prior !== null && verdict.outcome !== "REFUSE") notes.push(refiledNote(attempt.title, prior));
1323
+ }
1324
+
1325
+ // ── A refusal blocks the COMMAND, and every clean clause is NAMED in the
1326
+ // refusal so none of them is lost ───────────────────────────────────
1327
+ //
1328
+ // This read `rows.length > 0 && rows.every(r => !r.emitted)` — block only
1329
+ // when NOTHING in the command was clean. The concern behind it was real: a
1330
+ // hook's one lever is the whole Bash command, so blocking a mixed command
1331
+ // takes novel findings down with a duplicate, and withholding a real
1332
+ // finding with no artefact anywhere is the direction nothing here may fail
1333
+ // in.
1334
+ //
1335
+ // What it did not price is the bypass. One duplicate batched with one novel
1336
+ // finding was ALLOWED and the refusal downgraded to a note, so the cheapest
1337
+ // way past the arbiter became putting a refused filing in the same `&&`
1338
+ // chain as a clean one. A gate with a one-clause bypass is worse than no
1339
+ // gate, because it reads as working.
1340
+ //
1341
+ // And `emitted` is `outcome !== "REFUSE" || overridden`, so it is true for
1342
+ // an **UNMEASURED** row too: one unreadable `--body-file` beside any number
1343
+ // of duplicates allowed the whole command. A broken adjudicator was a
1344
+ // bypass as well as a note, which is the one thing the UNMEASURED policy in
1345
+ // this file's header exists to prevent.
1346
+ //
1347
+ // Blocking is affordable because nothing is lost by it. The refusal
1348
+ // ENUMERATES the clauses that were clean, so the agent withdraws the
1349
+ // refused one and re-runs the rest in one step, and the ledger has carried
1350
+ // every row — clean and refused — since the rows above were written. A
1351
+ // finding deferred by one command is not a finding silenced; a finding
1352
+ // filed alongside a duplicate was never adjudicated at all.
1353
+ //
1354
+ // An OVERRIDDEN refusal is deliberately not in `refusals`, so it does not
1355
+ // block: an override is a decision somebody made and recorded.
1356
+ //
1357
+ // The rows above are written clause by clause, so they cannot yet know
1358
+ // this. `markBlockedCommand` is where the command-level decision reaches
1359
+ // them, and `clean` is read BEFORE it so the refusal still enumerates the
1360
+ // clauses an agent should re-run — see that function's header for why that
1361
+ // ordering is the whole of #1344's wrong fix.
1362
+ const blocking = refusals.length > 0;
1363
+ const clean = rows.filter(r => r.emitted);
1364
+ if (blocking && clean.length > 0) refusals.push(cleanClauseNote(clean, rows.length));
1365
+ const recorded = blocking ? markBlockedCommand(rows) : rows;
1366
+
1367
+ // Whatever the verdict, say what the comparison set lost on the way in.
1368
+ // A dedupe run over a corpus three issues short is a weaker reading than
1369
+ // one run over the whole tracker, and no reader can tell them apart from
1370
+ // the outcome — the drop is only visible here, once per target tracker.
1371
+ for (const pending of cached.values()) {
1372
+ const reading = await pending;
1373
+ if (reading.dropped.length > 0) notes.push(corpusDropNote(reading.dropped));
554
1374
  }
555
1375
 
556
1376
  return {
557
- refusal: refusals.length > 0 ? refusals.join("\n\n") : null,
1377
+ refusal: blocking ? refusals.join("\n\n") : null,
558
1378
  note: notes.length > 0 ? notes.join("\n\n") : null,
559
- rows,
1379
+ rows: recorded,
560
1380
  };
561
1381
  }
562
1382
 
1383
+ /**
1384
+ * Why a clause of a BLOCKED command did not reach the tracker when nothing
1385
+ * was wrong with the clause (#1344).
1386
+ *
1387
+ * One exported constant, so there is one thing to mutate and one declaring
1388
+ * position for the string the ledger carries.
1389
+ */
1390
+ export const COMMAND_BLOCKED = "COMMAND_BLOCKED" satisfies WithheldBy;
1391
+
1392
+ /**
1393
+ * The command-level decision, applied to rows written clause by clause.
1394
+ *
1395
+ * ## What it fixes
1396
+ *
1397
+ * `filingGate` adjudicates one clause at a time and writes a row for each,
1398
+ * and the decision that matters — block the command, or let it run — is not
1399
+ * knowable until every clause has been read. So for the whole of #1338's
1400
+ * life, a command the hook went on to REFUSE left rows reading
1401
+ * `emitted: true` for every clause that had been clean on its own merits.
1402
+ * Nothing was filed: a hook's one lever is the entire Bash command. The
1403
+ * ledger overcounted filings by one row per clean clause of every blocked
1404
+ * mixed command, and an overcount there is not decoration — this ledger is
1405
+ * the record the arbiter's confidence is read off, and the direction it was
1406
+ * wrong in was toward suppressing real findings as duplicates.
1407
+ *
1408
+ * ## Three states, and the one that is new
1409
+ *
1410
+ * | state | `emitted` | `disposition` | `withheldBy` |
1411
+ * |---|---|---|---|
1412
+ * | reached the tracker | `true` | `ISSUE` | `null` |
1413
+ * | refused on its own merits | `false` | `DROP` | its own `ArbiterRefusal` |
1414
+ * | clean, and never attempted | `false` | `ISSUE` | `COMMAND_BLOCKED` |
1415
+ *
1416
+ * The third is the one this adds, and it must not be either of the others.
1417
+ * Marking it `DROP` with the sibling's refusal would say this clause was
1418
+ * wrong, which is the only thing the ledger knows it was not; leaving it
1419
+ * `emitted` says it was filed, which is #1344. `disposition` is deliberately
1420
+ * untouched — it is the adjudication's ROUTING decision, and
1421
+ * `arbitrateBatch` keeps it the same way for a candidate it withholds as
1422
+ * `BATCH_UNMEASURED`.
1423
+ *
1424
+ * The invariant `withheldBy === null` exactly when `emitted` — the one
1425
+ * `test/finding-arbiter.test.ts` holds over `CandidateRecord` — is preserved,
1426
+ * because the two row shapes exist to be read as one population.
1427
+ *
1428
+ * ## Call it AFTER `cleanClauseNote`, never before
1429
+ *
1430
+ * The cheapest wrong fix for #1344 is to flip `emitted` where the rows are
1431
+ * written. The count then comes out right and the refusal goes quiet: the
1432
+ * note that names the clean clauses is built from `rows.filter(r =>
1433
+ * r.emitted)`, so it would find none and tell the agent "0 of 2" with
1434
+ * nothing to re-run. That note is the half that makes blocking a mixed
1435
+ * command affordable at all (#1338), so the ordering is load-bearing and
1436
+ * `FG-94` is the case that holds it.
1437
+ *
1438
+ * ## What this does NOT claim
1439
+ *
1440
+ * `emitted: true` means the hook ALLOWED the command. It is a prediction,
1441
+ * not a receipt: this gate runs `PreToolUse`, and a `gh` that then fails on
1442
+ * auth, the network or a rate limit files nothing. That outcome is
1443
+ * **UNMEASURED by this ledger** and no value here stands in for it — a
1444
+ * fourth state inferred from something the gate cannot see would be exactly
1445
+ * the plausible-looking reading `.claude/rules/config-access.md` forbids.
1446
+ */
1447
+ export function markBlockedCommand(rows: readonly FilingLedgerRow[]): FilingLedgerRow[] {
1448
+ return rows.map(row =>
1449
+ row.emitted ? { ...row, emitted: false, withheldBy: COMMAND_BLOCKED } : { ...row },
1450
+ );
1451
+ }
1452
+
563
1453
  /**
564
1454
  * The refusal an agent reads.
565
1455
  *
@@ -586,6 +1476,43 @@ export function refusalMessage(v: FilingAdjudication): string {
586
1476
  ].join("\n");
587
1477
  }
588
1478
 
1479
+ /**
1480
+ * The clauses that were clean, named inside the refusal that blocks them.
1481
+ *
1482
+ * This is the half that makes blocking a mixed command affordable. A hook can
1483
+ * only block the whole Bash command, so a refusal that said nothing about the
1484
+ * clean clauses would cost the agent the work of reconstructing them — which
1485
+ * is the argument the `every`-based predicate was built on. Naming them turns
1486
+ * "the command was blocked" into "withdraw one, re-run these", and the titles
1487
+ * are quoted verbatim so the re-run is a copy rather than a recollection.
1488
+ */
1489
+ export function cleanClauseNote(clean: readonly FilingLedgerRow[], total: number): string {
1490
+ return [
1491
+ `[FindingArbiter] ${clean.length} of ${total} filings in this command WERE clean and are`,
1492
+ "not the reason it was blocked. A hook's one lever is the whole Bash command, so they are",
1493
+ `named here rather than lost, and all ${total} rows are recorded in ${ledgerPath()}.`,
1494
+ "Withdraw the refused one(s) and re-run these:",
1495
+ "",
1496
+ ...clean.map(r => ` - ${r.title}`),
1497
+ ].join("\n");
1498
+ }
1499
+
1500
+ /**
1501
+ * What the comparison set lost on the way in, said out loud.
1502
+ *
1503
+ * A dedupe run over a corpus three issues short is a weaker reading than one
1504
+ * run over the whole tracker, and the two produce the same ALLOW. The drops
1505
+ * are the only thing that can tell them apart, and they are invisible by the
1506
+ * time a verdict exists.
1507
+ */
1508
+ export function corpusDropNote(dropped: readonly CorpusDrop[]): string {
1509
+ return (
1510
+ `[FindingArbiter] ${dropped.length} open issue(s) were filtered out of the comparison set ` +
1511
+ `before this filing was adjudicated, so the dedupe read a smaller tracker than the one ` +
1512
+ `that exists: ${describeDrops(dropped)}.`
1513
+ );
1514
+ }
1515
+
589
1516
  /** Said out loud, because an UNMEASURED that nobody sees is a silent pass. */
590
1517
  export function unmeasuredNote(v: FilingAdjudication): string {
591
1518
  return (
@@ -596,10 +1523,80 @@ export function unmeasuredNote(v: FilingAdjudication): string {
596
1523
  );
597
1524
  }
598
1525
 
599
- /** An override is a decision somebody made, so it leaves a trace. */
600
- export function overrideNote(v: FilingAdjudication): string {
1526
+ /**
1527
+ * Said out loud for the same reason `unmeasuredNote` is: a row that cannot be
1528
+ * joined to anything is not a row that recorded something.
1529
+ *
1530
+ * The filing still proceeds — the ledger measures this gate and a measurement
1531
+ * apparatus must not block the thing it measures, which is the policy
1532
+ * `recordAdjudication` states for a ledger that cannot be written at all.
1533
+ * What must not happen is the quiet version: a key that looks fine.
1534
+ */
1535
+ export function unkeyedLedgerNote(): string {
1536
+ return (
1537
+ `[FindingArbiter] UNMEASURED row identity — \`${LEDGER_SESSION_ENV}\` is not set, so the ` +
1538
+ `rows this command appends to ${ledgerPath()} carry \`key: null\` and cannot be told apart ` +
1539
+ "from any other unkeyed row on that shared ledger. The filing is allowed and recorded; " +
1540
+ "what is lost is the join to its outcome, and it is lost permanently, because the " +
1541
+ "identity exists only at the moment of writing. No key was invented to cover the gap: " +
1542
+ "a plausible one reads as a measurement that was taken."
1543
+ );
1544
+ }
1545
+
1546
+ /**
1547
+ * An override is a decision somebody made, so it leaves a trace.
1548
+ *
1549
+ * `prior` is the ledger row this filing is waiving when the body was
1550
+ * re-drafted and the collision no longer reproduces. Naming its timestamp
1551
+ * rather than describing it is the point: a reader can find the refusal.
1552
+ */
1553
+ export function overrideNote(v: FilingAdjudication, prior: FilingLedgerRow | null = null): string {
1554
+ if (v.refusal !== null) {
1555
+ return (
1556
+ `[FindingArbiter] Allowed by --label ${FILING_OVERRIDE_LABEL}, over a ${v.refusal} ` +
1557
+ `refusal: ${v.reason}. Recorded in ${ledgerPath()}.`
1558
+ );
1559
+ }
1560
+ return (
1561
+ `[FindingArbiter] Allowed by --label ${FILING_OVERRIDE_LABEL}, over the ${prior?.refusal} ` +
1562
+ `refusal of this same title at ${prior?.at}. This adjudication did not reproduce it — the ` +
1563
+ "body has changed since, and the body is an input to the symptom keys — so the override is " +
1564
+ `recorded against that row rather than this one. Recorded in ${ledgerPath()}.`
1565
+ );
1566
+ }
1567
+
1568
+ /**
1569
+ * This title was refused before and is being filed again without the label.
1570
+ *
1571
+ * **Not a refusal.** #1536 says in as many words not to make the gate
1572
+ * stricter: the defect is that a re-draft was *invisible*, not that it got
1573
+ * through. So this is the visibility, and the filing proceeds.
1574
+ */
1575
+ export function refiledNote(title: string, prior: FilingLedgerRow): string {
1576
+ return (
1577
+ `[FindingArbiter] This title was refused at ${prior.at} (${prior.refusal}` +
1578
+ `${prior.duplicateOf.length > 0 ? `, against ${prior.duplicateOf.map(d => `#${d}`).join(", ")}` : ""}) ` +
1579
+ "and this adjudication does not reproduce it, because the body has changed and the body is " +
1580
+ `an input to the symptom keys. The filing is ALLOWED and nothing is blocked. If you meant to ` +
1581
+ `override that refusal, say so with --label ${FILING_OVERRIDE_LABEL} so it is counted; if the ` +
1582
+ `re-draft genuinely describes a different finding, this note is the only record that the two ` +
1583
+ `share a title. Title: ${title}`
1584
+ );
1585
+ }
1586
+
1587
+ /**
1588
+ * The prior-refusal lookup could not be performed, which is not the same as
1589
+ * finding nothing.
1590
+ *
1591
+ * Same split as `unmeasuredNote` and for the same reason: an override
1592
+ * attributed to no refusal and an override whose refusal could not be looked
1593
+ * up are different states, and only one of them is a reading.
1594
+ */
1595
+ export function unreadableLedgerNote(): string {
601
1596
  return (
602
- `[FindingArbiter] Allowed by --label ${FILING_OVERRIDE_LABEL}, over a ${v.refusal} ` +
603
- `refusal: ${v.reason}. Recorded in ${ledgerPath()}.`
1597
+ `[FindingArbiter] UNMEASURED prior refusals — ${ledgerPath()} exists and could not be read, ` +
1598
+ "so this command's rows carry `refiledAfter: null` meaning *not looked up* rather than *none " +
1599
+ "found*. The filing is allowed and recorded; an override in it may be counted against no " +
1600
+ "refusal."
604
1601
  );
605
1602
  }