rungate 0.8.13 → 0.8.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/README.md +182 -0
  2. package/gates/.gate-salt +1 -1
  3. package/hooks/HarnessAFKGate.hook.ts +5 -1
  4. package/hooks/HookCurrency.hook.ts +11 -8
  5. package/hooks/MergeGuard.hook.ts +7 -1
  6. package/hooks/StaleTTLCleanup.hook.ts +4 -4
  7. package/hooks/VerifyPhaseLock.hook.ts +3 -3
  8. package/hooks/lib/findWorkflow.ts +3 -2
  9. package/hooks/lib/paths.ts +14 -2
  10. package/hooks/lib/utils.ts +23 -3
  11. package/lib/active-milestone.ts +50 -0
  12. package/lib/ai-review-rounds.ts +99 -0
  13. package/lib/ai-review-suppression.ts +200 -21
  14. package/lib/bash-write-guard.ts +397 -23
  15. package/lib/board-flow.ts +280 -0
  16. package/lib/board-lane-health.ts +578 -0
  17. package/lib/board-mirror.ts +136 -39
  18. package/lib/board-ready-fanout.ts +297 -14
  19. package/lib/board-ready-rule.ts +1211 -0
  20. package/lib/board-throughput.ts +136 -0
  21. package/lib/board-walkthrough.ts +240 -0
  22. package/lib/body-evidence.ts +203 -0
  23. package/lib/branch-protection.ts +399 -9
  24. package/lib/bun-version.ts +36 -0
  25. package/lib/cli-commands.ts +75 -4
  26. package/lib/closing-reference-audit.ts +307 -6
  27. package/lib/config-loader.ts +254 -25
  28. package/lib/config-readers.ts +170 -10
  29. package/lib/config-trackable.ts +96 -57
  30. package/lib/conformity.ts +121 -7
  31. package/lib/create-sc.ts +25 -2
  32. package/lib/derived-spec.ts +21 -9
  33. package/lib/filing-compliance.ts +367 -0
  34. package/lib/filing-plan.ts +47 -21
  35. package/lib/finding-arbiter.ts +79 -5
  36. package/lib/finding-jury.ts +43 -4
  37. package/lib/finding-promotion.ts +1123 -0
  38. package/lib/generators/agents-md.ts +149 -0
  39. package/lib/git-isolation.ts +137 -1
  40. package/lib/github-api-base.ts +66 -0
  41. package/lib/github.ts +194 -9
  42. package/lib/graphql-cursor.ts +80 -0
  43. package/lib/hook-scopes.ts +78 -0
  44. package/lib/issue-create-override.ts +415 -3
  45. package/lib/issue-decomposition.ts +124 -7
  46. package/lib/issue-extraction.ts +9 -7
  47. package/lib/issue-file-overlap.ts +373 -0
  48. package/lib/issue-filing-gate.ts +1109 -52
  49. package/lib/issue-repair.ts +90 -9
  50. package/lib/issue-shape.ts +199 -0
  51. package/lib/live-issues.ts +31 -2
  52. package/lib/local-work.ts +423 -0
  53. package/lib/markdown-fence.ts +134 -0
  54. package/lib/milestone-title.ts +46 -0
  55. package/lib/scaffold/ai-review-findings.ts +148 -3
  56. package/lib/scaffold/ai-review-step.ts +65 -5
  57. package/lib/scaffold/ai-review-unmeasured-workflow.ts +3 -0
  58. package/lib/scaffold/steps.ts +115 -9
  59. package/lib/source-census.ts +108 -0
  60. package/lib/spec-deps.ts +55 -11
  61. package/lib/spec-placement.ts +203 -13
  62. package/lib/spec-registry.ts +75 -16
  63. package/lib/spec-source.ts +609 -0
  64. package/lib/spec-write-sweep.ts +4 -0
  65. package/lib/stage-ladder.ts +896 -3
  66. package/lib/state-claim-readings.ts +252 -0
  67. package/lib/success-doc.ts +7 -6
  68. package/lib/test-command-positions.ts +135 -1
  69. package/lib/work-status.ts +551 -0
  70. package/lib/worktree-repo.ts +14 -2
  71. package/package.json +7 -1
  72. package/scripts/ai-review-findings.ts +8 -13
  73. package/scripts/ai-review-threads.ts +16 -17
  74. package/scripts/audit-closing-references.ts +330 -0
  75. package/scripts/audit-specs.ts +59 -103
  76. package/scripts/board-conformance.ts +747 -40
  77. package/scripts/board-mirror.ts +594 -13
  78. package/scripts/board-ready.ts +979 -0
  79. package/scripts/board-snapshot.ts +464 -12
  80. package/scripts/claim-files.ts +578 -0
  81. package/scripts/criterion-inventory.ts +526 -50
  82. package/scripts/finding-promotion.ts +547 -0
  83. package/scripts/generate-code-map.ts +1 -1
  84. package/scripts/plan-issues.ts +279 -40
  85. package/scripts/plan-spec.ts +105 -3
  86. package/scripts/sync-sc-status.ts +147 -7
  87. package/scripts/worktree-census.ts +958 -0
  88. package/scripts/worktree-sweep.ts +269 -0
@@ -0,0 +1,80 @@
1
+ /**
2
+ * One decider for "is there another page, and what is its cursor".
3
+ *
4
+ * Covers SC-2720, SC-2721 (specs/BOARD-FLOW-SPEC.md).
5
+ *
6
+ * ## Why this is a module and not four `if`s
7
+ *
8
+ * Every GraphQL pager in this repository spelled the same line:
9
+ *
10
+ * ```ts
11
+ * c = page.pageInfo.hasNextPage ? page.pageInfo.endCursor : null;
12
+ * ```
13
+ *
14
+ * and every one of them **ends the loop and returns a confident partial
15
+ * reading** for three different malformed pages: a `pageInfo` that is
16
+ * absent, one that exists without `hasNextPage`, and one whose `endCursor`
17
+ * is `""`. The last is the nastiest — an empty string passes a `typeof`
18
+ * check and is then falsy, so a guard that looks correct lets it through.
19
+ *
20
+ * All three were found on `lib/board-throughput.ts` across two pull
21
+ * requests, one variant at a time, and the third was found with the
22
+ * correct spelling already sitting in `scripts/board-status-sweep.ts`.
23
+ * Fixing them one site at a time is the defect that keeps producing the
24
+ * defect: `.claude/rules/checks-must-be-able-to-fail.md` calls a
25
+ * behavioural suite over N copies "catches only the last one to regress".
26
+ *
27
+ * So the property is asserted across the sites rather than repaired at
28
+ * them. One binding, one mutation, every pager.
29
+ *
30
+ * ## A truncation is UNMEASURED, and that is not the same as an error
31
+ *
32
+ * The caller decides what to do — refuse the run, mark a row, throw — but
33
+ * it may not decide that a page it could not read was the last one. That
34
+ * distinction is the whole point and it is why `done` and `unreadable` are
35
+ * separate cases rather than one nullable cursor.
36
+ */
37
+
38
+ export type CursorReading =
39
+ /** There is another page, and this is a cursor that can fetch it. */
40
+ | { readonly kind: "more"; readonly cursor: string }
41
+ /** That was the last page. The reading is complete. */
42
+ | { readonly kind: "done" }
43
+ /** The page could not say. **Never treat this as `done`.** */
44
+ | { readonly kind: "unreadable"; readonly why: string };
45
+
46
+ /**
47
+ * Read a connection's `pageInfo`.
48
+ *
49
+ * Takes `unknown` on purpose: every caller is handing over a value parsed
50
+ * from a network response, and typing the parameter as a well-formed
51
+ * `pageInfo` would make the compiler assert exactly the property this
52
+ * function exists to check.
53
+ */
54
+ export function nextCursor(pageInfo: unknown): CursorReading {
55
+ if (typeof pageInfo !== "object" || pageInfo === null) {
56
+ return {
57
+ kind: "unreadable",
58
+ why: "the page carried no pageInfo, so whether more pages exist is unknown",
59
+ };
60
+ }
61
+ const info = pageInfo as { hasNextPage?: unknown; endCursor?: unknown };
62
+ if (typeof info.hasNextPage !== "boolean") {
63
+ return {
64
+ kind: "unreadable",
65
+ why: `pageInfo.hasNextPage is ${typeof info.hasNextPage}, not a boolean, so "no more pages" cannot be read from it`,
66
+ };
67
+ }
68
+ if (!info.hasNextPage) return { kind: "done" };
69
+ // **Non-empty, not merely a string.** `""` is a string and is falsy, so
70
+ // a `typeof` check passes it and `while (cursor)` then ends the loop —
71
+ // a guard that reads correctly and admits the exact value it was
72
+ // written to exclude. ai-review round 1 of #1794.
73
+ if (typeof info.endCursor !== "string" || info.endCursor.length === 0) {
74
+ return {
75
+ kind: "unreadable",
76
+ why: "the page says more exist and gave no usable endCursor, so the rest cannot be fetched",
77
+ };
78
+ }
79
+ return { kind: "more", cursor: info.endCursor };
80
+ }
@@ -376,6 +376,84 @@ export function unplacedHooks(input: {
376
376
  });
377
377
  }
378
378
 
379
+ /**
380
+ * A registry description that says its hook is not live (#1986).
381
+ *
382
+ * Prose, and that is the honest limit of this check: the registry carries no
383
+ * structured liveness field, so the claim it can compare is the one a person
384
+ * wrote. `TopLevelCdGuard`'s entry said "this hook is NOT LIVE" for weeks
385
+ * while `~/.claude/settings.json` registered it and it refused commands.
386
+ */
387
+ export const NOT_LIVE_CLAIM = /\bnot live\b/i;
388
+
389
+ /**
390
+ * Registry entries whose NOT LIVE claim the machine's registration contradicts,
391
+ * as lines a person reads at session start (#1986).
392
+ *
393
+ * The verdict is `hookRegistration`'s, not a second one. The registry scope is
394
+ * emptied first, because every registry entry carries its own command and a
395
+ * session does not load hooks from the registry: counted, it would make every
396
+ * NOT LIVE claim disagree with itself. With that scope empty, `registered`
397
+ * means a settings file a session loads names the hook — a disagreement;
398
+ * `unmeasured` means a machine scope could not be read — said as UNMEASURED,
399
+ * which is every CI runner; `unregistered` agrees with the claim, and is
400
+ * silent.
401
+ */
402
+ export function liveClaimLines(
403
+ entries: readonly { name?: unknown; description?: unknown }[],
404
+ readings: ScopeReading[],
405
+ ): string[] {
406
+ assertEveryScopeRead(readings);
407
+ const loaded = readings.map(r =>
408
+ r.scope === "repo-registry" ? { scope: r.scope, commands: [] as string[] } : r,
409
+ );
410
+ const lines: string[] = [];
411
+ for (const e of entries) {
412
+ if (typeof e.name !== "string" || typeof e.description !== "string") continue;
413
+ if (!NOT_LIVE_CLAIM.test(e.description)) continue;
414
+ const r = hookRegistration(e.name, loaded);
415
+ if (r.verdict === "registered") {
416
+ lines.push(
417
+ `Hook registry DISAGREES: ${e.name} is described as not live in .claude/rungate/hooks.json, ` +
418
+ `but ${r.registeredIn.join(", ")} registers it — correct the entry (#1986)`,
419
+ );
420
+ } else if (r.verdict === "unmeasured") {
421
+ lines.push(
422
+ `Hook registry UNMEASURED: ${e.name} is described as not live, and ${r.unreadable.join(", ")} ` +
423
+ `could not be read to check that claim (#1986)`,
424
+ );
425
+ }
426
+ }
427
+ return lines;
428
+ }
429
+
430
+ /**
431
+ * `liveClaimLines` over a fresh reading, as its own reading (#1986).
432
+ *
433
+ * It catches its own failure and says UNMEASURED, so a caller that runs it
434
+ * beside another reading cannot have one throw silence the other — review of
435
+ * #2026 found it first sharing `HookCurrency`'s tree-currency `catch`, where a
436
+ * git failure there would have dropped this comparison and been reported as
437
+ * the other reading's error.
438
+ */
439
+ export function liveClaimReport(input: {
440
+ repoRoot: string;
441
+ home: string;
442
+ readFile: (path: string) => string | null;
443
+ registry: readonly unknown[];
444
+ registryCommands: string[];
445
+ }): string[] {
446
+ try {
447
+ const scopes = readRegistrationScopes(input.repoRoot, input.home, input.readFile, input.registryCommands);
448
+ return liveClaimLines(input.registry as { name?: unknown; description?: unknown }[], scopes);
449
+ } catch (e) {
450
+ return [
451
+ `Hook registry UNMEASURED: NOT LIVE claims could not be compared — ` +
452
+ `${e instanceof Error ? e.message : String(e)} (#1986)`,
453
+ ];
454
+ }
455
+ }
456
+
379
457
  /** The same verdict for a list of hooks, over one reading. */
380
458
  export function registrationCensus(
381
459
  hooks: string[],
@@ -1,3 +1,6 @@
1
+ import { homedir } from "os";
2
+ import { join, resolve } from "path";
3
+
1
4
  import { interpreterPrograms, stripHeredocs } from "./bash-write-guard";
2
5
 
3
6
  /**
@@ -259,7 +262,160 @@ export function clauses(cmd: string, depth = 0): string[][] {
259
262
  * is worse than either position.
260
263
  */
261
264
  function heredocView(cmd: string): string {
262
- return [stripHeredocs(cmd), ...interpreterPrograms(cmd).map(p => p.program)].join("\n");
265
+ // `blankComments: false` (#1741). The blanking is #1176's write-guard
266
+ // safety measure and this parser never wanted it: it deleted every `##`
267
+ // markdown heading from a multi-line `gh issue create --body "…"`, so the
268
+ // dedupe and the symptom scan read bodies with holes. `tokenize` below
269
+ // implements the shell's comment rule for this side of the fence, where a
270
+ // wrong answer costs a misparsed flag rather than an unseen write.
271
+ return [
272
+ stripHeredocs(cmd, false),
273
+ ...interpreterPrograms(cmd).map(p => p.program),
274
+ ].join("\n");
275
+ }
276
+
277
+ /**
278
+ * The directory the first `gh issue create` in this command runs in (#1833).
279
+ *
280
+ * **An issue is a repository object, so nothing about a filing may depend on
281
+ * the session that happened to type it.** The gate used to hand every stage
282
+ * `process.cwd()` — the directory the HOOK was spawned in, which is the
283
+ * session's launch directory and not the command's. Measured 2026-11-06: one
284
+ * `gh issue create` run in `rg-wt-1675` was attributed to `rg-wt-threads2`,
285
+ * named a branch the command never touched, and reported a 735-byte
286
+ * `--body-file` as unreadable because it looked for it in the other checkout.
287
+ *
288
+ * **The directory is IN the command, and that is not a coincidence.** This
289
+ * repository forbids a top-level `cd` (`hooks/TopLevelCdGuard.hook.ts`), so
290
+ * every command that runs somewhere other than the session's directory
291
+ * spells that directory out — `(cd <path> && …)`. There is nowhere else to
292
+ * read it from: the hook payload carries the SESSION's directory, which is
293
+ * the value that was already wrong.
294
+ *
295
+ * **Subshell-aware, because the shell is.** A `cd` inside `( … )` or a
296
+ * backtick pair is undone when that scope closes, so
297
+ * `(cd /a && echo) && gh issue create` files from `from` and not from `/a`.
298
+ * `entered` is that stack. A backtick is a TOGGLE and not an opener —
299
+ * backticks do not nest, so the second one pops the scope the first pushed.
300
+ * Pushing on both was the first spelling of this, and it leaked a
301
+ * command-substitution's `cd` into everything after the closing backtick.
302
+ *
303
+ * **It descends into `-c` and `eval` arguments, exactly where `clauses()`
304
+ * does and for the same reason.** `bash -c "cd /wt/a && gh issue create …"`
305
+ * is a filing — `createsIssue` sees it through that recursion — so a reader
306
+ * of the top-level token stream alone would detect the filing and attribute
307
+ * it to the session, which is the whole of #1833 reached by another route.
308
+ * The inner scope's directory is discarded and only a filing found inside it
309
+ * is kept, because a wrapper's `cd` does not outlive the wrapper.
310
+ *
311
+ * `$(…)` needs nothing: `tokenize` already emits `$` and `(` separately, so
312
+ * a command substitution pushes and pops through the same stack.
313
+ *
314
+ * ## Two documented limits, both asserted rather than assumed
315
+ *
316
+ * **One answer per command, taken at the FIRST filing.** A command filing
317
+ * twice from two different directories would need two, and no such command
318
+ * has ever been written here; one binding that is sometimes coarse beats two
319
+ * that can disagree (`.claude/rules/checks-must-be-able-to-fail.md`, the
320
+ * fourth shape).
321
+ *
322
+ * **A `cd` this cannot resolve leaves the directory alone.** `cd -` is the
323
+ * only such spelling — it needs `OLDPWD`, which is the shell's state and not
324
+ * the command's text. A bare `cd` IS resolvable and goes to `homedir()`.
325
+ */
326
+ export function filingDirectory(cmd: string, from: string): string {
327
+ return scanForFiling(cmd, from, 0).found ?? from;
328
+ }
329
+
330
+ /**
331
+ * One scope's worth of the scan: the filing's directory if this text files,
332
+ * and the directory the text ends in.
333
+ *
334
+ * `depth` bounds the `-c` recursion at the same 4 `clauses()` uses — a
335
+ * wrapper chain that deep is not an accident, and the two readers must agree
336
+ * about which commands exist or one of them attributes a filing the other
337
+ * cannot see.
338
+ */
339
+ function scanForFiling(
340
+ cmd: string,
341
+ from: string,
342
+ depth: number,
343
+ ): { found: string | null; dir: string } {
344
+ let dir = from;
345
+ const entered: string[] = [];
346
+ let inBacktick = false;
347
+ let clause: string[] = [];
348
+ let found: string | null = null;
349
+
350
+ const settle = (): void => {
351
+ if (found !== null || clause.length === 0) return;
352
+ if (createsIssue(clause)) {
353
+ found = dir;
354
+ return;
355
+ }
356
+ // Before the `cd`, not after: a wrapper's argument runs in the directory
357
+ // the wrapper was invoked from, and the clause cannot be both.
358
+ if (depth < 4) {
359
+ for (const inner of commandArguments(clause)) {
360
+ const nested = scanForFiling(inner, dir, depth + 1);
361
+ if (nested.found !== null) {
362
+ found = nested.found;
363
+ return;
364
+ }
365
+ }
366
+ }
367
+ if (clause[0] === "cd") dir = cdTarget(clause.slice(1), dir);
368
+ };
369
+
370
+ const close = (): void => {
371
+ settle();
372
+ clause = [];
373
+ // An unbalanced closer is a malformed command, not a reason to pop an
374
+ // empty stack and lose the directory the filing actually ran in.
375
+ if (entered.length > 0) dir = entered.pop()!;
376
+ };
377
+
378
+ for (const t of tokenize(heredocView(cmd))) {
379
+ if (t === "`") {
380
+ if (inBacktick) close();
381
+ else {
382
+ settle();
383
+ clause = [];
384
+ entered.push(dir);
385
+ }
386
+ inBacktick = !inBacktick;
387
+ continue;
388
+ }
389
+ if (t === "(") {
390
+ settle();
391
+ clause = [];
392
+ entered.push(dir);
393
+ continue;
394
+ }
395
+ if (t === ")") {
396
+ close();
397
+ continue;
398
+ }
399
+ if (SEPARATORS.has(t)) {
400
+ settle();
401
+ clause = [];
402
+ continue;
403
+ }
404
+ clause.push(t);
405
+ }
406
+ settle();
407
+ return { found, dir };
408
+ }
409
+
410
+ /** Where a `cd` with these arguments lands, or `dir` when it cannot be read. */
411
+ function cdTarget(args: string[], dir: string): string {
412
+ const path = args.filter(a => !a.startsWith("-"));
413
+ if (path.length === 0) return args.includes("-") ? dir : homedir();
414
+ if (path.length > 1) return dir;
415
+ const target = path[0];
416
+ if (target === "~") return homedir();
417
+ if (target.startsWith("~/")) return join(homedir(), target.slice(2));
418
+ return resolve(dir, target);
263
419
  }
264
420
 
265
421
  /** Arguments of this clause that are themselves commands. */
@@ -278,11 +434,253 @@ function commandArguments(tokens: string[]): string[] {
278
434
  const basename = (t: string) => t.split("/").pop()!;
279
435
 
280
436
  /**
281
- * Does this clause invoke `gh issue create`?
437
+ * `gh api` flags that do NOT consume the following token.
438
+ *
439
+ * **Read off `gh api --help` on 2026-11-06, not guessed.** Rounds 1 and 2
440
+ * of #1805 each repaired one spelling of this parser that had been reasoned
441
+ * about rather than enumerated, and the enumeration immediately produced
442
+ * two things neither round had: `--allow-escape-sequences` was missing from
443
+ * this set, and `-f` is `--raw-field` while `-F` is `--field` — the
444
+ * opposite of what the round-1 comment said.
445
+ *
446
+ * Everything else beginning with `-` is assumed to take a value, which is
447
+ * the same conservative convention `BOOLEAN_FLAGS` follows above: guessing
448
+ * that a flag takes a value makes the scan skip a token it should have
449
+ * read, and the failure is a filing the gate does not recognise — visible.
450
+ * Guessing the other way desyncs the scan and makes a flag's VALUE read as
451
+ * the endpoint, which is a filing recognised against the wrong URL.
452
+ */
453
+ export const API_BOOLEAN_FLAGS = new Set([
454
+ "--allow-escape-sequences",
455
+ "--paginate",
456
+ "-i",
457
+ "--include",
458
+ "--silent",
459
+ "--slurp",
460
+ "--verbose",
461
+ ]);
462
+
463
+ /**
464
+ * Flags of `gh api` whose value is a `key=value` field.
465
+ *
466
+ * `-F`/`--field` is typed and `-f`/`--raw-field` is a string; the
467
+ * distinction does not matter to a gate reading titles. Both also accept
468
+ * `key=@path` and `key=@-` to take the value from a file or stdin — a
469
+ * DECLARED limit here: the key is seen, so the clause is still recognised
470
+ * as a filing, but the value resolves to the literal `@path` rather than
471
+ * the file's contents, so the dedupe compares a path. That is the safe
472
+ * direction — adjudicated, not missed — and it is written down rather than
473
+ * left for a sixth round to find.
474
+ */
475
+ const API_FIELD_FLAGS = new Set(["--field", "-F", "--raw-field", "-f"]);
476
+
477
+ /** A `gh api` clause, read in one walk. */
478
+ export interface ApiCall {
479
+ /** The first positional token — the endpoint — or `null`. */
480
+ readonly endpoint: string | null;
481
+ /** `-X`/`--method`, upper-cased, or `null` when it was not given. */
482
+ readonly method: string | null;
483
+ /** Every `key=value` field, last on the LINE wins, as `gh` reads them. */
484
+ readonly fields: Map<string, string>;
485
+ /** Was a body supplied with `--input`? */
486
+ readonly hasInput: boolean;
487
+ }
488
+
489
+ /**
490
+ * ONE walk over a `gh api` clause's tokens.
491
+ *
492
+ * ai-review round 1 of #1805 raised four findings and all four were this
493
+ * function not existing. The first cut read the endpoint with its own loop
494
+ * and the method and fields with `flagValues`, which consults
495
+ * `BOOLEAN_FLAGS` — the set belonging to `gh issue create`. So
496
+ * `gh api --silent -f title=… repos/o/r/issues`, which files an issue,
497
+ * desynced: `--silent` was assumed to take a value, the scan skipped the
498
+ * `-f`, and the clause resolved to no fields and no method. Two scanners
499
+ * with two grammars over one command, and only one of them had been told
500
+ * which command it was reading.
501
+ *
502
+ * Reading the fields in one pass is also what makes *last wins* true. The
503
+ * first cut collected every `-f` and then every `-F`, so
504
+ * `-F title=A -f title=B` landed on `A` — the opposite of what `gh` sends.
505
+ *
506
+ * ## Two deliberate readings
507
+ *
508
+ * **`--` does not end the walk.** pflag treats it as end-of-options, so a
509
+ * real `gh` may well reject what follows; this skips it and keeps reading,
510
+ * which can only make a clause MORE likely to be seen as a filing. That is
511
+ * the safe direction for a gate, and `--` becoming the endpoint was a
512
+ * filing that walked straight through.
513
+ *
514
+ * **An unknown flag takes a value**, the same convention `BOOLEAN_FLAGS`
515
+ * follows: guessing that way costs a skipped token and an unrecognised
516
+ * filing, which is visible. Guessing the other way desyncs the scan and
517
+ * reads a flag's value as the endpoint — a filing recognised against the
518
+ * wrong URL, which is worse and quieter.
519
+ */
520
+ export function apiCall(tokens: string[]): ApiCall | null {
521
+ const rest = afterGhSubcommand(tokens, "api");
522
+ if (rest === null) return null;
523
+ let endpoint: string | null = null;
524
+ let method: string | null = null;
525
+ let hasInput = false;
526
+ const fields = new Map<string, string>();
527
+ for (let i = 0; i < rest.length; i++) {
528
+ const t = rest[i];
529
+ if (t === "--") continue;
530
+ if (!t.startsWith("-") || t === "-") {
531
+ // Normalised HERE and nowhere else. Five consumers read this field;
532
+ // normalising at each of them is five chances to forget, and round 3
533
+ // of #1805 is what forgetting once costs.
534
+ if (endpoint === null) endpoint = barePath(t);
535
+ continue;
536
+ }
537
+ // **The attached short form is resolved BEFORE the `=` split, and the
538
+ // order is the whole of it.** `-ftitle=x` is one token whose value is
539
+ // itself a `key=value` pair, so splitting on the first `=` reads the
540
+ // flag as `-ftitle` and drops the field — and a field flag's value is
541
+ // ALWAYS a pair, so the one attached form that matters was the only
542
+ // one that could not work. ai-review round 2 of #1805; the round
543
+ // before it shipped this as a comment with no case behind it.
544
+ let name = t;
545
+ let value: string | null = null;
546
+ const attached = t.startsWith("--") ? null : /^-([A-Za-z])(.+)$/.exec(t);
547
+ if (attached !== null) {
548
+ name = `-${attached[1]}`;
549
+ value = attached[2];
550
+ } else {
551
+ const eq = t.indexOf("=");
552
+ if (eq !== -1) {
553
+ name = t.slice(0, eq);
554
+ value = t.slice(eq + 1);
555
+ }
556
+ }
557
+ if (value === null && !API_BOOLEAN_FLAGS.has(name) && i + 1 < rest.length) {
558
+ value = rest[++i];
559
+ }
560
+ if (name === "--input") hasInput = true;
561
+ else if (name === "-X" || name === "--method") {
562
+ if (value !== null) method = value.toUpperCase();
563
+ } else if (API_FIELD_FLAGS.has(name) && value !== null) {
564
+ const at = value.indexOf("=");
565
+ if (at > 0) fields.set(value.slice(0, at), value.slice(at + 1));
566
+ }
567
+ }
568
+ return { endpoint, method, fields, hasInput };
569
+ }
570
+
571
+ /** The REST issues COLLECTION — `repos/<owner>/<repo>/issues`, nothing deeper. */
572
+ const ISSUES_COLLECTION = /^\/?repos\/([^/?]+)\/([^/?]+)\/issues\/?(?:\?.*)?$/;
573
+
574
+ /**
575
+ * An endpoint as a bare path, whichever way it was written.
576
+ *
577
+ * `gh api` takes a fully-qualified URL as well as a path — it is how a
578
+ * Link-header pagination URL is replayed and how a GitHub Enterprise host
579
+ * is addressed — and posts it exactly the same way. ai-review round 3 of
580
+ * #1805: `https://api.github.com/repos/o/r/issues` matched neither the
581
+ * collection regex nor `graphql`, so a filing spelled that way walked
582
+ * around a gate that had just been widened twice.
583
+ *
584
+ * The `/api/v3` and `/api` prefixes are GHES's REST and GraphQL mounts.
585
+ * Stripping them makes the two hosts one shape, which is the point: a
586
+ * second regex per host is a second decider.
587
+ */
588
+ function barePath(endpoint: string): string {
589
+ const withoutHost = endpoint.replace(/^[a-z][a-z0-9+.-]*:\/\/[^/]+/i, "");
590
+ return withoutHost.replace(/^\/api(?:\/v3)?\//, "/").replace(/^\//, "");
591
+ }
592
+
593
+ /**
594
+ * The `owner/repo` a `gh api` filing targets, or `null`.
595
+ *
596
+ * The REST path carries it; a GraphQL `createIssue` carries a
597
+ * `repositoryId`, which is an opaque node id and not a slug, so that one is
598
+ * honestly `null` rather than guessed at. `null` means the dedupe runs
599
+ * against the session's default repo, which is the existing behaviour for
600
+ * a `gh issue create` with no `--repo`.
601
+ */
602
+ export function apiFilingRepo(tokens: string[]): string | null {
603
+ const call = apiCall(tokens);
604
+ const m = call === null ? null : ISSUES_COLLECTION.exec(call.endpoint ?? "");
605
+ return m === null ? null : `${m[1]}/${m[2]}`;
606
+ }
607
+
608
+ /**
609
+ * The fields of a REST issues-collection filing, or `null`.
610
+ *
611
+ * `null` for every clause that is not one — including `graphql`, which has
612
+ * its own reader — so a caller gets a map only when the map means what it
613
+ * thinks it means.
614
+ */
615
+ export function apiRestFields(tokens: string[]): Map<string, string> | null {
616
+ const call = apiCall(tokens);
617
+ if (call === null || !ISSUES_COLLECTION.test(call.endpoint ?? "")) return null;
618
+ return call.fields;
619
+ }
620
+
621
+ /**
622
+ * The GraphQL `query` variables this clause passes, or `null`.
623
+ *
624
+ * `gh api graphql -f query='mutation($title: String!){…}' -f title="…"` is
625
+ * the form `gh`'s own documentation recommends, because it avoids escaping
626
+ * quotes by hand. ai-review round 1 of #1805: the first cut read literals
627
+ * out of the document only, so the idiomatic spelling resolved to an empty
628
+ * title and an empty body — counted as a filing and compared against
629
+ * nothing, which is the one outcome worse than not counting it.
630
+ */
631
+ export function graphqlVariables(tokens: string[]): Map<string, string> | null {
632
+ const call = apiCall(tokens);
633
+ if (call === null || call.endpoint !== "graphql") return null;
634
+ return call.fields;
635
+ }
636
+
637
+ /** The tokens after `gh <sub>`, or `null` when this clause is not that. */
638
+ function afterGhSubcommand(tokens: string[], sub: string): string[] | null {
639
+ for (let i = 0; i + 1 < tokens.length; i++) {
640
+ if (basename(tokens[i]) === "gh" && tokens[i + 1] === sub) return tokens.slice(i + 2);
641
+ }
642
+ return null;
643
+ }
644
+
645
+ /** A `mutation { … createIssue( … ) … }` in a GraphQL document. */
646
+ const CREATE_ISSUE_MUTATION = /\bmutation\b[\s\S]*\bcreateIssue\s*\(/;
647
+
648
+ /**
649
+ * The GraphQL document this clause sends, or `null`.
650
+ *
651
+ * `gh api graphql` takes it as the `query` field whichever field flag
652
+ * spells it.
653
+ */
654
+ export function graphqlDocument(tokens: string[]): string | null {
655
+ return graphqlVariables(tokens)?.get("query") ?? null;
656
+ }
657
+
658
+ /**
659
+ * Does this clause create an issue?
660
+ *
661
+ * Three spellings, one decider (#1759). Measured on 2026-11-02, the first
662
+ * two of these returned nothing: `gh api repos/<o>/<r>/issues` and a
663
+ * `createIssue` GraphQL mutation both file an issue and neither is spelled
664
+ * `gh issue create`, so two of three filings walked around the gate that
665
+ * exists to count them.
282
666
  *
283
667
  * Compared on the basename, because `/usr/bin/gh issue create` and
284
668
  * `./gh issue create` are the same command and the first version of this
285
669
  * function allowed both.
670
+ *
671
+ * ## Reading is not filing, and that is the hard half
672
+ *
673
+ * `repos/<o>/<r>/issues` is the LIST endpoint as well as the create
674
+ * endpoint; the method is what separates them, and `gh api` chooses POST
675
+ * implicitly when any field is supplied. So a create is *fields present or
676
+ * POST asked for*, and an explicit `GET`/`HEAD` is a read whatever else is
677
+ * on the line.
678
+ *
679
+ * The regex stops at the collection — `issues/1759/comments` is deeper and
680
+ * is not a filing. That boundary is load-bearing rather than tidy: this
681
+ * gate's own refusals tell an agent to post a comment instead, so a parser
682
+ * that read any `gh api` touching `issues` would refuse the remedy it
683
+ * prescribes.
286
684
  */
287
685
  export function createsIssue(tokens: string[]): boolean {
288
686
  for (let i = 0; i + 2 < tokens.length; i++) {
@@ -290,7 +688,21 @@ export function createsIssue(tokens: string[]): boolean {
290
688
  return true;
291
689
  }
292
690
  }
293
- return false;
691
+ const call = apiCall(tokens);
692
+ if (call === null) return false;
693
+ const { endpoint, method, fields, hasInput } = call;
694
+ if (method === "GET" || method === "HEAD") return false;
695
+ if (endpoint === "graphql") {
696
+ // `--input` puts the document in a file, or on stdin, and this does
697
+ // not read it. A document nobody read is UNMEASURED, not absent, and
698
+ // UNMEASURED adjudicates — the same reading the REST arm below already
699
+ // takes of the same flag. ai-review round 3 of #1805 found the two
700
+ // arms disagreeing about one flag, which is the only fact that makes
701
+ // either of them wrong.
702
+ return hasInput || CREATE_ISSUE_MUTATION.test(fields.get("query") ?? "");
703
+ }
704
+ if (!ISSUES_COLLECTION.test(endpoint ?? "")) return false;
705
+ return fields.size > 0 || hasInput || method === "POST";
294
706
  }
295
707
 
296
708
  /**