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
@@ -3,33 +3,59 @@
3
3
  * The criterion inventory: for every criterion in one spec, what state it is
4
4
  * in and who has been near it.
5
5
  *
6
- * bun scripts/criterion-inventory.ts --snapshot <dir> [--spec <path>] [--json]
6
+ * bun scripts/criterion-inventory.ts [--snapshot <dir>] [--spec <path>] [--json]
7
7
  *
8
- * ## Why this takes a snapshot directory instead of fetching
8
+ * ## It takes its own reading — SC-2619, item D1
9
9
  *
10
10
  * The three readings it needs are a full issue list, a full pull-request list,
11
- * and the changed files of every pull request that names a criterion. The
12
- * third is one API call per pull request — sixty-two of them on the first run
13
- * — so a tool that fetched on every invocation would be slow enough that
14
- * nobody re-ran it, and a number nobody re-runs is the defect
15
- * `.claude/rules/checks-must-be-able-to-fail.md` is about.
11
+ * and the changed files of every pull request that names a criterion. Until
12
+ * #1718 all three were assembled by hand: the header printed two `gh`
13
+ * commands to copy, the run reported which pull requests were still
14
+ * UNCLASSIFIED, and you appended one line per pull request and ran it again.
16
15
  *
17
- * So the fetch is a separate, explicit step and the snapshot is an input you
18
- * can point at, date, and keep. Take one with:
16
+ * The number that came out on 2026-10-30 was therefore reproducible by nobody
17
+ * else. Nothing in the directory, and nothing in the output, said which
18
+ * tracker it was taken from, when, or whether a line had been edited after
19
+ * the fetch. That is the defect SC-2619 names, and it is the same shape as
20
+ * the one in `.claude/rules/config-access.md`: a reading nobody can retake is
21
+ * not a measurement.
19
22
  *
20
- * mkdir -p <dir>
21
- * gh issue list --state all --limit 3000 \
22
- * --json number,title,body,state > <dir>/issues.json
23
- * gh pr list --state all --limit 3000 \
24
- * --json number,title,body,state,mergedAt > <dir>/prs.json
23
+ * So with no `--snapshot` the command fetches all three itself and writes
24
+ * nothing. The changed-file read is still one API call per pull request, and
25
+ * it is still only taken for the pull requests that NAME a criterion — which
26
+ * the command now works out for itself by running the inventory once against
27
+ * an empty classification and asking it which numbers it could not place.
25
28
  *
26
- * Run it now. It reports which merged pull requests have no changed-file
27
- * reading, under UNCLASSIFIED. Fetch exactly those, one line each:
29
+ * ## `--snapshot <dir>` is a cache this command owns, not an input you build
28
30
  *
29
- * gh pr view <n> --json number,files \
30
- * -q '{number:.number,files:[.files[].path]}' >> <dir>/pr-files.jsonl
31
+ * Pass it and the first run writes the three readings there, beside a
32
+ * {@link PROVENANCE} file recording when, from which repository, and a
33
+ * digest of what was written. A later run reads all three back and retakes
34
+ * none of the three readings. It makes one further call only when `--repo`
35
+ * was omitted — the identity read the comparison below needs, which
36
+ * {@link resolveRepo} explains; with `--repo` given there is nothing left
37
+ * to resolve and a cache hit calls nothing.
31
38
  *
32
- * then run it again.
39
+ * This paragraph has now been wrong about that count twice. It said "no API
40
+ * call at all" after the identity read was added in review of #1878, and
41
+ * the correction then said "exactly one call" as a flat fact, which is
42
+ * false on the `--repo` path. Neither is a hard question; both were written
43
+ * without reading the function one screen below. A sentence about what a
44
+ * program does is a claim, and a claim needs the same evidence as a number.
45
+ *
46
+ * A cache is refused rather than believed whenever the record cannot settle
47
+ * what it is for — a record nobody consults settles nothing, which is this
48
+ * command's own subject in miniature. {@link dirState} and
49
+ * {@link cacheProblem} are the two deciders and between them they are the
50
+ * list; no count is stated here, because a hand-written number beside the
51
+ * thing it counts is the defect recorded on PR #1685 and this very
52
+ * paragraph had one. In outline:
53
+ *
54
+ * - no {@link PROVENANCE} at all — assembled by something other than this
55
+ * command, refused naming the directory ({@link dirState});
56
+ * - a record that is unreadable, or that carries no digest or no repository;
57
+ * - a digest that no longer matches — edited after the fetch;
58
+ * - a repository that is not the one this run resolved.
33
59
  *
34
60
  * ## Which absences are refusals, and which are the first pass
35
61
  *
@@ -39,24 +65,19 @@
39
65
  * report every criterion as NOT STARTED: the one direction that reads as
40
66
  * good news.
41
67
  *
42
- * `pr-files.jsonl` missing is **not**. It is the normal state of the first
43
- * pass, because it is populated from the UNCLASSIFIED numbers this script
44
- * itself reports. Refusing on it made the recipe above circular — the file
45
- * could only be filled from a reading that would not run until the file
46
- * existed — so it is read as empty and every merged pull request is
47
- * unclassified, which the run says by name.
48
- *
49
- * Both halves were raised by the required reviewer on #1642. The same round
50
- * flagged a `-c` that used to sit on the `gh pr view` command, on the
51
- * grounds that it broke the single-line output the `>>` append needs. It
52
- * does not: measured, with and without it, that command emits exactly one
53
- * line. It is gone anyway, because `-c` is `--comments` and is a no-op
54
- * beside `--json` — removed as misleading, not as a fix.
68
+ * `pr-files.jsonl` missing is **not**. It is the normal state of a cache
69
+ * written before any pull request named a criterion, and refusing on it
70
+ * made the old hand recipe circular — the file could only be filled from a
71
+ * reading that would not run until the file existed. It is read as empty
72
+ * and every merged pull request is unclassified, which the run says by
73
+ * name. Both halves were raised by the required reviewer on #1642.
55
74
  */
56
75
 
57
- import { existsSync, readFileSync, readdirSync } from "node:fs";
76
+ import { createHash } from "node:crypto";
77
+ import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
58
78
  import { isAbsolute, join } from "node:path";
59
79
 
80
+ import { ghWithoutGhToken } from "../lib/live-issues";
60
81
  import { hasContent, isIsoDay, parseCriteria } from "../lib/spec-evidence";
61
82
  import { oneScMentionPattern } from "../lib/sc-ids";
62
83
  import { localCalendarDay } from "../lib/local-calendar-day";
@@ -481,6 +502,365 @@ export function collectTestFiles(testDir: string): { file: string; content: stri
481
502
  return out;
482
503
  }
483
504
 
505
+ /**
506
+ * The file a snapshot this command took carries, and one assembled by hand
507
+ * does not. Named once, because the writer, the reader and the refusal all
508
+ * have to mean the same file — and the test imports it rather than spelling
509
+ * it again, so a rename cannot leave a case asserting about a filename
510
+ * nothing writes.
511
+ */
512
+ export const PROVENANCE = "taken.json";
513
+
514
+ /** What a `--snapshot` directory turned out to be. */
515
+ export type DirState = "empty" | "taken" | "hand";
516
+
517
+ /**
518
+ * Three states, never two.
519
+ *
520
+ * `empty` is a path with nothing of ours in it — the first run with a cache
521
+ * location, which writes. `taken` is one we wrote. `hand` is readings with
522
+ * no record of where they came from, which is SC-2619's refusal: folding it
523
+ * into `taken` is exactly the silent default the criterion exists to stop,
524
+ * and folding it into `empty` would OVERWRITE somebody's files.
525
+ */
526
+ export function dirState(dir: string): DirState {
527
+ if (existsSync(join(dir, PROVENANCE))) return "taken";
528
+ const data = ["issues.json", "prs.json", "pr-files.jsonl"];
529
+ return data.some(name => existsSync(join(dir, name))) ? "hand" : "empty";
530
+ }
531
+
532
+ /** The three readings a snapshot holds, in the order the digest reads them. */
533
+ export const SNAPSHOT_FILES = ["issues.json", "prs.json", "pr-files.jsonl"] as const;
534
+
535
+ /**
536
+ * A digest of the three readings, so a cache can say it has not been edited.
537
+ *
538
+ * {@link PROVENANCE} on its own answers *when* and *from where*, and the
539
+ * header used to claim it answered *whether a line was edited after the
540
+ * fetch* as well. It did not: hand-editing `issues.json` leaves the record
541
+ * untouched and the directory still reads as taken. Raised in review of
542
+ * #1878, and fixed by making the claim true rather than by narrowing it.
543
+ *
544
+ * An absent file contributes its name and nothing else, so deleting one is
545
+ * a change the digest sees — which matters because `pr-files.jsonl` is
546
+ * legitimately absent on a cache taken before any pull request named a
547
+ * criterion, and "absent" has to stay distinguishable from "emptied".
548
+ */
549
+ export function snapshotDigest(dir: string): string {
550
+ const h = createHash("sha256");
551
+ for (const name of SNAPSHOT_FILES) {
552
+ const path = join(dir, name);
553
+ h.update(name);
554
+ h.update(existsSync(path) ? readFileSync(path) : Buffer.alloc(0));
555
+ }
556
+ return h.digest("hex");
557
+ }
558
+
559
+ /**
560
+ * What {@link PROVENANCE} records.
561
+ *
562
+ * `repo` is the repository `gh` RESOLVED, never the flag as typed. A first
563
+ * draft stored `--repo` verbatim, so a fetch with the flag omitted stamped
564
+ * `null` — and the mismatch check below then had nothing to compare and
565
+ * passed. Two trees for different repositories sharing one cache directory,
566
+ * neither passing `--repo`, is the ordinary case on this machine and it was
567
+ * the one the guard could not see. Raised in round 2 of review on #1878.
568
+ */
569
+ export interface Taken {
570
+ by: string;
571
+ takenAt: string;
572
+ repo: string;
573
+ digest: string;
574
+ }
575
+
576
+ /**
577
+ * Which repository this invocation is about, asked of `gh` rather than
578
+ * inferred twice.
579
+ *
580
+ * `--repo` wins when given. Otherwise `gh` is asked what it would resolve,
581
+ * in the tree the rest of the command is reading — the same question it
582
+ * would answer internally on every later call, so there is one answer and
583
+ * not a local re-derivation free to disagree with it. Parsing `git remote`
584
+ * here instead would be a second decider, and it would get `gh repo
585
+ * set-default` and multi-remote trees wrong in the direction that refuses a
586
+ * legitimate cache.
587
+ */
588
+ export function resolveRepo(repo: string | undefined, exec: Exec): string {
589
+ if (repo !== undefined) return repo;
590
+ const raw = JSON.parse(exec(["repo", "view", "--json", "nameWithOwner"])) as { nameWithOwner?: string };
591
+ if (typeof raw.nameWithOwner !== "string" || raw.nameWithOwner === "") {
592
+ throw new Error("gh could not say which repository this tree belongs to, and no --repo was given");
593
+ }
594
+ return raw.nameWithOwner;
595
+ }
596
+
597
+ /**
598
+ * Why this cache must not be believed — or `null` when it may be.
599
+ *
600
+ * Reached only for a directory in the `taken` state, so the question is no
601
+ * longer *did we write this* but *is what we wrote still what is here, and
602
+ * is it about the repository being asked about*. Both were recorded by
603
+ * `writeSnapshotDir` from the first commit and neither was read back, which
604
+ * is the same shape as the defect this whole command is about: a provenance
605
+ * nobody checks settles nothing.
606
+ *
607
+ * `repo` is the RESOLVED repository, so the comparison always has two
608
+ * concrete sides and there is no input for which it declines to answer.
609
+ */
610
+ export function cacheProblem(dir: string, repo: string): string | null {
611
+ const path = join(dir, PROVENANCE);
612
+ let taken: Partial<Taken>;
613
+ try {
614
+ taken = JSON.parse(readFileSync(path, "utf-8")) as Partial<Taken>;
615
+ } catch (err) {
616
+ return `${path} is not readable JSON (${(err as Error).message}), so nothing says where this snapshot came from`;
617
+ }
618
+ if (typeof taken.digest !== "string") {
619
+ return `${path} records no digest, so it cannot say whether the readings beside it have been edited since`;
620
+ }
621
+ const now = snapshotDigest(dir);
622
+ if (now !== taken.digest) {
623
+ return (
624
+ `the readings in ${dir} have changed since ${path} was written (recorded ${taken.digest.slice(0, 12)}, ` +
625
+ `found ${now.slice(0, 12)}), so they are a hand-edited snapshot wearing a record of a fetch that no ` +
626
+ `longer describes them`
627
+ );
628
+ }
629
+ // An absent or non-string `repo` is a cache written before this field was
630
+ // recorded, and it is refused rather than waved through: "I cannot tell
631
+ // which repository this is about" is not the same fact as "it is the
632
+ // right one", and only one of them is reportable.
633
+ if (typeof taken.repo !== "string") {
634
+ return `${path} does not say which repository it was taken for, so a cache hit cannot be told from a wrong one`;
635
+ }
636
+ if (taken.repo !== repo) {
637
+ return (
638
+ `${dir} was taken for ${taken.repo} and this run is about ${repo}. A cache hit for the wrong ` +
639
+ `repository is indistinguishable from a right one in the output`
640
+ );
641
+ }
642
+ return null;
643
+ }
644
+
645
+ /** How a `gh` call is made. A parameter so the fetch has a seam. */
646
+ export type Exec = (args: readonly string[]) => string;
647
+
648
+ /**
649
+ * `gh`, run in the tree the rest of the command is reading.
650
+ *
651
+ * With no `--repo`, `gh` infers the repository from the git remote of its
652
+ * working directory — and `--project-root` is an independent value, so a
653
+ * caller pointing the spec and the test scan at one tree while standing in
654
+ * another would read a second repository's tracker and nothing in the
655
+ * output would say which. They happen to coincide on the dispatcher path,
656
+ * which is exactly why nothing caught it. Raised in review of #1878.
657
+ */
658
+ function execIn(root: string): Exec {
659
+ return args => ghWithoutGhToken(args, { cwd: root });
660
+ }
661
+
662
+ /**
663
+ * The page size for the two list reads.
664
+ *
665
+ * One number for both, because they are one reading taken in one shot and a
666
+ * limit that differed between them would truncate one list against the
667
+ * other — which reads as criteria nobody has started.
668
+ */
669
+ export const FETCH_LIMIT = 3000;
670
+
671
+ function repoArgs(repo: string | undefined): string[] {
672
+ return repo === undefined ? [] : ["--repo", repo];
673
+ }
674
+
675
+ /**
676
+ * ONE shape decision for a tracker list, wherever it came from.
677
+ *
678
+ * The cache path refused a truncated read, a JSON object and an empty list;
679
+ * the live path, added in this PR, refused none of them. A `gh issue list`
680
+ * that exits 0 and returns `[]` — a wrong repository, a rate-limited page,
681
+ * an error `gh` does not surface as a non-zero exit — would have reported
682
+ * every criterion NOT STARTED, which is the one direction that reads as
683
+ * good news, and a JSON error object would have died later inside
684
+ * `inventory` where the surrounding catch would have called it a failed
685
+ * fetch for the right outcome and the wrong reason. Raised in round 3 of
686
+ * review on #1878.
687
+ *
688
+ * Not a copy of the cache guard — the cache path calls this too. One answer
689
+ * to *is this a tracker reading*, so there is no pair of deciders free to
690
+ * drift, which is what the round-3 meta-finding was about: sweep the paths,
691
+ * do not patch the one that was named.
692
+ *
693
+ * `source` is what the refusal calls it: a file path on the cache path, a
694
+ * command on the live one. A refusal has to name something the reader can
695
+ * go and look at.
696
+ */
697
+ export function validateTracked(parsed: unknown, source: string): Tracked[] {
698
+ if (!Array.isArray(parsed)) {
699
+ throw new Error(
700
+ `UNMEASURED: ${source} parsed to ${parsed === null ? "null" : typeof parsed}, not an array. ` +
701
+ `\`gh\` emits a JSON array here; an object is usually its error payload.`,
702
+ );
703
+ }
704
+ return parsed as Tracked[];
705
+ }
706
+
707
+ /**
708
+ * Both lists together are either a reading or a failed fetch.
709
+ *
710
+ * Judged on the PAIR, because they are taken in one shot: a tracker this
711
+ * command was pointed at does not have neither issues nor pull requests,
712
+ * and either list coming back empty is the shape a failed fetch takes. The
713
+ * cache path has judged them together since #1642; the live path does now.
714
+ */
715
+ export function refuseEmptyPair(issues: Tracked[], prs: Tracked[], source: string): void {
716
+ if (issues.length === 0 || prs.length === 0) {
717
+ throw new Error(
718
+ `UNMEASURED: ${source} holds ${issues.length} issue(s) and ${prs.length} pull ` +
719
+ `request(s). An empty reading is a failed fetch, not an empty tracker.`,
720
+ );
721
+ }
722
+ }
723
+
724
+ /**
725
+ * Call `gh` and read what it said — as TWO refusals, not one.
726
+ *
727
+ * A single `try` around the call and the parse reported every failure as
728
+ * "did not emit readable JSON", so an auth failure, a rate limit or a wrong
729
+ * repository — anything that makes `gh` exit non-zero and produce no output
730
+ * at all — sent whoever was debugging it looking for truncated output. The
731
+ * real stderr was in the parentheses, but the framing named the wrong kind
732
+ * of failure, which is this file's own stated defect wearing a different
733
+ * hat. Raised in round 5 of review on #1878.
734
+ *
735
+ * Both sites call this, so there is one answer to *which failure was it*.
736
+ */
737
+ function readGh(exec: Exec, args: string[], command: string): unknown {
738
+ let text: string;
739
+ try {
740
+ text = exec(args);
741
+ } catch (err) {
742
+ throw new Error(
743
+ `UNMEASURED: ${command} failed and produced no reading (${(err as Error).message}). ` +
744
+ `A tracker that could not be reached is not an empty one.`,
745
+ );
746
+ }
747
+ try {
748
+ return JSON.parse(text);
749
+ } catch (err) {
750
+ throw new Error(
751
+ `UNMEASURED: ${command} exited 0 and what it emitted is not readable JSON ` +
752
+ `(${(err as Error).message}). A truncated or half-written reading is a failed fetch, ` +
753
+ `not an empty tracker.`,
754
+ );
755
+ }
756
+ }
757
+
758
+ /** The issue list and the pull-request list, live — validated like the cache. */
759
+ export function fetchTracked(
760
+ repo: string | undefined,
761
+ exec: Exec = ghWithoutGhToken,
762
+ ): { issues: Tracked[]; prs: Tracked[] } {
763
+ const limit = String(FETCH_LIMIT);
764
+ const read = (args: string[]): Tracked[] => {
765
+ const command = `gh ${args.slice(0, 2).join(" ")}${repo === undefined ? "" : ` --repo ${repo}`}`;
766
+ return validateTracked(readGh(exec, args, command), command);
767
+ };
768
+ const issues = read([
769
+ "issue", "list", "--state", "all", "--limit", limit, "--json", "number,title,body,state", ...repoArgs(repo),
770
+ ]);
771
+ const prs = read([
772
+ "pr", "list", "--state", "all", "--limit", limit,
773
+ "--json", "number,title,body,state,mergedAt", ...repoArgs(repo),
774
+ ]);
775
+ refuseEmptyPair(issues, prs, `the live reading of ${repo ?? "this tree's repository"}`);
776
+ return { issues, prs };
777
+ }
778
+
779
+ /**
780
+ * The paths one pull-request view reported, or a refusal naming it.
781
+ *
782
+ * `raw.files ?? []` read a missing key as *this pull request touched
783
+ * nothing*, so an error payload with a zero exit — a rate limit is the
784
+ * realistic one — silently downgraded a criterion from TOUCHED. That is the
785
+ * same direction-that-reads-as-good-news this file closed for the two list
786
+ * reads one round earlier and did not sweep to the third call.
787
+ *
788
+ * A pull request with an EMPTY `files` array is left alone: GitHub really
789
+ * does report that, and it is a reading. An absent or non-array key is not.
790
+ * Raised in round 4 of review on #1878.
791
+ */
792
+ export function validateChangedFiles(parsed: unknown, source: string): string[] {
793
+ const files = (parsed as { files?: unknown } | null)?.files;
794
+ if (!Array.isArray(files)) {
795
+ throw new Error(
796
+ `UNMEASURED: ${source} returned no \`files\` array (${files === undefined ? "the key is absent" : typeof files}). ` +
797
+ `A pull request whose changed files could not be read is not one that changed nothing.`,
798
+ );
799
+ }
800
+ return files.map((f, i) => {
801
+ const path = (f as { path?: unknown } | null)?.path;
802
+ if (typeof path !== "string") {
803
+ throw new Error(`UNMEASURED: ${source} entry ${i} has no string \`path\`, so its changed files are unreadable.`);
804
+ }
805
+ return path;
806
+ });
807
+ }
808
+
809
+ /**
810
+ * The changed paths of each pull request named, one call apiece.
811
+ *
812
+ * Only the ones that NAME a criterion are asked for — `main` works that set
813
+ * out by running the inventory once against an empty classification, which
814
+ * is the same `unclassified` list the hand recipe used to print for a person
815
+ * to copy.
816
+ */
817
+ export function fetchChangedFiles(
818
+ numbers: readonly number[],
819
+ repo: string | undefined,
820
+ exec: Exec = ghWithoutGhToken,
821
+ ): Record<number, string[]> {
822
+ const out: Record<number, string[]> = {};
823
+ for (const n of numbers) {
824
+ const command = `gh pr view ${n}${repo === undefined ? "" : ` --repo ${repo}`}`;
825
+ const args = ["pr", "view", String(n), "--json", "number,files", ...repoArgs(repo)];
826
+ out[n] = validateChangedFiles(readGh(exec, args, command), command);
827
+ }
828
+ return out;
829
+ }
830
+
831
+ /**
832
+ * Write a cache, with the record that makes it one.
833
+ *
834
+ * The raw path lists are written, not the `changedCode` verdict computed
835
+ * from them: storing the verdict would make the cache carry this version of
836
+ * `CODE_DIRS` forever, so widening that list would leave old caches
837
+ * answering with the old one and no reading would say so.
838
+ *
839
+ * {@link PROVENANCE} is written LAST, and carries the digest of what was
840
+ * written before it. A run killed partway leaves a directory in the `hand`
841
+ * state, which refuses, rather than one that looks taken and is
842
+ * half-written — and a directory edited afterwards fails the digest, which
843
+ * is the half {@link cacheProblem} answers.
844
+ */
845
+ export function writeSnapshotDir(
846
+ dir: string,
847
+ data: { issues: Tracked[]; prs: Tracked[]; files: Record<number, string[]> },
848
+ meta: { takenAt: string; repo: string },
849
+ ): void {
850
+ mkdirSync(dir, { recursive: true });
851
+ writeFileSync(join(dir, "issues.json"), JSON.stringify(data.issues));
852
+ writeFileSync(join(dir, "prs.json"), JSON.stringify(data.prs));
853
+ const lines = Object.entries(data.files).map(([n, files]) => JSON.stringify({ number: Number(n), files }));
854
+ writeFileSync(join(dir, "pr-files.jsonl"), lines.length === 0 ? "" : `${lines.join("\n")}\n`);
855
+ const taken: Taken = {
856
+ by: "criterion-inventory",
857
+ takenAt: meta.takenAt,
858
+ repo: meta.repo,
859
+ digest: snapshotDigest(dir),
860
+ };
861
+ writeFileSync(join(dir, PROVENANCE), `${JSON.stringify(taken, null, 2)}\n`);
862
+ }
863
+
484
864
  function readSnapshot(dir: string): Snapshot {
485
865
  const need = (name: string): string => {
486
866
  const path = join(dir, name);
@@ -507,6 +887,10 @@ function readSnapshot(dir: string): Snapshot {
507
887
  * `issues.filter is not a function`. A failed fetch reading as a
508
888
  * measurement is the whole thing this guard exists to stop. Raised by
509
889
  * the required reviewer on #1642.
890
+ *
891
+ * The shape and emptiness decisions themselves live in
892
+ * {@link validateTracked} and {@link refuseEmptyPair}, shared with the
893
+ * live path — see their comments for why that is one decider, not two.
510
894
  */
511
895
  const readList = (name: string): Tracked[] => {
512
896
  const text = need(name);
@@ -519,22 +903,11 @@ function readSnapshot(dir: string): Snapshot {
519
903
  `A truncated or half-written snapshot is a failed fetch, not an empty tracker.`,
520
904
  );
521
905
  }
522
- if (!Array.isArray(parsed)) {
523
- throw new Error(
524
- `UNMEASURED: ${join(dir, name)} parsed to ${parsed === null ? "null" : typeof parsed}, not an array. ` +
525
- `\`gh\` writes a JSON array here; an object is usually its error payload redirected into the file.`,
526
- );
527
- }
528
- return parsed as Tracked[];
906
+ return validateTracked(parsed, join(dir, name));
529
907
  };
530
908
  const issues = readList("issues.json");
531
909
  const prs = readList("prs.json");
532
- if (issues.length === 0 || prs.length === 0) {
533
- throw new Error(
534
- `UNMEASURED: the snapshot holds ${issues.length} issue(s) and ${prs.length} pull ` +
535
- `request(s). An empty reading is a failed fetch, not an empty tracker.`,
536
- );
537
- }
910
+ refuseEmptyPair(issues, prs, "the snapshot");
538
911
  // An absent `pr-files.jsonl` is the first pass, not a failed fetch: it is
539
912
  // populated FROM this script's own UNCLASSIFIED report, so refusing on it
540
913
  // made the documented recipe circular — the file could only be filled from
@@ -553,11 +926,47 @@ function readSnapshot(dir: string): Snapshot {
553
926
  return { issues, prs, prChangedCode };
554
927
  }
555
928
 
929
+ /**
930
+ * Take all three readings live, and write them to `dir` when there is one.
931
+ *
932
+ * The changed-file call is taken only for the pull requests that NAME a
933
+ * criterion, and the inventory itself is what says which those are: run it
934
+ * once against an empty classification and `mergedPrs` is exactly the set
935
+ * the id match found. That is the step the hand recipe made a person do, and
936
+ * the reason it is not a second matcher here — a list built by a different
937
+ * predicate from the one that consumes it would quietly ask about the wrong
938
+ * pull requests (`.claude/rules/checks-must-be-able-to-fail.md`, *two
939
+ * deciders*).
940
+ */
941
+ function takeReading(
942
+ dir: string | undefined,
943
+ repo: string,
944
+ specText: string,
945
+ testFiles: { file: string; content: string }[],
946
+ today: string,
947
+ exec: Exec,
948
+ ): Snapshot {
949
+ // The RESOLVED repository is passed on every call, so the list reads no
950
+ // longer depend on `gh`'s own cwd inference either — one resolution, and
951
+ // every reading in the run is demonstrably about the same repository.
952
+ const { issues, prs } = fetchTracked(repo, exec);
953
+ const naming = inventory(specText, { issues, prs, prChangedCode: {} }, testFiles, today);
954
+ const want = [...new Set(naming.flatMap(r => r.mergedPrs))].sort((a, b) => a - b);
955
+ const files = fetchChangedFiles(want, repo, exec);
956
+ const prChangedCode: Record<number, boolean> = {};
957
+ for (const [n, paths] of Object.entries(files)) prChangedCode[Number(n)] = changedCode(paths);
958
+ if (dir !== undefined) {
959
+ writeSnapshotDir(dir, { issues, prs, files }, { takenAt: new Date().toISOString(), repo });
960
+ }
961
+ return { issues, prs, prChangedCode };
962
+ }
963
+
556
964
  function main(): number {
557
965
  const argv = process.argv.slice(2);
558
966
  const dir = flag(argv, "--snapshot");
559
- if (!dir) {
560
- console.error("usage: bun scripts/criterion-inventory.ts --snapshot <dir> [--spec <path>]");
967
+ const repo = flag(argv, "--repo");
968
+ if (argv.includes("--snapshot") && !dir) {
969
+ console.error("usage: bun scripts/criterion-inventory.ts [--snapshot <dir>] [--spec <path>] [--repo <owner/name>]");
561
970
  return EXIT_REFUSED;
562
971
  }
563
972
  // `--project-root`, not `import.meta.dir/..`, for the reason registering
@@ -580,14 +989,81 @@ function main(): number {
580
989
  ? (isAbsolute(specFlag) ? specFlag : join(root, specFlag))
581
990
  : join(root, "specs/CODE-REVIEW-CONVERGENCE-SPEC.md");
582
991
 
583
- const snapshot = readSnapshot(dir);
584
992
  const testFiles = collectTestFiles(join(root, "test"));
585
993
  if (testFiles.length === 0) {
586
994
  console.error(`UNMEASURED: no test files under ${join(root, "test")}. Every criterion would read as unbound.`);
587
995
  return EXIT_REFUSED;
588
996
  }
589
997
  const today = inventoryToday();
590
- const rows = inventory(readFileSync(specPath, "utf-8"), snapshot, testFiles, today);
998
+ const specText = readFileSync(specPath, "utf-8");
999
+
1000
+ // SC-2619. A directory holding readings with no record of where they came
1001
+ // from is refused by name, and `taken` is the only state that is read back
1002
+ // — so the source of every number this prints is either a directory this
1003
+ // command wrote or the live API it just called.
1004
+ if (dir !== undefined && dirState(dir) === "hand") {
1005
+ console.error(
1006
+ `UNMEASURED: ${dir} holds a snapshot this command did not take — there is no ${join(dir, PROVENANCE)}, ` +
1007
+ `so nothing says which tracker it came from or when, and the numbers would be reproducible by nobody ` +
1008
+ `else. Drop --snapshot and the command takes its own reading, or delete ${dir} and pass --snapshot ` +
1009
+ `${dir} again to have one written there.`,
1010
+ );
1011
+ return EXIT_REFUSED;
1012
+ }
1013
+
1014
+ // Resolved ONCE, before either branch, and asked of `gh` in the tree
1015
+ // `--project-root` names. Both paths need it: the fetch passes it on
1016
+ // every call, and the cache hit compares it against what was recorded.
1017
+ // A cache hit therefore costs one cheap identity call and retakes none
1018
+ // of the three readings — the saving the cache exists for is intact, and
1019
+ // the alternative was a comparison that declined to answer whenever
1020
+ // `--repo` was omitted, which is the ordinary case.
1021
+ let resolved: string;
1022
+ try {
1023
+ resolved = resolveRepo(repo, execIn(root));
1024
+ } catch (err) {
1025
+ console.error(
1026
+ `UNMEASURED: could not establish which repository to read — ${(err as Error).message}. ` +
1027
+ `Pass --repo <owner/name>.`,
1028
+ );
1029
+ return EXIT_REFUSED;
1030
+ }
1031
+
1032
+ let snapshot: Snapshot;
1033
+ if (dir !== undefined && dirState(dir) === "taken") {
1034
+ // A record nobody reads back settles nothing — the digest and the repo
1035
+ // were both written from the first commit and neither was consulted,
1036
+ // which is the shape this command exists to stop. Raised in review.
1037
+ const problem = cacheProblem(dir, resolved);
1038
+ if (problem !== null) {
1039
+ console.error(`UNMEASURED: ${problem}. Delete ${dir} and run again to have a fresh one taken there.`);
1040
+ return EXIT_REFUSED;
1041
+ }
1042
+ try {
1043
+ snapshot = readSnapshot(dir);
1044
+ } catch (err) {
1045
+ // CAUGHT, like the fetch below. `readSnapshot`'s refusals are already
1046
+ // careful `UNMEASURED:` sentences, so the message is printed as it
1047
+ // stands rather than wrapped — but letting the throw out printed a
1048
+ // stack trace for a cache missing a reading, which reads as a crash
1049
+ // in this command. Raised in review of #1878.
1050
+ console.error((err as Error).message);
1051
+ return EXIT_REFUSED;
1052
+ }
1053
+ } else {
1054
+ try {
1055
+ snapshot = takeReading(dir, resolved, specText, testFiles, today, execIn(root));
1056
+ } catch (err) {
1057
+ // A failed fetch is UNMEASURED and says so. Letting the throw out
1058
+ // would print a stack trace naming `gh`, which reads as a crash in
1059
+ // this command rather than a tracker it could not reach.
1060
+ console.error(
1061
+ `UNMEASURED: could not take the reading — ${(err as Error).message}. That is not an empty tracker.`,
1062
+ );
1063
+ return EXIT_REFUSED;
1064
+ }
1065
+ }
1066
+ const rows = inventory(specText, snapshot, testFiles, today);
591
1067
 
592
1068
  const unclassified = [
593
1069
  ...new Set(rows.flatMap(r => r.mergedPrs).filter(n => snapshot.prChangedCode[n] === undefined)),