rungate 0.8.5 → 0.8.7

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.
@@ -97,16 +97,19 @@
97
97
 
98
98
  import { appendFileSync, existsSync, mkdirSync, readFileSync, statSync } from "fs";
99
99
  import { homedir } from "os";
100
- import { dirname, join } from "path";
100
+ import { dirname, join, resolve } from "path";
101
101
 
102
102
  import { githubSlugFromRemoteUrl, resolveRepoSlug } from "./branch-cleanup";
103
103
  import {
104
104
  createGitHubClient,
105
105
  listOpenIssues,
106
+ listPRs,
106
107
  parseOwnerRepo,
107
108
  TRUSTED_ASSOCIATIONS,
108
109
  type OpenIssuePage,
109
110
  } from "./github";
111
+ import { branchOf, toplevel } from "./launch-base";
112
+ import { readWorktreeRemote, repoSlug, type RemoteReading } from "./worktree-repo";
110
113
  import {
111
114
  duplicateCollisions,
112
115
  symptomHash,
@@ -137,6 +140,70 @@ import { clauses, createsIssue, flagValues, labelValues } from "./issue-create-o
137
140
  */
138
141
  export const FILING_OVERRIDE_LABEL = "arbiter-override";
139
142
 
143
+ /**
144
+ * The refusals no label waives, each with the sentence saying why.
145
+ *
146
+ * **One object, because the membership and the explanation are one fact.**
147
+ * They were two: a predicate listing the refusals and a message composing
148
+ * the sentence, which is the two-deciders shape
149
+ * `.claude/rules/checks-must-be-able-to-fail.md` names — and the drift was
150
+ * already live, because the shared sentence said *"an accounting of what
151
+ * this run has already filed"* over every member, which is true of the cap
152
+ * and false of a missing declaration. A reader told the wrong reason stops
153
+ * believing the refusal.
154
+ *
155
+ * The common property is not severity and not policy preference: **the label
156
+ * answers a claim ABOUT a finding, and none of these makes one.** A count
157
+ * does not, a missing count does not, and an absent declaration does not —
158
+ * it reports a fact about the COMMAND, which the agent fixes by writing one
159
+ * line rather than by arguing.
160
+ *
161
+ * `COMMENT_INSTEAD` joined on 2026-10-25, and it is the one that was costing
162
+ * something. It is the comment DEFAULT, and the default was waivable by a
163
+ * label the refusal itself told the agent to use — *"If this one genuinely
164
+ * is the exception, re-run with --label arbiter-override"* — four lines
165
+ * under the text explaining that the list of exceptions is closed. So the
166
+ * closed list had a fourth member, spelled in the refusal that enforced it,
167
+ * and `arbiter-override` was already on 7 of the 140 issues filed in the two
168
+ * days before the gate shipped: the token was in circulation before there
169
+ * was anything to override.
170
+ *
171
+ * Nothing legitimate is lost. The three declarations remain, cost one line,
172
+ * and a filing carrying one still goes through — `FG-176` is that control.
173
+ * What is removed is the route that beats the gate by making the filing
174
+ * WORSE: delete the declaration, add the label.
175
+ */
176
+ export const UNWAIVABLE_REFUSALS: Partial<Record<ArbiterRefusal, string>> = {
177
+ OVER_CAP:
178
+ "It answers a claim about a finding, and this refusal makes none — it is an " +
179
+ "accounting of what this run has already filed.",
180
+ UNMEASURED_CAP:
181
+ "It answers a claim about a finding, and this refusal makes none — the run's " +
182
+ "allowance could not be counted, which no argument about the finding changes.",
183
+ COMMENT_INSTEAD:
184
+ "It answers a claim about a finding, and this refusal makes none — it reports " +
185
+ "that no declaration was given. Write one of the three, or post the comment.",
186
+ };
187
+
188
+ /**
189
+ * Does `FILING_OVERRIDE_LABEL` waive this refusal?
190
+ *
191
+ * **ONE binding, and it exists because there were briefly two.** `filingGate`
192
+ * decided it when it chose whether the label overrides, and `refusalMessage`
193
+ * decided it again when it chose whether to offer the label — two deciders
194
+ * over one question, behaviourally one decider with a spare. They disagreed
195
+ * the moment the cap landed: the gate made `OVER_CAP` unwaivable and the
196
+ * message went on closing with *"re-run with --label arbiter-override"*, so
197
+ * the one refusal no label could open was also the one advertising the
198
+ * bypass. Found by the AI review of PR #1597.
199
+ *
200
+ * Derived from `UNWAIVABLE_REFUSALS` rather than restating its membership,
201
+ * so a refusal added there cannot be waivable here.
202
+ */
203
+ export function waivableRefusal(refusal: ArbiterRefusal | null): boolean {
204
+ return refusal === null || !(refusal in UNWAIVABLE_REFUSALS);
205
+ }
206
+
140
207
  /**
141
208
  * How many claims `SUCCESS.md` states under "Done, for the harness".
142
209
  *
@@ -176,6 +243,738 @@ export function namedClaim(text: string): number | null {
176
243
  return null;
177
244
  }
178
245
 
246
+ /**
247
+ * How many issues one run may file. **The gate (#1595, scope item 4).**
248
+ *
249
+ * ## Why a count, and not the declaration below it
250
+ *
251
+ * The declared-reason check in this file is a per-finding judgement, and the
252
+ * research #1595 was built on predicted exactly how that ends: *"a bar an
253
+ * agent applies by asking 'does this block a goal criterion?' re-decides 100
254
+ * times a day and will drift."* Measured on 2026-10-24, against the three
255
+ * issues filed that day by the author of the bar: **all three cleared it**,
256
+ * each on an individually sound argument, through the clause *it makes a
257
+ * green check lie* — which in a repository whose subject is checks that lie
258
+ * admits any true finding. Three for three is not a result a bar produces.
259
+ *
260
+ * A count has no clause to argue into. It is the only item on #1595's list
261
+ * that needs no reasoning to apply, and that is the whole of why it is the
262
+ * gate while the declaration is the record.
263
+ *
264
+ * ## The number, from two independent readings that converge
265
+ *
266
+ * - **Cloudflare, 131,246 reviews (Mar–Apr 2026): 1.2 findings per review,
267
+ * deliberately low.** The only published per-unit number anywhere, and
268
+ * `runIdFor` makes our unit the same unit — one checkout is one piece of
269
+ * work. Floored to the integer below it, because what Cloudflare counts
270
+ * is an inline COMMENT and what this counts is a tracker issue, which
271
+ * costs an agent a whole context to close.
272
+ * - **This machine, 2026-10-24: 64 issues created in 24 hours across 284
273
+ * registered worktrees — 0.23 filings per run per day.** A cap of 1 sits
274
+ * 4.4x above the mean, so it cannot bind on the ordinary run; it binds
275
+ * only where a run files a SECOND, which is where the 1→N pathology that
276
+ * #1595 measured actually lives.
277
+ *
278
+ * Tricorder's fourth criterion — a warning should occur *"with a small but
279
+ * noticeable frequency"* — is the same direction from a third source and is
280
+ * not a number, so it is not used as one.
281
+ *
282
+ * **Not configurable, on purpose.** A cap read from config is a cap an agent
283
+ * raises, and #1595 says in as many words that a cap nobody can defend is a
284
+ * cap someone raises. Changing it is an edit here, against the two readings
285
+ * above, which a reviewer can disagree with.
286
+ */
287
+ export const FILINGS_PER_RUN = 1;
288
+
289
+ /**
290
+ * How far back the cap counts.
291
+ *
292
+ * 24 hours, and the window is read off the instrument that measured the
293
+ * pathology rather than chosen: every number in #1595 is a per-day one —
294
+ * *"70–85% of everything closed each day"*, *"57 filed / 53 closed"* — and
295
+ * `~/.rungate/swarm-throughput.sh` names its column `churn24`. A run that
296
+ * has spent its allowance gets it back a day later, which is also what stops
297
+ * a long-lived checkout being permanently barred.
298
+ */
299
+ export const RUN_WINDOW_MS = 24 * 60 * 60 * 1000;
300
+
301
+ /**
302
+ * The one run every non-checkout directory shares.
303
+ *
304
+ * A sentinel rather than a path, so it cannot collide with a real toplevel
305
+ * and so a reader of the ledger can see at a glance which rows were filed
306
+ * from nowhere in particular. See `runIdFor` for why they share.
307
+ */
308
+ export const NON_CHECKOUT_RUN = "NON_CHECKOUT";
309
+
310
+ /**
311
+ * Which run a directory belongs to, or why that could not be read.
312
+ *
313
+ * **Three readings, because collapsing the third into the second is a
314
+ * fact-collapse in the cap's denominator.** `run` is a checkout's toplevel,
315
+ * or `NON_CHECKOUT_RUN` for the shared bucket — both of them ANSWERS. `null`
316
+ * is not an answer: the remote could not be read at all, and a gate that
317
+ * spelled that the same as "no origin" would move a real checkout into the
318
+ * shared allowance whenever git timed out.
319
+ */
320
+ export interface RunReading {
321
+ /** The run, or `null` when the reading failed. */
322
+ run: string | null;
323
+ /** Why it failed. Present only when `run` is null. */
324
+ why?: string;
325
+ }
326
+
327
+ /**
328
+ * Which RUN a filing belongs to — the checkout it was filed from.
329
+ *
330
+ * **Not the session, and the measurement is why.** `filingBatch` mints
331
+ * `${session}.${pid}`, and on the live ledger that resolves to **two**
332
+ * session values across 186 emitted rows while the pid changes on every
333
+ * hook invocation: one Claude Code session hosts every subagent, and each
334
+ * Bash call is its own process. So the key identifies a COMMAND and a
335
+ * SESSION and nothing in between, and a cap keyed on either is a cap
336
+ * shared by two hundred agents or a cap that resets every command.
337
+ *
338
+ * The checkout is the unit that is neither. It is one agent's piece of work
339
+ * from start to finish, it is the same unit Cloudflare's 1.2-per-review is
340
+ * measured over, and it is already in this gate's hand as `projectRoot`.
341
+ *
342
+ * Through `toplevel` from `lib/launch-base.ts`, so `/wt/x` and `/wt/x/lib`
343
+ * are one run and there is one binding for "which checkout is this".
344
+ *
345
+ * **A checkout counts as its own run only if it has an origin remote.**
346
+ * `toplevel` alone was not enough and the second review round said so: a
347
+ * bare `git -C <dir> rev-parse --show-toplevel` answers for a directory
348
+ * somebody `git init`ed a second ago, so `git init /tmp/x && cd /tmp/x`
349
+ * minted a fresh allowance for one command. Measured: two sibling `git
350
+ * init`s return two distinct toplevels and **no origin**. The remote is
351
+ * read through `readWorktreeRemote`/`repoSlug`, the same pair
352
+ * `lib/launch-base.ts` reads, so there is one opinion about what a
353
+ * repository is.
354
+ *
355
+ * ## The bound. This is a DEFAULT, not a boundary — four routes stand open
356
+ *
357
+ * Stated so a reader knows the shape of what is not covered, rather than
358
+ * rediscovering it one route at a time. Three fixes narrowed this predicate
359
+ * — `resolve()` → `toplevel()` → `toplevel()` + a real origin — and each
360
+ * left a cheaper route, because **the thing being defended against is not
361
+ * reachable from here at all.** A filer owns its own directory; no identity
362
+ * derived from that directory can resist one.
363
+ *
364
+ * | route | cost | still open |
365
+ * |---|---|---|
366
+ * | `git worktree add /tmp/y` | 1 command, carries the parent's origin | **yes** |
367
+ * | `git init` + `git remote add origin <real url>` | 2 commands | **yes** |
368
+ * | `git remote remove origin` | 1 command, re-keys an EXISTING checkout out of its own run and into the bucket | **yes** |
369
+ * | a sub-group checkout (`host:group/sub/name`) | not a bypass — `normaliseSlug` wants exactly two segments, so a legitimate unit is bucketed with the nowheres | **false negative** |
370
+ *
371
+ * `git worktree add` is the one that should NOT be read as a hole: one
372
+ * agent, one worktree, one piece of work is exactly the unit the cap is
373
+ * meant to meter, so a new worktree getting a new allowance is the unit
374
+ * working. What separates it from `git init /tmp/x` is not cost — it is
375
+ * that one is a unit of work and the other is a directory made to obtain a
376
+ * number. The residual exposure is an agent that creates a real worktree in
377
+ * order to launder a filing, and nothing in this function can see that.
378
+ *
379
+ * **The defence is a SECOND key with its own ceiling, keyed on the TARGET
380
+ * repository** — the one value in this gate's hand that the filer does not
381
+ * pick — refusing when either key is over. Not usable as the unit on its
382
+ * own: 284 registered worktrees against a measured 64 issues a day makes
383
+ * one allowance per repository a 98% refusal rate, which is a gag and not a
384
+ * cap, and with no `--repo` the target derives from origin, so as an
385
+ * admission test it is circular. Its number has to come from measurement
386
+ * and is deliberately not invented here.
387
+ *
388
+ * **Every directory that is not a checkout is ONE run, `NON_CHECKOUT_RUN`.**
389
+ * This read `resolve(projectRoot)` first, so each non-checkout directory was
390
+ * its own run — and that made the allowance keyable by the filer: `mkdir
391
+ * /tmp/x && cd /tmp/x && gh issue create` mints a fresh one, every time, at
392
+ * no cost. The first docblock said so out loud and argued the exposure was
393
+ * acceptable because nothing else here tracks a `cd` either. It is not
394
+ * acceptable for THIS field, because this one is the cap's denominator: a
395
+ * gate whose unit the filer chooses is not a gate. Reversed on 2026-10-24
396
+ * after the security review of PR #1597 named it, and the earlier reasoning
397
+ * is kept here rather than deleted because it is the argument a later agent
398
+ * will reach for again.
399
+ *
400
+ * The cost is real and is the one the first spelling was avoiding: every
401
+ * filing from outside a checkout on this machine now shares one allowance.
402
+ * That is the fail-closed direction, and it is narrow — an agent works in a
403
+ * worktree, which is a checkout, and `toplevel` resolves `/wt/x/lib` to
404
+ * `/wt/x` so sub-directories were never separate runs in the first place.
405
+ *
406
+ * Legacy rows are unaffected: they carry `run: null`, which matches no run
407
+ * and is counted towards nothing, so this does not fold them into the
408
+ * bucket. `null` and `NON_CHECKOUT_RUN` are different readings and stay so.
409
+ *
410
+ * What this still does NOT defend against is a filing that never reaches
411
+ * this chokepoint — `curl`, the MCP tools, another machine. This file's own
412
+ * header lists those, and the cap governs the default.
413
+ *
414
+ * **One bound on the INPUT, which this function cannot fix.** `projectRoot`
415
+ * reaches here from `process.cwd()` in `hooks/VerifyPhaseLock.hook.ts`,
416
+ * which is the SESSION's directory and not necessarily the agent's
417
+ * worktree — a hook has no way to learn the latter when they differ. So
418
+ * several agents hosted by one session, working in different worktrees, can
419
+ * share one allowance. Recorded as a stated limit rather than left implicit
420
+ * (#1595, after the security review of PR #1597).
421
+ *
422
+ * `read` is injectable **only so the failed-read state can be driven**: with
423
+ * a real git on PATH that state is a timeout or a git that vanished between
424
+ * two commands, and neither is producible in a test. It defaults to the real
425
+ * reader, and `worktreeDiskIdentity` takes the same parameter for the same
426
+ * reason — a gate whose default reader is a stub is the check that never
427
+ * looked, so the default is asserted rather than assumed.
428
+ */
429
+ export function runIdFor(
430
+ projectRoot: string,
431
+ read: (worktreePath: string) => RemoteReading = readWorktreeRemote,
432
+ ): RunReading {
433
+ const top = toplevel(projectRoot);
434
+ if (top === null) return { run: NON_CHECKOUT_RUN };
435
+ const remote = read(top);
436
+ // **The read failing is not the same fact as there being no origin.**
437
+ // `readWorktreeRemote` sets `error` for a timeout, a missing git and a
438
+ // healthy checkout with no remote alike; `missing` is the half that was
439
+ // observed. Without this split a ten-second git timeout re-buckets a real
440
+ // checkout into the shared allowance — one value carrying two facts, in
441
+ // the field that decides the cap's denominator, which is the shape this
442
+ // file already refuses for the ledger.
443
+ if (remote.error !== null && !remote.missing) {
444
+ return { run: null, why: remote.error };
445
+ }
446
+ // A checkout nobody can name is not a run. `git init` makes a toplevel in
447
+ // one command; it does not make an origin.
448
+ return { run: namesARepository(remote.url) ? top : NON_CHECKOUT_RUN };
449
+ }
450
+
451
+ /**
452
+ * Is this remote a URL or scp form naming a repository?
453
+ *
454
+ * **Narrower than `repoSlug` on purpose, and the extra condition is the
455
+ * point.** `repoSlug` accepts a bare `owner/name` as its last branch,
456
+ * because that is how a run's own `repo` ARGUMENT arrives — a different
457
+ * caller answering a different question. Reused here it makes
458
+ * `git remote add origin a/b` mint an allowance: two words, no URL, no
459
+ * repository, a fresh run. Found by the security review of `377e3a06`.
460
+ *
461
+ * So the transport form is required first and `repoSlug` still decides what
462
+ * a slug is. That is one reader per question rather than two informally
463
+ * aligned ones: this says *"is this a remote"*, `repoSlug` says *"which
464
+ * repository"*, and neither restates the other.
465
+ */
466
+ export function namesARepository(url: string | null): boolean {
467
+ if (url === null) return false;
468
+ const s = url.trim();
469
+ // `scheme://…` or scp-style `user@host:path`. A bare slug matches neither,
470
+ // and a filesystem path has no authority, so neither does it.
471
+ const transported = /^[a-z][a-z0-9+.-]*:\/\/\S+$/i.test(s) || /^[^/\s]*@[^/:\s]+:\S+$/.test(s);
472
+ return transported && repoSlug(s) !== null;
473
+ }
474
+
475
+ /**
476
+ * The suffix that tells an intent row apart from the outcome row it reserves.
477
+ *
478
+ * The two rows are one decision and the join between them matters, so the
479
+ * intent takes the outcome's key plus this rather than a key of its own.
480
+ * `summariseFindingOutcomes` refuses a corpus of repeated ids, so they cannot
481
+ * simply share one.
482
+ */
483
+ export const INTENT_KEY_SUFFIX = "#intent";
484
+
485
+ /** The suffix on the row that gives an intent back. See `releaseAllowance`. */
486
+ export const RELEASE_KEY_SUFFIX = "#released";
487
+
488
+ /**
489
+ * Every intent this run has registered inside the window, in ledger order.
490
+ *
491
+ * **One walk, two questions.** "How many has this run reserved" and "where in
492
+ * the queue is mine" are the same population read two ways, and two walks
493
+ * would be the fourth shape in `.claude/rules/checks-must-be-able-to-fail.md`
494
+ * — a mutation of either leaves the other holding the case up.
495
+ *
496
+ * **Intents and not `emitted` rows, since the race fix.** An intent is
497
+ * appended before the gate decides and an `emitted` row after, so a counter
498
+ * reading `emitted` cannot see a filing that is in flight — which is exactly
499
+ * the window two parallel hook processes both read in. See
500
+ * `FilingLedgerRow.intent`.
501
+ *
502
+ * A refused filing still consumes nothing: an intent is only ever appended
503
+ * for a clause the command-level decision has already cleared, so a clause
504
+ * refused on its merits, and every clause of a blocked command, registers
505
+ * none.
506
+ *
507
+ * A row whose `at` cannot be parsed is **counted**, not skipped. It is a row
508
+ * this writer appended; the alternative is a filing that escapes the count
509
+ * by carrying a timestamp nobody can read.
510
+ */
511
+ export function runIntents(
512
+ rows: readonly FilingLedgerRow[],
513
+ run: string,
514
+ now: number,
515
+ window: number = RUN_WINDOW_MS,
516
+ ): (string | null)[] {
517
+ // **One pass, in file order, and a release only cancels an intent that
518
+ // PRECEDES it.** Collecting released keys up front and filtering on the
519
+ // set is the shorter spelling and it is wrong: `filingBatch` mints the
520
+ // key from the session, the pid and the timestamp, so a retry inside the
521
+ // same millisecond reuses it — and a release written for the first
522
+ // attempt would free the second attempt's live reservation. Measured
523
+ // while building `FG-170`, where three calls shared a pinned `now`: the
524
+ // third filing was allowed against a spent allowance. Order is what tells
525
+ // a cancelled reservation from a later one wearing the same name, and
526
+ // this file is append-only, so order is the thing it always has.
527
+ const live: (string | null)[] = [];
528
+ for (const row of rows) {
529
+ const gave = row.releases ?? null;
530
+ if (gave !== null) {
531
+ const at = live.lastIndexOf(gave);
532
+ if (at !== -1) live.splice(at, 1);
533
+ continue;
534
+ }
535
+ if (row.intent !== true) continue;
536
+ if ((row.run ?? null) !== run) continue;
537
+ const at = Date.parse(row.at);
538
+ if (Number.isFinite(at) && now - at > window) continue;
539
+ live.push(row.key);
540
+ }
541
+ return live;
542
+ }
543
+
544
+ /**
545
+ * How many filings this run has already registered inside the window.
546
+ *
547
+ * Exported so a test reads the same answer the gate acts on.
548
+ */
549
+ export function intentsInRun(
550
+ rows: readonly FilingLedgerRow[],
551
+ run: string,
552
+ now: number,
553
+ window: number = RUN_WINDOW_MS,
554
+ ): number {
555
+ return runIntents(rows, run, now, window).length;
556
+ }
557
+
558
+ /**
559
+ * Where one intent sits in its run's queue, 1-based. **The race verdict.**
560
+ *
561
+ * `key` is the intent row's own key — the outcome row's, plus
562
+ * `INTENT_KEY_SUFFIX`.
563
+ *
564
+ * **Two different things produce "not found" and they take different
565
+ * positions.** Collapsing them to one answer is wrong in one direction or
566
+ * the other, and the first spelling of this function collapsed them:
567
+ *
568
+ * - **`key === null`** — `filingBatch` returned `null` because
569
+ * `CLAUDE_CODE_SESSION_ID` is absent, so the row has no identity. Our
570
+ * intent **is** in this queue; we appended it and cannot point at it. The
571
+ * safe position is `queue.length`: last among what is visible, and `1`
572
+ * when ours is the only one. Reading `queue.length + 1` here would count
573
+ * us twice and refuse **every** filing from an unkeyed session, which is a
574
+ * gag and contradicts `unkeyedLedgerNote`'s stated policy that such a
575
+ * filing proceeds.
576
+ * - **a key that is genuinely absent** — the re-read did not contain our own
577
+ * append. Our intent is **not** in this queue, so every row in it precedes
578
+ * us and the only safe position is `queue.length + 1`. Reading
579
+ * `queue.length` here hands us the last EXISTING slot rather than the next
580
+ * one, so with one other intent queued and a cap of 1 we would compute
581
+ * ordinal 1 and win while genuinely second. Found by the security review
582
+ * of `822d5d7d`.
583
+ *
584
+ * An empty queue with a null key is `0` — nothing has reserved anything,
585
+ * which is the same answer an absent ledger gives, and it cannot arise from
586
+ * our own append because that append put a row in the queue.
587
+ *
588
+ * **`lastIndexOf`, so two rows sharing a key take the LATER position.**
589
+ * `filingBatch` makes the key unique across live writers by carrying the pid,
590
+ * so a collision should not happen — but if one ever does, `indexOf` hands
591
+ * the loser the winner's position and the loser files. Reading from the back
592
+ * costs nothing and fails in the direction a cap must fail in.
593
+ */
594
+ export function intentOrdinal(
595
+ rows: readonly FilingLedgerRow[],
596
+ key: string | null,
597
+ run: string,
598
+ now: number,
599
+ window: number = RUN_WINDOW_MS,
600
+ ): number {
601
+ const queue = runIntents(rows, run, now, window);
602
+ if (key === null) return queue.length;
603
+ const at = queue.lastIndexOf(key);
604
+ return at === -1 ? queue.length + 1 : at + 1;
605
+ }
606
+
607
+ /**
608
+ * An intent row's `withheldBy`, between the append and the re-read.
609
+ *
610
+ * One exported constant for the same reason `COMMAND_BLOCKED` is one: a
611
+ * single declaring position for the string the ledger carries.
612
+ */
613
+ export const INTENT_PENDING = "INTENT_PENDING" satisfies WithheldBy;
614
+
615
+ /**
616
+ * What the queue said about one intent.
617
+ *
618
+ * Every outcome that APPENDED carries the row it appended, because the caller
619
+ * has to be able to release it. `UNRESERVED` is the one that did not.
620
+ */
621
+ export type AllowanceReading =
622
+ | { outcome: "WON"; intent: FilingLedgerRow }
623
+ /** `already` is how many intents preceded this one. */
624
+ | { outcome: "LOST"; already: number; intent: FilingLedgerRow }
625
+ /** The intent could not be appended, so no position was taken. */
626
+ | { outcome: "UNRESERVED" }
627
+ /** The intent was appended and the queue could not be read back. */
628
+ | { outcome: "UNCOUNTABLE"; intent: FilingLedgerRow };
629
+
630
+ /**
631
+ * Take a position in this run's queue, then read it back. **The race fix.**
632
+ *
633
+ * ## The race
634
+ *
635
+ * `read the ledger → decide → write the row` has the decision in the middle,
636
+ * and the hook does the writing after `filingGate` returns. Two hook
637
+ * processes — one session, parallel subagents, a `gh issue create` each —
638
+ * that both read before either wrote both counted zero filings and both
639
+ * filed, and the ledger afterwards is indistinguishable from two filings a
640
+ * day apart. The window is the whole of `filingGate`, which makes a network
641
+ * call to the tracker, so it is hundreds of milliseconds wide and not a
642
+ * theoretical one.
643
+ *
644
+ * ## Append-then-verify, and why there is no lock
645
+ *
646
+ * The intent is appended FIRST and the verdict is read off its position
647
+ * afterwards. Appends to one file are serialised by the filesystem, so the
648
+ * positions are a total order every process agrees on without coordinating:
649
+ * the first `FILINGS_PER_RUN` intents in a run's window win and every later
650
+ * one is `OVER_CAP`. Both racers see the same file; they just see themselves
651
+ * in different places in it.
652
+ *
653
+ * A lock would need a second artefact, an owner, and an answer for the
654
+ * process that dies holding it — and a hook that blocks on a stale lock file
655
+ * is a gate that stops every filing on the machine. The ordering the ledger
656
+ * already has is free.
657
+ *
658
+ * ## Both ledger failures REFUSE, and the first spelling got one of them wrong
659
+ *
660
+ * - **The re-read failed** (`UNCOUNTABLE`) — the file is present and
661
+ * unreadable. The ledger is the cap's STATE rather than its apparatus, so
662
+ * this refuses exactly as `UNMEASURED_CAP` does everywhere else here.
663
+ * - **The append failed** (`UNRESERVED`) — this ALLOWED, loudly, on
664
+ * `recordAdjudication`'s policy that a measurement apparatus must not block
665
+ * the thing it measures. That policy is right for the row that RECORDS a
666
+ * decision and wrong for the row that MAKES one: a failure to update the
667
+ * cap's state is indistinguishable from an attempt to disable it, so an
668
+ * unwritable ledger switched the cap off. The two branches were written in
669
+ * one commit and took opposite positions about the same file. Both refuse
670
+ * now, and `unreservedCapReason` names the write so an operator knows which
671
+ * half to repair.
672
+ *
673
+ * ## The caller must RELEASE what it reserved
674
+ *
675
+ * The intent is on the ledger from the moment `append` returns true, whatever
676
+ * the outcome. A command that goes on to file nothing has to give it back —
677
+ * `releaseAllowance` — or the ordinary two-clause command at a cap of one
678
+ * strands the run's allowance. The reading carries the row it appended so the
679
+ * caller has something to release.
680
+ */
681
+ export function reserveAllowance(
682
+ row: FilingLedgerRow,
683
+ run: string,
684
+ io: {
685
+ now: number;
686
+ append: (row: FilingLedgerRow) => boolean;
687
+ readLedger: () => FilingLedgerRow[] | null;
688
+ window?: number;
689
+ },
690
+ ): AllowanceReading {
691
+ const intent: FilingLedgerRow = {
692
+ ...row,
693
+ key: row.key === null ? null : `${row.key}${INTENT_KEY_SUFFIX}`,
694
+ intent: true,
695
+ // A reservation is not a receipt and makes no judgement: the outcome row
696
+ // carries both. See `FilingLedgerRow.intent` for why `emitted` here would
697
+ // double every filing this reserves.
698
+ emitted: false,
699
+ withheldBy: INTENT_PENDING,
700
+ refusal: null,
701
+ overridden: false,
702
+ };
703
+ if (!io.append(intent)) return { outcome: "UNRESERVED" };
704
+ const after = io.readLedger();
705
+ if (after === null) return { outcome: "UNCOUNTABLE", intent };
706
+ const ordinal = intentOrdinal(after, intent.key, run, io.now, io.window);
707
+ return ordinal > FILINGS_PER_RUN
708
+ ? { outcome: "LOST", already: ordinal - 1, intent }
709
+ : { outcome: "WON", intent };
710
+ }
711
+
712
+ /**
713
+ * Give back a reservation, by appending rather than by rewriting.
714
+ *
715
+ * Nothing in this file rewrites a row: the total order that appends give is
716
+ * the property the race fix rests on, and a file being rewritten underneath a
717
+ * concurrent reader has no order at all. So a release is a row naming the key
718
+ * it gives back, and `runIntents` subtracts it.
719
+ *
720
+ * Returns whether the release landed. A release that fails leaves the
721
+ * reservation standing, which costs the run an allowance it did not spend —
722
+ * loud, and the same direction as every other failure here.
723
+ */
724
+ export function releaseAllowance(
725
+ intent: FilingLedgerRow,
726
+ append: (row: FilingLedgerRow) => boolean,
727
+ ): boolean {
728
+ // A null-keyed intent cannot be named, so there is nothing to release and
729
+ // saying so is cheaper than appending a row that releases nothing.
730
+ if (intent.key === null) return false;
731
+ return append({
732
+ ...intent,
733
+ key: `${intent.key}${RELEASE_KEY_SUFFIX}`,
734
+ intent: false,
735
+ releases: intent.key,
736
+ emitted: false,
737
+ disposition: "DROP",
738
+ withheldBy: COMMAND_BLOCKED,
739
+ });
740
+ }
741
+
742
+ /** The refusal an agent reads when the run has spent its allowance. */
743
+ export function overCapReason(run: string, already: number, target: CommentTarget): string {
744
+ return [
745
+ `this run has already filed ${already} issue(s) in the last ${RUN_WINDOW_MS / 3_600_000}h, and the cap is ` +
746
+ `${FILINGS_PER_RUN}. The overflow is a comment.`,
747
+ "",
748
+ ` ${commentTargetSentence(target)}`,
749
+ "",
750
+ ` run: ${run}`,
751
+ "",
752
+ " There is no argument against this and no label that waives it. It is a count, not a",
753
+ " judgement about your finding, which may well be a good one — the cap exists because a",
754
+ " per-finding judgement drifts and a count does not. If several findings belong on the",
755
+ " tracker, they are one issue naming every instance, not several.",
756
+ ].join("\n");
757
+ }
758
+
759
+ /**
760
+ * The refusal when the allowance cannot be RESERVED (#1595).
761
+ *
762
+ * Separate text from `uncountableCapReason`, because an operator repairs a
763
+ * different half: that one is a file that cannot be read, this one a file
764
+ * that cannot be written. The refusal is the same because the consequence is
765
+ * the same — the cap's state did not change, so the cap did not hold.
766
+ */
767
+ export function unreservedCapReason(run: string, target: CommentTarget): string {
768
+ return [
769
+ `this run's allowance could not be RESERVED: the intent row could not be appended to ` +
770
+ `${ledgerPath()}. The cap is ${FILINGS_PER_RUN} per run and it is not measurable right now.`,
771
+ "",
772
+ ` ${commentTargetSentence(target)}`,
773
+ "",
774
+ ` run: ${run}`,
775
+ "",
776
+ " This refuses rather than allowing, and the symmetry is deliberate: a ledger that cannot",
777
+ " be WRITTEN is not a broken instrument beside the gate, it is the gate's own state failing",
778
+ " to change. Allowing here would mean anything able to make one file unwritable switches the",
779
+ " cap off. Repair or move the file — an operator's job, not a re-draft of this filing.",
780
+ ].join("\n");
781
+ }
782
+
783
+ /**
784
+ * The refusal when the allowance cannot be counted at all (#1595).
785
+ *
786
+ * Names the ledger, because this is the one refusal in the file an OPERATOR
787
+ * has to act on rather than the agent: nothing the filer writes will change
788
+ * it, and the remedy is to repair or move the file. Says so, so the agent
789
+ * does not spend a turn re-drafting a body that was never the problem.
790
+ */
791
+ export function unreadableRunReason(why: string, target: CommentTarget): string {
792
+ return [
793
+ `this filing's RUN could not be read, so there is no denominator to count against:`,
794
+ `${why}. The cap is ${FILINGS_PER_RUN} per run and this directory's run is unknown.`,
795
+ "",
796
+ ` ${commentTargetSentence(target)}`,
797
+ "",
798
+ " This is NOT the same as filing from somewhere that is not a checkout — that is an",
799
+ " answer, and it shares one allowance with every other such directory. A read that",
800
+ " failed is not an answer, and treating it as one would move a real checkout into the",
801
+ " shared allowance every time git timed out. Nothing about your finding is in question.",
802
+ ].join("\n");
803
+ }
804
+
805
+ export function uncountableCapReason(run: string, target: CommentTarget): string {
806
+ return [
807
+ `the filing ledger at ${ledgerPath()} is present and could not be read, so this run's`,
808
+ `allowance cannot be counted. An unreadable ledger is not an empty one — an ABSENT ledger`,
809
+ "is a machine that has filed nothing and allows — so this refuses rather than restoring a",
810
+ "full allowance to anything that can make one file unreadable.",
811
+ "",
812
+ ` ${commentTargetSentence(target)}`,
813
+ "",
814
+ ` run: ${run}`,
815
+ "",
816
+ " Nothing about your finding is in question and re-drafting it will not help. Repair or",
817
+ " move the ledger, or post the comment above. No label waives this one either.",
818
+ ].join("\n");
819
+ }
820
+
821
+ /**
822
+ * The closed list of reasons a finding cannot be a comment (#1595).
823
+ *
824
+ * **THE RECORD, NOT THE GATE. `FILINGS_PER_RUN` above is the gate.** This
825
+ * check was written as the bar and it is not one: applied on 2026-10-24 to
826
+ * the three issues filed that day, all three cleared it on individually
827
+ * sound arguments, because *it makes a green check lie* admits any true
828
+ * finding in a repository about checks that lie. It stays because a
829
+ * declaration is cheap to read, cheap to audit, and is the column that makes
830
+ * a per-class not-useful rate computable later. It stops nothing on its own.
831
+ *
832
+ * **DO NOT ADD A FOURTH.** A clause added later to admit one good finding is
833
+ * how the leak comes back, and it will look reasonable at the time.
834
+ * `test/issue-filing-gate.test.ts` binds the size of this object for exactly
835
+ * that reason — growing it fails the suite, which is the only form of "do
836
+ * not" that survives the next agent who has a good reason.
837
+ *
838
+ * **A declaration, not a judgement.** `lib/finding-arbiter.ts`'s header has
839
+ * said since it was written that `Disposition` defaults to `COMMENT` and that
840
+ * `ISSUE` requires an explicit declared reason from the caller
841
+ * (`Finding.outOfScope`). That decision never reached this file: the header
842
+ * above lists three stages that genuinely cannot run at a PreToolUse hook —
843
+ * no verifier group, no PR diff, no branch to scope against — and the
844
+ * out-of-scope declaration travelled with them without being one of them. It
845
+ * needs nothing but the command line this hook already holds.
846
+ *
847
+ * **Closed, and not free text.** A free-text `--reason` is the same bar as
848
+ * `NO_CLAIM`, which three of four filings on 2026-10-23 cleared in one
849
+ * sentence each. The research behind #1595 is that per-finding judgement
850
+ * drifts and categorical lists do not: Cloudflare's 1.2-findings-per-review
851
+ * comes from a *"What NOT to Flag"* exclusion list, and Google Tricorder's
852
+ * only published threshold acts on the analyzer rather than on the finding.
853
+ *
854
+ * **This is NOT a severity gate and NOT a worthiness score.** Both are
855
+ * excluded deliberately above and #1261 asked for duplicates-and-already-known
856
+ * in those words. Nothing here reads how bad the finding is. It reads whether
857
+ * somebody said which of three things is true of it.
858
+ *
859
+ * The values are the three #1595 names, verbatim. Adding a fourth is an edit
860
+ * to this object and a row in `test/issue-filing-gate.test.ts`; widening it to
861
+ * anything a caller can spell is the failure the whole mechanism exists to
862
+ * prevent.
863
+ */
864
+ export const COMMENT_EXEMPTIONS = {
865
+ "out-of-pr-diff": "the subject is outside any open PR's diff",
866
+ "evidence-expires": "the evidence expires — logs, or a measurement population",
867
+ "green-check-lies": "it makes a green check lie",
868
+ } as const;
869
+
870
+ /** One of the three declarations above. There is no fourth and no `other`. */
871
+ export type CommentExemption = keyof typeof COMMENT_EXEMPTIONS;
872
+
873
+ /**
874
+ * The words a caller writes to declare one.
875
+ *
876
+ * In the title or body rather than in a flag, for two reasons. It is where
877
+ * `namedClaim` already looks, so a filing carries its declarations in one
878
+ * place and the chokepoint needs one reading; and the declaration ends up in
879
+ * the issue a human later opens, which is the only position from which the
880
+ * per-class not-useful rate this records can ever be interpreted.
881
+ *
882
+ * Deliberately not a `--label`: a label `gh` does not already know about
883
+ * fails the create outright, with a message about labels, which would hide
884
+ * this gate behind an unrelated error.
885
+ */
886
+ export const EXEMPTION_PREFIX = "Cannot be a comment:";
887
+
888
+ /**
889
+ * Which declaration a filing makes, or `null` for none.
890
+ *
891
+ * **The token must be one of the three.** A prefix with an unknown word after
892
+ * it reads as no declaration at all rather than as a declaration of something
893
+ * else, because the hole in every format-only check is a value nobody can
894
+ * look up — the same hole `namedClaim` closes by BOUNDING the claim number
895
+ * instead of merely requiring a digit.
896
+ *
897
+ * All matches are scanned and the first recognised one wins, so a body that
898
+ * discusses the mechanism before declaring against it still reads.
899
+ *
900
+ * ## The refusal text must not satisfy this
901
+ *
902
+ * `exemptionRefusal` lists the three tokens, and an agent that pastes a
903
+ * refusal into the body it re-files with would otherwise clear the gate using
904
+ * the gate's own words — an allowlist that names what it exempts becomes
905
+ * evidence those things were named. The list is rendered so that no line of
906
+ * it parses here, and `test/issue-filing-gate.test.ts` asserts that by feeding
907
+ * the refusal back through this function rather than by trusting the layout.
908
+ */
909
+ export function declaredExemption(text: string): CommentExemption | null {
910
+ for (const m of text.matchAll(/cannot\s+be\s+a\s+comment\s*:\s*`?([a-z][a-z-]*)/gi)) {
911
+ const token = m[1].toLowerCase();
912
+ if (token in COMMENT_EXEMPTIONS) return token as CommentExemption;
913
+ }
914
+ return null;
915
+ }
916
+
917
+ /**
918
+ * Where the comment should go instead, when this gate refuses a filing.
919
+ *
920
+ * **A refusal that does not name the alternative becomes a refusal everybody
921
+ * routes around**, which is the argument `refusalMessage` already makes and
922
+ * the three VERIFY-lock bypasses in `lib/issue-create-override.ts` are what
923
+ * it looks like when it is ignored. #1595 asks for the target by name — *post
924
+ * this as a comment on PR #N or issue #M* — and for the message to say which.
925
+ *
926
+ * One discriminator, and `NO_PR` is a reading rather than a gap: a branch
927
+ * with no open PR is a real state an agent can act on (open the PR, or post
928
+ * on the issue the work is claimed under), and it is a different fact from a
929
+ * lookup that could not be performed. Collapsing them would be the Silent
930
+ * Default Substitution `.claude/rules/config-access.md` forbids, in the one
931
+ * sentence the agent actually reads.
932
+ */
933
+ export type CommentTarget =
934
+ | { reading: "PR"; number: number; branch: string }
935
+ | { reading: "NO_PR"; branch: string }
936
+ | { reading: "UNMEASURED"; why: string };
937
+
938
+ /**
939
+ * No target was looked up, said as a reading.
940
+ *
941
+ * The DEFAULT for `adjudicateFiling`, so the adjudicator stays a pure
942
+ * function of what it was handed and a caller that wants the network says so.
943
+ * `filingGate` supplies the live one; `evals/` and the unit rows do not, and
944
+ * an eval that silently opened a GitHub connection would be measuring the
945
+ * network as well as the adjudicator.
946
+ */
947
+ export const UNRESOLVED_COMMENT_TARGET: CommentTarget = {
948
+ reading: "UNMEASURED",
949
+ why: "no comment-target reader was supplied, so no open PR was looked up",
950
+ };
951
+
952
+ /**
953
+ * The alternative, in one sentence that names it and says which kind it is.
954
+ *
955
+ * Composed HERE and not at the refusal site, because the reading is the only
956
+ * thing that knows which of the three states it is in — the same reason
957
+ * `CorpusReading` carries its own `why` rather than letting a caller write a
958
+ * sentence that can be false for the input it is emitted on.
959
+ */
960
+ export function commentTargetSentence(target: CommentTarget): string {
961
+ switch (target.reading) {
962
+ case "PR":
963
+ return `Post it as a comment on PR #${target.number}, the open PR for branch \`${target.branch}\`.`;
964
+ case "NO_PR":
965
+ return (
966
+ `Branch \`${target.branch}\` has no open PR, so there is no diff to comment on yet: ` +
967
+ "post it on the issue this work is claimed under, or open the PR and comment there."
968
+ );
969
+ case "UNMEASURED":
970
+ return (
971
+ `UNMEASURED comment target — ${target.why}. The refusal stands: whether you declared a ` +
972
+ "reason is a fact about this command, not about the tracker. Post it on the PR or issue " +
973
+ "you are working, and say which."
974
+ );
975
+ }
976
+ }
977
+
179
978
  /** How many open issues the dedupe compares against. */
180
979
  export const OPEN_ISSUE_LIMIT = 100;
181
980
 
@@ -293,6 +1092,16 @@ export interface FilingAdjudication {
293
1092
  duplicateOf: string[];
294
1093
  collidingKeys: string[];
295
1094
  symptomHash: string;
1095
+ /**
1096
+ * Which reason the caller declared, or `null` for none (#1595).
1097
+ *
1098
+ * Carried on EVERY adjudication and not only on the refusal, because the
1099
+ * population is the point: the per-class not-useful rate #1595 asks to make
1100
+ * computable is `(closed wontfix/duplicate/no-change) / (all closed in that
1101
+ * class)`, and a column present only on the rows that were refused can
1102
+ * never supply its denominator.
1103
+ */
1104
+ exemption: CommentExemption | null;
296
1105
  }
297
1106
 
298
1107
  /**
@@ -385,6 +1194,146 @@ export interface FilingLedgerRow {
385
1194
  * states and only one of them is a reading.
386
1195
  */
387
1196
  refiledAfter: string | null;
1197
+ /**
1198
+ * Which of the three reasons the caller declared, or `null` (#1595).
1199
+ *
1200
+ * **Recorded on every row, kept and dropped alike, and that is the whole of
1201
+ * #1595's third scope item.** The rate it makes computable is per CLASS —
1202
+ * `(closed wontfix/duplicate/no-change) / (all closed in that class)` — and
1203
+ * the class key is `symptomHash`, already on this row since #1261. So the
1204
+ * join needs one new column and not a new store: group the rows by
1205
+ * `symptomHash`, read the declared reason off each, and the denominator is
1206
+ * every row in the group rather than only the ones somebody refused.
1207
+ *
1208
+ * The rate is deliberately NOT computed here or anywhere in #1595. Google
1209
+ * Tricorder's 10%/25% thresholds act on an ANALYZER over a population of a
1210
+ * reviewer's clicks; a closed-as-wontfix tracker issue costs an agent a
1211
+ * whole context, so the ratio is borrowed and the denominator is different.
1212
+ * Writing the column is what makes the question answerable later; writing a
1213
+ * threshold now would be the same unmeasured judgement this gate refuses.
1214
+ *
1215
+ * `null` is honest on three different rows and they are not told apart
1216
+ * here: a refused filing that declared nothing, an overridden one, and the
1217
+ * rows `scripts/arbitrate-finding.ts` and `lib/ai-review-jury.ts` write,
1218
+ * where no command line exists to carry a declaration. `refusal` and
1219
+ * `emitted` already separate those three, so a second encoding of the same
1220
+ * split would be a decider with a spare.
1221
+ */
1222
+ exemption: CommentExemption | null;
1223
+ /**
1224
+ * This row RESERVES the allowance; it does not record an outcome (#1595).
1225
+ *
1226
+ * **The whole of the race fix, written down as a column.** The cap used to
1227
+ * read the ledger, decide, and let the hook write the outcome afterwards —
1228
+ * three steps with the decision in the middle, so two hook processes that
1229
+ * both read before either wrote both saw a spent count of zero and both
1230
+ * filed. Nothing in the ledger could even show it afterwards: the two rows
1231
+ * are indistinguishable from two filings a day apart.
1232
+ *
1233
+ * An intent row is appended BEFORE the gate decides, and the decision is
1234
+ * then read off its POSITION among this run's intents in the window
1235
+ * (`intentsInRun`). Appends to one file are ordered by the filesystem, so
1236
+ * the position is a total order that needs no lock and no second file: the
1237
+ * first `FILINGS_PER_RUN` intents win and every later one is `OVER_CAP`.
1238
+ *
1239
+ * **`emitted: false`, always, and that is not a technicality.** A filing
1240
+ * count read off this ledger is `emitted && !intent`, and an intent row
1241
+ * that claimed `emitted: true` would double every filing it reserved —
1242
+ * #1344's overcount, reintroduced by the fix for the race. The outcome
1243
+ * lands on its own row, written by the hook as it always was, sharing this
1244
+ * row's key without the `INTENT_KEY_SUFFIX`.
1245
+ *
1246
+ * **A losing intent is never retracted, and it costs nothing.** It stays on
1247
+ * the ledger holding its ordinal, so later reads count it. That cannot gag
1248
+ * a run that has not spent its allowance: an intent can only lose when
1249
+ * `FILINGS_PER_RUN` intents precede it, and by induction those all won — so
1250
+ * a count at or above the cap always means the cap was genuinely reached.
1251
+ *
1252
+ * Absent on every row written before this existed, and on the rows
1253
+ * `scripts/arbitrate-finding.ts` and `lib/ai-review-jury.ts` write, neither
1254
+ * of which reserves anything. Absent reads as `false`.
1255
+ */
1256
+ intent?: boolean;
1257
+ /**
1258
+ * The `key` of an intent row this row gives back (#1595).
1259
+ *
1260
+ * **An intent that reserved an allowance for a command that then filed
1261
+ * nothing has to be released, and an append-only file releases by
1262
+ * appending.** The reservation is taken after the command-level decision
1263
+ * so a command already refused reserves nothing — but a refusal GENERATED
1264
+ * by the reservation loop, which is what a two-clause command at a cap of
1265
+ * one produces every time, arrives after clause 0 has already reserved.
1266
+ * Without this column that command files nothing and spends the run's only
1267
+ * allowance, and the corrected re-run is `OVER_CAP`: the exact outcome the
1268
+ * ordering exists to prevent, reached by the ordinary multi-clause path.
1269
+ *
1270
+ * `runIntents` subtracts released keys, so a released intent holds no
1271
+ * position. It is not retracted in place — nothing in this file rewrites a
1272
+ * row, because the total order appends give is the property the whole race
1273
+ * fix rests on.
1274
+ *
1275
+ * **A `null`-keyed intent cannot be released**, because nothing can name
1276
+ * it. That session's blocked multi-clause command does strand its
1277
+ * allowance for the window, and `unkeyedLedgerNote` already tells it that
1278
+ * its rows cannot be told apart. Fail-closed, stated rather than fixed by
1279
+ * inventing an identity.
1280
+ *
1281
+ * A release is visible only to reads that happen after it, so a racer that
1282
+ * already lost against a since-released intent stays lost and re-runs.
1283
+ * Conservative in the direction a cap must be conservative in.
1284
+ */
1285
+ releases?: string | null;
1286
+ /**
1287
+ * Which run filed it — the checkout, from `runIdFor` (#1595).
1288
+ *
1289
+ * **The cap's denominator, and it had to be written down before it could
1290
+ * be counted.** Nothing on this row could identify a run before: `key` is
1291
+ * `${session}.${pid}`, and on the live ledger that is two session values
1292
+ * across 186 emitted rows with the pid changing on every hook invocation.
1293
+ * So the existing identity answers "which command" and "which session"
1294
+ * and nothing in between, and the cap needs the unit between them.
1295
+ *
1296
+ * `null` on the rows `scripts/arbitrate-finding.ts` and
1297
+ * `lib/ai-review-jury.ts` write — neither adjudicates a `gh issue create`
1298
+ * from a checkout — and on every row written before this column existed.
1299
+ * **Not on a chokepoint filing from a directory that is not a checkout:**
1300
+ * `runIdFor` returns the `NON_CHECKOUT_RUN` bucket rather than `null`, so
1301
+ * the row still names a run and is still counted. Merging every
1302
+ * non-checkout filing on the machine into one allowance is deliberate and
1303
+ * is the fail-closed direction — see `runIdFor`, which first did the
1304
+ * opposite and was reversed.
1305
+ *
1306
+ * `emittedInRun` counts only rows whose `run` equals the run being
1307
+ * adjudicated, so a `null` row counts towards nothing. That is the honest
1308
+ * direction: a row that cannot name its run cannot be attributed to one,
1309
+ * and attributing it to all of them would cap every run on this machine
1310
+ * out of the backlog the column was added to measure.
1311
+ *
1312
+ * ## On an `UNMEASURED_CAP` row this field is a PLACEHOLDER, not a reading
1313
+ *
1314
+ * The gate writes `reading.run ?? NON_CHECKOUT_RUN`, and `runIdFor`
1315
+ * returns `null` when the remote read FAILED — a git timeout, a git that
1316
+ * vanished. So a row refused `UNMEASURED_CAP` for an unreadable run says
1317
+ * `NON_CHECKOUT`, which is a different fact: *"this is not a checkout"*
1318
+ * and *"I could not tell"* spelled identically, in the field that is the
1319
+ * cap's denominator. The same value, for two reasons — exactly the
1320
+ * conflation `RemoteReading.missing` exists to end one level down.
1321
+ *
1322
+ * It is harmless **today and only today**, for a reason that is a property
1323
+ * of the current readers rather than of the value: nothing aggregates by
1324
+ * `run`, and the two counters that read it (`intentsInRun`,
1325
+ * `emittedInRun`) key off `intent`/`emitted`, which are both false on an
1326
+ * `UNMEASURED_CAP` row. **The first reader that groups rows by `run` will
1327
+ * silently fold unreadable runs into the non-checkout bucket**, and it
1328
+ * will do so without touching this file.
1329
+ *
1330
+ * So: do not read this field off a refused row, and do not reach for it as
1331
+ * a discriminator between the two states — `FG-174` asserts that both
1332
+ * arms write the same value precisely so that a later case cannot. The fix
1333
+ * is a third sentinel, deliberately deferred to the decision-loop refactor
1334
+ * rather than added as a fifth patch to `runIdFor` (#1595, PR #1603).
1335
+ */
1336
+ run: string | null;
388
1337
  }
389
1338
 
390
1339
  /**
@@ -526,6 +1475,29 @@ export function readBodyFile(path: string, limit: number = MAX_BODY_FILE_BYTES):
526
1475
  }
527
1476
  }
528
1477
 
1478
+ /**
1479
+ * A resolved clause, as a `Finding` — the ONE binding (#1595).
1480
+ *
1481
+ * `adjudicateFiling` resolved this inline and `filingGate` now needs the same
1482
+ * object to compare a clause against its own siblings. Two spellings of "what
1483
+ * finding is this command filing" would be two deciders for one question, and
1484
+ * the second one always agrees with the first until the day it does not
1485
+ * (`.claude/rules/checks-must-be-able-to-fail.md`, the fourth shape).
1486
+ *
1487
+ * `body` is `null` for a `--body-file` that could not be read, which is the
1488
+ * UNMEASURED arm downstream; `finding.body` falls back to the inline value so
1489
+ * the keys are taken over whatever text there actually is. Those are
1490
+ * deliberately different fields and not one: an empty body that WAS read and
1491
+ * a body nobody could read are different facts.
1492
+ */
1493
+ export function filingFinding(
1494
+ attempt: FilingAttempt,
1495
+ readBody: (path: string) => string | null = readBodyFile,
1496
+ ): { body: string | null; finding: Finding } {
1497
+ const body = attempt.bodyFile === null ? attempt.body : readBody(attempt.bodyFile);
1498
+ return { body, finding: { id: UNFILED_ID, title: attempt.title, body: body ?? attempt.body } };
1499
+ }
1500
+
529
1501
  /**
530
1502
  * The single place that decides whether a filing may proceed.
531
1503
  *
@@ -540,6 +1512,7 @@ export async function adjudicateFiling(
540
1512
  attempt: FilingAttempt,
541
1513
  readExisting: () => Promise<CorpusReading>,
542
1514
  readBody: (path: string) => string | null = readBodyFile,
1515
+ readTarget: () => Promise<CommentTarget> = async () => UNRESOLVED_COMMENT_TARGET,
543
1516
  ): Promise<FilingAdjudication> {
544
1517
  // ── where is the body? ──
545
1518
  //
@@ -553,14 +1526,15 @@ export async function adjudicateFiling(
553
1526
  // not comparable: this is one bounded local `readFileSync`, the thing that
554
1527
  // doctrine protects is a network round trip to the GitHub API. Paying it
555
1528
  // first buys the category stage the body it classifies on.
556
- const body = attempt.bodyFile === null ? attempt.body : readBody(attempt.bodyFile);
557
- const finding: Finding = { id: UNFILED_ID, title: attempt.title, body: body ?? attempt.body };
1529
+ const { body, finding } = filingFinding(attempt, readBody);
558
1530
  const category = classifyCategory(finding);
1531
+ const declared = declaredExemption(`${attempt.title}\n${body ?? attempt.body}`);
559
1532
  const base = {
560
1533
  category,
561
1534
  symptomHash: symptomHash(finding),
562
1535
  duplicateOf: [] as string[],
563
1536
  collidingKeys: [] as string[],
1537
+ exemption: declared,
564
1538
  };
565
1539
 
566
1540
  // ── is it the kind we post at all? ──
@@ -692,9 +1666,27 @@ export async function adjudicateFiling(
692
1666
  // executes is not a rule; `.claude/rules/config-access.md` says that about
693
1667
  // ADRs and it was true of this line too.
694
1668
  //
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.
1669
+ // Cleanup is still postable, and this used to say so by spelling the
1670
+ // token: *"post it as cleanup with `--label arbiter-override`"*.
1671
+ //
1672
+ // **That was the complete bypass recipe, one field up from the tail it was
1673
+ // removed from on 2026-10-25.** `NO_CLAIM` is issued BEFORE
1674
+ // `COMMENT_INSTEAD`, so a filing that is undeclared and claimless is
1675
+ // refused here — and this sentence then handed over the label that waived
1676
+ // it, which carried the filing to the tracker without the comment default
1677
+ // ever being consulted. The refusal taught the route around itself, and
1678
+ // the route it taught was the cheapest one in the file.
1679
+ //
1680
+ // The sentence that replaces it keeps what was true — cleanup is postable
1681
+ // and the route is counted — and drops the recipe. An agent that already
1682
+ // holds the token still has it; one that does not does not learn it from
1683
+ // a refusal. `refusalMessage`'s waivable tail makes the same trade and
1684
+ // the argument is written out there.
1685
+ //
1686
+ // It is also no longer a sufficient instruction: since the sibling fix the
1687
+ // label alone posts nothing, so a filing that really is cleanup needs the
1688
+ // declaration too. A half-recipe that still worked would be worse than
1689
+ // either.
698
1690
  if (namedClaim(`${attempt.title}\n${body}`) === null) {
699
1691
  return {
700
1692
  ...base,
@@ -702,8 +1694,47 @@ export async function adjudicateFiling(
702
1694
  refusal: "NO_CLAIM",
703
1695
  reason:
704
1696
  `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}\``,
1697
+ `Name one as "Claim <1-${SUCCESS_CLAIM_COUNT}>" in the title or body. Genuine cleanup ` +
1698
+ `is still postable by a route that is deliberately not spelled in a refusal, and that ` +
1699
+ `route is recorded against this run and counted later`,
1700
+ };
1701
+ }
1702
+
1703
+ // ── it says what it moves. does anybody say why it cannot be a COMMENT? ──
1704
+ //
1705
+ // **The stage #1595 is about, and the one the header above was missing.**
1706
+ // Everything before this asks whether the finding is worth posting. This
1707
+ // one asks the question the arbiter's own docblock says comes first — *the
1708
+ // default is a comment, not an issue* — and nothing on the live filing path
1709
+ // asked it. Measured when #1595 was filed: 772 issues ever, 48 open, 3
1710
+ // older than three days, and 70–85% of everything closed each day since
1711
+ // 2026-10-20 had been filed less than six hours before it closed. Filing
1712
+ // tracked closing almost exactly. A tracker that is an output of the review
1713
+ // loop cannot be drained by closing faster.
1714
+ //
1715
+ // **LAST, and after `NO_CLAIM` specifically.** The cost doctrine would put
1716
+ // a regex over a string already in hand first, and first is wrong for the
1717
+ // reason the stage above gives: a duplicate must be refused as DUPLICATE
1718
+ // and an UNMEASURED tracker must stay UNMEASURED, because a policy refusal
1719
+ // that outranks a reading failure is a reading failure nobody ever sees.
1720
+ // Only an ALLOW reaches here, so this can mask nothing.
1721
+ //
1722
+ // After `NO_CLAIM` rather than before it, which is the one ordering choice
1723
+ // here worth defending. Putting it first makes `NO_CLAIM` unreachable for
1724
+ // the common filing — a shipped gate deleted as a side effect of adding
1725
+ // one — and the round trip it would save does not exist: `refusalMessage`
1726
+ // already tells every refused filing to resolve it in the PR or answer it
1727
+ // in a comment, so a `NO_CLAIM` refusal has already routed the agent here.
1728
+ //
1729
+ // **A declaration, never an inference.** There is no heuristic that reads
1730
+ // "this looks out of scope", because an inferred exception is exactly how a
1731
+ // filing default comes back — `Finding.outOfScope` says so in those words.
1732
+ if (declared === null) {
1733
+ return {
1734
+ ...base,
1735
+ outcome: "REFUSE",
1736
+ refusal: "COMMENT_INSTEAD",
1737
+ reason: exemptionReason(await readTarget()),
707
1738
  };
708
1739
  }
709
1740
 
@@ -713,10 +1744,40 @@ export async function adjudicateFiling(
713
1744
  refusal: null,
714
1745
  reason:
715
1746
  `no open issue shares this symptom, ${category} is not a dropped category, ` +
716
- `and it names SUCCESS.md claim ${namedClaim(`${attempt.title}\n${body}`)}`,
1747
+ `it names SUCCESS.md claim ${namedClaim(`${attempt.title}\n${body}`)}, and it declares ` +
1748
+ `\`${declared}\` — ${COMMENT_EXEMPTIONS[declared]}`,
717
1749
  };
718
1750
  }
719
1751
 
1752
+ /**
1753
+ * Why this filing was refused, and where the comment goes instead.
1754
+ *
1755
+ * ## The three tokens are rendered so that this sentence cannot satisfy the gate
1756
+ *
1757
+ * An agent that re-files after reading a refusal pastes the refusal. If the
1758
+ * list below spelled `Cannot be a comment: out-of-pr-diff` the gate's own
1759
+ * words would clear the gate — an allowlist that names what it exempts
1760
+ * becomes evidence those things were named. So the prefix never appears
1761
+ * adjacent to a token: the instruction line carries a `<placeholder>`, which
1762
+ * `declaredExemption` does not match, and the tokens are listed on their own
1763
+ * lines with no prefix. `test/issue-filing-gate.test.ts` feeds this string
1764
+ * back through `declaredExemption` rather than trusting the layout.
1765
+ */
1766
+ export function exemptionReason(target: CommentTarget): string {
1767
+ return [
1768
+ "nobody declared a reason this finding cannot be a comment, and a comment is the default.",
1769
+ "",
1770
+ ` ${commentTargetSentence(target)}`,
1771
+ "",
1772
+ " If filing genuinely IS the exception, say which of these three is true of it, on its",
1773
+ ` own line in the title or body, as \`${EXEMPTION_PREFIX} <one-token-from-below>\`:`,
1774
+ "",
1775
+ ...Object.entries(COMMENT_EXEMPTIONS).map(([token, meaning]) => ` ${token} — ${meaning}`),
1776
+ "",
1777
+ " The list is closed. A reason that is not one of those three is a reason to comment.",
1778
+ ].join("\n");
1779
+ }
1780
+
720
1781
  /**
721
1782
  * Why one existing issue was kept out of the comparison set.
722
1783
  *
@@ -872,6 +1933,64 @@ export async function openFindings(
872
1933
  }
873
1934
  }
874
1935
 
1936
+ /**
1937
+ * The open PR for this working directory's branch — the comment target.
1938
+ *
1939
+ * **Only ever called on the refusal arm**, so the allow path pays nothing for
1940
+ * it. The reading is composed from two probes and neither may be guessed:
1941
+ *
1942
+ * - the branch, through `branchOf` in `lib/launch-base.ts` — ONE binding for
1943
+ * "what branch is this directory on", rather than a second `rev-parse`
1944
+ * here that would agree with it until the day it did not;
1945
+ * - the open PRs whose head is that branch, through the same Octokit client
1946
+ * and the same `withTimeout` ceiling the corpus read uses.
1947
+ *
1948
+ * `HEAD` is filtered: a detached checkout has no branch to query a PR by, and
1949
+ * `head=owner:HEAD` would return an empty list that reads exactly like a
1950
+ * branch with no PR open. Two states, one observable — so the one that was
1951
+ * never asked says UNMEASURED.
1952
+ *
1953
+ * Every failure is UNMEASURED carrying its own `why`, never `NO_PR`. A
1954
+ * missing token, a 403 and a rate limit are all states where nobody looked,
1955
+ * and "this branch has no open PR" is a claim about the tracker. The refusal
1956
+ * stands either way: whether a reason was declared is a fact about the
1957
+ * command line, and the target is the helpful half of the sentence rather
1958
+ * than the deciding one.
1959
+ */
1960
+ export async function openPrForBranch(
1961
+ projectRoot: string,
1962
+ repo: string | null = null,
1963
+ ): Promise<CommentTarget> {
1964
+ const branch = branchOf(projectRoot);
1965
+ if (branch === null || branch === "HEAD") {
1966
+ return {
1967
+ reading: "UNMEASURED",
1968
+ why:
1969
+ branch === "HEAD"
1970
+ ? `\`${projectRoot}\` is a detached checkout, so there is no branch to find a PR for`
1971
+ : `the branch of \`${projectRoot}\` could not be read`,
1972
+ };
1973
+ }
1974
+ const slug = corpusSlug(projectRoot, repo);
1975
+ if (slug === null) {
1976
+ return { reading: "UNMEASURED", why: "no repository slug resolved, so no PR list was asked for" };
1977
+ }
1978
+ try {
1979
+ const { owner } = parseOwnerRepo(slug);
1980
+ const prs = await withTimeout(
1981
+ listPRs(createGitHubClient(), slug, { state: "open", head: `${owner}:${branch}`, per_page: 5 }),
1982
+ OPEN_ISSUE_TIMEOUT_MS,
1983
+ );
1984
+ const number = prs.find(p => typeof p?.number === "number")?.number;
1985
+ return number === undefined ? { reading: "NO_PR", branch } : { reading: "PR", number, branch };
1986
+ } catch {
1987
+ return {
1988
+ reading: "UNMEASURED",
1989
+ why: `the open PRs of ${slug} could not be read, so the PR for \`${branch}\` was never found`,
1990
+ };
1991
+ }
1992
+ }
1993
+
875
1994
  /**
876
1995
  * The open issues that may be used to suppress a filing.
877
1996
  *
@@ -1191,9 +2310,14 @@ export function priorRefusalFor(
1191
2310
  title: string,
1192
2311
  rows: readonly FilingLedgerRow[],
1193
2312
  ): FilingLedgerRow | null {
2313
+ // Bounded on the way in, because it was bounded on the way out: a title
2314
+ // over `MAX_LEDGER_TITLE` is stored truncated, so comparing the raw one
2315
+ // would never match its own prior row and the #1536 override would stop
2316
+ // surviving a re-draft for exactly the longest titles.
2317
+ const wanted = ledgerTitle(title);
1194
2318
  let best: FilingLedgerRow | null = null;
1195
2319
  for (const row of rows) {
1196
- if (row.title !== title) continue;
2320
+ if (row.title !== wanted) continue;
1197
2321
  if (row.refusal === null || row.refusal === "UNMEASURED") continue;
1198
2322
  if (row.emitted || row.overridden) continue;
1199
2323
  if (row.withheldBy !== row.refusal) continue;
@@ -1228,6 +2352,26 @@ export async function filingGate(
1228
2352
  readExisting?: (projectRoot: string, repo: string | null) => Promise<CorpusReading>;
1229
2353
  /** The adjudications already on the ledger. `null` means unreadable. */
1230
2354
  readLedger?: () => FilingLedgerRow[] | null;
2355
+ /**
2356
+ * Append one row, reporting whether it landed.
2357
+ *
2358
+ * The gate writes exactly one kind of row itself — the intent that
2359
+ * reserves the allowance (`reserveAllowance`) — and the hook still writes
2360
+ * every outcome row afterwards. Injectable so a test can drive the race
2361
+ * without a filesystem, and so the two racers in `FG-165` can share one.
2362
+ */
2363
+ appendLedger?: (row: FilingLedgerRow) => boolean;
2364
+ /**
2365
+ * Where a comment should go instead, when a filing is refused for having
2366
+ * declared no reason (#1595). Injectable for the same reason
2367
+ * `readExisting` is: the live one talks to GitHub.
2368
+ */
2369
+ readTarget?: (projectRoot: string, repo: string | null) => Promise<CommentTarget>;
2370
+ /**
2371
+ * The checkout's `origin`, for `runIdFor`. Injectable only so a FAILED
2372
+ * read can be driven — see `runIdFor`, where the default lives.
2373
+ */
2374
+ readRemote?: (worktreePath: string) => RemoteReading;
1231
2375
  },
1232
2376
  ): Promise<FilingGateReading> {
1233
2377
  const attempts = filingAttempts(cmd);
@@ -1251,6 +2395,22 @@ export async function filingGate(
1251
2395
  return started;
1252
2396
  };
1253
2397
 
2398
+ // The comment target, cached per tracker exactly as the corpus is, and
2399
+ // LAZY in a way the corpus is not: the thunk is only called on the
2400
+ // COMMENT_INSTEAD arm, so a command every clause of which is allowed pays
2401
+ // nothing for it. A hook has no retry and no patience to spend on a read
2402
+ // that only composes a sentence.
2403
+ const readTarget = options.readTarget ?? openPrForBranch;
2404
+ const targets = new Map<string, Promise<CommentTarget>>();
2405
+ const targetFor = (repo: string | null) => {
2406
+ const key = repo ?? "";
2407
+ const hit = targets.get(key);
2408
+ if (hit !== undefined) return hit;
2409
+ const started = readTarget(options.projectRoot, repo);
2410
+ targets.set(key, started);
2411
+ return started;
2412
+ };
2413
+
1254
2414
  const rows: FilingLedgerRow[] = [];
1255
2415
  const refusals: string[] = [];
1256
2416
  const notes: string[] = [];
@@ -1267,8 +2427,136 @@ export async function filingGate(
1267
2427
  const priorRows = (options.readLedger ?? (() => readLedgerRows()))();
1268
2428
  if (priorRows === null) notes.push(unreadableLedgerNote());
1269
2429
 
2430
+ // ── One issue per finding CLASS per run, never per instance (#1595) ──
2431
+ //
2432
+ // **Decided here and not in `adjudicateFiling`, because the unit is the
2433
+ // COMMAND.** `markBlockedCommand` is the same shape for the same reason: a
2434
+ // property of several clauses together cannot be read by a function that
2435
+ // sees one. *"Flag the class of bug, so the author fixes every instance,
2436
+ // not one line"* is CRC-N3, and this is its hook-side half — two clauses
2437
+ // sharing a class are one item saying *every instance*.
2438
+ //
2439
+ // Every sibling carries its CLAUSE INDEX as its id. `UNFILED_ID` for all of
2440
+ // them would make the comparison a no-op in exactly the configuration it is
2441
+ // written for, which `lib/finding-arbiter.ts` records happening once
2442
+ // already: *"treating the label as an identity is what made the in-batch
2443
+ // dedupe a no-op"*.
2444
+ //
2445
+ // Only clauses that CLEARED become siblings. The refusal says "fold it into
2446
+ // clause N", and that is only an instruction worth following if clause N is
2447
+ // itself going to be filed.
2448
+ const siblings: Finding[] = [];
2449
+ const siblingTitles = new Map<string, string>();
2450
+
2451
+ // ── The cap (#1595, scope item 4) ──
2452
+ //
2453
+ // **The gate. Everything else in this file is a judgement and this is a
2454
+ // count.** Resolved once per command, because the run is a property of
2455
+ // the command's directory and a `rev-parse` per clause would be three
2456
+ // spellings of one answer.
2457
+ //
2458
+ // `spent` carries the in-command emissions as well as the ledger's, so a
2459
+ // three-clause command cannot file three issues under a cap of one by
2460
+ // adjudicating every clause against a snapshot taken before any of them
2461
+ // landed. That is the same shape as the sibling list above.
2462
+ //
2463
+ // **An UNREADABLE ledger REFUSES, and this is the one place in the file
2464
+ // that fails closed.** It allowed at first, on the standing policy that a
2465
+ // measurement apparatus must not block the thing it measures — which is
2466
+ // right for `recordAdjudication` returning `false` rather than throwing,
2467
+ // and wrong here. The ledger is not the apparatus for the cap; it is the
2468
+ // cap's STATE. "Could not read it" means the allowance is unknown, and
2469
+ // allowing on an unknown allowance is not a loud note, it is the gate
2470
+ // removed by anything that can make one file unreadable.
2471
+ //
2472
+ // The two readings this turns on already exist and are already separated:
2473
+ // `readLedgerRows` returns `[]` for a genuinely absent file and `null`
2474
+ // for present-and-unreadable. An empty population is an answer — a
2475
+ // machine that has never filed has spent nothing — and it allows. `null`
2476
+ // is not an answer, and it refuses as `UNMEASURED_CAP`, which
2477
+ // `waivableRefusal` excludes so the label cannot clear it either.
2478
+ // **A run that could not be READ is a third state and rides the same
2479
+ // conversion as an unreadable ledger.** `runIdFor` returns `null` only for
2480
+ // a remote read that failed — a git timeout, git missing — never for a
2481
+ // directory that simply has no origin, which is an answer and buckets.
2482
+ // Without the split the timeout silently re-keys a real checkout into the
2483
+ // shared allowance, which is the denominator changing underneath the count.
2484
+ const reading = runIdFor(options.projectRoot, options.readRemote);
2485
+ const run = reading.run ?? NON_CHECKOUT_RUN;
2486
+ const nowMs = Date.parse(at);
2487
+ const uncountable = priorRows === null || reading.run === null;
2488
+ let spent = uncountable ? 0 : intentsInRun(priorRows ?? [], run, nowMs);
2489
+ // One binding for the UNMEASURED_CAP sentence, because there are now two
2490
+ // ways to be uncountable and they name different things to repair: a
2491
+ // ledger nobody can read, and a run nobody could resolve.
2492
+ const uncountableReason = (target: CommentTarget) =>
2493
+ reading.run === null
2494
+ ? unreadableRunReason(reading.why ?? "the remote could not be read", target)
2495
+ : uncountableCapReason(run, target);
2496
+ // The per-clause verdicts, kept so the race stage below can compose the
2497
+ // same refusal message the loop composes. One array, written once per
2498
+ // clause beside `rows`, so `rows[i]` and `verdicts[i]` are one clause.
2499
+ const verdicts: FilingAdjudication[] = [];
2500
+
1270
2501
  for (const [index, attempt] of attempts.entries()) {
1271
- const verdict = await adjudicateFiling(attempt, () => readFor(attempt.repo));
2502
+ const read1 = await adjudicateFiling(
2503
+ attempt,
2504
+ () => readFor(attempt.repo),
2505
+ readBodyFile,
2506
+ () => targetFor(attempt.repo),
2507
+ );
2508
+ // The in-run class check, applied to anything the per-filing stages did
2509
+ // not already refuse. It converts an UNMEASURED as well as an ALLOW, and
2510
+ // that is deliberate: this reading needs no tracker, so an unreadable
2511
+ // tracker is no reason to let one command file a class twice. The note
2512
+ // below is keyed off `read1` rather than `verdict` so the unreadable
2513
+ // tracker is still said out loud when that happens.
2514
+ const { finding } = filingFinding(attempt);
2515
+ // **The cap is applied before anything READS THE TRACKER'S ANSWER, and
2516
+ // it converts an UNMEASURED.** Every other
2517
+ // UNMEASURED arm in this file allows, which is right for a reading about
2518
+ // the environment — but if the cap sat behind them, a session with no
2519
+ // `GITHUB_TOKEN` would have no cap at all, and this file's own header
2520
+ // says a developer's credential usually is not in the environment. A
2521
+ // gate that switches itself off in the configuration most agents run in
2522
+ // is not a gate. The cap needs no tracker, so nothing about the tracker
2523
+ // may excuse it.
2524
+ //
2525
+ // **Against the OTHER refusal in this block, the class check runs first,
2526
+ // and that ordering is forced.** The two are not in tension with the
2527
+ // paragraph above: the tracker is what the cap must not wait for, and
2528
+ // the class check reads no tracker either.
2529
+ // At `FILINGS_PER_RUN = 1` a run's second clause is over the cap
2530
+ // whatever it says, so a cap placed first makes `SAME_CLASS_IN_RUN`
2531
+ // unreachable — a refusal nothing can ever emit, which is a check that
2532
+ // cannot fail. Measured when the cap landed with the cap first: FG-133
2533
+ // and FG-134 both went red and the class refusal was dead code.
2534
+ //
2535
+ // Nothing is weakened by the order, because BOTH refuse. What changes is
2536
+ // which sentence the agent reads, and for two clauses of one class
2537
+ // *"fold this into clause 1 and say every instance"* is strictly more
2538
+ // actionable than *"post a comment"* — the same argument this file makes
2539
+ // for reporting DUPLICATE ahead of NO_CLAIM.
2540
+ const sameClass =
2541
+ read1.outcome === "REFUSE" ? [] : duplicateCollisions(finding, siblings);
2542
+ const read2: FilingAdjudication =
2543
+ sameClass.length === 0
2544
+ ? read1
2545
+ : {
2546
+ ...read1,
2547
+ outcome: "REFUSE",
2548
+ refusal: "SAME_CLASS_IN_RUN",
2549
+ collidingKeys: sameClass[0].keys,
2550
+ // NOT `duplicateOf`: that field holds ISSUE numbers a reader can
2551
+ // open, and a clause index is not one. The reason names the
2552
+ // clause instead.
2553
+ reason:
2554
+ `clause ${Number(sameClass[0].id) + 1} of this same command already files this ` +
2555
+ `class — "${siblingTitles.get(sameClass[0].id)}" — sharing ` +
2556
+ `${sameClass[0].keys.length} key(s): ${sameClass[0].keys.slice(0, MAX_QUOTED_KEYS).join(", ")}. ` +
2557
+ "One issue per finding class per run, never per instance: fold this instance into " +
2558
+ "that filing and say *every instance* in it, rather than filing the second one.",
2559
+ };
1272
2560
  const labelled = attempt.labels.includes(FILING_OVERRIDE_LABEL);
1273
2561
  const prior = priorRows === null ? null : priorRefusalFor(attempt.title, priorRows);
1274
2562
  // **An override waives A REFUSAL, and the refusal need not be this
@@ -1277,7 +2565,107 @@ export async function filingGate(
1277
2565
  // `FilingLedgerRow.refiledAfter` for the two live rows 37 seconds apart
1278
2566
  // that measured it. Nothing here is stricter: `prior` cannot cause a
1279
2567
  // refusal, only name one that already happened.
1280
- const overridden = labelled && (verdict.outcome === "REFUSE" || prior !== null);
2568
+ // **`OVER_CAP` is not waivable, and that is the whole point of it**
2569
+ // (#1595). The override waives a claim about a FINDING — this is a
2570
+ // duplicate, this names no claim, this should have been a comment — and
2571
+ // every one of those is an argument the filer can answer. The cap makes
2572
+ // no claim about the finding at all, so there is nothing to answer, and
2573
+ // a label that waived it would hand back exactly the per-filing
2574
+ // judgement the cap exists to replace: a valid reason defeating the cap
2575
+ // IS the bar that let three of three filings through on 2026-10-24.
2576
+ //
2577
+ // ONE binding, applied to two inputs. The cap below has to know whether
2578
+ // the label would carry this clause to the tracker BEFORE it decides,
2579
+ // and the row has to record whether it did AFTER. Written as two
2580
+ // expressions those are two deciders over one question, which is how the
2581
+ // bypass this closes got in.
2582
+ //
2583
+ // The `prior` arm reads `waivableRefusal` too, and for the same reason
2584
+ // the current arm does. Without it a row re-drafted after an `OVER_CAP`
2585
+ // or `UNMEASURED_CAP` refusal records `overridden: true` — the label
2586
+ // waiving, in the ledger's own account, a refusal no label can waive.
2587
+ // Nothing reaches the tracker that should not, because the clause is
2588
+ // being ALLOWED on its merits by then; what breaks is the measurement,
2589
+ // and the count of overrides against the cap is the number this whole
2590
+ // change exists to make readable. Raised by the AI review at round 6.
2591
+ // **`v.exemption !== null` is the sibling-refusal fix, and it is not a
2592
+ // new policy** (#1595, 2026-10-25). The adjudicator returns the FIRST
2593
+ // refusal it reaches, so waiving that one emits a filing whose later
2594
+ // refusals were never computed. `COMMENT_INSTEAD` is issued last, after
2595
+ // `NO_CLAIM` — deliberately, and the reason is defended at the stage
2596
+ // itself — so a filing that is undeclared AND claimless is refused
2597
+ // `NO_CLAIM`, the label waives that, and the unwaivable member is never
2598
+ // consulted. The route this change closed was "delete the declaration";
2599
+ // the route that replaced it was "delete the declaration AND the claim".
2600
+ // A gate that gets cheaper to beat the worse the filing gets is not a
2601
+ // gate, and there is no reason to believe `NO_CLAIM` is the only sibling
2602
+ // that can win the race.
2603
+ //
2604
+ // Keying unwaivability on the refusal ISSUED was the actual defect:
2605
+ // absence of a declaration is a property of the ATTEMPT, and which
2606
+ // refusal fired is a property of the precedence. Reading `exemption` —
2607
+ // which `adjudicateFiling` already computed and carries on EVERY
2608
+ // adjudication, so this is not a second decider — asks the attempt
2609
+ // directly and closes every sibling at once.
2610
+ //
2611
+ // **Not by making `COMMENT_INSTEAD` win the precedence race.** That
2612
+ // deletes `NO_CLAIM` for the common filing as a side effect of adding
2613
+ // one gate, which is exactly what the comment at that stage warns
2614
+ // against. The ordering is untouched; `FG-178` asserts the refusal is
2615
+ // still `NO_CLAIM`, so a later change that reorders goes red and says so.
2616
+ //
2617
+ // The invariant this restores, stated so it can be tested as one: **no
2618
+ // filing without a declaration reaches the tracker, label or no label.**
2619
+ // Without the label that was already true — undeclared is
2620
+ // `COMMENT_INSTEAD` and `COMMENT_INSTEAD` is not emitted. The label was
2621
+ // the only hole.
2622
+ const overrideOf = (v: FilingAdjudication) =>
2623
+ labelled &&
2624
+ v.exemption !== null &&
2625
+ waivableRefusal(v.refusal) &&
2626
+ (v.outcome === "REFUSE" || (prior !== null && waivableRefusal(prior.refusal)));
2627
+
2628
+ // **The cap applies to anything that would REACH THE TRACKER, not to
2629
+ // anything that happens to be clean.** Gating it on `read1` being an
2630
+ // ALLOW — which is how it was first written, and what the AI review of
2631
+ // PR #1597 found at round 4 — makes `--label arbiter-override` a cap
2632
+ // bypass: a clause refused for any WAIVABLE reason skips the cap
2633
+ // entirely, the label then waives that refusal, and the filing lands
2634
+ // with the run already over its allowance. It is not a corner either.
2635
+ // The cheapest way to reach it was to DELETE the declaration: an
2636
+ // undeclared filing is `COMMENT_INSTEAD`, which was waivable, so
2637
+ // dropping one line and adding the label beat the gate. A cap that any
2638
+ // agent can step around by making its filing *worse* is not a cap.
2639
+ //
2640
+ // `COMMENT_INSTEAD` became unwaivable on 2026-10-25, so that specific
2641
+ // route is closed at its source as well as here. **This ordering stays**
2642
+ // — it is not the fix for one spelling of the bypass. Every remaining
2643
+ // waivable refusal reaches the tracker under the label, and the cap has
2644
+ // to be applied to all of them or it is applied to none.
2645
+ //
2646
+ // `SAME_CLASS_IN_RUN` keeps its precedence, because a clause refused for
2647
+ // it is not emitted and `wouldEmit` is therefore false — the conversion
2648
+ // only touches clauses that were going to reach the tracker.
2649
+ //
2650
+ // `uncountable` rides the same conversion rather than a second one. The
2651
+ // question *"may this clause reach the tracker?"* has one answer and one
2652
+ // place that applies it; "the allowance is spent" and "the allowance
2653
+ // cannot be read" are two reasons for the same No, and splitting them
2654
+ // across two branches is how the first bypass got in.
2655
+ const wouldEmit = read2.outcome !== "REFUSE" || overrideOf(read2);
2656
+ const capped = uncountable || spent >= FILINGS_PER_RUN;
2657
+ const verdict: FilingAdjudication =
2658
+ wouldEmit && capped
2659
+ ? {
2660
+ ...read2,
2661
+ outcome: "REFUSE",
2662
+ refusal: uncountable ? "UNMEASURED_CAP" : "OVER_CAP",
2663
+ reason: uncountable
2664
+ ? uncountableReason(await targetFor(attempt.repo))
2665
+ : overCapReason(run, spent, await targetFor(attempt.repo)),
2666
+ }
2667
+ : read2;
2668
+ const overridden = overrideOf(verdict);
1281
2669
  // **This clause's own reading, and nothing about the command.** The
1282
2670
  // command-level decision is not available yet — it needs every clause —
1283
2671
  // so `emitted` here is provisional and `markBlockedCommand` below applies
@@ -1286,11 +2674,12 @@ export async function filingGate(
1286
2674
  // refuse was recorded as having reached the tracker.
1287
2675
  const cleared = verdict.outcome !== "REFUSE" || overridden;
1288
2676
 
2677
+ verdicts.push(verdict);
1289
2678
  rows.push({
1290
2679
  at,
1291
2680
  key: batch === null ? null : `${batch}/${index}`,
1292
2681
  id: UNFILED_ID,
1293
- title: attempt.title,
2682
+ title: ledgerTitle(attempt.title),
1294
2683
  symptomHash: verdict.symptomHash,
1295
2684
  category: verdict.category,
1296
2685
  severity: null,
@@ -1310,10 +2699,35 @@ export async function filingGate(
1310
2699
  duplicateOf: verdict.duplicateOf.length > 0 ? verdict.duplicateOf : (prior?.duplicateOf ?? []),
1311
2700
  overridden,
1312
2701
  refiledAfter: prior?.at ?? null,
2702
+ exemption: verdict.exemption,
2703
+ run,
1313
2704
  });
1314
2705
 
2706
+ // A cleared clause is what a later clause of this command is compared
2707
+ // against, and it is what the cap counts. Both are applied AFTER the row,
2708
+ // so the clause never collides with itself and never caps itself out — a
2709
+ // self-collision would refuse every single-clause filing in the tree and
2710
+ // read exactly like a gate that works.
2711
+ //
2712
+ // `spent` moves on `cleared` and not on `emitted`, and they differ for
2713
+ // one row shape: a clean clause inside a command the hook goes on to
2714
+ // BLOCK. `markBlockedCommand` clears `emitted` on those below, so the
2715
+ // ledger never counts them and a re-run of that command gets its
2716
+ // allowance back. Reading `cleared` here is still right, because within
2717
+ // this command the clause is provisionally filing and a sibling must not
2718
+ // be allowed to file under the same allowance.
2719
+ if (cleared) {
2720
+ spent += 1;
2721
+ siblings.push({ ...finding, id: String(index) });
2722
+ siblingTitles.set(String(index), attempt.title);
2723
+ }
2724
+
1315
2725
  if (verdict.outcome === "REFUSE" && !overridden) refusals.push(refusalMessage(verdict));
1316
- if (verdict.outcome === "UNMEASURED") notes.push(unmeasuredNote(verdict));
2726
+ // `read1`, never `verdict`: a clause whose tracker could not be read AND
2727
+ // whose class a sibling already files is both facts at once, and the
2728
+ // conversion above keeps only the second. An UNMEASURED nobody sees is
2729
+ // the silent pass this file's header exists to prevent.
2730
+ if (read1.outcome === "UNMEASURED") notes.push(unmeasuredNote(read1));
1317
2731
  if (overridden) notes.push(overrideNote(verdict, prior));
1318
2732
  // A re-draft that cleared the gate on its own is not refused and not
1319
2733
  // blocked — the gate does not get stricter here (#1536). It is SAID, so
@@ -1359,6 +2773,85 @@ export async function filingGate(
1359
2773
  // them, and `clean` is read BEFORE it so the refusal still enumerates the
1360
2774
  // clauses an agent should re-run — see that function's header for why that
1361
2775
  // ordering is the whole of #1344's wrong fix.
2776
+ // ── The cap again, this time against the clauses that will actually file
2777
+ // (#1595) ────────────────────────────────────────────────────────────
2778
+ //
2779
+ // Everything above decided from a snapshot READ BEFORE the decision, which
2780
+ // is the race: `filingGate` calls the tracker in between, so the window is
2781
+ // hundreds of milliseconds and two parallel hooks both counted zero.
2782
+ // `reserveAllowance` closes it by appending first and reading the position
2783
+ // back — see its header for why there is no lock.
2784
+ //
2785
+ // **Only when nothing else refuses, and that ordering is load-bearing.** A
2786
+ // blocked command files nothing, so reserving for it would spend the run's
2787
+ // allowance on a command that was never going to reach the tracker, and the
2788
+ // agent's corrected re-run would then be `OVER_CAP`. It is the same rule
2789
+ // `markBlockedCommand` applies to `emitted`, applied one step earlier
2790
+ // because a reservation cannot be taken back.
2791
+ //
2792
+ // **Everything reserved is released if the command ends up filing
2793
+ // nothing**, and the guard above is not enough for that. `refusals.length
2794
+ // === 0` tests the refusals that existed BEFORE this stage; the stage
2795
+ // generates its own, and at `FILINGS_PER_RUN = 1` every command with two
2796
+ // emitting clauses generates one — clause 0 wins, clause 1 loses, the
2797
+ // refusal blocks the command, and clause 0's reservation sits on the
2798
+ // ledger holding the run's only allowance for a command that filed
2799
+ // nothing. That is the ordinary multi-clause path, not an edge case, and
2800
+ // the comment above was right about the invariant while the code guarded
2801
+ // it against the wrong population. Found by the security review of
2802
+ // `822d5d7d`.
2803
+ //
2804
+ // So: stop at the first clause that does not win, and give back every
2805
+ // reservation this command took. `releaseAllowance` appends rather than
2806
+ // rewriting, because the order appends give is what the whole fix rests
2807
+ // on.
2808
+ if (refusals.length === 0) {
2809
+ const append = options.appendLedger ?? ((r: FilingLedgerRow) => recordAdjudication(r));
2810
+ const readAgain = options.readLedger ?? (() => readLedgerRows());
2811
+ const reserved: FilingLedgerRow[] = [];
2812
+ for (const [index, row] of rows.entries()) {
2813
+ if (!row.emitted) continue;
2814
+ const reading = reserveAllowance(row, run, { now: nowMs, append, readLedger: readAgain });
2815
+ if (reading.outcome === "WON") {
2816
+ reserved.push(reading.intent);
2817
+ continue;
2818
+ }
2819
+ const refusal = reading.outcome === "LOST" ? "OVER_CAP" : "UNMEASURED_CAP";
2820
+ const target = await targetFor(attempts[index].repo);
2821
+ const reason =
2822
+ reading.outcome === "LOST"
2823
+ ? overCapReason(run, reading.already, target)
2824
+ : reading.outcome === "UNRESERVED"
2825
+ ? unreservedCapReason(run, target)
2826
+ : uncountableReason(target);
2827
+ if (reading.outcome === "UNRESERVED") notes.push(unreservedAllowanceNote());
2828
+ // The intent this clause took is released with the rest below: it won
2829
+ // no position, and a losing reservation that is never given back is
2830
+ // the same stranded allowance by a rarer route.
2831
+ if (reading.outcome !== "UNRESERVED") reserved.push(reading.intent);
2832
+ // **`waivableRefusal` is READ here, not restated.** Writing
2833
+ // `overridden: false` with a comment saying the predicate agrees makes
2834
+ // this a third place that decides whether a label waives something,
2835
+ // and a mutation of the predicate would leave this one holding the
2836
+ // case up — the fourth shape in
2837
+ // `.claude/rules/checks-must-be-able-to-fail.md`. It evaluates false
2838
+ // for both of these refusals; the point is that it evaluates.
2839
+ rows[index] = {
2840
+ ...row,
2841
+ emitted: false,
2842
+ disposition: "DROP",
2843
+ refusal,
2844
+ withheldBy: refusal,
2845
+ overridden: row.overridden && waivableRefusal(refusal),
2846
+ };
2847
+ refusals.push(refusalMessage({ ...verdicts[index], outcome: "REFUSE", refusal, reason }));
2848
+ // Nothing after this clause can file — the refusal blocks the command
2849
+ // — so reserving for it would strand another allowance.
2850
+ break;
2851
+ }
2852
+ if (refusals.length > 0) for (const intent of reserved) releaseAllowance(intent, append);
2853
+ }
2854
+
1362
2855
  const blocking = refusals.length > 0;
1363
2856
  const clean = rows.filter(r => r.emitted);
1364
2857
  if (blocking && clean.length > 0) refusals.push(cleanClauseNote(clean, rows.length));
@@ -1457,8 +2950,57 @@ export function markBlockedCommand(rows: readonly FilingLedgerRow[]): FilingLedg
1457
2950
  * a refusal nobody can act on becomes a refusal everybody routes around, and
1458
2951
  * the three VERIFY-lock bypasses in `lib/issue-create-override.ts` are what
1459
2952
  * that looks like when it happens.
2953
+ *
2954
+ * **The override stanza is printed only when the label would actually waive
2955
+ * this refusal**, read from `waivableRefusal` rather than decided here. For
2956
+ * one review round it was unconditional, so an `OVER_CAP` refusal said *"no
2957
+ * label waives it"* in `overCapReason` and then closed by telling the agent
2958
+ * to re-run with the label — in the same message, four lines apart. The cap
2959
+ * holds either way, because `filingGate` reads the same predicate; what the
2960
+ * contradiction costs is the next agent, who is taught by the gate's own
2961
+ * output to reach for the override on the gate it cannot open.
2962
+ *
2963
+ * ## The two stanzas treat the label's NAME differently, on purpose
2964
+ *
2965
+ * **Unwaivable: the label is named, to deny it.** An agent that has read
2966
+ * about the override and finds silence tries it anyway, spends a round, and
2967
+ * silence is also indistinguishable from a message written before the
2968
+ * refusal became unwaivable. The sentence comes from
2969
+ * `UNWAIVABLE_REFUSALS`, so the reason given is this refusal's own.
2970
+ *
2971
+ * **Waivable: the label is NOT named, and no step is offered.** The old text
2972
+ * was a complete recipe with its own permission attached — *"If this one
2973
+ * genuinely is the exception, re-run with --label …"* — and *this one
2974
+ * genuinely is the exception* is a judgement every filing makes about
2975
+ * itself, so the condition admits everything. A refusal that supplies both
2976
+ * the verdict and the way around it is read as the way around it. The fact
2977
+ * that a waiver exists is still stated, with its cost, because an agent
2978
+ * acting on a real exception needs to know the route is recorded and
2979
+ * counted; what it no longer does is spell the token for an agent that did
2980
+ * not already have it. Naming-to-deny and naming-to-offer are different
2981
+ * acts, and only the first is worth the words (#1595, 2026-10-25).
1460
2982
  */
1461
2983
  export function refusalMessage(v: FilingAdjudication): string {
2984
+ // **The BRANCH is `waivableRefusal`, the WORDS are the map.** Reading the
2985
+ // map for both would make this a second decider over "does the label
2986
+ // waive this" — the drift FG-156 exists to catch, and the mutation that
2987
+ // forces the predicate true would stop moving this message.
2988
+ const unwaivable = waivableRefusal(v.refusal)
2989
+ ? undefined
2990
+ : v.refusal === null
2991
+ ? undefined
2992
+ : UNWAIVABLE_REFUSALS[v.refusal];
2993
+ const tail = unwaivable
2994
+ ? [
2995
+ `--label ${FILING_OVERRIDE_LABEL} does NOT waive this one. ${unwaivable}`,
2996
+ `The attempt is recorded in ${ledgerPath()} either way.`,
2997
+ ]
2998
+ : [
2999
+ "A label waives this refusal. It is deliberately not spelled here and not offered",
3000
+ "as a step: every filing believes it is the exception, so a refusal that hands over",
3001
+ "the way around itself is read as the way around itself. If you reach for it, it is",
3002
+ `recorded in ${ledgerPath()} against this run and counted later.`,
3003
+ ];
1462
3004
  return [
1463
3005
  "[FindingArbiter] This filing was adjudicated and refused before it reached the tracker.",
1464
3006
  "",
@@ -1470,9 +3012,7 @@ export function refusalMessage(v: FilingAdjudication): string {
1470
3012
  "already in; or answer it in a PR comment with a reason. A reason closes a",
1471
3013
  "finding and silence does not. Filing is the exception, not the default.",
1472
3014
  "",
1473
- `If this one genuinely is the exception, re-run with --label ${FILING_OVERRIDE_LABEL}.`,
1474
- `The override is recorded in ${ledgerPath()} beside the refusal it waived, so`,
1475
- "an override that was right is evidence and one that was wrong is countable.",
3015
+ ...tail,
1476
3016
  ].join("\n");
1477
3017
  }
1478
3018
 
@@ -1543,6 +3083,57 @@ export function unkeyedLedgerNote(): string {
1543
3083
  );
1544
3084
  }
1545
3085
 
3086
+ /**
3087
+ * The cap could not take a position in the queue, so it did not hold.
3088
+ *
3089
+ * Said out loud for the reason `unkeyedLedgerNote` is said out loud: the
3090
+ * filing proceeds, and what proceeds is a filing nothing counted. A silent
3091
+ * version of this is a cap that switches itself off whenever one file cannot
3092
+ * be written, which is the shape `.claude/rules/config-access.md` calls
3093
+ * Silent Default Substitution.
3094
+ *
3095
+ * It allows rather than refusing because this is the WRITER failing, not the
3096
+ * state being unknown — `reserveAllowance` has the two apart, and the other
3097
+ * one refuses.
3098
+ */
3099
+ export function unreservedAllowanceNote(): string {
3100
+ return (
3101
+ "[FindingArbiter] UNMEASURED allowance — this filing's intent row could NOT be appended to " +
3102
+ `${ledgerPath()}, so it took no position in this run's queue and the per-run cap of ` +
3103
+ `${FILINGS_PER_RUN} could not hold for it. The filing is REFUSED, not allowed: see ` +
3104
+ "`unreservedCapReason`. This note names the writer so an operator repairs the file rather " +
3105
+ "than the filing."
3106
+ );
3107
+ }
3108
+
3109
+ /**
3110
+ * How long a title may be on a ledger row. **An atomicity bound, not a
3111
+ * cosmetic one.**
3112
+ *
3113
+ * The whole race fix rests on appends to one file being serialised, and that
3114
+ * holds for a write small enough to reach the filesystem as one. A row large
3115
+ * enough to be split can tear, and a torn row is a reservation that took no
3116
+ * position while its writer believes it did — the one failure this design
3117
+ * has no reading for. `readLedgerRows` already treats a torn final line as
3118
+ * expected and skips it, which is exactly the silent slot loss.
3119
+ *
3120
+ * The title is the one field on the row a FILER sets and nothing else
3121
+ * bounds: `--title` takes whatever the command line carries. So it is bounded
3122
+ * here, and `ledgerTitle` is the single binding — the lookup in
3123
+ * `priorRefusalFor` joins on this field, so a title bounded when written and
3124
+ * not when read would stop matching its own prior row.
3125
+ *
3126
+ * 200 is comfortably inside any plausible single-write limit with the rest of
3127
+ * the row, and about twice the longest title on the live ledger. Do not raise
3128
+ * it without saying what makes the larger write atomic.
3129
+ */
3130
+ export const MAX_LEDGER_TITLE = 200;
3131
+
3132
+ /** A title bounded for the ledger. One binding — see `MAX_LEDGER_TITLE`. */
3133
+ export function ledgerTitle(title: string): string {
3134
+ return title.length <= MAX_LEDGER_TITLE ? title : `${title.slice(0, MAX_LEDGER_TITLE)}…`;
3135
+ }
3136
+
1546
3137
  /**
1547
3138
  * An override is a decision somebody made, so it leaves a trace.
1548
3139
  *
@@ -1596,7 +3187,8 @@ export function unreadableLedgerNote(): string {
1596
3187
  return (
1597
3188
  `[FindingArbiter] UNMEASURED prior refusals — ${ledgerPath()} exists and could not be read, ` +
1598
3189
  "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."
3190
+ "found*. The same read is the cap's state, so the filing is also refused `UNMEASURED_CAP` " +
3191
+ "rather than allowed: an unreadable ledger is not an empty one, and an allowance that cannot " +
3192
+ "be counted is not an allowance that is free."
1601
3193
  );
1602
3194
  }