rungate 0.6.0 → 0.7.0

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 (113) hide show
  1. package/lib/affected-tests.ts +398 -0
  2. package/lib/agent-audit.ts +2 -3
  3. package/lib/agent-worktree.ts +287 -0
  4. package/lib/agents-md-sections.ts +81 -16
  5. package/lib/behavioral-cache.ts +150 -2
  6. package/lib/branch-protection.ts +790 -0
  7. package/lib/brief-ac-alignment.ts +104 -0
  8. package/lib/brief-references.ts +205 -0
  9. package/lib/bun-version.ts +93 -14
  10. package/lib/check-remedy.ts +140 -0
  11. package/lib/ci-checkout.ts +17 -0
  12. package/lib/ci-history-depth.ts +159 -0
  13. package/lib/ci-setup-step.ts +96 -0
  14. package/lib/claude-code-action.ts +85 -0
  15. package/lib/claude-tool-vocabulary.ts +188 -0
  16. package/lib/cli-commands.ts +15 -0
  17. package/lib/commit-sha.ts +42 -0
  18. package/lib/commit-subject.ts +90 -0
  19. package/lib/compliance-report.ts +377 -45
  20. package/lib/compliance.ts +191 -17
  21. package/lib/config-loader.ts +39 -1
  22. package/lib/config-trackable.ts +391 -0
  23. package/lib/conformity.ts +1087 -100
  24. package/lib/containment.ts +238 -0
  25. package/lib/content-hash.ts +24 -0
  26. package/lib/create-sc.ts +249 -16
  27. package/lib/dev-liveness.ts +180 -0
  28. package/lib/discovery-branch-points.ts +432 -0
  29. package/lib/discovery-stability.ts +481 -0
  30. package/lib/distribution-currency.ts +186 -0
  31. package/lib/doc-routing.ts +157 -0
  32. package/lib/evidence-prevalidator.ts +224 -2
  33. package/lib/evidence-satisfiability.ts +534 -12
  34. package/lib/failure-intake.ts +317 -0
  35. package/lib/fallow-availability.ts +157 -0
  36. package/lib/fs-write-capabilities.ts +232 -0
  37. package/lib/gate-run-split.ts +147 -0
  38. package/lib/generators/agents-md.ts +140 -32
  39. package/lib/git-isolation.ts +140 -0
  40. package/lib/github.ts +15 -0
  41. package/lib/google-auth-action.ts +93 -0
  42. package/lib/harness-project.ts +48 -0
  43. package/lib/harness-provenance.ts +255 -0
  44. package/lib/hook-evidence.ts +235 -0
  45. package/lib/hook-scopes.ts +386 -0
  46. package/lib/hook-target-tree.ts +398 -0
  47. package/lib/hook-trees.ts +447 -0
  48. package/lib/js-top-level-code.ts +78 -10
  49. package/lib/junit-checks.ts +52 -0
  50. package/lib/launch-base.ts +253 -0
  51. package/lib/line-citation.ts +372 -0
  52. package/lib/orphan-reaper.ts +468 -0
  53. package/lib/parity-binding.ts +205 -0
  54. package/lib/per-test-timeouts.ts +219 -0
  55. package/lib/plan-coverage.ts +151 -0
  56. package/lib/prior-branch.ts +201 -8
  57. package/lib/process-table.ts +146 -0
  58. package/lib/project-state-derivation.ts +219 -0
  59. package/lib/project-state-root.ts +258 -0
  60. package/lib/published-artifact.ts +525 -0
  61. package/lib/readdir-sorted.ts +45 -0
  62. package/lib/review-execution-reading.ts +206 -0
  63. package/lib/review-tool-agreement.ts +433 -0
  64. package/lib/rule-promotion.ts +234 -0
  65. package/lib/rule-retirement.ts +525 -0
  66. package/lib/run-branch.ts +612 -0
  67. package/lib/rungate-schema.ts +19 -0
  68. package/lib/runner-home.ts +274 -0
  69. package/lib/sc-id-cross-tree.ts +19 -7
  70. package/lib/sc-ids.ts +121 -13
  71. package/lib/sc-reservations.ts +289 -0
  72. package/lib/scaffold/ai-review-findings.ts +403 -0
  73. package/lib/scaffold/ai-review-step.ts +4661 -64
  74. package/lib/scaffold/managed-workflow.ts +587 -192
  75. package/lib/scaffold/owned-files.ts +152 -45
  76. package/lib/scaffold/pre-push-hook.ts +49 -5
  77. package/lib/scaffold/steps.ts +1413 -244
  78. package/lib/scaffold/workflow-census.ts +217 -0
  79. package/lib/scaffold/workflow-drift.ts +217 -0
  80. package/lib/scaffold/write-steps.ts +4 -0
  81. package/lib/scan-budget.ts +247 -0
  82. package/lib/scanner.ts +43 -51
  83. package/lib/scratch-roots.ts +50 -5
  84. package/lib/screenshot-discovery.ts +121 -0
  85. package/lib/screenshot-upload.ts +41 -1
  86. package/lib/secret-patterns.ts +511 -8
  87. package/lib/ship-mode.ts +219 -0
  88. package/lib/source-slice.ts +294 -0
  89. package/lib/stale-cleanup.ts +37 -3
  90. package/lib/suite-flake.ts +278 -0
  91. package/lib/suite-measurement.ts +23 -4
  92. package/lib/suite-run-reading.ts +241 -1
  93. package/lib/suite-timeout-margin.ts +193 -0
  94. package/lib/test-case-bodies.ts +883 -0
  95. package/lib/test-case-deletion.ts +653 -0
  96. package/lib/test-census.ts +97 -29
  97. package/lib/test-command-positions.ts +274 -0
  98. package/lib/test-suite-lock.ts +159 -16
  99. package/lib/tool-probe.ts +31 -9
  100. package/lib/top-level-cd.ts +393 -0
  101. package/lib/tree-entries.ts +89 -0
  102. package/lib/ts-ast.ts +200 -0
  103. package/lib/walk-test-files.ts +97 -0
  104. package/lib/workflow-actions.ts +263 -0
  105. package/lib/worktree-collect.ts +177 -5
  106. package/lib/worktree-repo.ts +36 -1
  107. package/package.json +2 -1
  108. package/scripts/ai-review-findings.ts +45 -0
  109. package/scripts/create-sc.ts +21 -1
  110. package/scripts/extract-constraints.ts +107 -7
  111. package/scripts/generate-code-map.ts +23 -30
  112. package/scripts/scaffold-project.ts +8 -1
  113. package/scripts/sync-sc-status.ts +77 -16
@@ -0,0 +1,883 @@
1
+ /**
2
+ * What a test file declares, and what each declaration's BODY is (#880).
3
+ *
4
+ * ## Why a body, when a title was enough for #659
5
+ *
6
+ * It was never enough. `lib/test-case-deletion.ts` has said since it was
7
+ * written that *"a name that is gone is a deleted passing test, a deleted
8
+ * failing test, a renamed test, or a test somebody moved to another file"*,
9
+ * and then compared `Set<string>` of titles — so three of those four read as
10
+ * the first one. Run `wf_99ed276b-cf3` is the bill: eight cases reported
11
+ * missing, seven of them renamed by the repair round, net coverage over the
12
+ * run 19 → 27, and the run refused.
13
+ *
14
+ * A title is the one part of a test that a rename is DEFINED as changing.
15
+ * The body is the part a rename is defined as leaving alone, so the body is
16
+ * what the comparison has to be about. #880 ranks its own three remedies and
17
+ * puts this first — *"the only one that is actually a measurement"* — with
18
+ * the other two, title similarity and a louder refusal, as heuristics.
19
+ *
20
+ * ## The comparison is identity, not similarity
21
+ *
22
+ * Two bodies are the same body when they are IDENTICAL after `normalisedBody`
23
+ * removes comments and collapses runs of whitespace. Those are the two kinds
24
+ * of difference that carry no behaviour. There is no threshold, no distance
25
+ * and no score, and that is a deliberate refusal of #880's option 2: a
26
+ * heuristic that guesses wrong in the reassuring direction — pairing a
27
+ * deleted case with an unrelated new one and reporting "renamed" — is worse
28
+ * than the refusal it replaces, because the operator stops looking.
29
+ *
30
+ * Everything this cannot pair is reported as a deletion, which is the
31
+ * pre-#880 answer. A case renamed AND edited in one round reads as a
32
+ * deletion plus an addition, and that is the direction to be wrong in.
33
+ *
34
+ * ## Why no hash
35
+ *
36
+ * #880 says "hash the normalised test body". The hash is an implementation
37
+ * detail of "compare the normalised body", and omitting it removes a whole
38
+ * class of reasoning about collisions for nothing — a test file holds
39
+ * hundreds of cases, not millions, so the normalised string IS the key. One
40
+ * fewer binding to mutate, and `normalisedBody` is the only thing deciding
41
+ * what "the same body" means.
42
+ *
43
+ * ## The scan knows about strings, templates, comments and regexes
44
+ *
45
+ * `lib/source-slice.ts` is the repository's structural-cut binding and is
46
+ * deliberately NOT used here: its docblock says in as many words that its
47
+ * bracket scan *"does not know about strings, comments or regex literals"*,
48
+ * and it refuses an anchor that occurs twice. Both are right for cutting one
49
+ * named construct out of a document and wrong for cutting every `test(...)`
50
+ * call out of a suite, where titles repeat and bodies are full of
51
+ * `toMatch(/[)(]/)`. So the scanner below is its own thing, and
52
+ * `matchingCallParen` is the ONE place that decides where a call ends.
53
+ *
54
+ * ## What was broken to prove it
55
+ *
56
+ * Run and counted over `test/unit/case-rename-detection.test.ts` +
57
+ * `test/deletion-verdict-relay.test.ts` +
58
+ * `test/unit/deleted-case-non-vacuous.test.ts` — 87 tests. Every count was
59
+ * predicted before the battery ran, and **the baseline row was read before
60
+ * any mutation row**: an instrument that has stopped reporting takes the
61
+ * baseline down with it, and that is the row nobody mutates anything to
62
+ * produce.
63
+ *
64
+ * **Provenance.** P1–P11 were first measured at a baseline of 82, before the
65
+ * second security review added the `describe`-chain key and two cases. They
66
+ * were ALL re-run against the final tree rather than carried over — a row
67
+ * measured on a tree nobody can check out is a claim rather than a count
68
+ * (`.claude/rules/parallel-sessions.md`). Only P1 moved, from 7 to 8, and
69
+ * the extra red is AC-18's control.
70
+ *
71
+ * | Row | Predicted | Measured | The input on which mutant and original differ |
72
+ * |---|---|---|---|
73
+ * | **baseline** — unmutated | 87 pass, 0 fail | **87 pass, 0 fail** | — |
74
+ * | P1 `renamePairs` short-circuited to `return []` | 8 | **8 of 87** | AC-1's pair: the original returns one `{from, to}`, the mutant none, and the renamed case goes back to being reported deleted |
75
+ * | P2 the call-site modifier dropped from `pairingKey` | 1 | **1 of 87** | `test("x", BODY)` becoming `test.skip("y", BODY)`: the original reports a deletion, the mutant a rename |
76
+ * | P3 the phantom `continue` removed | 3 | **3 of 87** | a line reading `const GATE_CHECK = 'test("a free port passes", …)'`: the original reports no case, the mutant one — whose name then discharges a real deletion |
77
+ * | P4 `MIN_IDENTIFYING_BODY` set to 0 | 4 | **4 of 87** | #659's fixture: a placeholder body disappearing beside an identical one appearing |
78
+ * | P5 the body index narrowed to the CHANGED cases | 1 | **1 of 87** | a file where one rename is the only change and a third case carries the same body at both commits |
79
+ * | P6 `normalisedBody` stops stripping comments | 2 | **2 of 87** | one body carrying a line comment and an otherwise identical one that does not |
80
+ * | P7 **the cheapest wrong fix** — string and numeric literals discarded | 2 | **2 of 87** | `expect(reading.total).toBe(4)` against the same body with `5`: the original calls them different cases, the mutant pairs them |
81
+ * | P8 `v2` reverted to `v1` in the library only | 4 | **13 of 87** | every artefact: the token the library writes stops matching the one `workflows/ship.js` recomputes |
82
+ * | P9 `renamedIds` dropped from the signature members, BOTH positions | 2 | **2 of 87** | one rename with `to` altered and the count unchanged — the `:n1` prefix still agrees, so only membership can see it |
83
+ * | P10 the `DELETION_RENAMED` block removed from `ship.js` | 2 | **2 of 87** | a CLEAN reply carrying one rename: the original prints both titles, the mutant prints what a round that renamed nothing prints |
84
+ * | P11 the rename line moved inside the CLEAN arm | 1 | **1 of 87** | a reply carrying one rename AND one deletion — #880's own scope note, and the arm a CLEAN-only line skips |
85
+ * | P12 the enclosing chain dropped from `pairingKey` | 1 | **1 of 87** | a case wrapped in `describe.skip` at the current commit, body unchanged |
86
+ * | P13 `blockSpans` short-circuited to `return []` | 3 | **3 of 87** | the same input, plus a case nested two blocks deep whose chain reads `["", ".skip"]` |
87
+ * | P14 the block-comment branch dropped from `literalSpans` | 1 | **1 of 87** | a source holding a star-slash comment: the original spans it, the mutant does not |
88
+ * | P15 `literalSpans` returning one span over the whole file | ≥15, with the phantom-drop control among them | **26 of 87**, control among them | every file: the original reads 7,514 declarations over the tree, the mutant none |
89
+ *
90
+ * **P7's first cut came back 1 against a predicted 2, and the low row was
91
+ * the finding.** AC-4's two bodies normalise to 39 characters once their
92
+ * literals are discarded, which is below `MIN_IDENTIFYING_BODY` — so the
93
+ * FLOOR refused that pair, not the normalisation, and the case witnessed
94
+ * nothing about the mutation it was written for (#492: a case held up by a
95
+ * guard it is not about). AC-9 was the same shape one layer in: only its
96
+ * direct `normalisedBody` comparison went red, while its `renamePairs`
97
+ * half was held up by the floor too. Both bodies were lengthened past the
98
+ * floor, and the row is 2 with the pairing as a witness rather than one
99
+ * unit assertion.
100
+ *
101
+ * **P8 came back 13 against a predicted 4, and the extra reds are the real
102
+ * kind** — read by name before the number was recorded. The prediction
103
+ * covered the four cases that compare the two signature implementations
104
+ * directly. The other nine are operator-line cases: a version disagreement
105
+ * makes `deletionVerdictReading` return `DELETION_SIGNATURE_DISAGREEMENT`
106
+ * for EVERY reply, so every case that reads a verdict goes red. Squarely
107
+ * about the mutated behaviour, the mutant parses, and 74 cases still pass.
108
+ * The fact it records is that a one-sided version bump is caught by the
109
+ * whole relay suite and not only by the parity cases.
110
+ *
111
+ * **P11's first cut came back 30, and it was not a mutation.** The `&&` in
112
+ * the replacement text was mangled on its way through the shell and
113
+ * `ship.js` stopped parsing, so every case that loads it died. A mutant
114
+ * that crashes is not a mutant — it measures that the file still parses
115
+ * (#485). Re-cut as a ternary with no ampersand, the row is 1, and the
116
+ * single red is the DELETED-arm case it was aimed at.
117
+ *
118
+ * None of the fifteen mutations is left in the tree; all were run and
119
+ * restored from a `cp` backup, and `lib/test-case-bodies.ts`,
120
+ * `lib/test-case-deletion.ts` and `workflows/ship.js` were confirmed
121
+ * byte-identical afterwards by sha256 — never by `git checkout --`.
122
+ */
123
+
124
+ /**
125
+ * One `test(...)` or `it(...)` declaration, in source order, whether or not
126
+ * its title can be read.
127
+ *
128
+ * `CaseDeclaration` below is the half with a readable title. Both come from
129
+ * `testDeclarations`, which is the one binding deciding what a declaration
130
+ * is — see its docblock for why that matters (#883).
131
+ */
132
+ export interface TestDeclaration {
133
+ /**
134
+ * The title as the source declared it, escapes resolved, or `null` when
135
+ * there is no single title to record.
136
+ *
137
+ * `null` covers the three forms that declare a test without naming one
138
+ * statically: `test.each([…])(…)`, a template title carrying `${…}`, and a
139
+ * title that is an identifier or a call. They are DECLARATIONS — deleting
140
+ * one removes coverage — and they are not CASES, because a name is what a
141
+ * rename pairs on and what a deletion is reported by. Counting them and
142
+ * naming them are different questions, and this field is where the two
143
+ * part company.
144
+ */
145
+ name: string | null;
146
+ body: string | null;
147
+ modifier: string;
148
+ enclosing: string[];
149
+ }
150
+
151
+ /** A declaration whose title is a plain string literal. */
152
+ export interface CaseDeclaration extends TestDeclaration {
153
+ /** The title as the source declared it, escapes resolved. */
154
+ name: string;
155
+ /**
156
+ * The call's arguments AFTER the title — the comma, the options object if
157
+ * there is one, and the callback — up to but excluding the call's closing
158
+ * paren.
159
+ *
160
+ * `null` when the call never closes, which is the honest reading for a
161
+ * truncated or unparseable file, and also when the declaration is not one
162
+ * — see `caseDeclarations` on phantoms. A `null` body pairs with nothing,
163
+ * so an unreadable case is reported as a deletion rather than matched.
164
+ */
165
+ body: string | null;
166
+ /**
167
+ * `""` for a plain `test(`, or the modifier as written — `.skip`,
168
+ * `.todo`, `.only`, `.failing`, `.skipIf`, `.todoIf`, `.runIf`.
169
+ *
170
+ * ## Why this is part of the case's identity and not metadata
171
+ *
172
+ * Found by the security review of this change, and it is the defect this
173
+ * whole module exists to avoid, arriving inside the fix for it. A round
174
+ * that turns
175
+ *
176
+ * test("a free port passes", () => { …body… })
177
+ *
178
+ * into
179
+ *
180
+ * test.skip("a free port passes, now quarantined", () => { …body… })
181
+ *
182
+ * leaves the body byte-identical. Pairing on the body alone reports it as
183
+ * a rename and says *"no coverage left with them"* — which is false: the
184
+ * assertions no longer run, which is #659's *"a gate that passes because
185
+ * its test is gone is not a gate that passed"* with the test still
186
+ * sitting in the file.
187
+ *
188
+ * The pre-#880 title comparison ignored the modifier too, and that was
189
+ * harmless because it never claimed anything had survived. The claim is
190
+ * what makes this load-bearing, so the modifier is keyed into the
191
+ * pairing and a case that changed modifier is reported as a DELETION.
192
+ */
193
+ modifier: string;
194
+ /**
195
+ * The modifiers of the `describe` / `suite` calls this one sits inside,
196
+ * outermost first — `[]` at the top level, `[".skip"]` inside a
197
+ * `describe.skip`, `["", ".skip"]` inside a plain describe holding a
198
+ * skipped one.
199
+ *
200
+ * The same defect as `modifier`, one level out, and found by the second
201
+ * security review after the first found the call-site one. Wrapping a
202
+ * renamed case in `describe.skip(...)` leaves the case's own call
203
+ * untouched and its body byte-identical, so a key built from the call
204
+ * site alone pairs it and says no coverage left with it. It did.
205
+ *
206
+ * A separate field rather than being folded into `modifier` at the scan,
207
+ * because `modifier` means what it says — the call-site modifier, which
208
+ * `AC-16` asserts directly. Both are data; `pairingKey` is the single
209
+ * place that decides what they MEAN for identity.
210
+ */
211
+ enclosing: string[];
212
+ }
213
+
214
+ /**
215
+ * `test("…")` and `it("…")`, including the `.skip`, `.only`, `.todo` and
216
+ * `.failing` forms.
217
+ *
218
+ * Moved here from `lib/test-case-deletion.ts` unchanged, so that the names
219
+ * and the bodies come from ONE scan. Two regexes answering "what is a test
220
+ * declaration" would be two deciders that agree until they do not, which is
221
+ * `.claude/rules/checks-must-be-able-to-fail.md`'s fourth shape — and this
222
+ * repository already has that defect once over, between this expression and
223
+ * `lib/test-census.ts`'s `DECLARATION`. Measured 2026-10-21: the two
224
+ * disagree on 174 of 483 test files here. That one is not #880's to fix and
225
+ * is filed separately; this module at least does not add a third.
226
+ *
227
+ * `describe` is deliberately not matched: a renamed describe block is not a
228
+ * renamed case.
229
+ *
230
+ * ## Two differences from the census expression it replaces (#883)
231
+ *
232
+ * Both deliberate and both measured on this tree, 2026-10-21:
233
+ *
234
+ * - **No bare-backtick alternative.** The census matched ``test` `` as well
235
+ * as `test(`, which is not a declaration form bun has. 153 of its 443
236
+ * extra matches were the word *test* before a backtick in prose.
237
+ * - **`each` is in the modifier list.** `test.each([…])(…)` is a real
238
+ * declaration — the census counted it and the case reader could not see
239
+ * it, 50 times here. It carries no static title, so it is a declaration
240
+ * with a `null` name.
241
+ *
242
+ * The title is no longer part of this expression. It is read by `titleAfter`
243
+ * from the open paren, which is what lets one scan answer both "is this a
244
+ * declaration" and "what is it called" without a declaration having to have
245
+ * a readable name to be counted.
246
+ */
247
+ const CASE_DECLARATION =
248
+ /(?:^|[^.\w$])(?:test|it)(\.(?:skip|only|todo|failing|skipIf|todoIf|runIf|each))?\s*\(/g;
249
+
250
+ const ESCAPES: Record<string, string> = { n: "\n", t: "\t", r: "\r", b: "\b", f: "\f", v: "\v", "0": "\0" };
251
+
252
+ /** A source-level string literal's VALUE. */
253
+ function unescape(raw: string): string {
254
+ return raw.replace(/\\(.)/g, (_, ch: string) => ESCAPES[ch] ?? ch);
255
+ }
256
+
257
+ // ── The scanner ──────────────────────────────────────────────────────────
258
+
259
+ /**
260
+ * Keywords after which a `/` opens a regular expression rather than dividing.
261
+ *
262
+ * The list is explicit rather than "any identifier", because the common case
263
+ * by far is `a / b` and reading that as a regex runs the scan to the end of
264
+ * the file. A form nobody thought of costs a `body` of `null`, which reports
265
+ * the case as a deletion — the direction this module is allowed to be wrong
266
+ * in.
267
+ */
268
+ const REGEX_AFTER = new Set([
269
+ "return", "typeof", "instanceof", "in", "of", "new", "delete", "void",
270
+ "do", "else", "yield", "await", "case", "throw",
271
+ ]);
272
+
273
+ /**
274
+ * Whether the `/` at `i` opens a regular expression.
275
+ *
276
+ * Reads the source backwards rather than threading a "previous token" through
277
+ * every caller. One binding, asked by both the paren scan and the
278
+ * normaliser, so the two cannot disagree about where a regex starts.
279
+ */
280
+ function regexHere(src: string, i: number): boolean {
281
+ let j = i - 1;
282
+ while (j >= 0 && /\s/.test(src[j])) j--;
283
+ if (j < 0) return true;
284
+ const c = src[j];
285
+ // A closer, a quote or a digit ends a VALUE, and a `/` after a value is
286
+ // division. `if (x) /re/.test(y)` is legal and is not written.
287
+ if (/[)\]}"'`\d]/.test(c)) return false;
288
+ if (/[\w$]/.test(c)) {
289
+ const m = /([A-Za-z_$][\w$]*)$/.exec(src.slice(Math.max(0, j - 24), j + 1));
290
+ return m !== null && REGEX_AFTER.has(m[1]);
291
+ }
292
+ // `(`, `,`, `=`, `:`, `;`, `!`, `&`, `|`, `?`, an operator, `{`, `[` — an
293
+ // expression is starting, so a `/` is a regex.
294
+ return true;
295
+ }
296
+
297
+ /** Past a `'…'` or `"…"` opening at `i`, or `null` when it does not close. */
298
+ function skipQuoted(src: string, i: number): number | null {
299
+ const quote = src[i];
300
+ for (let j = i + 1; j < src.length; j++) {
301
+ const c = src[j];
302
+ if (c === "\\") { j++; continue; }
303
+ if (c === quote) return j + 1;
304
+ if (c === "\n") return null;
305
+ }
306
+ return null;
307
+ }
308
+
309
+ /**
310
+ * Past the star-slash closing a block comment opening at `i`.
311
+ *
312
+ * Spelled in words rather than as the two characters, because those two
313
+ * characters inside this very comment would end it — which is how #877's
314
+ * first draft turned the rest of its own module into code.
315
+ */
316
+ function skipBlockComment(src: string, i: number): number | null {
317
+ const end = src.indexOf("*/", i + 2);
318
+ return end < 0 ? null : end + 2;
319
+ }
320
+
321
+ /** Past a regex literal opening at `i`, flags included. */
322
+ function skipRegex(src: string, i: number): number | null {
323
+ let inClass = false;
324
+ for (let j = i + 1; j < src.length; j++) {
325
+ const c = src[j];
326
+ if (c === "\\") { j++; continue; }
327
+ if (c === "\n") return null;
328
+ if (inClass) {
329
+ if (c === "]") inClass = false;
330
+ continue;
331
+ }
332
+ if (c === "[") { inClass = true; continue; }
333
+ if (c === "/") {
334
+ let k = j + 1;
335
+ while (k < src.length && /[a-z]/.test(src[k])) k++;
336
+ return k;
337
+ }
338
+ }
339
+ return null;
340
+ }
341
+
342
+ /** Past the backtick closing a template opening at `i`, interpolations and all. */
343
+ function skipTemplate(src: string, i: number): number | null {
344
+ for (let j = i + 1; j < src.length; j++) {
345
+ const c = src[j];
346
+ if (c === "\\") { j++; continue; }
347
+ if (c === "`") return j + 1;
348
+ if (c === "$" && src[j + 1] === "{") {
349
+ const end = skipBalanced(src, j + 1, "{", "}");
350
+ if (end === null) return null;
351
+ j = end - 1;
352
+ continue;
353
+ }
354
+ }
355
+ return null;
356
+ }
357
+
358
+ /**
359
+ * Past the closer matching the opener at `i`, skipping every literal and
360
+ * comment between them.
361
+ *
362
+ * The ONE place a bracket is counted, so the call scan, the template scan
363
+ * and anything added later cannot end up with three opinions about whether a
364
+ * `)` inside a string closes a call.
365
+ */
366
+ function skipBalanced(src: string, i: number, open: string, close: string): number | null {
367
+ let depth = 0;
368
+ let j = i;
369
+ while (j < src.length) {
370
+ const c = src[j];
371
+ if (c === '"' || c === "'") {
372
+ const end = skipQuoted(src, j);
373
+ if (end === null) return null;
374
+ j = end;
375
+ continue;
376
+ }
377
+ if (c === "`") {
378
+ const end = skipTemplate(src, j);
379
+ if (end === null) return null;
380
+ j = end;
381
+ continue;
382
+ }
383
+ if (c === "/" && src[j + 1] === "/") {
384
+ const nl = src.indexOf("\n", j);
385
+ j = nl < 0 ? src.length : nl;
386
+ continue;
387
+ }
388
+ if (c === "/" && src[j + 1] === "*") {
389
+ const end = skipBlockComment(src, j);
390
+ if (end === null) return null;
391
+ j = end;
392
+ continue;
393
+ }
394
+ if (c === "/" && regexHere(src, j)) {
395
+ const end = skipRegex(src, j);
396
+ // A `/` the regex scan cannot close is division after all; step over it
397
+ // rather than abandoning the whole cut.
398
+ j = end === null ? j + 1 : end;
399
+ continue;
400
+ }
401
+ if (c === open) depth++;
402
+ else if (c === close) {
403
+ depth--;
404
+ if (depth === 0) return j + 1;
405
+ }
406
+ j++;
407
+ }
408
+ return null;
409
+ }
410
+
411
+ /**
412
+ * The index of the `)` closing the call whose `(` is at `open`, or `null`.
413
+ *
414
+ * Exported so a caller can establish that the scan reaches past a hostile
415
+ * body rather than inferring it from a body that happens to look right.
416
+ */
417
+ export function matchingCallParen(src: string, open: number): number | null {
418
+ const end = skipBalanced(src, open, "(", ")");
419
+ return end === null ? null : end - 1;
420
+ }
421
+
422
+ /**
423
+ * The `[start, end)` ranges of every string, template, comment and regex in
424
+ * a source file, in ascending order.
425
+ *
426
+ * A `test("…"` sequence inside one of those is not a declaration: it is a
427
+ * repository that writes about its own tests. Measured 2026-10-21, this
428
+ * tree has eleven, `const GATE_CHECK = 'test("prove-label-…"'` in
429
+ * `test/prove-label-gate.test.ts` being the clearest.
430
+ *
431
+ * They were already harmless BY ACCIDENT — a paren that was never opened as
432
+ * code does not close, so the body came back `null` and a `null` body pairs
433
+ * with nothing. Accidental protection is the thing this repository's rules
434
+ * are mostly about, so it is made deliberate here: a phantom on the AFTER
435
+ * side whose parens happened to balance could otherwise discharge a real
436
+ * deletion, which is the reassuring-direction error with no witness.
437
+ */
438
+ export function literalSpans(source: string): Array<[number, number]> {
439
+ const spans: Array<[number, number]> = [];
440
+ let i = 0;
441
+ while (i < source.length) {
442
+ const c = source[i];
443
+ let end: number | null = null;
444
+ if (c === '"' || c === "'") end = skipQuoted(source, i);
445
+ else if (c === "`") end = skipTemplate(source, i);
446
+ else if (c === "/" && source[i + 1] === "/") {
447
+ const nl = source.indexOf("\n", i);
448
+ end = nl < 0 ? source.length : nl;
449
+ } else if (c === "/" && source[i + 1] === "*") end = skipBlockComment(source, i);
450
+ else if (c === "/" && regexHere(source, i)) end = skipRegex(source, i);
451
+ else {
452
+ i++;
453
+ continue;
454
+ }
455
+ // An unterminated literal: step one character rather than giving up on
456
+ // the file. The rest of the scan is still worth having, and the
457
+ // declarations inside the unterminated region simply are not marked.
458
+ if (end === null || end <= i) {
459
+ i++;
460
+ continue;
461
+ }
462
+ spans.push([i, end]);
463
+ i = end;
464
+ }
465
+ return spans;
466
+ }
467
+
468
+ // ── The declarations ─────────────────────────────────────────────────────
469
+
470
+ /**
471
+ * Every case a source file declares, with its body, in declaration order.
472
+ *
473
+ * `lib/test-case-deletion.ts`'s `caseNames` and `lib/test-census.ts`'s
474
+ * `countTestDeclarations` are both projections of this, so the count, the
475
+ * names and the bodies are one reading seen three ways and cannot fall out
476
+ * of step. Before #883 the count came from its own expression and disagreed
477
+ * with this one on 174 of this tree's 483 test files.
478
+ */
479
+ /**
480
+ * Is this offset inside a string, template or regex literal?
481
+ *
482
+ * ONE binding, exported, because the alternative is a reimplementation in
483
+ * whatever test checks it — and a test comparing two copies it wrote itself
484
+ * is green under every mutation of the real one. Measured: the first draft
485
+ * of this did exactly that, and breaking the production probe's boundary
486
+ * comparison was 0 of 89 red.
487
+ *
488
+ * Binary search, not `spans.some`. `literalSpans` scans forward, so its
489
+ * spans are ascending and disjoint; the probe runs once per declaration, so
490
+ * a linear one makes the reader quadratic in the number of string literals.
491
+ * Measured on a 520 KB source with 40,000 declarations: `literalSpans`
492
+ * itself is 7 ms, and 40,000 linear probes over its 40,000 spans are
493
+ * 8,854 ms — the entire cost of reading that file. `censusOf` reads every
494
+ * test file in the tree, with a 2 MB per-file ceiling above it. Found by
495
+ * the security review of #883, which named a different line as the cause;
496
+ * the number is what located this one.
497
+ */
498
+ export function literalProbe(spans: ReadonlyArray<[number, number]>): (at: number) => boolean {
499
+ return (at: number) => {
500
+ let lo = 0;
501
+ let hi = spans.length - 1;
502
+ while (lo <= hi) {
503
+ const mid = (lo + hi) >> 1;
504
+ const [s, e] = spans[mid]!;
505
+ if (at < s) hi = mid - 1;
506
+ else if (at >= e) lo = mid + 1;
507
+ else return true;
508
+ }
509
+ return false;
510
+ };
511
+ }
512
+
513
+ export function testDeclarations(source: string): TestDeclaration[] {
514
+ const out: TestDeclaration[] = [];
515
+ const spans = literalSpans(source);
516
+ const inLiteral = literalProbe(spans);
517
+ const blocks = blockSpans(source, inLiteral);
518
+ // A budget across the whole call, so a malformed file cannot turn an
519
+ // O(n) scan per declaration into a gate that never returns. It cannot be
520
+ // reached by a well-formed file: every body is scanned once, so the total
521
+ // is about the length of the source. A declaration past the budget gets
522
+ // no body and is therefore reported as a deletion — loud, and the safe
523
+ // direction — rather than silently paired.
524
+ let budget = Math.max(source.length * 8, 1_000_000);
525
+
526
+ for (const m of source.matchAll(CASE_DECLARATION)) {
527
+ // The LAST paren in the match is the call's own. The match now ends at
528
+ // that paren, so the only other candidate is the single leading
529
+ // delimiter character the anchor consumes — `;(test(` would otherwise
530
+ // hand the body scanner the wrong opening bracket.
531
+ const open = m.index! + m[0].lastIndexOf("(");
532
+ // A phantom — the sequence inside a string, a comment or a regex — is
533
+ // not a declaration and is DROPPED, not merely left body-less.
534
+ //
535
+ // Giving it a null body was the first draft and it is not enough: a
536
+ // phantom still carries a NAME, and `caseChanges` discharges a deletion
537
+ // whose name survives. So `const GATE_CHECK = 'test("a free port
538
+ // passes", …)'` added in the same round that deleted that case would
539
+ // report nothing gone — the deletion check's own defect, reachable
540
+ // through the name set rather than through the pairing. Found by the
541
+ // security review of this change.
542
+ //
543
+ // Dropped on BOTH sides, and the asymmetric alternative was declined
544
+ // deliberately. Keeping phantoms on the BEFORE side would make every
545
+ // edit to one of this tree's 148 string constants report a deleted
546
+ // test — a refusal naming something that was never a test, which is
547
+ // the cry-wolf failure #880 is about, arriving as its fix. The real
548
+ // risk the asymmetry guards against is `literalSpans` misclassifying a
549
+ // REAL declaration, and that is met directly instead: the control case
550
+ // in `test/unit/case-rename-detection.test.ts` compares this reading
551
+ // against the raw pattern over every test file in the tree and refuses
552
+ // any file that loses all of its declarations.
553
+ if (inLiteral(m.index! + m[0].search(/(?:test|it)/))) continue;
554
+ // Read AFTER the phantom drop: a phantom needs no title, so this is
555
+ // work skipped rather than work capped. The security review of this
556
+ // change asked for the title scan to be charged against the body
557
+ // budget too, on the grounds that an unterminated quote makes it scan
558
+ // to end-of-file. Measured on a 520 KB source with 40,000
559
+ // declarations: 8,794 ms well-formed against 8,852 ms with a bad quote
560
+ // at the top — 0.7%. The quadratic was somewhere else (see `inLiteral`
561
+ // above), budgeting this would have degraded real titles to `null` for
562
+ // no measured gain, and the draft that did it was reverted.
563
+ const title = titleAfter(source, open);
564
+ const titleEnd = title.end;
565
+ let body: string | null = null;
566
+ if (budget > 0) {
567
+ const close = matchingCallParen(source, open);
568
+ // Charged what the scan actually READ, not what it might have. The
569
+ // first draft charged `source.length - open` whether the call closed
570
+ // after forty characters or never — which spends the budget in
571
+ // proportion to how early a case appears in the file, and reported
572
+ // 620 of this tree's 7,650 declarations as unreadable instead of 11.
573
+ // The instrument case below is what caught it.
574
+ budget -= (close === null ? source.length : close) - open;
575
+ if (close !== null && close >= titleEnd) body = source.slice(titleEnd, close);
576
+ }
577
+ out.push({
578
+ name: title.name,
579
+ body,
580
+ modifier: m[1] ?? "",
581
+ enclosing: blocks.filter(b => open > b.start && open < b.end).map(b => b.modifier),
582
+ });
583
+ }
584
+ return out;
585
+ }
586
+
587
+ /**
588
+ * The declarations with a readable title — what a rename or a deletion is
589
+ * reported by.
590
+ *
591
+ * A projection and not a second scan. `testDeclarations` is the binding; a
592
+ * mutation of it moves this, `caseNames` and `countTestDeclarations`
593
+ * together, which is the property #883 exists to buy.
594
+ */
595
+ export function caseDeclarations(source: string): CaseDeclaration[] {
596
+ return testDeclarations(source).filter((d): d is CaseDeclaration => d.name !== null);
597
+ }
598
+
599
+ /**
600
+ * The title argument of a call whose open paren is at `open`.
601
+ *
602
+ * `null` for every form that declares a test without naming one statically:
603
+ * `test.each([…])`, where the first argument is the table; a template
604
+ * carrying `${…}`, whose text would look deleted the moment the
605
+ * interpolation changed; and an identifier or call, where the name is not in
606
+ * the source at all.
607
+ *
608
+ * `end` is where the body starts, and it is returned rather than recomputed
609
+ * by the caller — the two are the same scan, and a caller deriving the body
610
+ * boundary separately would be a second decider for one position.
611
+ */
612
+ function titleAfter(src: string, open: number): { name: string | null; end: number } {
613
+ let i = open + 1;
614
+ while (i < src.length && /\s/.test(src[i]!)) i++;
615
+ const quote = src[i];
616
+ if (quote !== '"' && quote !== "'" && quote !== "`") return { name: null, end: i };
617
+ const end = quote === "`" ? skipTemplate(src, i) : skipQuoted(src, i);
618
+ if (end === null) return { name: null, end: i };
619
+ const raw = src.slice(i + 1, end - 1);
620
+ if (quote === "`" && raw.includes("${")) return { name: null, end };
621
+ return { name: unescape(raw), end };
622
+ }
623
+
624
+ /** `describe(` and `suite(`, with the modifier captured. */
625
+ const BLOCK_DECLARATION =
626
+ /(?:^|[^.\w$])(?:describe|suite)(\.(?:skip|only|todo|failing|skipIf|todoIf|runIf|each))?\s*\(/g;
627
+
628
+ /**
629
+ * Where each `describe` / `suite` call starts and ends, outermost first.
630
+ *
631
+ * Ordered by start, so `filter` over it yields a case's enclosing chain
632
+ * from the outside in without a second sort. A block whose call does not
633
+ * close is skipped rather than extended to the end of the file: a span
634
+ * running to EOF would put every later case inside it and silently change
635
+ * what they are compared as.
636
+ */
637
+ function blockSpans(
638
+ source: string,
639
+ inLiteral: (at: number) => boolean,
640
+ ): Array<{ start: number; end: number; modifier: string }> {
641
+ const out: Array<{ start: number; end: number; modifier: string }> = [];
642
+ for (const m of source.matchAll(BLOCK_DECLARATION)) {
643
+ const at = m.index! + m[0].search(/(?:describe|suite)/);
644
+ if (inLiteral(at)) continue;
645
+ const open = m.index! + m[0].lastIndexOf("(");
646
+ const close = matchingCallParen(source, open);
647
+ if (close === null) continue;
648
+ out.push({ start: open, end: close, modifier: m[1] ?? "" });
649
+ }
650
+ return out;
651
+ }
652
+
653
+ /**
654
+ * A body with the differences that carry no behaviour removed.
655
+ *
656
+ * Comments go — a round that renames seven cases rewrites the prose around
657
+ * them, and a comment is not a test. Runs of whitespace collapse to one
658
+ * space — a rename reflows the indentation of everything it wraps.
659
+ *
660
+ * **Nothing else goes, and that is the load-bearing sentence.** Every step
661
+ * past this point is the cheapest wrong fix for "my rename was not
662
+ * detected": drop the string literals, compare only the identifiers, count
663
+ * the `expect(` calls. Each one pairs more cases, each one makes the symptom
664
+ * go away, and each one is #880's "wrong in the reassuring direction" — a
665
+ * deleted test reported as a rename, which is strictly worse than the
666
+ * refusal this replaces because nobody goes looking afterwards.
667
+ */
668
+ export function normalisedBody(body: string): string {
669
+ let out = "";
670
+ let i = 0;
671
+ while (i < body.length) {
672
+ const c = body[i];
673
+ if (c === '"' || c === "'") {
674
+ const end = skipQuoted(body, i);
675
+ if (end === null) { out += body.slice(i); break; }
676
+ out += body.slice(i, end);
677
+ i = end;
678
+ continue;
679
+ }
680
+ if (c === "`") {
681
+ const end = skipTemplate(body, i);
682
+ if (end === null) { out += body.slice(i); break; }
683
+ out += body.slice(i, end);
684
+ i = end;
685
+ continue;
686
+ }
687
+ if (c === "/" && body[i + 1] === "/") {
688
+ const nl = body.indexOf("\n", i);
689
+ out += " ";
690
+ i = nl < 0 ? body.length : nl;
691
+ continue;
692
+ }
693
+ if (c === "/" && body[i + 1] === "*") {
694
+ const end = skipBlockComment(body, i);
695
+ out += " ";
696
+ if (end === null) break;
697
+ i = end;
698
+ continue;
699
+ }
700
+ if (c === "/" && regexHere(body, i)) {
701
+ const end = skipRegex(body, i);
702
+ if (end === null) { out += c; i++; continue; }
703
+ out += body.slice(i, end);
704
+ i = end;
705
+ continue;
706
+ }
707
+ out += c;
708
+ i++;
709
+ }
710
+ return out.replace(/\s+/g, " ").trim();
711
+ }
712
+
713
+ /** A case present at both readings under two different titles. */
714
+ export interface RenamePair {
715
+ from: string;
716
+ to: string;
717
+ }
718
+
719
+ /**
720
+ * The shortest normalised body that is allowed to identify a case.
721
+ *
722
+ * ## This is a threshold, and here is where the number came from
723
+ *
724
+ * A body says "this is the same test" only insofar as it is about
725
+ * something. `, () => { expect(1).toBe(1); }` is about nothing: it is the
726
+ * body of a placeholder, and two placeholders in one file are two different
727
+ * tests that happen to be written identically. Pairing on it would report a
728
+ * deleted test as a rename — #880's reassuring-direction error, in the one
729
+ * place nobody ever looks again, because the whole point of reporting a
730
+ * rename is that the operator stops investigating.
731
+ *
732
+ * **Found by a test that is not about this, which is why it is a constant
733
+ * and not a comment.** `test/unit/deleted-case-non-vacuous.test.ts` is
734
+ * #659's fixture: three cases deleted, one added, and the added one's body
735
+ * was copied from one of the deleted ones. Without a floor, the first
736
+ * draft of this module paired them and reported one of three deletions as
737
+ * a rename.
738
+ *
739
+ * Measured over this repository, 2026-10-21 — 7,508 cases in 484 files.
740
+ * Every distinct normalised body that two cases in one file share, by
741
+ * length: **0, 10, 42, 55, 86, 94, 160, 369**. The 5th percentile of all
742
+ * bodies is **82** and the median is **277**.
743
+ *
744
+ * 48 sits between the three boilerplate lengths and the five substantial
745
+ * ones, and below the 5th percentile, so it excludes essentially no real
746
+ * case from being paired.
747
+ *
748
+ * ## The floor and the uniqueness rule are two guards, and each has an
749
+ * input only it reaches
750
+ *
751
+ * Named, because two guards answering one question are behaviourally one
752
+ * (`.claude/rules/checks-must-be-able-to-fail.md`, the fourth shape) and
753
+ * the only thing that makes keeping both honest is being able to say which
754
+ * input each is for:
755
+ *
756
+ * - **the floor only** — #659's fixture. A 30-character body, unique
757
+ * among the disappeared cases AND unique among the appeared ones, so
758
+ * the uniqueness rule sees a clean one-to-one match. It is a
759
+ * placeholder shared between two unrelated tests.
760
+ * - **uniqueness only** — `test/unit/bash-tool-guard.test.ts`, whose two
761
+ * cases share a 369-character body. Far above the floor and still
762
+ * evidence of nothing, because it names two cases rather than one.
763
+ *
764
+ * Both costs of the floor, stated rather than implied:
765
+ *
766
+ * - too HIGH — a short but genuine rename reads as a deletion, which is
767
+ * the pre-#880 answer and the direction to be wrong in.
768
+ * - too LOW — a deleted placeholder is reported as a rename and nobody
769
+ * looks for it. That is the direction this number exists to avoid.
770
+ *
771
+ * And the proxy, named because a threshold can always be satisfied
772
+ * directly: padding a test body past 48 characters would make it pairable.
773
+ * Nothing is gained by it — the worst a pair produces is a LESS severe
774
+ * report, and anyone able to edit the test file could simply not delete the
775
+ * test. This is a cry-wolf problem, not an adversary.
776
+ */
777
+ export const MIN_IDENTIFYING_BODY = 48;
778
+
779
+ /**
780
+ * The cases that changed title and nothing else.
781
+ *
782
+ * ## Uniqueness is a precondition, and it is asked of the WHOLE file
783
+ *
784
+ * A pair is only claimed when the body occurs exactly once among ALL cases
785
+ * at the previous commit and exactly once among ALL cases at the current
786
+ * one — not merely once among the cases that changed. A body five cases
787
+ * share is not evidence about any of them, and narrowing the question to
788
+ * the changed set would let the one that moved borrow the uniqueness of
789
+ * the four that did not. Measured 2026-10-21: `test/unit/suite-denominator.test.ts`
790
+ * has five cases sharing one body, which is exactly that input.
791
+ *
792
+ * The titles are checked the same way. Measured on this repository,
793
+ * **17 of 483 test files declare the same case title twice**, so duplicate
794
+ * titles are ordinary here rather than hypothetical, and `deletedCases` has
795
+ * folded them into a `Set` since #659 — deleting one of two identically
796
+ * titled cases has always been invisible and still is.
797
+ *
798
+ * A `null` body — a call the scan could not close — pairs with nothing, and
799
+ * so does one below `MIN_IDENTIFYING_BODY`. "I could not read this" and
800
+ * "this body is about nothing" are both readings that identify no case, and
801
+ * a reading that identifies no case must not match another one that
802
+ * identifies no case.
803
+ */
804
+ /**
805
+ * What a case is compared BY, or `null` when it is comparable to nothing.
806
+ *
807
+ * ONE binding, so there is one thing to mutate and one place where a
808
+ * component of a case's identity can be forgotten. Asking "is the body long
809
+ * enough" in the index and again in the loop below would be two deciders
810
+ * that agree, and a mutation of either would leave the other refusing
811
+ * (`.claude/rules/checks-must-be-able-to-fail.md`, the fourth shape).
812
+ *
813
+ * The modifiers are part of the key and not side conditions for the same
814
+ * reason: a side condition is a second place a rule can be dropped. `test`
815
+ * and `test.skip` carrying one body produce two different keys and
816
+ * therefore never pair, and they do so by the same arithmetic that already
817
+ * refuses two unrelated bodies. The enclosing `describe` chain is in the
818
+ * key for the same reason it exists — a case wrapped in `describe.skip`
819
+ * does not run, and a rename report says it does.
820
+ *
821
+ * ## What the key does NOT claim, named rather than omitted
822
+ *
823
+ * A `.only` ANYWHERE in the after source suppresses every other case in
824
+ * the file, so strictly a pair in such a file is a pair of cases that no
825
+ * longer run. That is deliberately not refused here. It is a property of
826
+ * the file and not of the pair: a committed `.only` means almost nothing
827
+ * in the file ran, which the previous build commit's LEDGER reports
828
+ * directly and far more loudly than a rename line could. Folding it in
829
+ * would make `renamePairs` answer a question the ledger already answers,
830
+ * which is a second decider.
831
+ */
832
+ function pairingKey(d: CaseDeclaration): string | null {
833
+ if (d.body === null) return null;
834
+ const body = normalisedBody(d.body);
835
+ if (body.length < MIN_IDENTIFYING_BODY) return null;
836
+ return `${d.enclosing.join(">")}\u0000${d.modifier}\u0000${body}`;
837
+ }
838
+
839
+ export function renamePairs(
840
+ before: readonly CaseDeclaration[],
841
+ after: readonly CaseDeclaration[],
842
+ ): RenamePair[] {
843
+ const beforeTitles = new Set(before.map(d => d.name));
844
+ const afterTitles = new Set(after.map(d => d.name));
845
+ const disappeared = before.filter(d => !afterTitles.has(d.name));
846
+ const appeared = after.filter(d => !beforeTitles.has(d.name));
847
+
848
+ // Indexed over EVERY case at the commit, not over the changed ones. The
849
+ // question "does this body identify one case" is about the file, and a
850
+ // body shared with a case that did not move is still shared.
851
+ const index = (all: readonly CaseDeclaration[]): Map<string, CaseDeclaration[]> => {
852
+ const by = new Map<string, CaseDeclaration[]>();
853
+ for (const d of all) {
854
+ const key = pairingKey(d);
855
+ if (key === null) continue;
856
+ const at = by.get(key);
857
+ if (at) at.push(d);
858
+ else by.set(key, [d]);
859
+ }
860
+ return by;
861
+ };
862
+ const wasThere = index(before);
863
+ const isThere = index(after);
864
+
865
+ const once = (list: readonly CaseDeclaration[], name: string) =>
866
+ list.filter(d => d.name === name).length === 1;
867
+
868
+ const out: RenamePair[] = [];
869
+ for (const d of disappeared) {
870
+ const key = pairingKey(d);
871
+ if (key === null) continue;
872
+ const from = wasThere.get(key);
873
+ const to = isThere.get(key);
874
+ if (!from || from.length !== 1 || !to || to.length !== 1) continue;
875
+ // The survivor carrying this body has to be a case that ARRIVED. A body
876
+ // unchanged under an unchanged title is not a rename, and would
877
+ // otherwise pair with itself.
878
+ if (!appeared.includes(to[0])) continue;
879
+ if (!once(disappeared, d.name) || !once(appeared, to[0].name)) continue;
880
+ out.push({ from: d.name, to: to[0].name });
881
+ }
882
+ return out;
883
+ }