@aburi/diff 0.1.0 → 0.3.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.
package/dist/index.mjs CHANGED
@@ -1,11 +1,16 @@
1
- import { serializeCanonical } from "@aburi/core";
1
+ import { RESERVED_LANGUAGE_IDS, computeWeaklyConnectedComponents, reconstructCallEdgesFromIR, serializeCanonical, trySymbolId } from "@aburi/core";
2
2
 
3
3
  //#region src/components.ts
4
4
  /**
5
- * §6.1 — Component diff. Component identity is `id`; when a Component is present in both
5
+ * `docs/design/diff-algorithm.md` §6.1 — Component diff. Assumes `components[].id` is unique on each side (ir-schema.md §14
6
+ * #2) and does not check it: `buildDiff` establishes that before calling, and a caller
7
+ * reaching this export directly owns the obligation, because the lookup map here is
8
+ * last-write-wins and a repeat is lost rather than reported.
9
+ *
10
+ * Component identity is `id`; when a Component is present in both
6
11
  * base and head with the same id, the three delta booleans describe which axes actually
7
12
  * moved (roots reshuffle, public API globs, or framework hint list). `modified` deltas
8
- * are intentionally absent from this diff (§5.2.3): fields are reported as before/after
13
+ * are intentionally absent from this diff (diff-algorithm.md §5.2.3): fields are reported as before/after
9
14
  * pairs via the `changed[]` entries so consumers can render them without stringifying
10
15
  * arrays.
11
16
  */
@@ -47,21 +52,61 @@ function diffComponents(base, head) {
47
52
  };
48
53
  }
49
54
  /**
50
- * §6.2 — Dependency diff. Identity is the composite `(from, to, via)` triple; direction
51
- * and effect changes are surfaced as an added + removed pair so `modified` is not part of
52
- * the schema (§6.2 tail).
55
+ * Build a side view from a document. The only construction site there is.
56
+ *
57
+ * `buildDiff` reads `lostFiles` for its own Symbol classification too, from this same object,
58
+ * so "a Symbol reported unknown and the edges it took with it cannot disagree about which file
59
+ * went missing" is a property of the wiring rather than a claim in a comment.
60
+ *
61
+ * Exported because `DependencySideView` is public and `diffDependencies` requires one: without
62
+ * a factory a caller would have to reproduce the `symbols[].source.file` keying and the
63
+ * `stats.skippedFiles` read, and the likeliest outcome of that is a caller who gets it wrong.
64
+ */
65
+ function dependencySideView(ir) {
66
+ const symbolFiles = /* @__PURE__ */ new Map();
67
+ for (const symbol of ir.symbols) symbolFiles.set(symbol.id, symbol.source.file);
68
+ const lostFiles = /* @__PURE__ */ new Map();
69
+ for (const file of ir.stats.skippedFiles ?? []) lostFiles.set(file.path, file.reason);
70
+ return {
71
+ symbolFiles,
72
+ lostFiles
73
+ };
74
+ }
75
+ /**
76
+ * `docs/design/diff-algorithm.md` §6.2 — Dependency diff. Identity is the composite
77
+ * `(from, to, via)` triple; direction and effect changes are surfaced as an added + removed
78
+ * pair so `modified` is not part of the schema (§6.2 tail). Uniqueness of that triple is the caller's obligation on the same
79
+ * terms as `diffComponents` above — a repeat here is indistinguishable in the output from
80
+ * the flip it encodes.
81
+ *
82
+ * `sides` is what separates a deletion from a loss (`docs/design/diff-algorithm.md` §6.2.1).
83
+ * It is required rather than optional: omitting it would classify every edge into a lost file
84
+ * as a deletion again — silently, and while still writing `unknown: []`, which this schema
85
+ * defines as "nothing was unknown" rather than "nobody looked". A caller with no skip list to
86
+ * offer says so by passing a side view whose `lostFiles` is empty, which is the honest spelling
87
+ * of an IR written before `stats.skippedFiles` existed.
88
+ *
89
+ * The return type declares `unknown` present, where the schema leaves it optional for documents
90
+ * that predate the field. A reader may find it missing; this function always writes it.
53
91
  */
54
- function diffDependencies(base, head) {
92
+ function diffDependencies(base, head, sides) {
55
93
  const baseKeys = /* @__PURE__ */ new Map();
56
94
  for (const d of base) baseKeys.set(dependencyKey(d), d);
57
95
  const headKeys = /* @__PURE__ */ new Map();
58
96
  for (const d of head) headKeys.set(dependencyKey(d), d);
59
97
  const added = [];
60
98
  const removed = [];
99
+ const unknown = [];
61
100
  for (const [key, dep] of headKeys) {
62
101
  const b = baseKeys.get(key);
63
102
  if (b === void 0) {
64
- added.push(dep);
103
+ const lostFiles = endpointsLostBy(dep, sides.head, sides.base);
104
+ if (lostFiles.length > 0) unknown.push({
105
+ dependency: dep,
106
+ absentFrom: "base",
107
+ lostFiles
108
+ });
109
+ else added.push(dep);
65
110
  continue;
66
111
  }
67
112
  if (b.direction !== dep.direction || (b.effect ?? null) !== (dep.effect ?? null)) {
@@ -69,16 +114,71 @@ function diffDependencies(base, head) {
69
114
  added.push(dep);
70
115
  }
71
116
  }
72
- for (const [key, dep] of baseKeys) if (!headKeys.has(key)) removed.push(dep);
117
+ for (const [key, dep] of baseKeys) {
118
+ if (headKeys.has(key)) continue;
119
+ const lostFiles = endpointsLostBy(dep, sides.base, sides.head);
120
+ if (lostFiles.length > 0) unknown.push({
121
+ dependency: dep,
122
+ absentFrom: "head",
123
+ lostFiles
124
+ });
125
+ else removed.push(dep);
126
+ }
73
127
  added.sort(compareDependencies);
74
128
  removed.sort(compareDependencies);
129
+ unknown.sort((a, b) => compareDependencies(a.dependency, b.dependency));
75
130
  return {
76
131
  added,
77
- removed
132
+ removed,
133
+ unknown
78
134
  };
79
135
  }
136
+ /**
137
+ * The endpoint files `absent` never analysed, read through `holder` because that is the
138
+ * document the edge — and therefore the Symbol behind each endpoint — actually comes from.
139
+ *
140
+ * Both endpoints are checked: an edge dies when *either* end's file goes, including one whose
141
+ * other end survived, and that half is the easiest to miss because the surviving Symbol is
142
+ * right there in both documents.
143
+ *
144
+ * Deduped and sorted by path, so an intra-file edge collapses to the one file it lost.
145
+ */
146
+ function endpointsLostBy(dep, holder, absent) {
147
+ const byPath = /* @__PURE__ */ new Map();
148
+ for (const endpoint of [dep.from, dep.to]) {
149
+ const file = holder.symbolFiles.get(endpoint);
150
+ if (file === void 0) continue;
151
+ const reason = absent.lostFiles.get(file);
152
+ if (reason === void 0) continue;
153
+ byPath.set(file, reason);
154
+ }
155
+ return [...byPath.entries()].map(([path, reason]) => ({
156
+ path,
157
+ reason
158
+ })).sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0);
159
+ }
160
+ /**
161
+ * `docs/design/diff-algorithm.md` §6.2 — the fields Dependency identity is made of, in key order, and the join that turns
162
+ * them into one. Both halves are exported so the entry-point uniqueness check keys on
163
+ * exactly what this file keys on — a check with its own notion of identity would let through
164
+ * the duplicates that actually collide here, and a check that shared only the join would
165
+ * still be free to disagree about which fields identity is made of.
166
+ *
167
+ * Core's invariant #13 joins the same triple with a different separator. The two agree for
168
+ * every endpoint that satisfies the id grammars of ir-schema.md §3.1 and §4, which is every
169
+ * Document the integrity checker accepts; they could in principle disagree for one that does
170
+ * not, and `buildDiff` runs no grammar check on the IRs it is handed.
171
+ */
172
+ const DEPENDENCY_IDENTITY_FIELDS = [
173
+ "from",
174
+ "to",
175
+ "via"
176
+ ];
177
+ function dependencyIdentity(parts) {
178
+ return parts.join("::");
179
+ }
80
180
  function dependencyKey(d) {
81
- return `${d.from}::${d.to}::${d.via}`;
181
+ return dependencyIdentity(DEPENDENCY_IDENTITY_FIELDS.map((field) => d[field]));
82
182
  }
83
183
  function compareDependencies(a, b) {
84
184
  const keyA = dependencyKey(a);
@@ -151,48 +251,112 @@ function validateLineFuzz(value) {
151
251
  return value;
152
252
  }
153
253
  /**
154
- * Two-index diff: build key-indexed maps for both sides, then classify each key into
155
- * `added` / `removed` / `modified`. Line-fuzzed identities are matched within tolerance
156
- * so cosmetic line shifts do not produce added/removed noise. `modified` only fires when
157
- * the identity key stays the same but the content differs.
254
+ * §5.2 — pair the two sides by identity key within ±`lineFuzz`, then classify each element
255
+ * into `added` / `removed` / `modified`. `modified` fires only when a pairing holds and the
256
+ * content differs, so a cosmetic line shift produces nothing.
257
+ *
258
+ * Several elements of one Symbol routinely share a key — two `guard` rules, two calls to one
259
+ * target, two `@Get` — so which base element a head element takes is a real choice. Two
260
+ * passes make it: first the elements whose key **and content** agree, then whatever is left.
261
+ * An untouched element is therefore claimed by its own counterpart before an edited or
262
+ * deleted neighbour can take it, and the remainder pairs by proximity — where a genuine edit
263
+ * lands. Taking the first key hit instead reported a deleted `guard@1` by removing its
264
+ * untouched `guard@3` neighbour *and* listing that same neighbour as modified.
265
+ *
266
+ * Each pass is an order-preserving assignment rather than a per-element search, because a
267
+ * greedy pass takes a pairing that leaves a better set unreachable. Two identical guards
268
+ * shifted down two lines are the smallest case: the first head element is nearest to the
269
+ * *second* base element, and claiming it strands the other head outside the window, so a
270
+ * block that moved intact comes back as an `added` and a `removed`.
158
271
  */
159
272
  function differentiate(base, head, isEqual, lineFuzz) {
160
- const added = [];
161
- const removed = [];
162
- const modified = [];
163
- const consumedBase = /* @__PURE__ */ new Set();
164
- for (const h of head) {
165
- let matchIdx = -1;
166
- for (let j = 0; j < base.length; j++) {
167
- if (consumedBase.has(j)) continue;
168
- const b = base[j];
169
- if (b === void 0) continue;
170
- if (b.key !== h.key) continue;
171
- if (Math.abs(b.line - h.line) > lineFuzz) continue;
172
- matchIdx = j;
173
- break;
174
- }
175
- if (matchIdx === -1) {
176
- added.push(h.item);
177
- continue;
273
+ const freeBase = new Set(base.map((_, index) => index));
274
+ const freeHead = new Set(head.map((_, index) => index));
275
+ const partnerOf = /* @__PURE__ */ new Map();
276
+ for (const contentMustAgree of [true, false]) {
277
+ const admits = (b, h) => b.key === h.key && Math.abs(b.line - h.line) <= lineFuzz && (!contentMustAgree || isEqual(b.item, h.item));
278
+ for (const [baseIndex, headIndex] of assignInOrder(base, head, freeBase, freeHead, admits)) {
279
+ freeBase.delete(baseIndex);
280
+ freeHead.delete(headIndex);
281
+ const counterpart = base[baseIndex];
282
+ if (counterpart !== void 0) partnerOf.set(headIndex, counterpart);
178
283
  }
179
- consumedBase.add(matchIdx);
180
- const bmatch = base[matchIdx];
181
- if (bmatch === void 0) continue;
182
- if (!isEqual(bmatch.item, h.item)) modified.push(h.item);
183
284
  }
184
- for (let j = 0; j < base.length; j++) {
185
- if (consumedBase.has(j)) continue;
186
- const b = base[j];
187
- if (b === void 0) continue;
188
- removed.push(b.item);
285
+ const added = [];
286
+ const modified = [];
287
+ for (const [index, h] of head.entries()) {
288
+ const counterpart = partnerOf.get(index);
289
+ if (counterpart === void 0) added.push(h.item);
290
+ else if (!isEqual(counterpart.item, h.item)) modified.push(h.item);
189
291
  }
190
292
  return {
191
293
  added,
192
- removed,
294
+ removed: base.filter((_, index) => freeBase.has(index)).map((b) => b.item),
193
295
  modified
194
296
  };
195
297
  }
298
+ const NO_PAIRINGS = {
299
+ pairs: 0,
300
+ distance: 0
301
+ };
302
+ /** `a` is preferred over `b`: more pairings wins, and among equals the tighter one does. */
303
+ function better(a, b) {
304
+ return a.pairs !== b.pairs ? a.pairs > b.pairs : a.distance < b.distance;
305
+ }
306
+ /**
307
+ * The best set of non-crossing pairings between the still-free elements of `base` and `head`,
308
+ * as `[baseIndex, headIndex]` in ascending order — most pairings first, then least total line
309
+ * movement.
310
+ *
311
+ * Non-crossing is the whole content of the rule, and ir-schema §14 #11 is what licenses it:
312
+ * these arrays are ordered by line, so `i < j` means element `i` sits above element `j` in the
313
+ * file. Two pairings that cross would have an element move above one it was below, which is
314
+ * not a line shift — it is a different element. Restricting to non-crossing sets also makes
315
+ * the optimum reachable by a suffix recurrence rather than by a general assignment algorithm.
316
+ *
317
+ * Maximising the count before minimising distance is what stops a near pairing from being
318
+ * taken at the cost of a far one that would otherwise have no partner at all.
319
+ */
320
+ function assignInOrder(base, head, freeBase, freeHead, admits) {
321
+ const best = Array.from({ length: base.length + 1 }, () => Array.from({ length: head.length + 1 }, () => NO_PAIRINGS));
322
+ const pairingAt = (i, j) => {
323
+ const b = base[i];
324
+ const h = head[j];
325
+ if (b === void 0 || h === void 0) return null;
326
+ if (!freeBase.has(i) || !freeHead.has(j) || !admits(b, h)) return null;
327
+ const rest = best[i + 1]?.[j + 1] ?? NO_PAIRINGS;
328
+ return {
329
+ pairs: rest.pairs + 1,
330
+ distance: rest.distance + Math.abs(b.line - h.line)
331
+ };
332
+ };
333
+ for (let i = base.length - 1; i >= 0; i--) for (let j = head.length - 1; j >= 0; j--) {
334
+ const skipBase = best[i + 1]?.[j] ?? NO_PAIRINGS;
335
+ const skipHead = best[i]?.[j + 1] ?? NO_PAIRINGS;
336
+ let winner = better(skipBase, skipHead) ? skipBase : skipHead;
337
+ const paired = pairingAt(i, j);
338
+ if (paired !== null && better(paired, winner)) winner = paired;
339
+ const row = best[i];
340
+ if (row !== void 0) row[j] = winner;
341
+ }
342
+ const chosen = [];
343
+ let i = 0;
344
+ let j = 0;
345
+ while (i < base.length && j < head.length) {
346
+ const here = best[i]?.[j] ?? NO_PAIRINGS;
347
+ const paired = pairingAt(i, j);
348
+ if (paired !== null && paired.pairs === here.pairs && paired.distance === here.distance) {
349
+ chosen.push([i, j]);
350
+ i++;
351
+ j++;
352
+ continue;
353
+ }
354
+ const skipBase = best[i + 1]?.[j] ?? NO_PAIRINGS;
355
+ if (skipBase.pairs === here.pairs && skipBase.distance === here.distance) i++;
356
+ else j++;
357
+ }
358
+ return chosen;
359
+ }
196
360
  function diffRules(base, head, lineFuzz) {
197
361
  const mapper = (r) => ({
198
362
  item: r,
@@ -208,7 +372,7 @@ function diffEffects(base, head) {
208
372
  const mapper = (e) => ({
209
373
  item: e,
210
374
  key: `${e.id}::${e.target}`,
211
- line: e.line
375
+ line: e.line ?? 0
212
376
  });
213
377
  return differentiate(base.map(mapper), head.map(mapper), effectsEqual, Number.POSITIVE_INFINITY);
214
378
  }
@@ -303,6 +467,13 @@ function diffSignature(base, head) {
303
467
  typeParametersChanged: !arraysEqual(base?.typeParameters ?? empty.added.map(String), head?.typeParameters ?? empty.added.map(String))
304
468
  };
305
469
  }
470
+ /**
471
+ * Parameters are positional, so the index is part of the identity and the fuzz below is 0.
472
+ * That makes each key unique within its list, so §5.2.0 never has a choice to make here and
473
+ * both of its passes reduce to the same positional comparison. Dropping the index from the
474
+ * key would make two same-named parameters ambiguous and hand the choice back to §5.2.0,
475
+ * which is not what a positional list wants.
476
+ */
306
477
  const inputMapper = (input, index) => ({
307
478
  item: input,
308
479
  key: `${index}:${input.name}`,
@@ -417,6 +588,15 @@ function compareUnorderedSet(a, b) {
417
588
  * The result is de-duplicated so `InvoiceService.createInvoice` collapses to
418
589
  * `["invoice", "service", "create"]` — Jaccard similarity relies on set semantics, so
419
590
  * repeated tokens must not double-count.
591
+ *
592
+ * **The camel boundary is ASCII.** `isCamelBoundary` compares code points against `a`–`z`,
593
+ * `A`–`Z` and `0`–`9`, so a name written in a script with no ASCII case boundary and no
594
+ * separator comes back whole: `获取用户信息` and `ユーザー情報を取得する` are one token each,
595
+ * and so is `получитьПользователя` — its camel hump does not register. A separator still
596
+ * splits (`ユーザー.取得` gives two), and a mixed name splits on its ASCII half.
597
+ *
598
+ * That makes the token count a poor measure of how much such a name says, which matters
599
+ * wherever a count is read as a proxy for that — see §3.4.3's admissibility rule.
420
600
  */
421
601
  function tokenizeName(input) {
422
602
  const seen = /* @__PURE__ */ new Set();
@@ -466,47 +646,280 @@ function isCamelBoundary(prev, curr) {
466
646
  * purpose of §3.4.1). Empty on one side only returns 0.0.
467
647
  */
468
648
  function jaccard(a, b) {
469
- if (a.length === 0 && b.length === 0) return 1;
470
- if (a.length === 0 || b.length === 0) return 0;
471
- const setA = new Set(a);
472
- const setB = new Set(b);
649
+ return jaccardSets(new Set(a), new Set(b));
650
+ }
651
+ function jaccardSets(a, b) {
652
+ if (a.size === 0 && b.size === 0) return 1;
653
+ if (a.size === 0 || b.size === 0) return 0;
654
+ const [small, large] = a.size <= b.size ? [a, b] : [b, a];
473
655
  let intersection = 0;
474
- for (const t of setA) if (setB.has(t)) intersection++;
475
- const union = setA.size + setB.size - intersection;
476
- return intersection / union;
656
+ for (const token of small) if (large.has(token)) intersection++;
657
+ return intersection / (a.size + b.size - intersection);
477
658
  }
478
- /** name-token Jaccard shortcut used by nameSimilarity and ownerSimilarity call sites. */
659
+ /**
660
+ * Jaccard over the tokens of two strings. Part of the module's surface rather than an
661
+ * internal shortcut: the two formulas below go through a token table they share for one
662
+ * matching pass, so this has no caller inside this file.
663
+ */
479
664
  function jaccardTokens(a, b) {
480
665
  return jaccard(tokenizeName(a), tokenizeName(b));
481
666
  }
667
+ const tokenizeEveryTime = (value) => new Set(tokenizeName(value));
482
668
  /**
483
669
  * §3.4.1 — Jaccard over the tokens of the full qualified name. The last segment is not
484
670
  * given extra weight; the entire path contributes uniformly because the intersection is
485
671
  * what the score should reward.
486
672
  */
487
673
  function nameSimilarity(baseName, headName) {
488
- return jaccardTokens(baseName, headName);
674
+ return nameFormula(tokenizeEveryTime, baseName, headName);
675
+ }
676
+ /**
677
+ * §3.4.1 — Jaccard over the tokens of the **last segment**: the member name with its owner
678
+ * removed. What §3.4's composite reads, because §3.4.6 decides the owner separately and
679
+ * reading it on both axes charges for it twice.
680
+ */
681
+ function memberSimilarity(baseName, headName) {
682
+ return memberFormula(tokenizeEveryTime, baseName, headName);
489
683
  }
490
684
  /**
491
- * §3.4.6 — owner similarity: same as nameSimilarity but restricted to everything **before**
492
- * the last segment. Compensates for the R-8 same-name-different-class collision, where
493
- * `UserRepo.getUser` should not be pair-swapped with `AdminRepo.getUser`.
685
+ * §3.4.6 (R-8) — whether two Symbols are close enough in *scope* to be the same Symbol: the
686
+ * same owner, or one whose owner was renamed. A gate rather than a score, because grading the
687
+ * owner cannot do what R-8 asks. `UserRepo.findById` and `AdminRepo.findById` agree on their
688
+ * member name and their signature, so a shared `Repo` token at weight 0.2 carries them to
689
+ * 0.8667 against a 0.85 threshold — while `UsersRepository.findById`, which *is* the rename,
690
+ * shares no owner token and scores 0.8000. The collision outscores the rename, and raising the
691
+ * weight only moves both: at 0.3 two three-token class names sharing two tokens land on
692
+ * exactly 0.85.
494
693
  *
495
694
  * Owner extraction:
496
695
  * - `Class::method` → `Class`
497
696
  * - `A.B.C.method` → `A.B.C`
498
697
  * - `topLevel` → `` (empty)
499
698
  *
500
- * When both owners are empty (top-level functions), returns 1.0 because both live in the
501
- * same "no-owner" bucket. When one is empty and the other is not, returns 0.0 because the
502
- * two Symbols live in structurally different scopes.
699
+ * Two empty owners are compatible: top-level Symbols share the one outer scope. One empty and
700
+ * one not are never compatible — the two live at different depths.
701
+ *
702
+ * Otherwise the owners must correspond segment for segment, and within a segment every token
703
+ * on each side must find a distinct partner on the other under `sameWord`. Both sides must be
704
+ * covered, so `UserRepo` and `UserRepoV2` are two classes rather than one renamed — an added
705
+ * token is as much evidence of a sibling as of a rename, and R-8's business is refusing the
706
+ * collision.
707
+ */
708
+ function ownersAreCompatible(baseName, headName) {
709
+ return ownerGate(tokenizeEveryTime, baseName, headName);
710
+ }
711
+ /**
712
+ * §3.4.6 — the tokens `a` and `b` name the same thing.
713
+ *
714
+ * Equal, or the same word inflected: `user`/`users`, `entity`/`entities`. Nothing else, and
715
+ * that is the whole of the rule rather than a first approximation.
716
+ *
717
+ * A bare prefix test is the obvious generalisation and it cannot be made to work. It admits
718
+ * `repo`/`report`, `cache`/`cached`, `con`/`controller` — two distinct classes, which is
719
+ * exactly the collision R-8 exists to refuse. Every measure that might separate those from a
720
+ * real rename fails, because the two populations interleave rather than sitting on opposite
721
+ * sides of anything:
722
+ *
723
+ * ```
724
+ * dice levenshtein
725
+ * accept UserRepo/UsersRepository 0.571 7
726
+ * reject RepoManager/ReportManager 0.818 2
727
+ * accept Repo/Repository 0.500 6
728
+ * reject CacheStore/CachedStore 0.842 1
729
+ * ```
730
+ *
731
+ * The renames to accept score *lower* than the collisions to refuse, on both. There is no
732
+ * threshold, and a length-growth rule fares no better: `con`→`controller` grows by 7 and
733
+ * `user`→`users` by 1, so anything admitting the second admits the first.
734
+ *
735
+ * Inflection is not on that spectrum. It is a closed, mechanical relation between two spellings
736
+ * of one word, so it can be recognised rather than estimated — and it covers the case a plain
737
+ * equality test misses most often, a class pluralised in place.
738
+ *
739
+ * What this gives up is the abbreviation family: `UserRepo` → `UsersRepository` no longer
740
+ * clears the gate on `repo`/`repository`. That is a real rename reported as `added` +
741
+ * `removed`, and §3.4.6 records it as the price of refusing `repo`/`report`, which no rule
742
+ * over the two strings alone can tell apart. The evidence that would settle it is not in the
743
+ * strings: the owner is itself a Symbol, and whether *it* paired is the question being
744
+ * guessed at here.
745
+ */
746
+ function sameWord(a, b) {
747
+ if (a === b) return true;
748
+ const [short, long] = a.length <= b.length ? [a, b] : [b, a];
749
+ return pluralises(short, long);
750
+ }
751
+ /**
752
+ * The longest owner segment the matching will search.
753
+ *
754
+ * `augment` is Kuhn's, so the search is cubic in the token count and recursive with it. A
755
+ * class name is a handful of words; anything past this is not a name the gate has an opinion
756
+ * about, and `buildDiff` takes IR JSON from a caller rather than only from `aburi scan`, so
757
+ * the bound is what turns an adversarial 1600-token identifier from a hang into an answer.
758
+ * Refusing is the safe direction: the pair falls to `added` + `removed`.
503
759
  */
504
- function ownerSimilarity(baseName, headName) {
760
+ const MAX_OWNER_SEGMENT_TOKENS = 32;
761
+ /** English noun inflection, which is what a pluralised class name goes through. */
762
+ function pluralises(singular, plural) {
763
+ if (plural === `${singular}s` || plural === `${singular}es`) return true;
764
+ return singular.endsWith("y") && plural === `${singular.slice(0, -1)}ies`;
765
+ }
766
+ function nameFormula(setOf, baseName, headName) {
767
+ return jaccardSets(setOf(baseName), setOf(headName));
768
+ }
769
+ function memberFormula(setOf, baseName, headName) {
770
+ return jaccardSets(setOf(lastSegment(baseName)), setOf(lastSegment(headName)));
771
+ }
772
+ function ownerGate(setOf, baseName, headName) {
505
773
  const baseOwner = extractOwner(baseName);
506
774
  const headOwner = extractOwner(headName);
507
- if (baseOwner === "" && headOwner === "") return 1;
508
- if (baseOwner === "" || headOwner === "") return 0;
509
- return jaccardTokens(baseOwner, headOwner);
775
+ if (baseOwner === "" && headOwner === "") return true;
776
+ if (baseOwner === "" || headOwner === "") return false;
777
+ if (baseOwner === headOwner) return true;
778
+ return segmentsCorrespond(baseOwner, headOwner, setOf);
779
+ }
780
+ /**
781
+ * §3.4.6 — the two owners name the same scope: segment for segment, token for token.
782
+ *
783
+ * Compared per segment rather than over the owner as a whole, because `tokenizeName` dedups
784
+ * and an owner is a *path*. `Users.UserRepo` collapses to `{users, user, repo}` while
785
+ * `Users.UsersRepository` collapses to `{users, repository}` — the namespace and the class
786
+ * share a word, so one side loses a token and the two stop being comparable before any
787
+ * spelling is looked at. Segment by segment they line up: `Users`/`Users`, then
788
+ * `UserRepo`/`UsersRepository`.
789
+ *
790
+ * A rename changes what a class is called, not how deeply it is nested, so a differing segment
791
+ * count is a differing scope.
792
+ */
793
+ function segmentsCorrespond(baseOwner, headOwner, setOf) {
794
+ const baseSegments = baseOwner.split(".");
795
+ const headSegments = headOwner.split(".");
796
+ if (baseSegments.length !== headSegments.length) return false;
797
+ return baseSegments.every((segment, index) => {
798
+ const counterpart = headSegments[index];
799
+ if (counterpart === void 0) return false;
800
+ if (segment === counterpart) return true;
801
+ return coversBothWays(setOf(segment), setOf(counterpart));
802
+ });
803
+ }
804
+ /**
805
+ * Whether the two token sets admit a perfect matching under `sameWord`.
806
+ *
807
+ * Sizes must agree, after which an injection from one side is a bijection — so only one
808
+ * direction is searched. The search is augmenting-path rather than greedy, because a greedy
809
+ * pass can strand a token a different choice would have matched: over `{user, users}` and
810
+ * `{user, userx}`, taking the identical pair first leaves `users` with nothing, though
811
+ * `user`→`userx` with `users`→`user` covers both. One segment runs to a handful of tokens, so
812
+ * the exact answer costs nothing worth saving.
813
+ */
814
+ function coversBothWays(a, b) {
815
+ if (a.size !== b.size) return false;
816
+ if (a.size > MAX_OWNER_SEGMENT_TOKENS) return false;
817
+ const right = [...b];
818
+ const partnerOf = /* @__PURE__ */ new Map();
819
+ for (const token of a) if (!augment(token, right, partnerOf, /* @__PURE__ */ new Set())) return false;
820
+ return true;
821
+ }
822
+ /** Kuhn's step: claim a free partner for `token`, or displace one that can move on. */
823
+ function augment(token, right, partnerOf, visited) {
824
+ for (const candidate of right) {
825
+ if (visited.has(candidate) || !sameWord(token, candidate)) continue;
826
+ visited.add(candidate);
827
+ const holder = partnerOf.get(candidate);
828
+ if (holder === void 0 || augment(holder, right, partnerOf, visited)) {
829
+ partnerOf.set(candidate, token);
830
+ return true;
831
+ }
832
+ }
833
+ return false;
834
+ }
835
+ /**
836
+ * §3.4.6 — a necessary condition on two non-empty owners, cheaper than the full gate: their
837
+ * first segments must correspond, since segments are compared positionally.
838
+ *
839
+ * A filter, not a decision. It relaxes `coversBothWays`' perfect matching to "every token
840
+ * finds some partner", so it can only ever admit more than the gate does; answering `true`
841
+ * says the gate has to be asked. Loosening it further costs correctness nothing and speed a
842
+ * little — refusing something the gate would accept is the direction that would break recall.
843
+ */
844
+ function firstSegmentsCouldAgree(baseOwner, headOwner, setOf) {
845
+ const baseFirst = baseOwner.slice(0, dotOrEnd(baseOwner));
846
+ const headFirst = headOwner.slice(0, dotOrEnd(headOwner));
847
+ if (baseFirst === headFirst) return true;
848
+ const baseTokens = setOf(baseFirst);
849
+ const headTokens = setOf(headFirst);
850
+ if (baseTokens.size !== headTokens.size) return false;
851
+ if (baseTokens.size > MAX_OWNER_SEGMENT_TOKENS) return false;
852
+ for (const token of baseTokens) {
853
+ let partnered = false;
854
+ for (const candidate of headTokens) if (sameWord(token, candidate)) {
855
+ partnered = true;
856
+ break;
857
+ }
858
+ if (!partnered) return false;
859
+ }
860
+ return true;
861
+ }
862
+ function dotOrEnd(owner) {
863
+ const dot = owner.indexOf(".");
864
+ return dot < 0 ? owner.length : dot;
865
+ }
866
+ /**
867
+ * A scorer that tokenises each distinct name once.
868
+ *
869
+ * Stage 4 scores every (base, head) pair in a bucket, so a bucket of K on each side asks for
870
+ * K² similarities over 2K distinct names — tokenising on every call splits the same strings
871
+ * into the same tokens hundreds of thousands of times. The table lives for one call rather
872
+ * than for the process, because the names it holds are only the ones that pass is comparing.
873
+ */
874
+ function createNameScorer() {
875
+ const sets = /* @__PURE__ */ new Map();
876
+ const setOf = (value) => {
877
+ const cached = sets.get(value);
878
+ if (cached !== void 0) return cached;
879
+ const built = new Set(tokenizeName(value));
880
+ sets.set(value, built);
881
+ return built;
882
+ };
883
+ const owners = /* @__PURE__ */ new Map();
884
+ const ownerOf = (qname) => {
885
+ const cached = owners.get(qname);
886
+ if (cached !== void 0) return cached;
887
+ const built = extractOwner(qname);
888
+ owners.set(qname, built);
889
+ return built;
890
+ };
891
+ /**
892
+ * §3.4.6's gate, with the segment split and the matching skipped where they can be.
893
+ *
894
+ * The gate is the costliest thing stage 4 asks per candidate — it splits both owners into
895
+ * segments, tokenises each and runs an augmenting-path matching. Two shortcuts, in order of
896
+ * how much they save:
897
+ *
898
+ * - **Identical owners.** A bucket of methods on one class asks about the same owner over
899
+ * and over, and `ownerGate` already answers those on a string compare; doing it here skips
900
+ * the two `extractOwner` calls as well, which are substrings on every candidate.
901
+ * - **A different first segment.** Segments correspond positionally, so owners whose first
902
+ * segments cannot be the same word are incompatible whatever the rest says. The check is
903
+ * one `sameWord` over two token sets the table already holds, against a full matching over
904
+ * every segment.
905
+ *
906
+ * Not memoised on the pair. A bulk rename produces as many distinct owner pairs as
907
+ * candidates, so a table keyed on them grows with the cross-product — enough to exceed
908
+ * V8's Map limit on the very input this is meant to make fast.
909
+ */
910
+ const compatible = (baseName, headName) => {
911
+ const baseOwner = ownerOf(baseName);
912
+ const headOwner = ownerOf(headName);
913
+ if (baseOwner === headOwner) return true;
914
+ if (baseOwner === "" || headOwner === "") return false;
915
+ if (!firstSegmentsCouldAgree(baseOwner, headOwner, setOf)) return false;
916
+ return segmentsCorrespond(baseOwner, headOwner, setOf);
917
+ };
918
+ return {
919
+ name: (baseName, headName) => nameFormula(setOf, baseName, headName),
920
+ member: (baseName, headName) => memberFormula(setOf, baseName, headName),
921
+ ownersCompatible: compatible
922
+ };
510
923
  }
511
924
  function extractOwner(qname) {
512
925
  const staticIdx = qname.indexOf("::");
@@ -528,9 +941,75 @@ function lastSegment(qname) {
528
941
  //#region src/match.ts
529
942
  /** Fingerprint for the 12-hex-char "everything zero" (i.e. dropped) canonical hash. */
530
943
  const ZERO_LOGIC_FP = "000000000000";
944
+ /** §3.3 — the similarity a multi-candidate logic-fingerprint group must reach to pair. */
945
+ const NAME_DISAMBIGUATION_THRESHOLD = .85;
946
+ /**
947
+ * §3.8 — accept candidate pairings highest score first, taking each base and each head at
948
+ * most once. Stages 3, 4 and 4.5 all choose from a set of possible pairings, and all three
949
+ * used to decide one head at a time — which let an earlier head consume a base that was a
950
+ * later head's exact match, and reported the loser as `added` beside the pair it lost.
951
+ *
952
+ * The two id sets come back with the pairings because every caller needs them to work out
953
+ * what is left over, and deriving them again at the call site is a chance to derive the
954
+ * wrong one: reading the head ids out as the base ids typechecks, and reproduces the very
955
+ * symptom this exists to prevent.
956
+ *
957
+ * Not free, and §8.2 carries the bound: `candidates` is every pairing that clears its
958
+ * threshold, so this holds O(base × head) records for stages 3 and 4 in the worst case where
959
+ * the per-head loop it replaced held one, and sorting them is O(C log C). Stage 4 buys that
960
+ * back and more with `createNameScorer`.
961
+ *
962
+ * It is not an optimal assignment — a greedy sweep can still strand a pair whose partners
963
+ * were both taken by higher-scoring ones — but it never passes over the best available
964
+ * pairing, which is the case that shows up in a review as one symbol appearing twice.
965
+ *
966
+ * Stage 4.5 does not call this, because that licence is what it cannot borrow: §3.4.5's
967
+ * candidates are all worth the same, so no pairing is the best available and stranding one
968
+ * buys nothing. See `bestPairing`.
969
+ */
970
+ function acceptInScoreOrder(candidates) {
971
+ candidates.sort(compareCandidates);
972
+ const baseIds = /* @__PURE__ */ new Set();
973
+ const headIds = /* @__PURE__ */ new Set();
974
+ const pairs = [];
975
+ for (const candidate of candidates) {
976
+ if (baseIds.has(candidate.base.id) || headIds.has(candidate.head.id)) continue;
977
+ baseIds.add(candidate.base.id);
978
+ headIds.add(candidate.head.id);
979
+ pairs.push(candidate);
980
+ }
981
+ return {
982
+ pairs,
983
+ baseIds,
984
+ headIds
985
+ };
986
+ }
987
+ /**
988
+ * Highest score first, then `(base.id, head.id)` ascending. The two id keys are what make
989
+ * the order total, and they are a total order only because ids are unique within a Document
990
+ * (ir-schema.md §14 #1), which `buildDiff` establishes before the first stage runs. Without
991
+ * them equal scores resolve to enumeration order, and the diff stops being a function of the
992
+ * two Documents.
993
+ */
994
+ function compareCandidates(a, b) {
995
+ if (a.score !== b.score) return b.score - a.score;
996
+ if (a.base.id !== b.base.id) return a.base.id < b.base.id ? -1 : 1;
997
+ return a.head.id < b.head.id ? -1 : a.head.id > b.head.id ? 1 : 0;
998
+ }
999
+ /** The entries of `symbols` that no accepted pairing claimed, in their original order. */
1000
+ function unclaimed(symbols, claimed) {
1001
+ return symbols.filter((symbol) => !claimed.has(symbol.id));
1002
+ }
531
1003
  /**
532
1004
  * §3.1 — segments Symbols with identical `id` into paired matches. Runs first because it
533
1005
  * is the highest-confidence signal (no heuristics, just hash lookup).
1006
+ *
1007
+ * Assumes `id` is unique on each side (ir-schema.md §14 #1) and does not check it:
1008
+ * `buildDiff` establishes that before calling, and a caller reaching this export directly
1009
+ * owns the obligation. A repeat on the head side loses all but the last entry to the lookup
1010
+ * map and then removes every one of them from `remainingHead`; a repeat on the base side
1011
+ * pairs the same head Symbol more than once. The later stages track consumed base Symbols
1012
+ * by id and lose a repeat the same way.
534
1013
  */
535
1014
  function matchStageId(base, head) {
536
1015
  const headById = /* @__PURE__ */ new Map();
@@ -557,7 +1036,9 @@ function matchStageId(base, head) {
557
1036
  }
558
1037
  /**
559
1038
  * §3.2 — git rename detection. When a rename map is available (typical of ref-driven
560
- * scans), rewrite the base id with the head-side file path and look for a hit.
1039
+ * scans), rewrite the base id with the head-side file path and look for a hit. Two base
1040
+ * files renamed onto one target predict the same head id, so the claimants are collected
1041
+ * before one is chosen.
561
1042
  *
562
1043
  * The rewriter only touches the `file` portion of the id — the `<language>:` prefix and
563
1044
  * the trailing `#<qualified-name>` segment stay unchanged so a moved file with the same
@@ -572,255 +1053,757 @@ function matchStageGitRename(remainingBase, remainingHead, renameMap) {
572
1053
  };
573
1054
  const headById = /* @__PURE__ */ new Map();
574
1055
  for (const h of remainingHead) headById.set(h.id, h);
575
- const matched = [];
576
- const usedHead = /* @__PURE__ */ new Set();
577
- const remaining = [];
1056
+ const claimants = /* @__PURE__ */ new Map();
578
1057
  for (const b of remainingBase) {
579
1058
  const newPath = renameMap.get(b.source.file);
580
- if (newPath === void 0) {
581
- remaining.push(b);
582
- continue;
583
- }
1059
+ if (newPath === void 0) continue;
584
1060
  const expectedId = rewriteIdFile(b.id, b.source.file, newPath);
585
- const h = headById.get(expectedId);
586
- if (h === void 0 || usedHead.has(h.id)) {
587
- remaining.push(b);
588
- continue;
589
- }
1061
+ if (expectedId === null) continue;
1062
+ const head = headById.get(expectedId);
1063
+ if (head === void 0) continue;
1064
+ const claim = claimants.get(expectedId);
1065
+ if (claim === void 0) claimants.set(expectedId, {
1066
+ head,
1067
+ bases: [b]
1068
+ });
1069
+ else claim.bases.push(b);
1070
+ }
1071
+ const matched = [];
1072
+ const usedBase = /* @__PURE__ */ new Set();
1073
+ const usedHead = /* @__PURE__ */ new Set();
1074
+ for (const { head, bases } of claimants.values()) {
1075
+ const base = lowestId(bases);
590
1076
  matched.push({
591
- base: b,
592
- head: h,
1077
+ base,
1078
+ head,
593
1079
  rationale: "git-rename"
594
1080
  });
595
- usedHead.add(h.id);
1081
+ usedBase.add(base.id);
1082
+ usedHead.add(head.id);
596
1083
  }
597
1084
  return {
598
1085
  matched,
599
- remainingBase: remaining,
600
- remainingHead: remainingHead.filter((h) => !usedHead.has(h.id))
1086
+ remainingBase: unclaimed(remainingBase, usedBase),
1087
+ remainingHead: unclaimed(remainingHead, usedHead)
601
1088
  };
602
1089
  }
1090
+ /** Total on the non-empty claim lists above: a claim is created holding its first base. */
1091
+ function lowestId(symbols) {
1092
+ let lowest = symbols[0];
1093
+ for (const symbol of symbols) if (symbol.id < lowest.id) lowest = symbol;
1094
+ return lowest;
1095
+ }
1096
+ /**
1097
+ * Predict the id a base Symbol would carry after git moved its file. The second Symbol-id
1098
+ * derivation in the codebase after `makeSymbolId` itself, so it goes back through the same
1099
+ * constructor rather than re-concatenating the parts: `trySymbolId` rejects a rename target
1100
+ * the id grammar cannot express (a backslash path, say) instead of minting an id no head
1101
+ * Symbol can ever equal.
1102
+ *
1103
+ * Returns `null` for that case, and the unchanged id when no rename applies — the caller
1104
+ * treats a null the same way it treats a lookup miss, leaving the pair for stage 3.
1105
+ */
603
1106
  function rewriteIdFile(id, oldPath, newPath) {
604
1107
  const colon = id.indexOf(":");
605
1108
  const hash = id.indexOf("#");
606
1109
  if (colon < 0 || hash < 0 || hash < colon) return id;
607
- const language = id.slice(0, colon);
608
1110
  if (id.slice(colon + 1, hash) !== oldPath) return id;
609
- return `${language}:${newPath}${id.slice(hash)}`;
1111
+ return trySymbolId({
1112
+ language: id.slice(0, colon),
1113
+ file: newPath,
1114
+ qualifiedName: id.slice(hash + 1)
1115
+ });
610
1116
  }
611
1117
  /**
612
- * §3.3 — group base Symbols by `fingerprint.logic` and match head Symbols whose logic
613
- * fingerprint is in the map. Two disambiguation branches:
614
- * - single candidate → paired with `logic-fingerprint`
615
- * - multiple candidates → best `nameSimilarity` wins if ≥ 0.85; otherwise leave both
616
- * sides in remaining for stage 4 to re-evaluate
1118
+ * §3.3 — group both sides by `fingerprint.logic` and pair within each group. Two branches:
1119
+ * - single base candidate → paired with `logic-fingerprint`, no similarity test
1120
+ * - several → `nameSimilarity` disambiguates at ≥ 0.85; a group that cannot reach it is left
1121
+ * whole for stage 4 to re-evaluate
617
1122
  *
618
1123
  * Dropped symbols are excluded (§3.3 tail) — their logic fingerprint is the sentinel
619
1124
  * `"000000000000"` and would collide with every other dropped Symbol in the workspace.
620
1125
  * They flow to the stage-4.5 weak matcher instead.
621
1126
  */
622
1127
  function matchStageLogicFingerprint(remainingBase, remainingHead) {
623
- const logicMap = /* @__PURE__ */ new Map();
624
- const carryBase = [];
625
- for (const b of remainingBase) {
626
- if (b.dropped || b.fingerprint.logic === ZERO_LOGIC_FP) {
627
- carryBase.push(b);
628
- continue;
629
- }
630
- const bucket = logicMap.get(b.fingerprint.logic) ?? [];
631
- bucket.push(b);
632
- logicMap.set(b.fingerprint.logic, bucket);
1128
+ const baseGroups = groupByLogic(remainingBase);
1129
+ const headGroups = groupByLogic(remainingHead);
1130
+ const scorer = createNameScorer();
1131
+ const matched = [];
1132
+ for (const [logic, heads] of headGroups) {
1133
+ const bases = baseGroups.get(logic);
1134
+ if (bases === void 0) continue;
1135
+ matched.push(...pairWithinLogicGroup(bases, heads, scorer));
633
1136
  }
1137
+ const usedBase = new Set(matched.map((pair) => pair.base.id));
1138
+ const usedHead = new Set(matched.map((pair) => pair.head.id));
1139
+ return {
1140
+ matched,
1141
+ remainingBase: unclaimed(remainingBase, usedBase),
1142
+ remainingHead: unclaimed(remainingHead, usedHead)
1143
+ };
1144
+ }
1145
+ /**
1146
+ * Symbols by logic fingerprint, skipping the ones §3.3 excludes. Both sides are grouped, so
1147
+ * a group is a self-contained problem: the Symbols in it can only pair with each other, and
1148
+ * no group’s outcome depends on any other’s.
1149
+ */
1150
+ function groupByLogic(symbols) {
1151
+ const groups = /* @__PURE__ */ new Map();
1152
+ for (const symbol of symbols) {
1153
+ if (symbol.dropped || symbol.fingerprint.logic === ZERO_LOGIC_FP) continue;
1154
+ const bucket = groups.get(symbol.fingerprint.logic) ?? [];
1155
+ bucket.push(symbol);
1156
+ groups.set(symbol.fingerprint.logic, bucket);
1157
+ }
1158
+ return groups;
1159
+ }
1160
+ /**
1161
+ * §3.3’s two branches, over one logic-fingerprint group.
1162
+ *
1163
+ * A lone base candidate pairs with no similarity test — identical logic is taken as proof on
1164
+ * its own. With more than one, names disambiguate and a group that cannot reach the
1165
+ * threshold is left whole for stage 4.
1166
+ *
1167
+ * The loop is what keeps the second branch feeding the first: a scored round that consumes
1168
+ * all but one base leaves that one unconditional, which is how the per-head version behaved
1169
+ * when its candidate list shrank to a single entry.
1170
+ */
1171
+ function pairWithinLogicGroup(bases, heads, scorer) {
1172
+ let freeBase = [...bases];
1173
+ let freeHead = [...heads];
634
1174
  const matched = [];
635
- const carryHead = [];
636
- const usedBaseIds = /* @__PURE__ */ new Set();
637
- for (const h of remainingHead) {
638
- if (h.dropped || h.fingerprint.logic === ZERO_LOGIC_FP) {
639
- carryHead.push(h);
640
- continue;
641
- }
642
- const candidates = logicMap.get(h.fingerprint.logic);
643
- if (candidates === void 0 || candidates.length === 0) {
644
- carryHead.push(h);
645
- continue;
646
- }
647
- if (candidates.length === 1) {
648
- const only = candidates[0];
649
- if (only === void 0) continue;
1175
+ while (freeBase.length > 0 && freeHead.length > 0) {
1176
+ const lone = freeBase.length === 1 ? freeBase[0] : void 0;
1177
+ if (lone !== void 0) {
1178
+ const head = closestNameTo(lone, freeHead, scorer);
1179
+ if (head === void 0) break;
650
1180
  matched.push({
651
- base: only,
652
- head: h,
1181
+ base: lone,
1182
+ head,
653
1183
  rationale: "logic-fingerprint"
654
1184
  });
655
- usedBaseIds.add(only.id);
656
- logicMap.delete(h.fingerprint.logic);
657
- continue;
1185
+ break;
1186
+ }
1187
+ const candidates = [];
1188
+ for (const base of freeBase) for (const head of freeHead) {
1189
+ const score = scorer.name(base.name, head.name);
1190
+ if (score >= NAME_DISAMBIGUATION_THRESHOLD) candidates.push({
1191
+ base,
1192
+ head,
1193
+ score
1194
+ });
658
1195
  }
659
- let best = null;
660
- for (const c of candidates) {
661
- const score = nameSimilarity(c.name, h.name);
662
- if (best === null || score > best.score) best = {
663
- symbol: c,
1196
+ const accepted = acceptInScoreOrder(candidates);
1197
+ if (accepted.pairs.length === 0) break;
1198
+ for (const { base, head } of accepted.pairs) matched.push({
1199
+ base,
1200
+ head,
1201
+ rationale: "logic-fingerprint+name-disambiguation"
1202
+ });
1203
+ freeBase = unclaimed(freeBase, accepted.baseIds);
1204
+ freeHead = unclaimed(freeHead, accepted.headIds);
1205
+ }
1206
+ return matched;
1207
+ }
1208
+ /**
1209
+ * The head whose name is closest to `base`, ties going to the lower id. The lone-candidate
1210
+ * branch pairs whatever it is given, so this only decides *which* head it takes — but that
1211
+ * decision was array order, and it is visible in the diff.
1212
+ */
1213
+ function closestNameTo(base, heads, scorer) {
1214
+ let best;
1215
+ for (const head of heads) {
1216
+ const score = scorer.name(base.name, head.name);
1217
+ if (best === void 0 || score > best.score) {
1218
+ best = {
1219
+ head,
664
1220
  score
665
1221
  };
1222
+ continue;
666
1223
  }
667
- if (best !== null && best.score >= .85) {
668
- matched.push({
669
- base: best.symbol,
670
- head: h,
671
- rationale: "logic-fingerprint+name-disambiguation"
672
- });
673
- usedBaseIds.add(best.symbol.id);
674
- const remainingBucket = candidates.filter((c) => c.id !== best?.symbol.id);
675
- if (remainingBucket.length === 0) logicMap.delete(h.fingerprint.logic);
676
- else logicMap.set(h.fingerprint.logic, remainingBucket);
677
- } else carryHead.push(h);
1224
+ if (score === best.score && head.id < best.head.id) best = {
1225
+ head,
1226
+ score
1227
+ };
678
1228
  }
679
- const finalBase = [...carryBase];
680
- for (const bucket of logicMap.values()) for (const b of bucket) if (!usedBaseIds.has(b.id)) finalBase.push(b);
681
- return {
682
- matched,
683
- remainingBase: finalBase,
684
- remainingHead: carryHead
685
- };
1229
+ return best?.head;
686
1230
  }
687
1231
  /**
688
1232
  * §3.4 — name + signature similarity with `(kind, signatureNullness)` bucket pre-filter.
689
1233
  * `signatureNullness` distinguishes symbols with no signature (`interface`, `type`,
690
1234
  * `class`) from callable ones so that a class body is never paired against a function.
691
1235
  *
692
- * The composite score:
693
- * 0.5 * nameSimilarity + 0.3 * signatureSimilarity + 0.2 * ownerSimilarity
1236
+ * §3.4.6's owner gate runs before the score: a pair whose owners are not the same class, or
1237
+ * one a rename of the other, is not the same Symbol however well the rest agrees, and no
1238
+ * weight small enough to leave the name axis meaning something can outvote a matching member
1239
+ * name and signature.
1240
+ *
1241
+ * The composite score, over the pairs that clear it:
1242
+ * 0.5 * memberSimilarity + 0.3 * signatureSimilarity + 0.2 * OWNER_AXIS_SATISFIED
1243
+ *
1244
+ * `memberSimilarity` reads the last segment, not the whole qualified name: the gate has
1245
+ * already settled the owner, and reading it again on the name axis charges for it twice —
1246
+ * which is what kept a renamed class from ever pairing (§3.4.6).
1247
+ *
1248
+ * §3.4.3 threshold table, applied per head by the token count of its last name segment:
1249
+ * - 1 token → 1.0 (an exact match on both remaining axes)
1250
+ * - 2 tokens → 0.95 (strict, avoids `getUser` vs `getUsers`)
1251
+ * - default → 0.85
694
1252
  *
695
- * §3.4.3 threshold table:
696
- * - 1-token name → 1.0 (unreachable → never paired; false-positive shield)
697
- * - 2-token name → 0.95 (strict, avoids `getUser` vs `getUsers`)
698
- * - default → 0.85
1253
+ * §3.4.3 also names two Symbols the stage does not read at all, because for them the score is
1254
+ * high on evidence it does not have rather than on a resemblance: one whose signature is
1255
+ * null, since `signatureSimilarity(null, null)` is 1.0 and the bucket key restricts it to
1256
+ * candidates that are equally signature-less; and one whose qualified name carries a single
1257
+ * distinct token, since that is the whole of what its identity amounts to. Neither can be
1258
+ * expressed as a threshold — the second wants a bar above the top of the scale.
699
1259
  *
700
- * §3.4.3 tail — if both sides are signature-less, we skip pairing entirely because
701
- * signatureSimilarity always returns 1.0 for `null + null` and would flood the bucket with
702
- * false pairings.
1260
+ * Every pairing in a bucket that clears its head’s threshold becomes a candidate, and the
1261
+ * candidates are settled in score order rather than one head at a time — see
1262
+ * `acceptInScoreOrder`. That doubles the pairings scored, from a bucket that shrank as heads
1263
+ * consumed it to the full bucket every time; `createNameScorer` more than pays for it by
1264
+ * tokenising each distinct name once per pass instead of once per comparison.
703
1265
  */
704
1266
  function matchStageNameSignature(remainingBase, remainingHead) {
705
1267
  const buckets = /* @__PURE__ */ new Map();
706
1268
  for (const b of remainingBase) {
707
1269
  if (b.dropped) continue;
1270
+ if (!saysEnoughToPair(b.name)) continue;
708
1271
  const key = bucketKey(b);
709
- const bucket = buckets.get(key) ?? [];
710
- bucket.push(b);
1272
+ const bucket = buckets.get(key) ?? {
1273
+ members: [],
1274
+ byToken: /* @__PURE__ */ new Map()
1275
+ };
1276
+ const position = bucket.members.length;
1277
+ bucket.members.push(b);
1278
+ for (const token of memberTokens(b.name)) {
1279
+ const sharing = bucket.byToken.get(token) ?? [];
1280
+ sharing.push(position);
1281
+ bucket.byToken.set(token, sharing);
1282
+ }
711
1283
  buckets.set(key, bucket);
712
1284
  }
713
- const matched = [];
714
- const remainingHeadOut = [];
715
- const usedBaseIds = /* @__PURE__ */ new Set();
1285
+ const visitsOf = /* @__PURE__ */ new Map();
1286
+ for (const bucket of buckets.values()) visitsOf.set(bucket, new Int32Array(bucket.members.length));
1287
+ const scorer = createNameScorer();
1288
+ const candidates = [];
1289
+ let visitCount = 0;
716
1290
  for (const h of remainingHead) {
717
- if (h.dropped) {
718
- remainingHeadOut.push(h);
719
- continue;
720
- }
721
- const key = bucketKey(h);
722
- const bucket = buckets.get(key);
723
- if (bucket === void 0 || bucket.length === 0) {
724
- remainingHeadOut.push(h);
725
- continue;
726
- }
727
- if ((h.signature === null || h.signature === void 0) && bucket.every((c) => c.signature === null || c.signature === void 0)) {
728
- remainingHeadOut.push(h);
729
- continue;
730
- }
731
- let best = null;
732
- for (const c of bucket) {
733
- const score = .5 * nameSimilarity(c.name, h.name) + .3 * signatureSimilarity(c.signature ?? null, h.signature ?? null) + .2 * ownerSimilarity(c.name, h.name);
734
- if (best === null || score > best.score) best = {
735
- symbol: c,
736
- score
737
- };
738
- }
1291
+ if (h.dropped) continue;
1292
+ if (h.signature === null || h.signature === void 0) continue;
1293
+ if (!saysEnoughToPair(h.name)) continue;
1294
+ const bucket = buckets.get(bucketKey(h));
1295
+ if (bucket === void 0) continue;
739
1296
  const threshold = thresholdFor(h.name);
740
- if (best !== null && best.score >= threshold) {
741
- matched.push({
742
- base: best.symbol,
743
- head: h,
744
- rationale: "name-signature"
745
- });
746
- usedBaseIds.add(best.symbol.id);
747
- buckets.set(key, bucket.filter((c) => c.id !== best?.symbol.id));
748
- } else remainingHeadOut.push(h);
749
- }
750
- const remainingBaseOut = [];
751
- for (const b of remainingBase) {
752
- if (b.dropped) {
753
- remainingBaseOut.push(b);
1297
+ const memberFloor = lowestUsefulMember(threshold);
1298
+ const tokens = memberTokens(h.name);
1299
+ let reach = 0;
1300
+ for (const token of tokens) reach += bucket.byToken.get(token)?.length ?? 0;
1301
+ if (reach >= bucket.members.length) {
1302
+ for (const b of bucket.members) collectCandidate(b, h, scorer, memberFloor, threshold, candidates);
754
1303
  continue;
755
1304
  }
756
- if (!usedBaseIds.has(b.id)) remainingBaseOut.push(b);
1305
+ const visited = visitsOf.get(bucket);
1306
+ if (visited === void 0) continue;
1307
+ visitCount++;
1308
+ for (const token of tokens) for (const position of bucket.byToken.get(token) ?? []) {
1309
+ if (visited[position] === visitCount) continue;
1310
+ visited[position] = visitCount;
1311
+ const b = bucket.members[position];
1312
+ if (b !== void 0) collectCandidate(b, h, scorer, memberFloor, threshold, candidates);
1313
+ }
757
1314
  }
1315
+ const accepted = acceptInScoreOrder(candidates);
758
1316
  return {
759
- matched,
760
- remainingBase: remainingBaseOut,
761
- remainingHead: remainingHeadOut
1317
+ matched: accepted.pairs.map(({ base, head }) => ({
1318
+ base,
1319
+ head,
1320
+ rationale: "name-signature"
1321
+ })),
1322
+ remainingBase: unclaimed(remainingBase, accepted.baseIds),
1323
+ remainingHead: unclaimed(remainingHead, accepted.headIds)
762
1324
  };
763
1325
  }
1326
+ /**
1327
+ * §3.4 — score one candidate pairing and keep it if it clears the head's threshold.
1328
+ *
1329
+ * A plain function rather than a closure over the head loop: both branches of the walk need
1330
+ * it, and a closure built per head is the cross-product moved into the allocator — measurably
1331
+ * so, at around 1.6x on a bucket the index cannot narrow.
1332
+ *
1333
+ * §3.4.3's floor is read before §3.4.6's gate and is the only early exit here. It is one
1334
+ * Jaccard over token sets the pass already holds, where the gate splits both owners into
1335
+ * segments, tokenises each and runs an augmenting-path matching. The gate short-circuits
1336
+ * internally on identical owners and on first segments that cannot correspond, so there is
1337
+ * nothing left worth hoisting out of it.
1338
+ */
1339
+ function collectCandidate(base, head, scorer, memberFloor, threshold, candidates) {
1340
+ const member = scorer.member(base.name, head.name);
1341
+ if (member < memberFloor) return;
1342
+ if (!scorer.ownersCompatible(base.name, head.name)) return;
1343
+ const score = .5 * member + .3 * signatureSimilarity(base.signature ?? null, head.signature ?? null) + .2 * OWNER_AXIS_SATISFIED;
1344
+ if (score >= threshold) candidates.push({
1345
+ base,
1346
+ head,
1347
+ score
1348
+ });
1349
+ }
764
1350
  function bucketKey(s) {
765
1351
  const sig = s.signature === null || s.signature === void 0 ? "no-sig" : "has-sig";
766
1352
  return `${s.kind}::${sig}`;
767
1353
  }
1354
+ /**
1355
+ * §3.4.0 — the least `memberSimilarity` that leaves `threshold` reachable.
1356
+ *
1357
+ * `0.5 * member + 0.3 * signature + 0.2 * 1` must reach the threshold, and the signature axis
1358
+ * is worth at most 0.3, so `member >= 2 * (threshold - 0.5)`. Refusing below this is exact
1359
+ * rather than approximate: nothing the other two axes can do rescues a pair under it.
1360
+ *
1361
+ * Reading it before §3.4.6's gate is what keeps stage 4 off the cross-product. The gate splits
1362
+ * and tokenises two owners; this is one Jaccard over token sets the pass has already built,
1363
+ * and it refuses most of what a shared token admits.
1364
+ */
1365
+ function lowestUsefulMember(threshold) {
1366
+ return 2 * (threshold - .5);
1367
+ }
1368
+ /**
1369
+ * §3.4.0 — the token that stands in for a member name carrying none.
1370
+ *
1371
+ * `Foo.Bar.` has an empty last segment and two tokens in its qualified name, so it is
1372
+ * admissible, and two such Symbols score 1.0 on an axis comparing two empty sets. They have
1373
+ * no token to be indexed under and cannot pair with anything that has one, so they share a
1374
+ * key of their own. A real token cannot collide with it: `tokenizeName` never emits a space.
1375
+ */
1376
+ const NO_MEMBER_TOKENS = " none";
1377
+ function memberTokens(qname) {
1378
+ const tokens = tokenizeName(lastSegment(qname));
1379
+ return tokens.length === 0 ? [NO_MEMBER_TOKENS] : tokens;
1380
+ }
1381
+ /**
1382
+ * §3.4.3 — the composite score a pair must reach, by how many tokens the head's last name
1383
+ * segment has. A one-token segment still asks for the whole scale, which a pair reaches on an
1384
+ * identical member name and signature past §3.4.6's gate: `0.5 + 0.3 + 0.2`, exactly 1 in
1385
+ * IEEE 754. The owner need not be identical, only compatible — `UserRepo.get` and
1386
+ * `UserRepos.get` reach it.
1387
+ */
1388
+ const EXACT_MATCH_ONLY = 1;
1389
+ const TWO_TOKEN_THRESHOLD = .95;
1390
+ const DEFAULT_THRESHOLD = .85;
1391
+ /**
1392
+ * §3.4.6 — what the owner axis is worth to a pair that clears its gate, which is every pair
1393
+ * that reaches the score. Written as a value rather than folded into the weights so the
1394
+ * composite keeps the 0.5/0.3/0.2 shape §3.4.3's rows are calibrated against: dropping the
1395
+ * term and renormalising would move every threshold without changing what any of them means.
1396
+ */
1397
+ const OWNER_AXIS_SATISFIED = 1;
768
1398
  function thresholdFor(qname) {
769
1399
  const tokens = tokenizeName(lastSegment(qname)).length;
770
- if (tokens <= 1) return 1;
771
- if (tokens === 2) return .95;
772
- return .85;
1400
+ if (tokens <= 1) return EXACT_MATCH_ONLY;
1401
+ if (tokens === 2) return TWO_TOKEN_THRESHOLD;
1402
+ return DEFAULT_THRESHOLD;
773
1403
  }
774
1404
  /**
775
- * §3.4.5 — dropped-only weak matcher. For dropped Symbols the fingerprint is zeroed and
776
- * name/signature are the only remaining signals. Score is a coarse "did the last name
777
- * segment or file basename survive?" — if either half matches we pair (threshold 0.5).
1405
+ * §3.4.3 — whether a Symbol's qualified name says enough for stage 4 to read it at all.
1406
+ *
1407
+ * The score is built from three things the name supplies: its tokens, its owner's tokens,
1408
+ * and a signature. A name of one distinct token supplies one word and an owner that either
1409
+ * repeats it or is empty, and `main(x: string): void` against another `main(x: string): void`
1410
+ * scores the full 1.0 on that — two unrelated CLI entry points reported as one move. The
1411
+ * table's first row was written to refuse this and could not: 1.0 is the top of the scale,
1412
+ * so no threshold sits above it. Being unpairable is a property of the name, not a score it
1413
+ * failed to reach, so it is decided here rather than by the comparison.
1414
+ *
1415
+ * Counted over the whole qualified name, because that is what the score reads.
1416
+ * `UserRepo.get` supplies three tokens and pairs, though its last segment is one — the
1417
+ * measure `thresholdFor` uses, and the wrong one for this question. Tokens are deduped, so
1418
+ * `Main.main` supplies one and does not.
778
1419
  *
779
- * This is deliberately lax; diff-algorithm.md §3.4.5 already accepts that dropped Symbols live
780
- * outside the main IR review surface, so occasional false pairings only affect the
781
- * "Drop-rule variation" fold-out section in the Markdown projection.
1420
+ * Read off both sides, because the property belongs to a pairing. It was once read off the
1421
+ * head alone, on the arithmetic that a short name anywhere capped the score at 0.75 — true
1422
+ * while the name axis read the whole qualified name, and false since §3.4.6 became a gate and
1423
+ * the axis moved to the last segment. `Main.main` is one deduped token and clears the gate
1424
+ * against `Mains.main`, whose member name is identical, so the pair reaches the top of the
1425
+ * scale from a name saying one word.
1426
+ *
1427
+ * The count stands in for how much the name says, and `tokenizeName` splits on ASCII case
1428
+ * boundaries, so a name written in a script that has none is one token however long it is:
1429
+ * `ユーザー情報を取得する` is refused here on the same footing as `main`. For that name the
1430
+ * proxy is wrong — two unrelated Symbols do not carry it by coincidence the way two carry
1431
+ * `main` — and the cost is a stage-4 move this stage will not find. Fixing it means measuring
1432
+ * the name by something other than a bare token count, which is §3.4.1's to change.
1433
+ */
1434
+ function saysEnoughToPair(qname) {
1435
+ return tokenizeName(qname).length > 1;
1436
+ }
1437
+ /**
1438
+ * §3.4.5 — dropped-only weak matcher. For dropped Symbols the fingerprint is zeroed, so the
1439
+ * only signals left are the trailing segment of the qualified name and the file basename.
1440
+ * Either one alone is enough to pair, which is deliberately lax: §3.4.5 accepts a
1441
+ * false-positive risk because dropped Symbols sit outside the IR's main review surface.
1442
+ *
1443
+ * What it does not accept is a signal that identifies nothing. A basename hit on `index.ts`
1444
+ * — the most common filename in a TypeScript monorepo — paired every dropped Symbol of one
1445
+ * kind under one with every other, at a score they all tied on, and the results landed in
1446
+ * `summary.moved`, which `--fail-on moved` gates on. So a half counts only when exactly one
1447
+ * dropped base and one dropped head carry that key: such a key names a pair, where a key
1448
+ * several Symbols carry names a group, and a group is not a pairing.
1449
+ *
1450
+ * That makes the candidates the identifying keys themselves — at most one pairing each,
1451
+ * two axes, so at most `2 × min(base, head)` of them rather than the cross-product a shared
1452
+ * basename used to produce.
1453
+ *
1454
+ * "Exactly one" is counted over the Symbols this stage is handed, not over every dropped
1455
+ * Symbol in the Document — stages 1 and 2 have already taken theirs, and a key they emptied
1456
+ * out identifies again. That is the intended reading, since the question is which leftover a
1457
+ * key picks out, but it is also how a shared `index.ts` comes back: three dropped classes
1458
+ * under one, two of them matched by id, and the basename identifies the two that are left.
1459
+ *
1460
+ * It also leaves nothing for §3.4.5's 0.5-per-half scale to rank, so §3.8's sweep is the
1461
+ * wrong instrument: it settles conflicts by score, and with none to settle by it would drop
1462
+ * one identified pairing for another over nothing but the id it sorts under. `bestPairing`
1463
+ * takes a maximum matching instead.
782
1464
  */
783
1465
  function matchStageDroppedWeak(remainingBase, remainingHead) {
784
- const droppedBase = remainingBase.filter((s) => s.dropped);
785
- const nonDroppedBase = remainingBase.filter((s) => !s.dropped);
786
- const droppedHead = remainingHead.filter((s) => s.dropped);
787
- const nonDroppedHead = remainingHead.filter((s) => !s.dropped);
788
- const matched = [];
789
- const usedBaseIds = /* @__PURE__ */ new Set();
790
- const carryHead = [];
791
- for (const h of droppedHead) {
792
- let best = null;
793
- for (const b of droppedBase) {
794
- if (b.kind !== h.kind) continue;
795
- if (usedBaseIds.has(b.id)) continue;
796
- const nameHit = lastSegment(b.name) === lastSegment(h.name) ? 1 : 0;
797
- const fileHit = basename(b.source.file) === basename(h.source.file) ? 1 : 0;
798
- const score = .5 * nameHit + .5 * fileHit;
799
- if (best === null || score > best.score) best = {
800
- symbol: b,
801
- score
802
- };
803
- }
804
- if (best !== null && best.score >= .5) {
805
- matched.push({
806
- base: best.symbol,
807
- head: h,
808
- rationale: "dropped-weak-match"
809
- });
810
- usedBaseIds.add(best.symbol.id);
811
- } else carryHead.push(h);
812
- }
1466
+ const bases = remainingBase.filter((s) => s.dropped);
1467
+ const heads = remainingHead.filter((s) => s.dropped);
1468
+ const identified = [];
1469
+ for (const keyOf of [nameKey, fileKey]) identified.push(...pairsIdentifiedBy(bases, heads, keyOf));
1470
+ const matched = bestPairing(identified);
813
1471
  return {
814
- matched,
815
- remainingBase: [...nonDroppedBase, ...droppedBase.filter((b) => !usedBaseIds.has(b.id))],
816
- remainingHead: [...nonDroppedHead, ...carryHead]
1472
+ matched: matched.map(({ base, head }) => ({
1473
+ base,
1474
+ head,
1475
+ rationale: "dropped-weak-match"
1476
+ })),
1477
+ remainingBase: unclaimed(remainingBase, new Set(matched.map((edge) => edge.base.id))),
1478
+ remainingHead: unclaimed(remainingHead, new Set(matched.map((edge) => edge.head.id)))
817
1479
  };
818
1480
  }
1481
+ /**
1482
+ * As many of the identified pairings as can hold at once.
1483
+ *
1484
+ * Each axis identifies a Symbol at most once, so a Symbol carries at most two pairings and
1485
+ * the whole set is the union of two matchings — which is a disjoint union of simple paths and
1486
+ * even cycles. Alternate pairings along a component are therefore a maximum matching of it,
1487
+ * and walking each component from a fixed end makes the choice among the maximum matchings
1488
+ * canonical rather than a property of the input order.
1489
+ *
1490
+ * The alternative would be §3.8's sweep, and it is the wrong instrument once §3.4.5's score
1491
+ * is gone: over `Shared.ts#Alpha`, `Other.ts#Beta` against `Other.ts#Alpha`,
1492
+ * `Shared.ts#Gamma`, all three pairings are identified and it takes one where two hold.
1493
+ */
1494
+ function bestPairing(edges) {
1495
+ const ordered = [...edges].sort(byEndpoints);
1496
+ const atBase = /* @__PURE__ */ new Map();
1497
+ const atHead = /* @__PURE__ */ new Map();
1498
+ for (const [index, edge] of ordered.entries()) {
1499
+ appendTo(atBase, edge.base.id, index);
1500
+ appendTo(atHead, edge.head.id, index);
1501
+ }
1502
+ const adjacent = (index) => {
1503
+ const edge = ordered[index];
1504
+ if (edge === void 0) return [];
1505
+ return [...atBase.get(edge.base.id) ?? [], ...atHead.get(edge.head.id) ?? []].filter((other) => other !== index);
1506
+ };
1507
+ const walked = ordered.map(() => false);
1508
+ const matching = [];
1509
+ /** Follow a component from `start`, taking every other pairing along it. */
1510
+ const walkFrom = (start) => {
1511
+ let step = start;
1512
+ let take = true;
1513
+ while (!walked[step]) {
1514
+ walked[step] = true;
1515
+ const edge = ordered[step];
1516
+ if (take && edge !== void 0) matching.push(edge);
1517
+ take = !take;
1518
+ const next = adjacent(step).find((other) => walked[other] === false);
1519
+ if (next === void 0) return;
1520
+ step = next;
1521
+ }
1522
+ };
1523
+ for (const [index] of ordered.entries()) if (!walked[index] && adjacent(index).length <= 1) walkFrom(index);
1524
+ for (const [index] of ordered.entries()) if (!walked[index]) walkFrom(index);
1525
+ return matching;
1526
+ }
1527
+ function byEndpoints(a, b) {
1528
+ if (a.base.id !== b.base.id) return a.base.id < b.base.id ? -1 : 1;
1529
+ return a.head.id < b.head.id ? -1 : a.head.id > b.head.id ? 1 : 0;
1530
+ }
1531
+ function appendTo(table, key, index) {
1532
+ const bucket = table.get(key);
1533
+ if (bucket === void 0) table.set(key, [index]);
1534
+ else bucket.push(index);
1535
+ }
1536
+ /**
1537
+ * The pairings a key picks out on its own: those whose key exactly one dropped base and one
1538
+ * dropped head carry. A key held by two Symbols on either side is discarded rather than
1539
+ * resolved — with the fingerprint zeroed there is nothing left to tell the members apart, and
1540
+ * guessing between them is the false pairing this rule exists to refuse.
1541
+ */
1542
+ function pairsIdentifiedBy(bases, heads, keyOf) {
1543
+ const soleBase = soleCarriers(bases, keyOf);
1544
+ const soleHead = soleCarriers(heads, keyOf);
1545
+ const pairs = [];
1546
+ for (const [key, base] of soleBase) {
1547
+ const head = soleHead.get(key);
1548
+ if (head !== void 0) pairs.push({
1549
+ base,
1550
+ head
1551
+ });
1552
+ }
1553
+ return pairs;
1554
+ }
1555
+ /** Keys carried by exactly one of `symbols`, mapped to it. */
1556
+ function soleCarriers(symbols, keyOf) {
1557
+ const sole = /* @__PURE__ */ new Map();
1558
+ const shared = /* @__PURE__ */ new Set();
1559
+ for (const symbol of symbols) {
1560
+ const key = keyOf(symbol);
1561
+ if (shared.has(key)) continue;
1562
+ if (sole.has(key)) {
1563
+ sole.delete(key);
1564
+ shared.add(key);
1565
+ continue;
1566
+ }
1567
+ sole.set(key, symbol);
1568
+ }
1569
+ return sole;
1570
+ }
1571
+ /**
1572
+ * The two halves §3.4.5 scores. `kind` leads because it gates a pair before either half is
1573
+ * read, and `/` separates because no kind, qualified-name segment or basename contains one.
1574
+ */
1575
+ function nameKey(symbol) {
1576
+ return `${symbol.kind}/${lastSegment(symbol.name)}`;
1577
+ }
1578
+ function fileKey(symbol) {
1579
+ return `${symbol.kind}/${basename(symbol.source.file)}`;
1580
+ }
819
1581
  function basename(path) {
820
1582
  const slash = path.lastIndexOf("/");
821
1583
  return slash >= 0 ? path.slice(slash + 1) : path;
822
1584
  }
823
1585
 
1586
+ //#endregion
1587
+ //#region src/slice.ts
1588
+ /**
1589
+ * Slice View clustering pass — docs/design/slice-view.md §2, §4–§8.
1590
+ *
1591
+ * Groups the changed-Symbol set of a diff into weakly-connected components
1592
+ * over the union of base and head call edges. Emits a `SliceRecord[]` whose
1593
+ * cluster ids are `"slice:" + <smallest-member Symbol id>`, both `slices[]`
1594
+ * and each `members[]` sorted ascending.
1595
+ *
1596
+ * Pure function: `(changes, baseCallEdges, headCallEdges)` → `SliceRecord[]`.
1597
+ * Determinism, idempotence, input-order insensitivity, and locality are all
1598
+ * guaranteed — see `computeWeaklyConnectedComponents` in `@aburi/core`.
1599
+ *
1600
+ * Returns `[]` when no SymbolChange is Node-eligible per §4.1; callers should
1601
+ * still serialise the empty array — the Markdown projection omits the section
1602
+ * (§9.4 / §12.5) but the JSON always emits the key so consumers never
1603
+ * distinguish "field absent" from "no slices" (§11.2).
1604
+ *
1605
+ * Every returned record has passed `assertSliceRecordInvariant` (§7.4).
1606
+ */
1607
+ function computeSlices(input) {
1608
+ const nodeIds = collectNodeIds(input.changes);
1609
+ if (nodeIds.length === 0) return [];
1610
+ const nodeIdSet = new Set(nodeIds);
1611
+ return computeWeaklyConnectedComponents(nodeIds, collectEdges(input.baseCallEdges, input.headCallEdges, nodeIdSet), (id) => id).map(makeSliceRecord);
1612
+ }
1613
+ const SLICE_ID_PREFIX = "slice:";
1614
+ /**
1615
+ * §7.1 — the single place production code derives a Slice id. Everything else
1616
+ * in `src/` either receives an id or renders one. (Tests spell the prefix out
1617
+ * literally on purpose: an expectation written in terms of the function under
1618
+ * test would agree with it no matter what it produced.)
1619
+ *
1620
+ * The cast is the one place a `SliceId` comes into existence. `SliceId` and
1621
+ * `SymbolId` are separate brands precisely so this concatenation cannot be
1622
+ * open-coded anywhere else: a bare `"slice:" + x` evaluates to `string`, which
1623
+ * `SliceRecord.id` no longer accepts.
1624
+ */
1625
+ function sliceIdFor(anchor) {
1626
+ return `${SLICE_ID_PREFIX}${anchor}`;
1627
+ }
1628
+ /**
1629
+ * Build one SliceRecord from an ascending-sorted component and check its own
1630
+ * post-condition before letting it out (§7.4 layer 1).
1631
+ *
1632
+ * The check is not defending against untrusted input — this function builds
1633
+ * the id itself, so the derivation clause is true by construction here and
1634
+ * only the two clauses about `members` can actually fire. Those are the point:
1635
+ * `members[0]` is the anchor only because `computeWeaklyConnectedComponents`
1636
+ * returns each component sorted ascending, a guarantee that lives one layer
1637
+ * down and is invisible from this file. If it ever stops holding, the diff
1638
+ * would otherwise keep emitting well-formed-looking SliceRecords naming the
1639
+ * wrong anchor. Here it fails instead.
1640
+ */
1641
+ function makeSliceRecord(members) {
1642
+ const anchor = members[0];
1643
+ if (anchor === void 0) throw new DiffError("computeSlices: the clustering utility returned an empty component; every weakly-connected component contains at least the node that seeded it (slice-view.md §6).", { code: "slice-invariant-violated" });
1644
+ const record = {
1645
+ id: sliceIdFor(anchor),
1646
+ members: [...members]
1647
+ };
1648
+ assertSliceRecordInvariant(record);
1649
+ return record;
1650
+ }
1651
+ /**
1652
+ * §7.1 — the anchor of a Slice: its lexicographically smallest member.
1653
+ *
1654
+ * Answers from `members[0]`. `id` is derived from the anchor, so
1655
+ * reconstructing the anchor by stripping the `"slice:"` prefix is circular at
1656
+ * best and, for a record that broke the derivation, silently wrong: it would
1657
+ * name a Symbol that is not in the Slice. `id` is read here only to name the
1658
+ * offending record in the error message. Consumers that need the anchor call
1659
+ * this; consumers that need a label keep using `id` directly.
1660
+ */
1661
+ function sliceAnchor(record) {
1662
+ const anchor = record.members[0];
1663
+ if (anchor === void 0) {
1664
+ const violation = emptyMembersViolation(record.id);
1665
+ throw new DiffError(violation.message, {
1666
+ code: "slice-invariant-violated",
1667
+ value: violation.subject
1668
+ });
1669
+ }
1670
+ return anchor;
1671
+ }
1672
+ /**
1673
+ * Report which clause of the §7.1 / §8.2 invariant a value breaks, or `null`
1674
+ * when it is a well-formed `SliceRecord`. Non-throwing counterpart of
1675
+ * `assertSliceRecordInvariant`: the pass wants an exception, a schema
1676
+ * validator wants a verdict it can turn into its own error.
1677
+ *
1678
+ * Takes `unknown` rather than `SliceRecord` deliberately. §7.4 layer 2 points
1679
+ * this at documents written by third-party or older producers — data that has
1680
+ * not been type-checked by definition — so anything that assumed a well-typed
1681
+ * argument would crash on exactly the input it exists to reject.
1682
+ */
1683
+ function sliceRecordViolation(value) {
1684
+ if (typeof value !== "object" || value === null) return {
1685
+ kind: "malformed-shape",
1686
+ subject: "<not an object>",
1687
+ message: `Expected a SliceRecord object; got ${value === null ? "null" : typeof value}.`
1688
+ };
1689
+ const { id, members } = value;
1690
+ const subject = typeof id === "string" ? id : "<missing id>";
1691
+ if (typeof id !== "string") return {
1692
+ kind: "malformed-shape",
1693
+ subject,
1694
+ message: `SliceRecord ${subject}: id must be a string; got ${typeof id}.`
1695
+ };
1696
+ if (!Array.isArray(members) || members.some((member) => typeof member !== "string")) return {
1697
+ kind: "malformed-shape",
1698
+ subject,
1699
+ message: `SliceRecord ${subject}: members must be an array of strings.`
1700
+ };
1701
+ const anchor = members[0];
1702
+ if (anchor === void 0) return emptyMembersViolation(subject);
1703
+ const reservedAnchor = reservedNamespaceOf(anchor);
1704
+ if (reservedAnchor !== null) return {
1705
+ kind: "anchor-in-reserved-namespace",
1706
+ subject,
1707
+ message: `SliceRecord anchor "${anchor}" uses the reserved language token "${reservedAnchor}", so its Slice id would repeat the prefix (ir-schema.md §3.5, slice-view.md §7.5).`
1708
+ };
1709
+ for (let i = 1; i < members.length; i++) {
1710
+ const previous = members[i - 1];
1711
+ const current = members[i];
1712
+ if (previous < current) continue;
1713
+ return {
1714
+ kind: "members-unordered",
1715
+ subject,
1716
+ message: `SliceRecord ${subject}: members[] is not in strictly ascending order at index ${i} ("${current}" follows "${previous}"), so members[0] is not necessarily the anchor (slice-view.md §8.2 for the order, §11.1 for uniqueness).`
1717
+ };
1718
+ }
1719
+ const expected = sliceIdFor(anchor);
1720
+ if (id !== expected) return {
1721
+ kind: "id-not-derived",
1722
+ subject,
1723
+ message: `SliceRecord id "${id}" is not derived from the anchor "${anchor}"; expected "${expected}" (slice-view.md §7.1).`
1724
+ };
1725
+ return null;
1726
+ }
1727
+ /** The reserved token an id opens with, or `null`. Shares the list `@aburi/core` enforces. */
1728
+ function reservedNamespaceOf(id) {
1729
+ const colon = id.indexOf(":");
1730
+ if (colon < 0) return null;
1731
+ const token = id.slice(0, colon);
1732
+ return RESERVED_LANGUAGE_IDS.has(token) ? token : null;
1733
+ }
1734
+ /** Single source of the empty-`members[]` wording, shared with `sliceAnchor`. */
1735
+ function emptyMembersViolation(subject) {
1736
+ return {
1737
+ kind: "members-empty",
1738
+ subject,
1739
+ message: `SliceRecord ${subject}: members[] is empty, so the Slice has no anchor (slice-view.md §11.1 requires at least one member).`
1740
+ };
1741
+ }
1742
+ /**
1743
+ * Throwing form of `sliceRecordViolation`. Raised as a coded `DiffError` so
1744
+ * callers branch on `code` rather than parsing the message; which clause broke
1745
+ * is `SliceRecordViolation.kind`, for callers that need to tell them apart.
1746
+ */
1747
+ function assertSliceRecordInvariant(record) {
1748
+ const violation = sliceRecordViolation(record);
1749
+ if (violation === null) return;
1750
+ throw new DiffError(violation.message, {
1751
+ code: "slice-invariant-violated",
1752
+ value: violation.subject
1753
+ });
1754
+ }
1755
+ /**
1756
+ * §4.1 Node selection: keep every SymbolChange whose status is
1757
+ * added / removed / changed / moved+changed / dropped-toggled. The identity
1758
+ * is the head-side Symbol id where present (added / changed / moved+changed /
1759
+ * dropped-toggled), the base-side id for removed. Pure moved and unchanged
1760
+ * (already stripped upstream) are excluded — §4.1 / §4.3.
1761
+ *
1762
+ * The returned array is deliberately not deduplicated: a well-formed
1763
+ * SymbolChange list from `buildDiff` never mentions the same Symbol id
1764
+ * twice, and Union-Find would coalesce any accidental duplicate anyway.
1765
+ */
1766
+ function collectNodeIds(changes) {
1767
+ const ids = [];
1768
+ for (const change of changes) {
1769
+ const id = nodeIdOf(change);
1770
+ if (id === null) continue;
1771
+ ids.push(id);
1772
+ }
1773
+ return ids;
1774
+ }
1775
+ function nodeIdOf(change) {
1776
+ switch (change.status) {
1777
+ case "added": return change.symbol.id;
1778
+ case "removed": return change.symbol.id;
1779
+ case "unknown": return change.symbol.id;
1780
+ case "changed":
1781
+ case "moved+changed":
1782
+ case "dropped-toggled": return change.after.id;
1783
+ case "moved": return null;
1784
+ }
1785
+ }
1786
+ /**
1787
+ * §5.1 Edge selection: union of base and head, restricted to edges whose
1788
+ * BOTH endpoints are Nodes, canonicalised to `(u, v)` with `u < v` (self-
1789
+ * loops implicitly dropped). Multi-edges collapse naturally inside the WCC
1790
+ * primitive — no explicit dedup needed.
1791
+ *
1792
+ * The union is the load-bearing rule of §5.3: a controller that called an
1793
+ * old service in base and a new service in head needs both edges to land
1794
+ * all three Symbols in a single Slice.
1795
+ */
1796
+ function collectEdges(baseEdges, headEdges, nodeIds) {
1797
+ const pairs = [];
1798
+ for (const edge of baseEdges) appendEdgeIfBothNodes(edge, nodeIds, pairs);
1799
+ for (const edge of headEdges) appendEdgeIfBothNodes(edge, nodeIds, pairs);
1800
+ return pairs;
1801
+ }
1802
+ function appendEdgeIfBothNodes(edge, nodeIds, out) {
1803
+ if (!nodeIds.has(edge.from) || !nodeIds.has(edge.to)) return;
1804
+ out.push([edge.from, edge.to]);
1805
+ }
1806
+
824
1807
  //#endregion
825
1808
  //#region src/status.ts
826
1809
  /**
@@ -830,8 +1813,8 @@ function basename(path) {
830
1813
  * drop-rule flip, not a genuine code edit (§4.1 rationale).
831
1814
  *
832
1815
  * "pathChanged" catches both physical file relocation AND in-file rename: any Symbol id
833
- * mismatch between base and head means the identifier moved, and DF9 ("method 名 rename
834
- * (同 file、同 logic) → moved") relies on this. Stage-1 pairs cannot trigger the id branch
1816
+ * mismatch between base and head means the identifier moved, and DF9 ("method rename
1817
+ * (same file, same logic) → moved") relies on this. Stage-1 pairs cannot trigger the id branch
835
1818
  * (they match by exact id), so this only affects stage-2+ pairings where the pair was
836
1819
  * discovered via fingerprint or name/signature similarity.
837
1820
  */
@@ -850,7 +1833,7 @@ function dropDirection(head) {
850
1833
 
851
1834
  //#endregion
852
1835
  //#region src/diff.ts
853
- const DIFF_SCHEMA = "https://aburi.dev/schema/aburi.diff.v1.json";
1836
+ const DIFF_SCHEMA = "https://aburi.kage1020.com/schema/aburi.diff.v1.json";
854
1837
  const DEFAULT_GENERATOR = {
855
1838
  name: "aburi",
856
1839
  version: "0.0.0"
@@ -863,8 +1846,8 @@ const DEFAULT_GENERATOR = {
863
1846
  * serialisation.
864
1847
  */
865
1848
  function buildDiff(input) {
866
- assertIRShape(input.baseIR, "baseIR");
867
- assertIRShape(input.headIR, "headIR");
1849
+ assertDiffable(input.baseIR, "baseIR");
1850
+ assertDiffable(input.headIR, "headIR");
868
1851
  ensureSchemasAgree(input.baseIR, input.headIR);
869
1852
  const stage1 = matchStageId(input.baseIR.symbols, input.headIR.symbols);
870
1853
  const stage2 = matchStageGitRename(stage1.remainingBase, stage1.remainingHead, input.gitRenames ?? null);
@@ -879,6 +1862,8 @@ function buildDiff(input) {
879
1862
  ...stage4_5.matched
880
1863
  ];
881
1864
  const summary = {
1865
+ unknown: 0,
1866
+ depsUnknown: 0,
882
1867
  added: 0,
883
1868
  removed: 0,
884
1869
  moved: 0,
@@ -894,6 +1879,7 @@ function buildDiff(input) {
894
1879
  depsAdded: 0,
895
1880
  depsRemoved: 0
896
1881
  };
1882
+ let unknown = 0;
897
1883
  const symbols = [];
898
1884
  for (const pair of pairs) {
899
1885
  const status = classifyStatus(pair.base, pair.head);
@@ -942,16 +1928,48 @@ function buildDiff(input) {
942
1928
  }
943
1929
  const finalRemainingHead = stage4_5.remainingHead;
944
1930
  const finalRemainingBase = stage4_5.remainingBase;
945
- for (const h of finalRemainingHead) if (h.dropped) summary.droppedAdded++;
946
- else {
1931
+ const baseSide = dependencySideView(input.baseIR);
1932
+ const headSide = dependencySideView(input.headIR);
1933
+ const lostByHead = headSide.lostFiles;
1934
+ const lostByBase = baseSide.lostFiles;
1935
+ for (const h of finalRemainingHead) {
1936
+ if (h.dropped) {
1937
+ summary.droppedAdded++;
1938
+ continue;
1939
+ }
1940
+ const reason = lostByBase.get(h.source.file);
1941
+ if (reason !== void 0) {
1942
+ unknown++;
1943
+ symbols.push({
1944
+ status: "unknown",
1945
+ symbol: h,
1946
+ absentFrom: "base",
1947
+ reason
1948
+ });
1949
+ continue;
1950
+ }
947
1951
  summary.added++;
948
1952
  symbols.push({
949
1953
  status: "added",
950
1954
  symbol: h
951
1955
  });
952
1956
  }
953
- for (const b of finalRemainingBase) if (b.dropped) summary.droppedRemoved++;
954
- else {
1957
+ for (const b of finalRemainingBase) {
1958
+ if (b.dropped) {
1959
+ summary.droppedRemoved++;
1960
+ continue;
1961
+ }
1962
+ const reason = lostByHead.get(b.source.file);
1963
+ if (reason !== void 0) {
1964
+ unknown++;
1965
+ symbols.push({
1966
+ status: "unknown",
1967
+ symbol: b,
1968
+ absentFrom: "head",
1969
+ reason
1970
+ });
1971
+ continue;
1972
+ }
955
1973
  summary.removed++;
956
1974
  symbols.push({
957
1975
  status: "removed",
@@ -962,10 +1980,20 @@ function buildDiff(input) {
962
1980
  summary.componentsAdded = components.added.length;
963
1981
  summary.componentsRemoved = components.removed.length;
964
1982
  summary.componentsChanged = components.changed.length;
965
- const dependencies = diffDependencies(input.baseIR.dependencies, input.headIR.dependencies);
1983
+ const dependencies = diffDependencies(input.baseIR.dependencies, input.headIR.dependencies, {
1984
+ base: baseSide,
1985
+ head: headSide
1986
+ });
966
1987
  summary.depsAdded = dependencies.added.length;
967
1988
  summary.depsRemoved = dependencies.removed.length;
1989
+ summary.depsUnknown = dependencies.unknown.length;
1990
+ summary.unknown = unknown;
968
1991
  symbols.sort(compareSymbolChange);
1992
+ const slices = computeSlices({
1993
+ changes: symbols,
1994
+ baseCallEdges: reconstructCallEdgesFromIR(input.baseIR),
1995
+ headCallEdges: reconstructCallEdgesFromIR(input.headIR)
1996
+ });
969
1997
  return {
970
1998
  $schema: DIFF_SCHEMA,
971
1999
  generator: input.generator ?? DEFAULT_GENERATOR,
@@ -974,9 +2002,42 @@ function buildDiff(input) {
974
2002
  summary,
975
2003
  symbols,
976
2004
  components,
977
- dependencies
2005
+ dependencies,
2006
+ slices,
2007
+ notCompared: filesNeitherSideRead(lostByBase, lostByHead)
978
2008
  };
979
2009
  }
2010
+ /**
2011
+ * Paths both documents record as never analysed, with each side's own reason.
2012
+ *
2013
+ * This is the loss `unknown` cannot describe. That status is derived from the matcher's
2014
+ * leftovers — a Symbol one document holds and the other lacks — and a file skipped on both
2015
+ * sides contributes Symbols to neither, so it leaves no leftover to classify and the whole
2016
+ * document falls silent about it. Silence is the one thing it must not do here: a diff with
2017
+ * nothing to say about a path is exactly what a diff that compared it and found it unchanged
2018
+ * looks like.
2019
+ *
2020
+ * The intersection, not the union. A one-sided loss has leftovers on the other side and is
2021
+ * reported as `unknown` there; listing it here as well would count one loss twice, in two
2022
+ * vocabularies that mean different things.
2023
+ *
2024
+ * Always returns an array, empty included. Optionality in the schema covers documents written
2025
+ * before the field existed, and no arithmetic elsewhere in a diff would let a reader tell that
2026
+ * case from a run that missed nothing (docs/design/diff-algorithm.md §10.1).
2027
+ */
2028
+ function filesNeitherSideRead(lostByBase, lostByHead) {
2029
+ const both = [];
2030
+ for (const [path, baseReason] of lostByBase) {
2031
+ const headReason = lostByHead.get(path);
2032
+ if (headReason === void 0) continue;
2033
+ both.push({
2034
+ path,
2035
+ baseReason,
2036
+ headReason
2037
+ });
2038
+ }
2039
+ return both.sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0);
2040
+ }
980
2041
  /** §9.1 — refuse to diff across schema versions. */
981
2042
  function ensureSchemasAgree(base, head) {
982
2043
  if (base.$schema !== head.$schema) throw new DiffError(`Base IR schema "${base.$schema}" does not match head IR schema "${head.$schema}"; a diff across schema versions is not supported.`, {
@@ -984,31 +2045,100 @@ function ensureSchemasAgree(base, head) {
984
2045
  value: base.$schema
985
2046
  });
986
2047
  }
2048
+ /** Identity is a single field, so joining the one-member tuple is joining nothing. */
2049
+ const soleField = (parts) => parts.join("");
2050
+ const IDENTIFIED_COLLECTIONS = [
2051
+ {
2052
+ field: "symbols",
2053
+ identityFields: ["id"],
2054
+ keyOf: soleField,
2055
+ noun: "id",
2056
+ show: soleField,
2057
+ consequence: "stage 1 pairs Symbols by id and every later stage tracks the base Symbols it has consumed by id, so a repeat leaves one entry out of the diff entirely or classifies its counterpart twice (ir-schema.md §14 #1)"
2058
+ },
2059
+ {
2060
+ field: "components",
2061
+ identityFields: ["id"],
2062
+ keyOf: soleField,
2063
+ noun: "id",
2064
+ show: soleField,
2065
+ consequence: "Component identity is the id, so a repeat hides one entry and can report a change the two revisions do not contain (ir-schema.md §14 #2)"
2066
+ },
2067
+ {
2068
+ field: "dependencies",
2069
+ identityFields: DEPENDENCY_IDENTITY_FIELDS,
2070
+ keyOf: dependencyIdentity,
2071
+ noun: "(from, to, via) triple",
2072
+ show: (parts) => `(${parts.join(", ")})`,
2073
+ consequence: "direction and effect are deliberately outside Dependency identity (§6.2), so a repeat surfaces as an added + removed pair no reader can tell from a real flip (ir-schema.md §14 #13)"
2074
+ }
2075
+ ];
987
2076
  /**
988
- * Top-level shape check. Refuses to enter the 5-stage matcher when a caller hands in an
989
- * IR-shaped object that is missing one of the collections the matcher requires as an
990
- * array. Without this, a malformed `baseIR = { symbols: undefined, ... }` would crash
991
- * deep inside `matchStageId` with `TypeError: undefined is not iterable`, leaving the
992
- * root cause obscured. Not a full schema validation — just an entry-point smoke test.
2077
+ * The two things `buildDiff` needs before stage 1 runs: a Document it can walk, and
2078
+ * identities it can key on. diff-algorithm.md §3.7 states the second and why it is checked
2079
+ * here as well as at extraction time.
2080
+ *
2081
+ * Neither half is a full schema validation. A Symbol that reaches stage 1 is an object with
2082
+ * a string `id`, because the identity scan reads that much; nothing checks it carries a
2083
+ * `fingerprint`, which is `checkIRIntegrity` #20's job and runs when the CLI reads an IR off
2084
+ * disk. What this does buy is that a malformed collection is named — `symbols: undefined`
2085
+ * used to surface as `TypeError: undefined is not iterable` and `symbols: [null]` as
2086
+ * `TypeError: Cannot read properties of null (reading 'id')`, both from inside
2087
+ * `matchStageId`, with neither the collection nor the index named.
993
2088
  */
994
- function assertIRShape(ir, name) {
995
- if (ir === null || typeof ir !== "object") throw new DiffError(`${name} must be an IR object; got ${typeof ir}.`, {
996
- code: "ir-shape-invalid",
997
- value: name
998
- });
999
- if (typeof ir.$schema !== "string" || ir.$schema.length === 0) throw new DiffError(`${name}.$schema must be a non-empty schema URL.`, {
1000
- code: "ir-shape-invalid",
1001
- value: `${name}.$schema`
1002
- });
1003
- for (const field of [
1004
- "symbols",
1005
- "components",
1006
- "dependencies"
1007
- ]) if (!Array.isArray(ir[field])) throw new DiffError(`${name}.${field} must be an array.`, {
2089
+ function assertDiffable(ir, name) {
2090
+ if (ir === null || typeof ir !== "object") throw shapeError(name, `${name} must be an IR object; got ${describeValue(ir)}.`);
2091
+ if (typeof ir.$schema !== "string" || ir.$schema.length === 0) throw shapeError(`${name}.$schema`, `${name}.$schema must be a non-empty schema URL.`);
2092
+ for (const collection of IDENTIFIED_COLLECTIONS) assertUniqueIdentity(ir[collection.field], `${name}.${collection.field}`, collection);
2093
+ }
2094
+ function assertUniqueIdentity(entries, subject, collection) {
2095
+ if (!Array.isArray(entries)) throw shapeError(subject, `${subject} must be an array.`);
2096
+ const firstSeen = /* @__PURE__ */ new Map();
2097
+ for (const [index, entry] of entries.entries()) {
2098
+ const entrySubject = `${subject}[${index}]`;
2099
+ const parts = identityFieldsOf(entry, entrySubject, collection);
2100
+ const key = collection.keyOf(parts);
2101
+ const first = firstSeen.get(key);
2102
+ if (first === void 0) {
2103
+ firstSeen.set(key, index);
2104
+ continue;
2105
+ }
2106
+ const shown = collection.show(parts);
2107
+ throw new DiffError(`${entrySubject} repeats the ${collection.noun} "${shown}" first seen at index ${first}; ${collection.consequence}.`, {
2108
+ code: "ir-identity-collision",
2109
+ value: shown
2110
+ });
2111
+ }
2112
+ }
2113
+ /**
2114
+ * The identity fields of one entry, established as strings on the way out. Reading them is
2115
+ * what forces the check: without it a Symbol carrying no `id` has nothing to collide with,
2116
+ * passes, and derives a Slice anchored on `undefined` several stages later — which
2117
+ * `assertSliceRecordInvariant` reports as `slice-invariant-violated`, the one code the CLI
2118
+ * presents as a bug in Aburi rather than in the caller's IR.
2119
+ */
2120
+ function identityFieldsOf(entry, subject, collection) {
2121
+ if (typeof entry !== "object" || entry === null || Array.isArray(entry)) throw shapeError(subject, `${subject} must be an object; got ${describeValue(entry)}.`);
2122
+ const parts = [];
2123
+ for (const field of collection.identityFields) {
2124
+ const value = entry[field];
2125
+ if (typeof value !== "string") throw shapeError(`${subject}.${field}`, `${subject}.${field} must be a string; got ${describeValue(value)}.`);
2126
+ parts.push(value);
2127
+ }
2128
+ return parts;
2129
+ }
2130
+ function shapeError(subject, message) {
2131
+ return new DiffError(message, {
1008
2132
  code: "ir-shape-invalid",
1009
- value: `${name}.${field}`
2133
+ value: subject
1010
2134
  });
1011
2135
  }
2136
+ function describeValue(value) {
2137
+ if (value === void 0) return "undefined";
2138
+ if (value === null) return "null";
2139
+ if (Array.isArray(value)) return "an array";
2140
+ return `a ${typeof value}`;
2141
+ }
1012
2142
  /**
1013
2143
  * Deterministic ordering of the `symbols[]` output:
1014
2144
  * 1. by status (alphabetical) — pins added/changed/moved sections
@@ -1024,10 +2154,19 @@ function compareSymbolChange(a, b) {
1024
2154
  return idA < idB ? -1 : idA > idB ? 1 : 0;
1025
2155
  }
1026
2156
  function referenceId(change) {
1027
- if (change.status === "added" || change.status === "removed") return change.symbol.id;
2157
+ if (change.status === "added" || change.status === "removed" || change.status === "unknown") return change.symbol.id;
1028
2158
  return change.after.id;
1029
2159
  }
1030
2160
  /**
2161
+ * The files a document's scan never analysed, by path, with why.
2162
+ *
2163
+ * `stats.skippedFiles` is Class B: absent means the writer predates the field, not that
2164
+ * nothing was lost. An empty map is the honest answer either way — with no enumeration
2165
+ * there is no absence this function can explain, and guessing from
2166
+ * `totalFiles > parsedFiles` would attach a reason to whichever Symbols happened to be
2167
+ * missing. The CLI says so on stderr instead; a diff cannot invent the list.
2168
+ */
2169
+ /**
1031
2170
  * Byte-deterministic serialiser for a DiffResult. Delegates to `@aburi/core`
1032
2171
  * `serializeCanonical` so the sort order, NFC normalisation, and codepoint key sort are
1033
2172
  * shared with the IR side.
@@ -1037,5 +2176,5 @@ function writeCanonicalDiff(diff, options = {}) {
1037
2176
  }
1038
2177
 
1039
2178
  //#endregion
1040
- export { DEFAULT_LINE_FUZZ, DiffError, MAX_LINE_FUZZ, MIN_LINE_FUZZ, buildDiff, classifyStatus, computeSymbolDelta, diffComponents, diffDependencies, dropDirection, jaccard, jaccardTokens, lastSegment, matchStageDroppedWeak, matchStageGitRename, matchStageId, matchStageLogicFingerprint, matchStageNameSignature, nameSimilarity, ownerSimilarity, signatureSimilarity, tokenizeName, writeCanonicalDiff };
2179
+ export { DEFAULT_LINE_FUZZ, DiffError, MAX_LINE_FUZZ, MIN_LINE_FUZZ, assertSliceRecordInvariant, buildDiff, classifyStatus, computeSlices, computeSymbolDelta, dependencySideView, diffComponents, diffDependencies, dropDirection, jaccard, jaccardTokens, lastSegment, matchStageDroppedWeak, matchStageGitRename, matchStageId, matchStageLogicFingerprint, matchStageNameSignature, memberSimilarity, nameSimilarity, ownersAreCompatible, signatureSimilarity, sliceAnchor, sliceRecordViolation, tokenizeName, writeCanonicalDiff };
1041
2180
  //# sourceMappingURL=index.mjs.map