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
@@ -344,12 +344,37 @@ export function claimedImprovements(
344
344
  return out;
345
345
  }
346
346
 
347
- /** Improvements a retro declares outstanding — reported, never hidden. */
348
- export function openImprovements(stages: readonly Stage[]): { stage: string; what: string }[] {
347
+ /**
348
+ * Improvements a retro declares outstanding — reported, never hidden.
349
+ *
350
+ * **The WHOLE improvement, not a two-field summary** (#1745). It used to
351
+ * return `{stage, what}`, and the only caller printed it to a `console.log`
352
+ * nobody reads — so three improvements that nothing could measure were
353
+ * invisible to the document every session is told to read first, while
354
+ * `test/stage-ladder.test.ts` scored stage ITEMS and reported the ladder
355
+ * healthy. That is the fail-open SUCCESS.md claim 4 names: *could not
356
+ * measure* reading as *nothing wrong*.
357
+ *
358
+ * `mechanism` and `issue` ride along because a reader needs both: the first
359
+ * says whether anybody has decided HOW, the second whether it is on the
360
+ * tracker at all. One function answers *what is outstanding* — a renderer
361
+ * that re-filtered `status === "open"` itself would be a second decider over
362
+ * one input, and a mutation of either would leave the other holding the case
363
+ * up.
364
+ */
365
+ export function openImprovements(stages: readonly Stage[]): ({ stage: string } & Improvement)[] {
349
366
  return stages.flatMap(s =>
350
367
  (s.retro?.improvements ?? [])
351
368
  .filter(im => im.status === "open")
352
- .map(im => ({ stage: s.id, what: im.what })),
369
+ // `stage` LAST. Spelled `{ stage: s.id, ...im }` for one commit, which
370
+ // lets an improvement carrying its own `stage` key overwrite the one
371
+ // computed from the stage it is actually in — and the key
372
+ // `OPEN_WITHOUT_ISSUE` matches on in `test/stage-ladder.test.ts` is
373
+ // `${stage}: ${what}`, so data in `project-state.json` could forge a
374
+ // ratchet key and tick a line reserved for a different improvement.
375
+ // Found by the security review of #1812. The computed field is the
376
+ // identity here, so it goes last and the data cannot reach it.
377
+ .map(im => ({ ...im, stage: s.id })),
353
378
  );
354
379
  }
355
380
 
@@ -626,3 +651,871 @@ export function ladderViolations(raw: unknown): string[] {
626
651
 
627
652
  return out;
628
653
  }
654
+
655
+ /* ────────────────────────────────────────────────────────────────────────
656
+ * #1849 — a verify command may not name a test that does not exist.
657
+ *
658
+ * `verify` is free text. Nothing related it to the set of test titles that
659
+ * exist, so a command could name a case nobody wrote and its item could be
660
+ * ticked against it. Three of Stage G's five verify commands did exactly
661
+ * that; two of Stage C's six did, and one of those named a FILE whose 47
662
+ * tests contain nothing matching — which is the half the runtime guard
663
+ * cannot see, because `grep -qE '^ [1-9][0-9]* pass'` only catches a title
664
+ * that matches nothing IN THE FILE NAMED.
665
+ *
666
+ * Static, by AC-1: this reads the file, it does not run it. A check that
667
+ * had to run the suite to know whether the suite would be selected is the
668
+ * thing it is checking.
669
+ * ──────────────────────────────────────────────────────────────────────── */
670
+
671
+ /**
672
+ * What a single `bun test <file> -t <name>` fragment turned out to be.
673
+ *
674
+ * `UNMEASURED` is a first-class reading and not a quiet pass, for the
675
+ * reason `.claude/rules/config-access.md` gives: a fragment this cannot
676
+ * read has not been checked, and "not checked" and "fine" are different
677
+ * facts. Every one is reported.
678
+ */
679
+ export const VERIFY_TITLE_READINGS = ["MATCHED", "NO_SUCH_TITLE", "FILE_ABSENT", "UNMEASURED"] as const;
680
+ export type VerifyTitleReading = (typeof VERIFY_TITLE_READINGS)[number];
681
+
682
+ export interface VerifyTitleFragment {
683
+ /** The item, improvement or goal the command belongs to. */
684
+ where: string;
685
+ /** The path as the command spells it, relative to the project root. */
686
+ file: string;
687
+ /** The `-t` pattern, verbatim. */
688
+ name: string;
689
+ reading: VerifyTitleReading;
690
+ /** What the reader saw. Empty only on `MATCHED`. */
691
+ why: string;
692
+ }
693
+
694
+ /**
695
+ * `bun test <file> -t "<name>"`, wherever it appears in a command.
696
+ *
697
+ * Global and non-anchored because a verify may chain several with `&&` —
698
+ * C6 chains three — and a chain whose FIRST command is checked and whose
699
+ * second is not is the population defect this repository keeps paying for
700
+ * (#1818).
701
+ */
702
+ const BUN_TEST_T = /bun test\s+(\S+)\s+-t\s+(["'])(.*?)\2/g;
703
+
704
+ /**
705
+ * `describe(` / `test(` / `it(`, with a quoted title and any modifier.
706
+ *
707
+ * The lookbehind is load-bearing. `\b` alone matches between the `.` and
708
+ * the `t` of `RegExp.prototype.test`, so `/^ 1 pass$/m.test(\`${out}\`)` —
709
+ * an ordinary line in this file's own suite — read as a declaration with
710
+ * an interpolated title, and marked the whole file UNMEASURED. Found by
711
+ * AC-4's mutation failing to redden anything: the victim it picked was a
712
+ * fragment this parser had quietly given up on.
713
+ *
714
+ * The HEAD of the declaration — everything up to and including the open
715
+ * paren — is `DECLARATION_HEAD`, shared verbatim with `UNRESOLVED_CALL`.
716
+ * Rounds 6 and 7 each found the two patterns disagreeing about one
717
+ * character of it: first the modifier chain (`?` against `*`, so
718
+ * `test.only.skip("inner", …)` fell between them), then the space before
719
+ * the paren (`describe ("outer", …)`, same gap). The second was round 6's
720
+ * finding with one name replaced, and the sweep I should have run then is
721
+ * this constant: every part they must agree on in ONE place, rather than
722
+ * a third round finding the third character.
723
+ *
724
+ * Why the gap is the damaging direction: a declaration this pattern
725
+ * cannot see contributes no title, and the unresolved scan — seeing a
726
+ * quote as the first argument — calls the file readable anyway. A name
727
+ * missing from a set reported as WHOLE turns a verify command naming a
728
+ * real test into a refusal, and everywhere else in this module an
729
+ * unreadable declaration degrades to UNMEASURED instead.
730
+ *
731
+ * Group 1 is the name, and the two patterns' later groups are numbered
732
+ * from it: `TITLE_CALL` takes 2 and 3, `UNRESOLVED_CALL` takes 2.
733
+ */
734
+ const DECLARATION_HEAD = String.raw`(?<![.\w$])(describe|test|it)(?:\.\w+)*\s*\(\s*`;
735
+ const TITLE_CALL = new RegExp(
736
+ String.raw`${DECLARATION_HEAD}(["'\`])((?:\\.|(?!\2).)*)\2`,
737
+ "g",
738
+ );
739
+
740
+ /**
741
+ * Every name `bun test -t` could match in one source file.
742
+ *
743
+ * **Measured, not assumed** (2026-11-07, bun 1.3.14). Against
744
+ * `describe("outer group") > test("inner case")`:
745
+ *
746
+ * | `-t` pattern | result |
747
+ * |------------------------------|--------|
748
+ * | `inner case` | runs |
749
+ * | `outer group` | runs |
750
+ * | `outer group inner case` | runs |
751
+ * | `outer group > inner case` | NO |
752
+ * | `group.*inner` | runs |
753
+ *
754
+ * So the thing matched is a regular expression against the **space-joined**
755
+ * path of enclosing describes plus the title — not the reporter's `>`
756
+ * spelling, and not a substring test. Getting this from the documentation
757
+ * rather than from the binary would have produced a check that refuses
758
+ * every path pattern in the tree.
759
+ *
760
+ * Returns `null` when the source cannot be parsed into a path set with
761
+ * confidence. A file whose nesting this cannot follow is UNMEASURED, never
762
+ * a refusal: the cost of reading it wrong is a red row for a command that
763
+ * is correct, which is how a check becomes an obstacle people route around.
764
+ * `scanSource` says when that is — see its three guards.
765
+ */
766
+ /**
767
+ * Why a file's names could not be read — the two causes are different
768
+ * facts and the message must not conflate them.
769
+ *
770
+ * It did. Everything unreadable was reported as "builds at least one
771
+ * title by interpolation", and the first file that proved it wrong was
772
+ * `test/board-ready-rule.test.ts`, whose real cause was a regex the
773
+ * scanner could not see. A reader chasing that message would have gone
774
+ * looking for a template literal that is not there.
775
+ */
776
+ export type TitleReading =
777
+ | { paths: string[]; why: null }
778
+ | { paths: null; why: "INTERPOLATED" | "UNPARSEABLE" };
779
+
780
+ export function titleReading(raw: string): TitleReading {
781
+ const scan = scanSource(raw);
782
+ if (!scan.ok) return { paths: null, why: "UNPARSEABLE" };
783
+ const paths = pathsFrom(scan);
784
+ return paths === null ? { paths: null, why: "INTERPOLATED" } : { paths, why: null };
785
+ }
786
+
787
+ export function titlePathsIn(raw: string): string[] | null {
788
+ // Comments are masked before the title scan. A `describe("outer group",
789
+ // …)` written INSIDE a comment is not a declaration, and reading it as
790
+ // one adds a name no test has — the docblock in
791
+ // `test/stage-ladder.test.ts` explaining that hazard became a title path
792
+ // of that file. Masked rather than removed, so offsets still line up.
793
+ const scan = scanSource(raw);
794
+ if (!scan.ok) return null;
795
+ return pathsFrom(scan);
796
+ }
797
+
798
+ /** The path set of an already-scanned source, or `null` if interpolated. */
799
+ /**
800
+ * Does the declaration starting at `at` sit inside a string literal?
801
+ *
802
+ * Strictly inside, so a span's own opening quote is not "in" it. The
803
+ * head is `describe`/`test`/`it`, which in real source is never inside
804
+ * a string and in a fixture always is — the whole distinction, taken
805
+ * from the scan rather than guessed at.
806
+ */
807
+ function headIsInAString(scan: Scan, at: number): boolean {
808
+ return scan.strings.some(([a, b]) => at > a && at < b);
809
+ }
810
+
811
+ function pathsFrom(scan: Scan): string[] | null {
812
+ const source = scan.forTitles;
813
+
814
+ const stack: { title: string; depth: number }[] = [];
815
+ const paths: string[] = [];
816
+ let depth = 0;
817
+ let interpolated = false;
818
+
819
+ // One pass, walking the braces between title calls. `lastIndex` on a
820
+ // global regex is the cursor; the text between two calls is where the
821
+ // depth moves. The depth is read off `forDepth`, where strings are
822
+ // masked too — a `{` inside a title would otherwise open a block.
823
+ TITLE_CALL.lastIndex = 0;
824
+ let cursor = 0;
825
+ for (const m of source.matchAll(TITLE_CALL)) {
826
+ const at = m.index!;
827
+ depth += braceDelta(scan.forDepth.slice(cursor, at));
828
+ cursor = at;
829
+ // Pop on STRICTLY greater. A describe records the depth INSIDE its own
830
+ // body, which is the depth every call it encloses is read at, so `>=`
831
+ // pops the enclosing describe at its own first child and every path
832
+ // comes out as the bare test title. The first draft had `>=` and the
833
+ // probe caught it: `test/stage-ladder.test.ts` read 41 paths of which
834
+ // not one carried its describe.
835
+ while (stack.length > 0 && stack[stack.length - 1]!.depth > depth) stack.pop();
836
+
837
+ // A declaration quoted INSIDE a string is a fixture, not a test.
838
+ if (headIsInAString(scan, at)) continue;
839
+
840
+ const [, kind, quote, raw] = m as unknown as [string, string, string, string];
841
+ if (quote === "`" && raw.includes("${")) {
842
+ // An interpolated title is a name this cannot know. One is enough to
843
+ // make the whole file's path set incomplete, and an incomplete set
844
+ // can only produce false refusals.
845
+ interpolated = true;
846
+ continue;
847
+ }
848
+ const title = raw.replace(/\\(.)/g, "$1");
849
+ const path = [...stack.map(s => s.title), title].join(" ");
850
+ paths.push(path);
851
+ if (kind === "describe") stack.push({ title, depth: depth + 1 });
852
+ }
853
+
854
+ if (interpolated) return null;
855
+ return paths;
856
+ }
857
+
858
+ /**
859
+ * One tokenizer pass, two masked copies of the source and a verdict.
860
+ *
861
+ * ## Why one pass and not two scanners
862
+ *
863
+ * The first version had a `blankComments` and a `braceDelta` that each
864
+ * walked the text with their own idea of what a token is, and both were
865
+ * missing the same thing. Review of #1877 traced it, in full: neither
866
+ * recognised a **regex literal**, so the `"` inside a character class like
867
+ * `/["x]/` — an idiom that already appears in this repository, at
868
+ * `test/branch-cleanup-slug.test.ts` — opened a string that never closed.
869
+ * The scan then ran off the end of the slice without ever seeing the `}`
870
+ * that closed the enclosing block, the depth came back 1 instead of 0, and
871
+ * a sibling `test` was recorded as nested inside a `describe` whose body
872
+ * had already ended.
873
+ *
874
+ * That is the dangerous direction: not a refusal, not a `null`, but a
875
+ * **confident wrong answer** — a path this invented, which a verify
876
+ * command naming no real test could then match. It is also what the old
877
+ * `braceDelta` docstring claimed it handled. Two deciders, the same blind
878
+ * spot, and a comment asserting the property neither had.
879
+ *
880
+ * ## The three guards
881
+ *
882
+ * 1. Regex literals are recognised and masked, so ordinary files stay
883
+ * readable rather than being written off as UNMEASURED.
884
+ * 2. Anything unterminated — string, template, comment, regex — sets
885
+ * `ok: false`. The old `endOfString` returned `text.length`, which
886
+ * spells "the rest of the file is inside this string" and is how a
887
+ * misparse became silent.
888
+ * 3. Braces must never go negative and must return to zero at the end.
889
+ * This is the GLOBAL check, and it is the one that does not depend on
890
+ * having thought of every token: a scan knocked off the rails by
891
+ * something nobody anticipated comes out unbalanced.
892
+ *
893
+ * Any of the three failing makes `titlePathsIn` return `null`, which is
894
+ * UNMEASURED and reported — never a refusal.
895
+ *
896
+ * `forTitles` keeps string literals (the titles live in them) and blanks
897
+ * comments and regexes. `forDepth` blanks all three. Both are the same
898
+ * length as the input, so one set of offsets indexes both.
899
+ */
900
+ interface Scan {
901
+ forTitles: string;
902
+ forDepth: string;
903
+ /**
904
+ * `[start, end)` of every string and template the scan walked.
905
+ *
906
+ * `forTitles` keeps string content, because that is where a title
907
+ * lives — so by itself it cannot tell a declaration from a fixture
908
+ * string that quotes one. Round 9 measured what that costs: **346
909
+ * names across 69 files existed only inside a string**, each one a
910
+ * `-t` pattern away from a confident MATCHED against a test that
911
+ * exists nowhere. That is #1849's own failure, one level deeper.
912
+ *
913
+ * The scanner already walks every string to mask `forDepth`. This is
914
+ * the same walk, reported instead of discarded — no second parse, and
915
+ * nothing to keep in step with the first.
916
+ */
917
+ strings: [number, number][];
918
+ ok: boolean;
919
+ /**
920
+ * How far the scan actually got. Everything from here on is RAW — not
921
+ * masked, comments included.
922
+ *
923
+ * Round 2 of review found `titlesIn` reading `forTitles` whole while
924
+ * ignoring `ok`, so a `describe("phantom")` sitting in a comment in the
925
+ * unscanned tail of an unparseable file was returned as a declared
926
+ * title, and the literal fast path reported MATCHED for a test that
927
+ * exists nowhere. The mitigation for a confidently-wrong answer was
928
+ * itself confidently wrong. A reader of a failed scan may only trust
929
+ * the prefix the scan completed.
930
+ */
931
+ scannedUpTo: number;
932
+ }
933
+
934
+ /**
935
+ * Characters after which a `/` opens a regex rather than dividing.
936
+ *
937
+ * `!` is in the set and needs the lookback below: in TypeScript a `!`
938
+ * after an expression is the non-null assertion, so `a.b! / c` is
939
+ * DIVISION, while `!/re/.test(x)` is negation followed by a regex. Both
940
+ * spellings are live in this tree; `test/crc-reading.test.ts` has the
941
+ * first.
942
+ */
943
+ const REGEX_MAY_FOLLOW = new Set([..."(,=:[!&|?{};+-*%~^<>", "\n"]);
944
+
945
+ /**
946
+ * Keywords after which a `/` opens a regex.
947
+ *
948
+ * Without these, `return /labels\s*:/.test(src)` reads the `/` as
949
+ * division, scans on INTO the pattern, and the `"` in the next regex on
950
+ * the same line opens a string that never closes. That is
951
+ * `test/board-ready-rule.test.ts:478`, which five live verify fragments
952
+ * point at — so the whole file went UNMEASURED and five items lost their
953
+ * check. A character class is not the only way in.
954
+ */
955
+ const REGEX_AFTER_WORD = new Set([
956
+ "return", "typeof", "instanceof", "in", "of", "new", "delete",
957
+ "void", "do", "else", "case", "yield", "await", "throw",
958
+ ]);
959
+
960
+ /**
961
+ * Is the `/` at `at` opening a regex, or dividing? ONE decider.
962
+ *
963
+ * It lives at module scope because there are two walkers that have to
964
+ * answer it — `scanSource` over the file, and `endOfSubstitution` inside
965
+ * a `${…}` — and round 5 found them holding two copies, of which the
966
+ * inner one had missed round 3's two fixes. Two guards answering the
967
+ * same question about the same input are behaviourally ONE guard: no
968
+ * case over the outer scanner can tell them apart, and the stale copy
969
+ * reads as covered. `.claude/rules/checks-must-be-able-to-fail.md`
970
+ * names the shape.
971
+ *
972
+ * `prev` is the last significant token, which each caller tracks itself
973
+ * — a whole word, or one character, or the two-character `++`/`--`.
974
+ * Both callers must merge those two, or `i++ / n` arrives here spelled
975
+ * `+` and is indistinguishable from binary plus.
976
+ *
977
+ * `before` is the token before `prev`, and it is read for exactly one
978
+ * case: `!`. See `endsAnExpression`.
979
+ */
980
+ function opensARegexAfter(prev: string, before: string): boolean {
981
+ if (REGEX_AFTER_WORD.has(prev)) return true;
982
+ if (prev === "++" || prev === "--") return false;
983
+ if (prev === "!") return !endsAnExpression(before);
984
+ return prev.length === 1 && REGEX_MAY_FOLLOW.has(prev);
985
+ }
986
+
987
+ /**
988
+ * Did this token finish a value? The whole of the `!` decision.
989
+ *
990
+ * `a.b! / c` is a non-null assertion then DIVISION; `return !/re/` is
991
+ * negation then a REGEX. The two are told apart by what sits before the
992
+ * `!`, and nothing else can tell them apart.
993
+ *
994
+ * Round 3 asked this question by LAST CHARACTER, so `return` ended in
995
+ * `n`, counted as a value, and an ordinary file became unreadable. The
996
+ * repair then was to delete the lookback and TRIAL-PARSE instead: treat
997
+ * the `/` as a regex if some later `/` on the line could close it.
998
+ * Round 8 found what that costs — `expect(z.oneRound! / z.passed)
999
+ * .toBeCloseTo(1 / 3, 5)` in `test/crc-reading.test.ts` pairs the two
1000
+ * slashes and masks everything between them. The docstring that
1001
+ * replaced the lookback claimed this shape had no instance in the tree.
1002
+ * It had one the whole time, and the claim was never swept for.
1003
+ *
1004
+ * So the question is asked again, of the WHOLE token this time, which
1005
+ * is the version that answers `return` correctly. A trial-parse was
1006
+ * never evidence: a line almost always has another `/` somewhere.
1007
+ */
1008
+ function endsAnExpression(token: string): boolean {
1009
+ if (token === ")" || token === "]") return true;
1010
+ if (token === '"' || token === "'" || token === "`" || token === "/re/") return true;
1011
+ return /^[\w$]/.test(token) && !REGEX_AFTER_WORD.has(token);
1012
+ }
1013
+
1014
+ function scanSource(text: string): Scan {
1015
+ const titles = text.split("");
1016
+ const depth = text.split("");
1017
+ const blank = (buf: string[], from: number, to: number) => {
1018
+ for (let k = from; k < to && k < buf.length; k++) if (buf[k] !== "\n") buf[k] = " ";
1019
+ };
1020
+
1021
+ let i = 0;
1022
+ // The last two significant tokens — each a whole word, one character,
1023
+ // or the two-character `++`/`--`. Two, because `!` is decided by what
1024
+ // came before it (`endsAnExpression`). Round 4 deleted the second slot
1025
+ // as dead and it was: the decision that needed it had been replaced by
1026
+ // a trial-parse. Round 8 found what the trial-parse got wrong.
1027
+ let prev = "\n";
1028
+ let before = "\n";
1029
+ let ok = true;
1030
+ let braces = 0;
1031
+ const strings: [number, number][] = [];
1032
+
1033
+ /**
1034
+ * Is the `/` at `at` opening a regex, or dividing?
1035
+ *
1036
+ * Round 3 of review found both remaining members of this set, and both
1037
+ * were real:
1038
+ *
1039
+ * - `return !/\bcwd\s*:/.test(line)` — the old lookback asked whether
1040
+ * the token before `!` "ends an expression" by its LAST CHARACTER, so
1041
+ * `return` ended in `n` and counted as one. The regex was read as
1042
+ * division, the scan ran on into the pattern, and the pattern's real
1043
+ * closing `/` was then taken as a new regex that never closed. One
1044
+ * ordinary file became unreadable
1045
+ * (`test/unit/git-identity-isolation.test.ts:91`).
1046
+ * - `i++ / n` — `prev` was a bare `+` either way, so postfix increment
1047
+ * was indistinguishable from binary plus. MEASURED on a planted
1048
+ * file: a `test("swallowed")` sitting after it was silently dropped
1049
+ * from the name set with a CLEAN reading, while the same file with
1050
+ * `i + 1` kept all three titles. A real test vanishing with no
1051
+ * UNMEASURED signal is a false refusal waiting to happen.
1052
+ *
1053
+ * `++`/`--` are one token, so postfix is visible. `!` is decided by
1054
+ * the token BEFORE it — `endsAnExpression`, which is where round 8's
1055
+ * correction lives and which replaced the trial-parse that stood here
1056
+ * between rounds 3 and 8.
1057
+ *
1058
+ * The decision is `opensARegexAfter`, at module scope, because
1059
+ * `endOfSubstitution` has to make it too — see its own note.
1060
+ */
1061
+ const opensARegex = () => opensARegexAfter(prev, before);
1062
+ const remember = (tok: string) => {
1063
+ before = prev;
1064
+ prev = tok;
1065
+ };
1066
+
1067
+ while (i < text.length) {
1068
+ const c = text[i]!;
1069
+
1070
+ // An identifier or keyword is one token, not its last letter.
1071
+ if (/[A-Za-z_$]/.test(c)) {
1072
+ let j = i;
1073
+ while (j < text.length && /[\w$]/.test(text[j]!)) j++;
1074
+ remember(text.slice(i, j));
1075
+ i = j;
1076
+ continue;
1077
+ }
1078
+
1079
+ if (c === "/" && text[i + 1] === "/") {
1080
+ const end = text.indexOf("\n", i);
1081
+ const stop = end === -1 ? text.length : end;
1082
+ blank(titles, i, stop);
1083
+ blank(depth, i, stop);
1084
+ i = stop;
1085
+ continue;
1086
+ }
1087
+ if (c === "/" && text[i + 1] === "*") {
1088
+ const end = text.indexOf("*/", i + 2);
1089
+ if (end === -1) { ok = false; break; }
1090
+ blank(titles, i, end + 2);
1091
+ blank(depth, i, end + 2);
1092
+ i = end + 2;
1093
+ continue;
1094
+ }
1095
+ // `++` and `--` are ONE token. Character-by-character, postfix
1096
+ // increment and binary plus both leave `prev` as a bare `+`.
1097
+ if ((c === "+" || c === "-") && text[i + 1] === c) {
1098
+ remember(c + c);
1099
+ i += 2;
1100
+ continue;
1101
+ }
1102
+
1103
+ if (c === "/" && opensARegex()) {
1104
+ const end = endOfRegex(text, i);
1105
+ if (end === -1) { ok = false; break; }
1106
+ blank(titles, i, end);
1107
+ blank(depth, i, end);
1108
+ i = end;
1109
+ remember("/re/");
1110
+ continue;
1111
+ }
1112
+ if (c === '"' || c === "'" || c === "`") {
1113
+ const end = endOfString(text, i);
1114
+ if (end === -1) { ok = false; break; }
1115
+ // Kept in `forTitles` — this is where a title lives. The span is
1116
+ // reported so a reader can tell a title from a fixture that quotes one.
1117
+ strings.push([i, end]);
1118
+ blank(depth, i, end);
1119
+ i = end;
1120
+ remember(c);
1121
+ continue;
1122
+ }
1123
+ if (c === "{") braces++;
1124
+ else if (c === "}") {
1125
+ braces--;
1126
+ if (braces < 0) { ok = false; break; }
1127
+ }
1128
+ if (!/\s/.test(c)) remember(c);
1129
+ i++;
1130
+ }
1131
+
1132
+ return {
1133
+ forTitles: titles.join(""),
1134
+ forDepth: depth.join(""),
1135
+ strings,
1136
+ ok: ok && braces === 0,
1137
+ // Where the loop stopped. On a clean run that is the end; on a bail
1138
+ // it is the token that defeated it, and nothing past it was masked.
1139
+ scannedUpTo: i,
1140
+ };
1141
+ }
1142
+
1143
+ /** Index just past a regex literal's closing `/` and flags, or -1. */
1144
+ function endOfRegex(text: string, from: number): number {
1145
+ let i = from + 1;
1146
+ let inClass = false;
1147
+ while (i < text.length) {
1148
+ const c = text[i]!;
1149
+ if (c === "\\") { i += 2; continue; }
1150
+ if (c === "\n") return -1; // a regex literal cannot span a line
1151
+ if (c === "[") inClass = true;
1152
+ else if (c === "]") inClass = false;
1153
+ else if (c === "/" && !inClass) {
1154
+ i++;
1155
+ while (i < text.length && /[a-z]/.test(text[i]!)) i++;
1156
+ return i;
1157
+ }
1158
+ i++;
1159
+ }
1160
+ return -1;
1161
+ }
1162
+
1163
+ /**
1164
+ * Index just past a string's closing quote, or -1 when it never closes.
1165
+ *
1166
+ * A template is NOT "scan to the next backtick". `${x.map(p => \`-${p}\`)}`
1167
+ * — a template nested inside its own substitution — is ordinary in this
1168
+ * tree, and the naive scan ends the outer template at the INNER opening
1169
+ * backtick. Everything after that is read in the wrong state, which on
1170
+ * `test/issue-file-overlap.test.ts` ate a `{` and the file came out with
1171
+ * a negative brace depth 280 lines later. So a substitution is walked as
1172
+ * a brace group, with its own strings and templates inside it.
1173
+ */
1174
+ function endOfString(text: string, from: number): number {
1175
+ const quote = text[from]!;
1176
+ if (quote === "`") return endOfTemplate(text, from);
1177
+ let i = from + 1;
1178
+ while (i < text.length) {
1179
+ if (text[i] === "\\") { i += 2; continue; }
1180
+ if (text[i] === quote) return i + 1;
1181
+ if (text[i] === "\n") return -1; // a quoted string does not span lines
1182
+ i++;
1183
+ }
1184
+ return -1;
1185
+ }
1186
+
1187
+ /**
1188
+ * A template, walked to its closing backtick.
1189
+ *
1190
+ * A substitution holding its OWN template — `${xs.map(p => \`-${p}\`)}` —
1191
+ * ends this scan at the inner opening backtick. That is a real misparse
1192
+ * and it is deliberately NOT fixed here.
1193
+ *
1194
+ * It was attempted: a recursive substitution walker took the unparseable
1195
+ * corpus from four files to eleven, because the substitution needs its
1196
+ * own regex handling, which needs its own character-class handling, and
1197
+ * each repair had the next instance of the same class inside it. Three
1198
+ * rounds, which is where AGENTS.md rule 5 says stop repairing and
1199
+ * re-scope.
1200
+ *
1201
+ * The re-scope is `titlesIn` plus the fallback in `verifyTitleFragments`:
1202
+ * a file this cannot nest correctly still yields its title LITERALS, and
1203
+ * a pattern matching one of those is MATCHED without any nesting being
1204
+ * believed. The parser is allowed to be imperfect; what it is not allowed
1205
+ * to be is confidently wrong, and `scan.ok` is what separates those.
1206
+ */
1207
+ function endOfTemplate(text: string, from: number): number {
1208
+ let i = from + 1;
1209
+ while (i < text.length) {
1210
+ if (text[i] === "\\") { i += 2; continue; }
1211
+ if (text[i] === "`") return i + 1;
1212
+ if (text[i] === "$" && text[i + 1] === "{") {
1213
+ const end = endOfSubstitution(text, i + 1);
1214
+ if (end === -1) return -1;
1215
+ i = end;
1216
+ continue;
1217
+ }
1218
+ i++;
1219
+ }
1220
+ return -1;
1221
+ }
1222
+
1223
+ /**
1224
+ * Index just past the `}` closing a `${…}`, or -1.
1225
+ *
1226
+ * The first attempt at this was deleted for taking the unparseable
1227
+ * corpus from 4 files to 11, and the reason was precise: it knew about
1228
+ * strings and comments and **not** about regex literals, so it repeated
1229
+ * the exact defect the outer scanner had just been fixed for. One level
1230
+ * down, same blind spot. It is here now, with the regex branch.
1231
+ *
1232
+ * And the branch calls `opensARegexAfter`, the SAME decider the outer
1233
+ * scanner uses. Round 5 found this walker holding its own copy of the
1234
+ * rule, missing round 3's two fixes — so `${i++ / 2}` and `${a.b! / c}`
1235
+ * each opened a phantom regex and the whole file went UNMEASURED. One
1236
+ * question, one decider; a copy of it is a guard nothing can mutate.
1237
+ */
1238
+ function endOfSubstitution(text: string, from: number): number {
1239
+ let i = from + 1;
1240
+ let open = 1;
1241
+ let prev = "{";
1242
+ let before = "{";
1243
+ while (i < text.length) {
1244
+ const c = text[i]!;
1245
+ if (/[A-Za-z_$]/.test(c)) {
1246
+ let j = i;
1247
+ while (j < text.length && /[\w$]/.test(text[j]!)) j++;
1248
+ before = prev;
1249
+ prev = text.slice(i, j);
1250
+ i = j;
1251
+ continue;
1252
+ }
1253
+ // `++`/`--` as one token, for the reason `opensARegexAfter` states:
1254
+ // split, postfix increment arrives there spelled `+`.
1255
+ if ((c === "+" || c === "-") && text[i + 1] === c) { before = prev; prev = c + c; i += 2; continue; }
1256
+ if (c === "/" && text[i + 1] === "/") {
1257
+ const e = text.indexOf("\n", i);
1258
+ i = e === -1 ? text.length : e;
1259
+ continue;
1260
+ }
1261
+ if (c === "/" && text[i + 1] === "*") {
1262
+ const e = text.indexOf("*/", i + 2);
1263
+ if (e === -1) return -1;
1264
+ i = e + 2;
1265
+ continue;
1266
+ }
1267
+ if (c === "/" && opensARegexAfter(prev, before)) {
1268
+ const e = endOfRegex(text, i);
1269
+ if (e === -1) return -1;
1270
+ i = e;
1271
+ before = prev;
1272
+ prev = "/re/";
1273
+ continue;
1274
+ }
1275
+ if (c === '"' || c === "'" || c === "`") {
1276
+ const e = endOfString(text, i);
1277
+ if (e === -1) return -1;
1278
+ i = e;
1279
+ before = prev;
1280
+ prev = c;
1281
+ continue;
1282
+ }
1283
+ if (c === "{") open++;
1284
+ else if (c === "}") {
1285
+ open--;
1286
+ if (open === 0) return i + 1;
1287
+ }
1288
+ if (!/\s/.test(c)) { before = prev; prev = c; }
1289
+ i++;
1290
+ }
1291
+ return -1;
1292
+ }
1293
+
1294
+ /**
1295
+ * A `describe` / `test` / `it` whose call does NOT open with a quote.
1296
+ *
1297
+ * Review round 2 named `test.each(CASES)("%s", fn)` — 46 files here use
1298
+ * it — and the general shape is wider than that one spelling: anything
1299
+ * whose first argument is not a string literal declares names this
1300
+ * cannot resolve.
1301
+ *
1302
+ * | spelling | first argument |
1303
+ * |---|---|
1304
+ * | `test.each(CASES)("%s", fn)` | `CASES`, and the title is printf bun fills in |
1305
+ * | `test.skipIf(cond)("title")` | `cond` |
1306
+ * | `test(NAME, fn)` | a variable |
1307
+ *
1308
+ * Enumerated as a SHAPE rather than repaired per spelling, because the
1309
+ * finding named one member of exactly this population (#1818). A file
1310
+ * holding one of these has names this cannot see, so a pattern matching
1311
+ * nothing in it is UNMEASURED — never the false refusal review predicted.
1312
+ *
1313
+ * It opens with `DECLARATION_HEAD`, the same string `TITLE_CALL` opens
1314
+ * with, because the two must agree on what a declaration IS. They did
1315
+ * not in round 6 (the modifier chain) and again in round 7 (the space
1316
+ * before the paren), and both gaps were silent — see `TITLE_CALL`'s
1317
+ * note. One constant is the only version of that agreement a later edit
1318
+ * cannot break one-sidedly.
1319
+ */
1320
+ const UNRESOLVED_CALL = new RegExp(String.raw`${DECLARATION_HEAD}(.)`, "g");
1321
+
1322
+ /**
1323
+ * `TITLE_CALL`, anchored, so the two patterns can be asked to agree
1324
+ * about one declaration rather than about their own spelling.
1325
+ */
1326
+ const TITLE_CALL_AT = new RegExp(TITLE_CALL.source, "y");
1327
+
1328
+ function hasUnresolvedDeclaration(scan: Scan): boolean {
1329
+ const masked = scan.forTitles;
1330
+ UNRESOLVED_CALL.lastIndex = 0;
1331
+ for (const m of masked.matchAll(UNRESOLVED_CALL)) {
1332
+ // A declaration quoted inside a string is a fixture. Asked here too,
1333
+ // or a fixture string would be the thing reported unresolved.
1334
+ if (headIsInAString(scan, m.index!)) continue;
1335
+ // Group 2: group 1 is the declaration name, captured by the shared
1336
+ // `DECLARATION_HEAD`.
1337
+ const first = m[2]!;
1338
+ if (first !== '"' && first !== "'" && first !== "`") return true;
1339
+ // A quote is not the same fact as a title this can READ. Round 8: a
1340
+ // template literal spanning two lines matches no `TITLE_CALL`, and
1341
+ // a check on the first character alone sees a backtick and calls the
1342
+ // file complete — so the name vanished from a set reported as whole,
1343
+ // which is the false refusal. Sharing the head (round 7) made the
1344
+ // patterns START alike; this makes them AGREE, which is the property
1345
+ // that was wanted, and it holds for a title shape nobody has thought
1346
+ // of yet.
1347
+ TITLE_CALL_AT.lastIndex = m.index!;
1348
+ if (!TITLE_CALL_AT.test(masked)) return true;
1349
+ }
1350
+ return false;
1351
+ }
1352
+
1353
+ /**
1354
+ * Every title LITERAL in a file, with no nesting believed.
1355
+ *
1356
+ * Comments are masked, so a `describe("…")` in prose is still excluded,
1357
+ * but nothing here depends on brace depth — which is the half that can
1358
+ * be confidently wrong. This is what a file the scanner cannot nest
1359
+ * falls back to.
1360
+ *
1361
+ * **Only the prefix the scan completed is read.** Past that point
1362
+ * nothing was masked, so a `describe("phantom")` inside a COMMENT in the
1363
+ * tail of an unparseable file would be returned as a declared name, and
1364
+ * the literal fast path in `verifyTitleFragments` would report MATCHED
1365
+ * for a test that exists nowhere. Round 2 of review on #1877.
1366
+ */
1367
+ export function titlesIn(raw: string): string[] {
1368
+ const scan = scanSource(raw);
1369
+ const source = scan.forTitles.slice(0, scan.scannedUpTo);
1370
+ const out: string[] = [];
1371
+ TITLE_CALL.lastIndex = 0;
1372
+ for (const m of source.matchAll(TITLE_CALL)) {
1373
+ // A declaration quoted INSIDE a string is a fixture, not a test.
1374
+ if (headIsInAString(scan, m.index!)) continue;
1375
+ const [, , quote, text] = m as unknown as [string, string, string, string];
1376
+ if (quote === "`" && text.includes("${")) continue;
1377
+ out.push(text.replace(/\\(.)/g, "$1"));
1378
+ }
1379
+ return out;
1380
+ }
1381
+
1382
+ /**
1383
+ * Can this file's set of names be known in full?
1384
+ *
1385
+ * The single predicate behind every UNMEASURED, so there is one place
1386
+ * that decides and one place to mutate. `false` means a pattern matching
1387
+ * nothing here is UNMEASURED rather than a refusal.
1388
+ */
1389
+ export function namesAreComplete(raw: string): { complete: boolean; why: string | null } {
1390
+ const scan = scanSource(raw);
1391
+ if (!scan.ok) {
1392
+ return { complete: false, why: "the scanner could not read the whole file — an unterminated string, comment or regex, or braces that do not balance" };
1393
+ }
1394
+ if (hasUnresolvedDeclaration(scan)) {
1395
+ return { complete: false, why: "it declares at least one test whose title is not a string literal (`.each`, `.skipIf(…)(…)`, or a variable)" };
1396
+ }
1397
+ if (pathsFrom(scan) === null) {
1398
+ return { complete: false, why: "it builds at least one title by interpolation" };
1399
+ }
1400
+ return { complete: true, why: null };
1401
+ }
1402
+
1403
+ /** Net `{` minus `}` over an already-masked slice. */
1404
+ function braceDelta(masked: string): number {
1405
+ let d = 0;
1406
+ for (const c of masked) {
1407
+ if (c === "{") d++;
1408
+ else if (c === "}") d--;
1409
+ }
1410
+ return d;
1411
+ }
1412
+
1413
+ /**
1414
+ * Every `bun test … -t …` in one command, read against the tree.
1415
+ *
1416
+ * `readSource` returns the file's text, or `null` when there is no such
1417
+ * file. Injected rather than read here so the caller owns the root and so
1418
+ * a test can plant a corpus without a temp directory — the same reason
1419
+ * `promote` takes its registry.
1420
+ *
1421
+ * A command containing no such fragment yields NOTHING. That is not a
1422
+ * pass: `verifyTitleViolations` counts it separately, so "this shape was
1423
+ * not checked" stays visible instead of being absorbed into a green.
1424
+ */
1425
+ export function verifyTitleFragments(
1426
+ where: string,
1427
+ verify: string,
1428
+ readSource: (file: string) => string | null,
1429
+ ): VerifyTitleFragment[] {
1430
+ const out: VerifyTitleFragment[] = [];
1431
+ BUN_TEST_T.lastIndex = 0;
1432
+ for (const m of verify.matchAll(BUN_TEST_T)) {
1433
+ const file = m[1]!;
1434
+ const name = m[3]!;
1435
+ const push = (reading: VerifyTitleReading, why: string) => out.push({ where, file, name, reading, why });
1436
+
1437
+ const src = readSource(file);
1438
+ if (src === null) {
1439
+ push("FILE_ABSENT", `${file} does not exist, so this command selects nothing`);
1440
+ continue;
1441
+ }
1442
+ const literals = titlesIn(src);
1443
+ // An empty name set is NOT a reason to excuse the command. Whether it
1444
+ // means "unreadable" or "declares nothing" is the same question the
1445
+ // no-match path below asks, and it is asked there, once. Short-cutting
1446
+ // on the COUNT sent a readable file that declares nothing — a `-t`
1447
+ // aimed at the wrong file, which is the whole case this exists for —
1448
+ // to UNMEASURED, and UNMEASURED refuses nothing.
1449
+ let re: RegExp;
1450
+ try {
1451
+ re = new RegExp(name);
1452
+ } catch (e) {
1453
+ push("UNMEASURED", `-t ${JSON.stringify(name)} is not a regular expression: ${e instanceof Error ? e.message : String(e)}`);
1454
+ continue;
1455
+ }
1456
+
1457
+ // A literal match needs no nesting to be believed, so it is asked
1458
+ // first and answers every live fragment in the plan today.
1459
+ if (literals.some(t => re.test(t))) {
1460
+ push("MATCHED", "");
1461
+ continue;
1462
+ }
1463
+
1464
+ // Then nesting: the pattern may name a PATH spanning a describe and
1465
+ // the test inside it.
1466
+ const paths = titlePathsIn(src);
1467
+ if (paths !== null && paths.some(p => re.test(p))) {
1468
+ push("MATCHED", "");
1469
+ continue;
1470
+ }
1471
+
1472
+ // Nothing matched. Whether that is a REFUSAL or an UNMEASURED turns
1473
+ // on one question, asked in one place: could this file's names be
1474
+ // known in full? Refusing a file whose names this cannot see is the
1475
+ // false red that makes a check an obstacle.
1476
+ const { complete, why } = namesAreComplete(src);
1477
+ if (!complete) {
1478
+ push("UNMEASURED", `${JSON.stringify(name)} matches nothing in ${file}, and ${file} cannot be read in full: ${why}`);
1479
+ continue;
1480
+ }
1481
+ push(
1482
+ "NO_SUCH_TITLE",
1483
+ `no describe/test title in ${file} matches ${JSON.stringify(name)} — ${(paths ?? literals).length} name(s) read`,
1484
+ );
1485
+ }
1486
+ return out;
1487
+ }
1488
+
1489
+ /**
1490
+ * The refusal. One line per fragment that is not `MATCHED`, naming the
1491
+ * item, the file and the title — AC-2, because a bare count sends the next
1492
+ * reader back through every command in the plan.
1493
+ *
1494
+ * `UNMEASURED` is reported and does NOT refuse. It is a statement that
1495
+ * this instrument could not see the fragment, and turning that into a red
1496
+ * row would make the honest reading the expensive one.
1497
+ */
1498
+ export function verifyTitleViolations(
1499
+ commands: readonly { where: string; verify: string | null }[],
1500
+ readSource: (file: string) => string | null,
1501
+ ): { violations: string[]; unmeasured: string[]; matched: number; outOfShape: number } {
1502
+ const violations: string[] = [];
1503
+ const unmeasured: string[] = [];
1504
+ let matched = 0;
1505
+ let outOfShape = 0;
1506
+
1507
+ for (const c of commands) {
1508
+ if (c.verify === null || c.verify.trim().length === 0) continue;
1509
+ const frags = verifyTitleFragments(c.where, c.verify, readSource);
1510
+ if (frags.length === 0) {
1511
+ outOfShape++;
1512
+ continue;
1513
+ }
1514
+ for (const f of frags) {
1515
+ if (f.reading === "MATCHED") matched++;
1516
+ else if (f.reading === "UNMEASURED") unmeasured.push(`${f.where}: ${f.why}`);
1517
+ else violations.push(`${f.where}: ${f.why}`);
1518
+ }
1519
+ }
1520
+ return { violations, unmeasured, matched, outOfShape };
1521
+ }