rungate 0.8.1 → 0.8.2

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.
@@ -0,0 +1,605 @@
1
+ /**
2
+ * Adjudicate a `gh issue create` BEFORE it becomes an issue (#1261).
3
+ *
4
+ * ## The gap this closes
5
+ *
6
+ * `lib/finding-arbiter.ts`, `lib/finding-jury.ts` and
7
+ * `scripts/arbitrate-finding.ts` decide whether a finding is worth filing.
8
+ * All three are built and tested. Measured on `origin/main` at `3969cdae`:
9
+ * `hooks/VerifyPhaseLock.hook.ts` contained **zero** references to either
10
+ * `arbiter` or `arbitrate`, and the only mention of the CLI anywhere in the
11
+ * tree is `package.json`'s `files[]` — the line that *publishes* it. So the
12
+ * adjudicator existed and nothing on the filing path called it, which is
13
+ * #1241's defect ("a library function with no production caller is not
14
+ * shipped, however well tested") standing in front of the mechanism that is
15
+ * supposed to control the intake rate of the whole backlog.
16
+ *
17
+ * What the chokepoint gated on instead was whether the agent had typed
18
+ * `--label follow-up`. That is a test that somebody typed a string, not a
19
+ * test that a finding earned a filing, and every agent who wants to file
20
+ * learns to type it.
21
+ *
22
+ * ## Only two stages are decidable here, and that is on purpose
23
+ *
24
+ * `arbitrate` runs five stages. Three of them cannot run at a PreToolUse
25
+ * hook: there is no verifier group to convene, no PR whose changed files
26
+ * would make `Pre-existing` decidable, and no branch to scope against.
27
+ * `arbitrate` says so itself — `votes === undefined` is `UNMEASURED`, so
28
+ * calling it from here would refuse every filing for a reason that is about
29
+ * the hook and not about the finding.
30
+ *
31
+ * So this runs the two stages that ARE decidable from a command line and an
32
+ * issue list, through the arbiter's own bindings rather than new ones:
33
+ *
34
+ * | stage | question | binding | on failure |
35
+ * |---|---|---|---|
36
+ * | category | is it the kind we post at all? | `classifyCategory` + `DROPPED_CATEGORIES` | `DROPPED_CATEGORY` |
37
+ * | dedupe | is this new? | `duplicateCollisions` | `DUPLICATE` |
38
+ *
39
+ * Category first, because it is free and the dedupe costs a `gh issue list`.
40
+ * That is `arbitrate`'s own cost-order doctrine, applied to a different pair
41
+ * of instruments. It is also the pair #1261 asks for in those words — *the
42
+ * blog's mechanism is about duplicates and already-known, which is
43
+ * measurable* — and the reason there is deliberately **no severity gate and
44
+ * no worthiness score** here.
45
+ *
46
+ * ## UNMEASURED: where the issue and the lane brief disagreed, and why
47
+ *
48
+ * Stated because the two instructions this was built from point in opposite
49
+ * directions and a reader will otherwise assume one of them was missed.
50
+ *
51
+ * - #1261's body: *"Anything unreadable → allow and annotate, do not refuse:
52
+ * a broken adjudicator must not become a gag on the tracker."*
53
+ * - The lane brief: *"An arbiter that cannot run is UNMEASURED, not a pass.
54
+ * Do not fall through to allowing the filing silently. Say which state you
55
+ * are in."*
56
+ *
57
+ * They are reconcilable and the resolution is the word *silently*. The
58
+ * **decider** is fail-closed: `adjudicateFiling` never reports `ALLOW` for a
59
+ * reading it did not take — `UNMEASURED` is its own outcome value and is
60
+ * never collapsed into a pass. That is the shape of `resolveThroughLinks` in
61
+ * `lib/bash-write-guard.ts`, whose `catch` returns a distinct "cannot be
62
+ * resolved" rather than a missing one. The **policy** over that outcome is
63
+ * allow, announce it on `systemMessage`, and write the row to the ledger
64
+ * marked `UNMEASURED` so it is countable afterwards.
65
+ *
66
+ * The issue is right about the direction and the argument is worth keeping:
67
+ * this runs on a PreToolUse hook with no retry, so a fail-closed `gh issue
68
+ * list` timeout gags the tracker on a network hiccup, which is strictly worse
69
+ * than the status quo it replaces. The brief is right that a silent
70
+ * fall-through is how a guard rots. Doing both costs one extra outcome value.
71
+ *
72
+ * ## WHAT THIS DOES NOT COVER
73
+ *
74
+ * - **Anything that is not Bash.** `curl` against the REST API, the GitHub
75
+ * MCP tools and a filing from another machine never reach a PreToolUse hook
76
+ * on Bash. `lib/issue-create-override.ts` lists the rest of that boundary
77
+ * and it is unchanged here; this file adds a second question at the same
78
+ * chokepoint, not a wider one.
79
+ * - **A body passed as `--body-file` that cannot be READ** — absent,
80
+ * oversized, or stdin. The file itself is now opened and adjudicated
81
+ * (#1300); only a genuine failure to read it is `UNMEASURED`.
82
+ *
83
+ * This entry used to say that *every* `--body-file` was UNMEASURED, which
84
+ * was true, documented, and much larger than it sounds: across the last 300
85
+ * issues on this tracker, 300 have bodies over five lines and 283 exceed
86
+ * 2,000 characters, so the exempted class was in practice the whole
87
+ * population — and the gate adjudicated the short filings while waving
88
+ * through the long ones. Worth keeping as a worked instance of the second
89
+ * shape in `.claude/rules/checks-must-be-able-to-fail.md`: the limitation
90
+ * was stated plainly and still hid its own size, because nothing had
91
+ * measured how much of the input it covered. **A declared limitation is not
92
+ * a priced one.**
93
+ * - **Whether a refusal was right.** The ledger records what was adjudicated,
94
+ * not what the outcome should have been. It supplies the left-hand side of
95
+ * that join and nothing more, exactly as `CandidateRecord` says of itself.
96
+ */
97
+
98
+ import { appendFileSync, mkdirSync, readFileSync, statSync } from "fs";
99
+ import { homedir } from "os";
100
+ import { dirname, join } from "path";
101
+
102
+ import { resolveRepoSlug } from "./branch-cleanup";
103
+ import { createGitHubClient, listOpenIssues } from "./github";
104
+ import {
105
+ duplicateCollisions,
106
+ symptomHash,
107
+ symptomKeys,
108
+ UNFILED_ID,
109
+ type ArbiterRefusal,
110
+ type Finding,
111
+ type WithheldBy,
112
+ } from "./finding-arbiter";
113
+ import {
114
+ classifyCategory,
115
+ DROPPED_CATEGORIES,
116
+ type Disposition,
117
+ type FindingCategory,
118
+ } from "./finding-jury";
119
+ import { clauses, createsIssue, flagValues, labelValues } from "./issue-create-override";
120
+
121
+ /**
122
+ * The label that waives this gate.
123
+ *
124
+ * Separate from `OVERRIDE_LABELS`, which waives the VERIFY-phase lock. The
125
+ * two gates answer different questions about the same command — *should you
126
+ * be filing right now* and *is this finding worth filing* — and one label
127
+ * waiving both would make it impossible to count how often each was
128
+ * overridden, which is the measurement #1261 exists to start.
129
+ */
130
+ export const FILING_OVERRIDE_LABEL = "arbiter-override";
131
+
132
+ /** How many open issues the dedupe compares against. */
133
+ export const OPEN_ISSUE_LIMIT = 100;
134
+
135
+ /**
136
+ * The largest `--body-file` this will read (#1300).
137
+ *
138
+ * A bound and not a guess: the longest issue body on this tracker across its
139
+ * last 300 is a few thousand characters, so 256 KiB is two orders of
140
+ * magnitude of headroom and still refuses to pull an arbitrary file into the
141
+ * hook. Over it is UNMEASURED, which allows — the cap can cost a dedupe, it
142
+ * can never cost a filing.
143
+ */
144
+ export const MAX_BODY_FILE_BYTES = 256 * 1024;
145
+
146
+ /** One `gh issue create` clause, as much of it as the two stages read. */
147
+ export interface FilingAttempt {
148
+ title: string;
149
+ body: string;
150
+ labels: string[];
151
+ /**
152
+ * The path given to `--body-file` / `-F`, or `null` when the body is
153
+ * inline. `"-"` is stdin and is not a path.
154
+ *
155
+ * The PATH and not a boolean (#1300): a flag saying only *that* the body is
156
+ * elsewhere is enough to declare the filing unreadable and not enough to
157
+ * read it, which is how the dedupe came to skip the filings most worth
158
+ * deduplicating.
159
+ */
160
+ bodyFile: string | null;
161
+ }
162
+
163
+ /**
164
+ * ALLOW and REFUSE are decisions. UNMEASURED is neither, and it is a value of
165
+ * its own so that no caller can mistake it for the first one.
166
+ */
167
+ export type FilingOutcome = "ALLOW" | "REFUSE" | "UNMEASURED";
168
+
169
+ export interface FilingAdjudication {
170
+ outcome: FilingOutcome;
171
+ refusal: ArbiterRefusal | null;
172
+ /** Why, in words a reader can act on without re-running anything. */
173
+ reason: string;
174
+ category: FindingCategory;
175
+ duplicateOf: string[];
176
+ collidingKeys: string[];
177
+ symptomHash: string;
178
+ }
179
+
180
+ /**
181
+ * One adjudication, in the field names `CandidateRecord` already uses.
182
+ *
183
+ * Deliberately a superset of that interface rather than a new vocabulary:
184
+ * `arbitrateBatch` writes `CandidateRecord` rows for findings it considered
185
+ * inside a review round, this writes rows for findings somebody tried to
186
+ * file, and the whole value of either is the population they form together.
187
+ * A second set of names for `category` / `refusal` / `withheldBy` would make
188
+ * that union a join nobody can write.
189
+ *
190
+ * `severity` and `jury` are always `null` here and are present anyway, so the
191
+ * two row shapes parse under one reader. A chokepoint has no verifier group,
192
+ * and an absent vote is not a severity of `Important`.
193
+ */
194
+ export interface FilingLedgerRow {
195
+ at: string;
196
+ id: string;
197
+ title: string;
198
+ symptomHash: string;
199
+ category: FindingCategory;
200
+ severity: null;
201
+ disposition: Disposition;
202
+ refusal: ArbiterRefusal | null;
203
+ /** Did it reach the tracker? */
204
+ emitted: boolean;
205
+ withheldBy: WithheldBy | null;
206
+ jury: null;
207
+ duplicateOf: string[];
208
+ /** The refusal was overridden with `--label arbiter-override`. */
209
+ overridden: boolean;
210
+ }
211
+
212
+ /**
213
+ * The three flags this gate reads, through the same arity walk the VERIFY
214
+ * lock uses. None is comma-separated: `gh` splits a `--label` list on commas
215
+ * and a title containing one is still a title.
216
+ */
217
+ const TITLE_FLAG = { long: "--title", short: "-t" };
218
+ const BODY_FLAG = { long: "--body", short: "-b" };
219
+ const BODY_FILE_FLAG = { long: "--body-file", short: "-F" };
220
+
221
+ /**
222
+ * Every `gh issue create` in this command, one entry per clause.
223
+ *
224
+ * Per clause and not per command, for the reason `verifyPhaseRefusal` is:
225
+ * `gh issue comment … && gh issue create …` is a create, and a reading over
226
+ * the whole string lets the first half excuse the second.
227
+ */
228
+ export function filingAttempts(cmd: string): FilingAttempt[] {
229
+ return clauses(cmd)
230
+ .filter(createsIssue)
231
+ .map(tokens => {
232
+ const bodyFile = flagValues(tokens, BODY_FILE_FLAG);
233
+ return {
234
+ title: flagValues(tokens, TITLE_FLAG).join(" "),
235
+ body: flagValues(tokens, BODY_FLAG).join("\n"),
236
+ labels: labelValues(tokens),
237
+ // The LAST one, matching `gh`: a repeated flag overrides.
238
+ bodyFile: bodyFile.at(-1) ?? null,
239
+ };
240
+ });
241
+ }
242
+
243
+ /**
244
+ * A `--body-file`, or `null` when it could not be read (#1300).
245
+ *
246
+ * `null` for every failure, and the failures are not told apart on purpose:
247
+ * absent, unreadable, a directory, oversized and stdin all mean the same
248
+ * thing to the caller — nobody read the symptom — and all of them ALLOW. The
249
+ * one distinction that matters here is read / not-read, and an empty file is
250
+ * READ: it returns `""`, which yields no symptom keys and lands on the
251
+ * existing "names no symbol" arm rather than on this one.
252
+ *
253
+ * `"-"` is stdin. `gh` accepts it and there is nothing on disk to open, so it
254
+ * stays unreadable exactly as before.
255
+ *
256
+ * The path comes from a command the agent is about to run anyway, so reading
257
+ * it grants this hook no reach it did not already have.
258
+ */
259
+ export function readBodyFile(path: string, limit: number = MAX_BODY_FILE_BYTES): string | null {
260
+ if (path === "-" || path.trim() === "") return null;
261
+ try {
262
+ if (statSync(path).size > limit) return null;
263
+ return readFileSync(path, "utf-8");
264
+ } catch {
265
+ return null;
266
+ }
267
+ }
268
+
269
+ /**
270
+ * The single place that decides whether a filing may proceed.
271
+ *
272
+ * `readExisting` is a thunk and not a value so the `gh issue list` is never
273
+ * paid for a finding the category stage already drops. It returns `null` for
274
+ * "could not be read", which is a different fact from an empty tracker — the
275
+ * distinction `.claude/rules/config-access.md` makes about a corrupt config,
276
+ * applied to the one input this gate cannot produce itself.
277
+ */
278
+ export async function adjudicateFiling(
279
+ attempt: FilingAttempt,
280
+ readExisting: () => Promise<readonly Finding[] | null>,
281
+ readBody: (path: string) => string | null = readBodyFile,
282
+ ): Promise<FilingAdjudication> {
283
+ // ── where is the body? ──
284
+ //
285
+ // Resolved before anything reads it, because every stage below wants the
286
+ // real one. `null` means "there is a file and it could not be read", which
287
+ // is UNMEASURED further down — distinct from an inline body, and never
288
+ // collapsed into an empty one.
289
+ //
290
+ // This read happens before the category stage, which inverts the
291
+ // cost-ordering doctrine one paragraph up. Deliberate, and the costs are
292
+ // not comparable: this is one bounded local `readFileSync`, the thing that
293
+ // doctrine protects is a network round trip to the GitHub API. Paying it
294
+ // first buys the category stage the body it classifies on.
295
+ const body = attempt.bodyFile === null ? attempt.body : readBody(attempt.bodyFile);
296
+ const finding: Finding = { id: UNFILED_ID, title: attempt.title, body: body ?? attempt.body };
297
+ const category = classifyCategory(finding);
298
+ const base = {
299
+ category,
300
+ symptomHash: symptomHash(finding),
301
+ duplicateOf: [] as string[],
302
+ collidingKeys: [] as string[],
303
+ };
304
+
305
+ // ── is it the kind we post at all? ──
306
+ if (DROPPED_CATEGORIES.has(category)) {
307
+ return {
308
+ ...base,
309
+ outcome: "REFUSE",
310
+ refusal: "DROPPED_CATEGORY",
311
+ reason:
312
+ `the title reads as a ${category} finding, and ${category} findings are ` +
313
+ `dropped outright: they cost a review round and change no behaviour`,
314
+ };
315
+ }
316
+
317
+ // ── can the symptom be read out of this command at all? ──
318
+ //
319
+ // Two UNMEASURED arms, and they are separate because they are separate
320
+ // facts. The first cut asked `title.trim() === "" || keys.length === 0`,
321
+ // which the AI review on #1282 caught: a filing with a blank `--title` and
322
+ // a full `--body` HAS a readable symptom, so that disjunct skipped the
323
+ // dedupe on an input it could have adjudicated — and then printed "names no
324
+ // symbol, no file and no reading" about a body naming all three. A reason
325
+ // that is false for the input it was emitted on is worse than no reason.
326
+ //
327
+ // The title is read by `classifyCategory` above and nowhere here, so a
328
+ // blank one costs the category stage its input and costs the dedupe
329
+ // nothing: `symptomKeys` contributes title symbols and paths but no
330
+ // quantities, so a title is never what makes a pair a duplicate anyway.
331
+ //
332
+ // The body-file arm NARROWED rather than disappeared (#1300). It used to
333
+ // fire on every `--body-file`, which measured against this tracker is
334
+ // essentially every real filing — a detector narrower than what it
335
+ // detects, and narrowed in the worst direction, since the findings that
336
+ // need a file are the long detailed ones. It now fires only when the file
337
+ // genuinely could not be read.
338
+ if (body === null) {
339
+ return {
340
+ ...base,
341
+ outcome: "UNMEASURED",
342
+ refusal: "UNMEASURED",
343
+ reason:
344
+ `the body file \`${attempt.bodyFile}\` could not be read (absent, unreadable, ` +
345
+ `stdin, or over ${MAX_BODY_FILE_BYTES} bytes), so there was nothing to deduplicate on`,
346
+ };
347
+ }
348
+ if (symptomKeys(finding).length === 0) {
349
+ return {
350
+ ...base,
351
+ outcome: "UNMEASURED",
352
+ refusal: "UNMEASURED",
353
+ reason: "the filing names no symbol, no file and no reading, so there is nothing to deduplicate it on",
354
+ };
355
+ }
356
+
357
+ // ── is this new? ──
358
+ const existing = await readExisting();
359
+ if (existing === null) {
360
+ return {
361
+ ...base,
362
+ outcome: "UNMEASURED",
363
+ refusal: "UNMEASURED",
364
+ reason: "the open-issue set could not be read, so whether this symptom is already filed was never asked",
365
+ };
366
+ }
367
+ const collisions = duplicateCollisions(finding, existing);
368
+ if (collisions.length > 0) {
369
+ return {
370
+ ...base,
371
+ outcome: "REFUSE",
372
+ refusal: "DUPLICATE",
373
+ duplicateOf: collisions.map(c => c.id),
374
+ collidingKeys: collisions[0].keys,
375
+ reason:
376
+ `the symptom is already reported as ${collisions.map(c => `#${c.id}`).join(", ")} — ` +
377
+ `shared ${collisions[0].keys.length} key(s): ${collisions[0].keys.slice(0, 6).join(", ")}`,
378
+ };
379
+ }
380
+
381
+ return {
382
+ ...base,
383
+ outcome: "ALLOW",
384
+ refusal: null,
385
+ reason: `no open issue shares this symptom, and ${category} is not a dropped category`,
386
+ };
387
+ }
388
+
389
+ /**
390
+ * The open issues, as findings — or `null` when the set could not be read.
391
+ *
392
+ * `null` and `[]` are different facts and the caller treats them differently:
393
+ * an empty tracker means nothing is a duplicate, an unreadable one means
394
+ * nobody asked. Every failure path here returns `null` rather than `[]`, so a
395
+ * `gh` that is missing, unauthenticated, rate-limited, slow or returning
396
+ * something unexpected cannot be mistaken for a clean tracker.
397
+ *
398
+ * **Through Octokit and never the GitHub CLI.** `lib/`, `hooks/` and `gates/`
399
+ * may not reach `gh` as a subprocess — GITHUB-API-MIGRATION-SPEC.md's SC-893,
400
+ * enforced by a ratchet in `test/ticked-sc-cover.test.ts` whose known-offender
401
+ * list #395 emptied and which refuses in both directions. The first cut of
402
+ * this file shelled out and CI caught it. The architectural reason is the one
403
+ * `getIssueLabels` records: a hook runs in whatever environment the session
404
+ * has, and a subprocess needs the CLI installed and authenticated there.
405
+ *
406
+ * **The cost, stated because it decides what this gate does on a dev box:**
407
+ * `createGitHubClient` needs `GITHUB_TOKEN` or `GH_TOKEN`, and a developer's
408
+ * GitHub credential usually lives in the CLI's keyring and not in the
409
+ * environment. With no token this returns `null`, the dedupe is UNMEASURED,
410
+ * and only the category stage runs. That is visible rather than silent — the
411
+ * ledger row says `UNMEASURED` and the agent is told — and it is the honest
412
+ * reading: nobody asked the tracker. Export a token, or supply the set below.
413
+ *
414
+ * `RUNGATE_OPEN_FINDINGS` names a JSON file to read instead of calling the
415
+ * API. It is a production seam and not a test hook — a consumer on a
416
+ * non-GitHub tracker, an agent working offline, or a session with no token
417
+ * has no other way to supply the comparison set. Pointing it at an empty
418
+ * array switches the dedupe off, and that is the direction this gate is
419
+ * allowed to be wrong in: the result is a duplicate reaching the tracker,
420
+ * never a real finding silenced.
421
+ */
422
+ export async function openFindings(projectRoot: string): Promise<readonly Finding[] | null> {
423
+ const override = process.env.RUNGATE_OPEN_FINDINGS;
424
+ if (override !== undefined && override !== "") {
425
+ try {
426
+ return asFindings(JSON.parse(readFileSync(override, "utf-8")));
427
+ } catch {
428
+ return null;
429
+ }
430
+ }
431
+ try {
432
+ const { slug } = resolveRepoSlug({ projectRoot });
433
+ if (slug === null) return null;
434
+ const issues = await listOpenIssues(createGitHubClient(), slug, OPEN_ISSUE_LIMIT);
435
+ return issues.map(i => ({ id: String(i.number), title: i.title, body: i.body }));
436
+ } catch {
437
+ // Every failure lands here as `null`, which is "nobody asked" and not
438
+ // "nothing matched" — a missing token, a 403, a rate limit and an
439
+ // unreachable API are all states this must not report as a clean tracker.
440
+ return null;
441
+ }
442
+ }
443
+
444
+ /** Supplied rows as `Finding`s, or `null` if the shape is not what we asked for. */
445
+ function asFindings(parsed: unknown): readonly Finding[] | null {
446
+ if (!Array.isArray(parsed)) return null;
447
+ const out: Finding[] = [];
448
+ for (const row of parsed) {
449
+ if (row === null || typeof row !== "object") return null;
450
+ const r = row as Record<string, unknown>;
451
+ const id = r.number ?? r.id;
452
+ if (typeof id !== "number" && typeof id !== "string") return null;
453
+ if (typeof r.title !== "string") return null;
454
+ out.push({ id: String(id), title: r.title, body: typeof r.body === "string" ? r.body : "" });
455
+ }
456
+ return out;
457
+ }
458
+
459
+ /** Where the adjudications land. One line of JSON per decision. */
460
+ export function ledgerPath(): string {
461
+ const explicit = process.env.RUNGATE_FINDING_LEDGER;
462
+ if (explicit !== undefined && explicit !== "") return explicit;
463
+ const work = process.env.RUNGATE_WORK_DIR || process.env.PAI_WORK_DIR || join(homedir(), ".rungate");
464
+ return join(work, "finding-ledger.jsonl");
465
+ }
466
+
467
+ /**
468
+ * Append one row. Returns whether it landed.
469
+ *
470
+ * **A ledger that cannot be written must not refuse a filing.** The record
471
+ * exists to measure the gate, and a measurement apparatus that blocks the
472
+ * thing it measures is worse than no measurement — so this reports its own
473
+ * failure to the caller rather than throwing into the hook, and the caller
474
+ * says so on `systemMessage`. That is the same split as the UNMEASURED policy
475
+ * in this file's header: the writer is honest about failing, the policy over
476
+ * that failure is to proceed loudly.
477
+ */
478
+ export function recordAdjudication(row: FilingLedgerRow, path: string = ledgerPath()): boolean {
479
+ try {
480
+ mkdirSync(dirname(path), { recursive: true });
481
+ appendFileSync(path, `${JSON.stringify(row)}\n`, "utf-8");
482
+ return true;
483
+ } catch {
484
+ return false;
485
+ }
486
+ }
487
+
488
+ export interface FilingGateReading {
489
+ /** The block reason, or `null` to allow. */
490
+ refusal: string | null;
491
+ /** Something the agent should see even though nothing was blocked. */
492
+ note: string | null;
493
+ /** One row per `gh issue create` clause, in clause order. */
494
+ rows: FilingLedgerRow[];
495
+ }
496
+
497
+ /** Nothing here created an issue, so there is nothing to adjudicate. */
498
+ const NO_FILING: FilingGateReading = { refusal: null, note: null, rows: [] };
499
+
500
+ /**
501
+ * Adjudicate every filing in one Bash command.
502
+ *
503
+ * One exported entry so `hooks/VerifyPhaseLock.hook.ts` stays a trigger and
504
+ * the decision stays in `lib/` (#365, HOOK-ARCHITECTURE-SPEC).
505
+ */
506
+ export async function filingGate(
507
+ cmd: string,
508
+ options: {
509
+ projectRoot: string;
510
+ now?: string;
511
+ readExisting?: (projectRoot: string) => Promise<readonly Finding[] | null>;
512
+ },
513
+ ): Promise<FilingGateReading> {
514
+ const attempts = filingAttempts(cmd);
515
+ if (attempts.length === 0) return NO_FILING;
516
+
517
+ const at = options.now ?? new Date().toISOString();
518
+ const read = options.readExisting ?? openFindings;
519
+ // Read once per command, not once per clause: two creates in one command
520
+ // adjudicated against two different snapshots is a reading nobody can act
521
+ // on. The PROMISE is cached rather than its value, so two clauses cannot
522
+ // both start a request before either has resolved.
523
+ let cached: Promise<readonly Finding[] | null> | undefined;
524
+ const readExisting = () => (cached ??= read(options.projectRoot));
525
+
526
+ const rows: FilingLedgerRow[] = [];
527
+ const refusals: string[] = [];
528
+ const notes: string[] = [];
529
+
530
+ for (const attempt of attempts) {
531
+ const verdict = await adjudicateFiling(attempt, readExisting);
532
+ const overridden = verdict.outcome === "REFUSE" && attempt.labels.includes(FILING_OVERRIDE_LABEL);
533
+ const emitted = verdict.outcome !== "REFUSE" || overridden;
534
+
535
+ rows.push({
536
+ at,
537
+ id: UNFILED_ID,
538
+ title: attempt.title,
539
+ symptomHash: verdict.symptomHash,
540
+ category: verdict.category,
541
+ severity: null,
542
+ disposition: emitted ? "ISSUE" : "DROP",
543
+ refusal: verdict.refusal,
544
+ emitted,
545
+ withheldBy: emitted ? null : verdict.refusal,
546
+ jury: null,
547
+ duplicateOf: verdict.duplicateOf,
548
+ overridden,
549
+ });
550
+
551
+ if (verdict.outcome === "REFUSE" && !overridden) refusals.push(refusalMessage(verdict));
552
+ if (verdict.outcome === "UNMEASURED") notes.push(unmeasuredNote(verdict));
553
+ if (overridden) notes.push(overrideNote(verdict));
554
+ }
555
+
556
+ return {
557
+ refusal: refusals.length > 0 ? refusals.join("\n\n") : null,
558
+ note: notes.length > 0 ? notes.join("\n\n") : null,
559
+ rows,
560
+ };
561
+ }
562
+
563
+ /**
564
+ * The refusal an agent reads.
565
+ *
566
+ * It names the category, the signal that matched, and the override — because
567
+ * a refusal nobody can act on becomes a refusal everybody routes around, and
568
+ * the three VERIFY-lock bypasses in `lib/issue-create-override.ts` are what
569
+ * that looks like when it happens.
570
+ */
571
+ export function refusalMessage(v: FilingAdjudication): string {
572
+ return [
573
+ "[FindingArbiter] This filing was adjudicated and refused before it reached the tracker.",
574
+ "",
575
+ ` refusal: ${v.refusal}`,
576
+ ` category: ${v.category}`,
577
+ ` why: ${v.reason}`,
578
+ "",
579
+ "Resolve it where the finding is, in this order: fix it in the PR you are",
580
+ "already in; or answer it in a PR comment with a reason. A reason closes a",
581
+ "finding and silence does not. Filing is the exception, not the default.",
582
+ "",
583
+ `If this one genuinely is the exception, re-run with --label ${FILING_OVERRIDE_LABEL}.`,
584
+ `The override is recorded in ${ledgerPath()} beside the refusal it waived, so`,
585
+ "an override that was right is evidence and one that was wrong is countable.",
586
+ ].join("\n");
587
+ }
588
+
589
+ /** Said out loud, because an UNMEASURED that nobody sees is a silent pass. */
590
+ export function unmeasuredNote(v: FilingAdjudication): string {
591
+ return (
592
+ `[FindingArbiter] UNMEASURED — this filing was NOT adjudicated: ${v.reason}. ` +
593
+ "It is allowed through, because a broken adjudicator must not become a gag on " +
594
+ `the tracker, and the row is recorded in ${ledgerPath()} as UNMEASURED rather ` +
595
+ "than as a finding that passed. Those are different states."
596
+ );
597
+ }
598
+
599
+ /** An override is a decision somebody made, so it leaves a trace. */
600
+ export function overrideNote(v: FilingAdjudication): string {
601
+ return (
602
+ `[FindingArbiter] Allowed by --label ${FILING_OVERRIDE_LABEL}, over a ${v.refusal} ` +
603
+ `refusal: ${v.reason}. Recorded in ${ledgerPath()}.`
604
+ );
605
+ }