@aburi/diff 0.2.0 → 0.4.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/LICENSE +202 -21
- package/README.md +2 -2
- package/dist/index.d.mts +244 -52
- package/dist/index.mjs +1 -1280
- package/package.json +5 -6
- package/dist/index.d.mts.map +0 -1
- package/dist/index.mjs.map +0 -1
- package/src/components.ts +0 -111
- package/src/delta.ts +0 -304
- package/src/diff.ts +0 -250
- package/src/errors.ts +0 -44
- package/src/index.ts +0 -54
- package/src/match.ts +0 -351
- package/src/signature.ts +0 -53
- package/src/similarity.ts +0 -134
- package/src/slice.ts +0 -321
- package/src/status.ts +0 -36
package/dist/index.mjs
CHANGED
|
@@ -1,1280 +1 @@
|
|
|
1
|
-
import { RESERVED_LANGUAGE_IDS, computeWeaklyConnectedComponents, reconstructCallEdgesFromIR, serializeCanonical, trySymbolId } from "@aburi/core";
|
|
2
|
-
|
|
3
|
-
//#region src/components.ts
|
|
4
|
-
/**
|
|
5
|
-
* §6.1 — Component diff. Component identity is `id`; when a Component is present in both
|
|
6
|
-
* base and head with the same id, the three delta booleans describe which axes actually
|
|
7
|
-
* 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
|
|
9
|
-
* pairs via the `changed[]` entries so consumers can render them without stringifying
|
|
10
|
-
* arrays.
|
|
11
|
-
*/
|
|
12
|
-
function diffComponents(base, head) {
|
|
13
|
-
const baseById = /* @__PURE__ */ new Map();
|
|
14
|
-
for (const c of base) baseById.set(c.id, c);
|
|
15
|
-
const headById = /* @__PURE__ */ new Map();
|
|
16
|
-
for (const c of head) headById.set(c.id, c);
|
|
17
|
-
const added = [];
|
|
18
|
-
const removed = [];
|
|
19
|
-
const changed = [];
|
|
20
|
-
for (const [id, headComp] of headById) {
|
|
21
|
-
const baseComp = baseById.get(id);
|
|
22
|
-
if (baseComp === void 0) {
|
|
23
|
-
added.push(headComp);
|
|
24
|
-
continue;
|
|
25
|
-
}
|
|
26
|
-
const rootsChanged = !stringArraysEqual(baseComp.roots, headComp.roots);
|
|
27
|
-
const publicApiChanged = !stringArraysEqual(baseComp.publicApi ?? [], headComp.publicApi ?? []);
|
|
28
|
-
const frameworksChanged = !stringArraysEqual(baseComp.frameworks ?? [], headComp.frameworks ?? []);
|
|
29
|
-
if (rootsChanged || publicApiChanged || frameworksChanged) changed.push({
|
|
30
|
-
before: baseComp,
|
|
31
|
-
after: headComp,
|
|
32
|
-
delta: {
|
|
33
|
-
rootsChanged,
|
|
34
|
-
publicApiChanged,
|
|
35
|
-
frameworksChanged
|
|
36
|
-
}
|
|
37
|
-
});
|
|
38
|
-
}
|
|
39
|
-
for (const [id, baseComp] of baseById) if (!headById.has(id)) removed.push(baseComp);
|
|
40
|
-
sortById(added);
|
|
41
|
-
sortById(removed);
|
|
42
|
-
changed.sort((a, b) => a.after.id < b.after.id ? -1 : a.after.id > b.after.id ? 1 : 0);
|
|
43
|
-
return {
|
|
44
|
-
added,
|
|
45
|
-
removed,
|
|
46
|
-
changed
|
|
47
|
-
};
|
|
48
|
-
}
|
|
49
|
-
/**
|
|
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).
|
|
53
|
-
*/
|
|
54
|
-
function diffDependencies(base, head) {
|
|
55
|
-
const baseKeys = /* @__PURE__ */ new Map();
|
|
56
|
-
for (const d of base) baseKeys.set(dependencyKey(d), d);
|
|
57
|
-
const headKeys = /* @__PURE__ */ new Map();
|
|
58
|
-
for (const d of head) headKeys.set(dependencyKey(d), d);
|
|
59
|
-
const added = [];
|
|
60
|
-
const removed = [];
|
|
61
|
-
for (const [key, dep] of headKeys) {
|
|
62
|
-
const b = baseKeys.get(key);
|
|
63
|
-
if (b === void 0) {
|
|
64
|
-
added.push(dep);
|
|
65
|
-
continue;
|
|
66
|
-
}
|
|
67
|
-
if (b.direction !== dep.direction || (b.effect ?? null) !== (dep.effect ?? null)) {
|
|
68
|
-
removed.push(b);
|
|
69
|
-
added.push(dep);
|
|
70
|
-
}
|
|
71
|
-
}
|
|
72
|
-
for (const [key, dep] of baseKeys) if (!headKeys.has(key)) removed.push(dep);
|
|
73
|
-
added.sort(compareDependencies);
|
|
74
|
-
removed.sort(compareDependencies);
|
|
75
|
-
return {
|
|
76
|
-
added,
|
|
77
|
-
removed
|
|
78
|
-
};
|
|
79
|
-
}
|
|
80
|
-
function dependencyKey(d) {
|
|
81
|
-
return `${d.from}::${d.to}::${d.via}`;
|
|
82
|
-
}
|
|
83
|
-
function compareDependencies(a, b) {
|
|
84
|
-
const keyA = dependencyKey(a);
|
|
85
|
-
const keyB = dependencyKey(b);
|
|
86
|
-
return keyA < keyB ? -1 : keyA > keyB ? 1 : 0;
|
|
87
|
-
}
|
|
88
|
-
function stringArraysEqual(a, b) {
|
|
89
|
-
if (a.length !== b.length) return false;
|
|
90
|
-
for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
|
|
91
|
-
return true;
|
|
92
|
-
}
|
|
93
|
-
function sortById(items) {
|
|
94
|
-
items.sort((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
//#endregion
|
|
98
|
-
//#region src/errors.ts
|
|
99
|
-
var DiffError = class extends Error {
|
|
100
|
-
code;
|
|
101
|
-
value;
|
|
102
|
-
constructor(message, detail, options) {
|
|
103
|
-
super(message, options);
|
|
104
|
-
this.name = "DiffError";
|
|
105
|
-
this.code = detail.code;
|
|
106
|
-
this.value = detail.value;
|
|
107
|
-
}
|
|
108
|
-
};
|
|
109
|
-
|
|
110
|
-
//#endregion
|
|
111
|
-
//#region src/delta.ts
|
|
112
|
-
const DEFAULT_LINE_FUZZ = 2;
|
|
113
|
-
const MAX_LINE_FUZZ = 10;
|
|
114
|
-
const MIN_LINE_FUZZ = 0;
|
|
115
|
-
/**
|
|
116
|
-
* §5 — Compute the full per-Symbol delta between two paired Symbols. The three axis
|
|
117
|
-
* booleans (`apiChanged` / `logicChanged` / `syntaxChanged`) come from fingerprint
|
|
118
|
-
* comparison; the array deltas (`rules` / `effects` / `calls` / `decorators`) come from
|
|
119
|
-
* identity-preserving diff with configurable line fuzz.
|
|
120
|
-
*/
|
|
121
|
-
function computeSymbolDelta(base, head, options = {}) {
|
|
122
|
-
const fuzz = validateLineFuzz(options.lineFuzz ?? 2);
|
|
123
|
-
const delta = {
|
|
124
|
-
apiChanged: base.fingerprint.api !== head.fingerprint.api,
|
|
125
|
-
logicChanged: base.fingerprint.logic !== head.fingerprint.logic,
|
|
126
|
-
syntaxChanged: base.fingerprint.syntax !== head.fingerprint.syntax,
|
|
127
|
-
componentChanged: (base.component ?? null) !== (head.component ?? null),
|
|
128
|
-
visibilityChanged: base.visibility !== head.visibility
|
|
129
|
-
};
|
|
130
|
-
delta.rules = diffRules(base.rules, head.rules, fuzz);
|
|
131
|
-
delta.effects = diffEffects(base.effects, head.effects);
|
|
132
|
-
delta.calls = diffCalls(base.calls, head.calls, fuzz);
|
|
133
|
-
delta.decorators = diffDecorators(base.decorators, head.decorators, fuzz);
|
|
134
|
-
delta.signature = diffSignature(base.signature ?? null, head.signature ?? null);
|
|
135
|
-
return delta;
|
|
136
|
-
}
|
|
137
|
-
/**
|
|
138
|
-
* §5.2.1 range check. Loud on violation rather than silently clamping so a config typo
|
|
139
|
-
* (`lineFuzz: 999`) or an upstream numeric bug (`NaN`, `Infinity`) surfaces at the diff
|
|
140
|
-
* boundary instead of quietly rounding into a range that produces the wrong deltas.
|
|
141
|
-
*/
|
|
142
|
-
function validateLineFuzz(value) {
|
|
143
|
-
if (!Number.isFinite(value) || !Number.isInteger(value)) throw new DiffError(`config.diff.lineFuzz must be an integer in [${0}, ${10}]; got ${String(value)}.`, {
|
|
144
|
-
code: "invalid-line-fuzz",
|
|
145
|
-
value: String(value)
|
|
146
|
-
});
|
|
147
|
-
if (value < 0 || value > 10) throw new DiffError(`config.diff.lineFuzz must be within [${0}, ${10}]; got ${value}.`, {
|
|
148
|
-
code: "invalid-line-fuzz",
|
|
149
|
-
value: String(value)
|
|
150
|
-
});
|
|
151
|
-
return value;
|
|
152
|
-
}
|
|
153
|
-
/**
|
|
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.
|
|
158
|
-
*/
|
|
159
|
-
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;
|
|
178
|
-
}
|
|
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
|
-
}
|
|
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);
|
|
189
|
-
}
|
|
190
|
-
return {
|
|
191
|
-
added,
|
|
192
|
-
removed,
|
|
193
|
-
modified
|
|
194
|
-
};
|
|
195
|
-
}
|
|
196
|
-
function diffRules(base, head, lineFuzz) {
|
|
197
|
-
const mapper = (r) => ({
|
|
198
|
-
item: r,
|
|
199
|
-
key: r.type,
|
|
200
|
-
line: r.line
|
|
201
|
-
});
|
|
202
|
-
return differentiate(base.map(mapper), head.map(mapper), rulesEqual, lineFuzz);
|
|
203
|
-
}
|
|
204
|
-
function rulesEqual(a, b) {
|
|
205
|
-
return a.type === b.type && (a.condition ?? null) === (b.condition ?? null) && (a.what ?? null) === (b.what ?? null) && (a.expr ?? null) === (b.expr ?? null) && (a.loopKind ?? null) === (b.loopKind ?? null);
|
|
206
|
-
}
|
|
207
|
-
function diffEffects(base, head) {
|
|
208
|
-
const mapper = (e) => ({
|
|
209
|
-
item: e,
|
|
210
|
-
key: `${e.id}::${e.target}`,
|
|
211
|
-
line: e.line ?? 0
|
|
212
|
-
});
|
|
213
|
-
return differentiate(base.map(mapper), head.map(mapper), effectsEqual, Number.POSITIVE_INFINITY);
|
|
214
|
-
}
|
|
215
|
-
function effectsEqual(a, b) {
|
|
216
|
-
return a.id === b.id && a.target === b.target && a.plugin === b.plugin && a.confidence === b.confidence;
|
|
217
|
-
}
|
|
218
|
-
function diffCalls(base, head, lineFuzz) {
|
|
219
|
-
const mapper = (c) => ({
|
|
220
|
-
item: c,
|
|
221
|
-
key: c.target,
|
|
222
|
-
line: c.line
|
|
223
|
-
});
|
|
224
|
-
return differentiate(base.map(mapper), head.map(mapper), callsEqual, lineFuzz);
|
|
225
|
-
}
|
|
226
|
-
function callsEqual(a, b) {
|
|
227
|
-
return a.target === b.target && (a.resolved ?? null) === (b.resolved ?? null);
|
|
228
|
-
}
|
|
229
|
-
/**
|
|
230
|
-
* §5.2.2 — decorator diff. Identity is `name`; when the same-named decorator is present
|
|
231
|
-
* on both sides within the line-fuzz window, the argument list determines whether the
|
|
232
|
-
* entry is a modified pair or an implicit no-op.
|
|
233
|
-
*/
|
|
234
|
-
function diffDecorators(base, head, lineFuzz) {
|
|
235
|
-
const mapper = (d) => ({
|
|
236
|
-
item: d,
|
|
237
|
-
key: d.name,
|
|
238
|
-
line: d.line
|
|
239
|
-
});
|
|
240
|
-
return differentiate(base.map(mapper), head.map(mapper), decoratorsEqual, lineFuzz);
|
|
241
|
-
}
|
|
242
|
-
function decoratorsEqual(a, b) {
|
|
243
|
-
if (a.name !== b.name) return false;
|
|
244
|
-
if (a.arguments.length !== b.arguments.length) return false;
|
|
245
|
-
for (let i = 0; i < a.arguments.length; i++) if (a.arguments[i] !== b.arguments[i]) return false;
|
|
246
|
-
return true;
|
|
247
|
-
}
|
|
248
|
-
/**
|
|
249
|
-
* §5.3 — signature delta. Three cases:
|
|
250
|
-
* - both sides `null` → `null` (nothing to compare)
|
|
251
|
-
* - exactly one side `null` → the present side is emitted verbatim as
|
|
252
|
-
* `added` (when only head has a signature) or `removed` (when only base has one);
|
|
253
|
-
* the three axis booleans compare the missing side against `false` defaults
|
|
254
|
-
* - both sides non-null → per-list sub-deltas:
|
|
255
|
-
* - `inputs`: strict positional compare via `differentiate(..., lineFuzz: 0)` — index
|
|
256
|
-
* used as the line key so ordered parameter lists match position-for-position
|
|
257
|
-
* - `outputs`: positional compare (added/removed emitted when the arrays diverge at
|
|
258
|
-
* an index), no `modified` category
|
|
259
|
-
* - `throws`: unordered set diff — duplicates collapse per Set semantics
|
|
260
|
-
* - `async` / `generator` / `typeParameters` change flags follow the raw fields
|
|
261
|
-
*/
|
|
262
|
-
function diffSignature(base, head) {
|
|
263
|
-
if (base === null && head === null) return null;
|
|
264
|
-
if (base === null || head === null) {
|
|
265
|
-
const empty = {
|
|
266
|
-
added: [],
|
|
267
|
-
removed: [],
|
|
268
|
-
modified: []
|
|
269
|
-
};
|
|
270
|
-
const present = base ?? head;
|
|
271
|
-
if (present === null) return null;
|
|
272
|
-
const isBaseNull = base === null;
|
|
273
|
-
return {
|
|
274
|
-
inputs: isBaseNull ? {
|
|
275
|
-
added: [...present.inputs],
|
|
276
|
-
removed: [],
|
|
277
|
-
modified: []
|
|
278
|
-
} : {
|
|
279
|
-
added: [],
|
|
280
|
-
removed: [...present.inputs],
|
|
281
|
-
modified: []
|
|
282
|
-
},
|
|
283
|
-
outputs: isBaseNull ? {
|
|
284
|
-
added: [...present.outputs],
|
|
285
|
-
removed: [],
|
|
286
|
-
modified: []
|
|
287
|
-
} : {
|
|
288
|
-
added: [],
|
|
289
|
-
removed: [...present.outputs],
|
|
290
|
-
modified: []
|
|
291
|
-
},
|
|
292
|
-
throws: isBaseNull ? {
|
|
293
|
-
added: [...present.throws],
|
|
294
|
-
removed: [],
|
|
295
|
-
modified: []
|
|
296
|
-
} : {
|
|
297
|
-
added: [],
|
|
298
|
-
removed: [...present.throws],
|
|
299
|
-
modified: []
|
|
300
|
-
},
|
|
301
|
-
asyncChanged: (base?.async ?? false) !== (head?.async ?? false),
|
|
302
|
-
generatorChanged: (base?.generator ?? false) !== (head?.generator ?? false),
|
|
303
|
-
typeParametersChanged: !arraysEqual(base?.typeParameters ?? empty.added.map(String), head?.typeParameters ?? empty.added.map(String))
|
|
304
|
-
};
|
|
305
|
-
}
|
|
306
|
-
const inputMapper = (input, index) => ({
|
|
307
|
-
item: input,
|
|
308
|
-
key: `${index}:${input.name}`,
|
|
309
|
-
line: index
|
|
310
|
-
});
|
|
311
|
-
return {
|
|
312
|
-
inputs: differentiate(base.inputs.map(inputMapper), head.inputs.map(inputMapper), (a, b) => a.name === b.name && a.type === b.type, 0),
|
|
313
|
-
outputs: diffStringList(base.outputs, head.outputs),
|
|
314
|
-
throws: diffStringSet(base.throws, head.throws),
|
|
315
|
-
asyncChanged: base.async !== head.async,
|
|
316
|
-
generatorChanged: base.generator !== head.generator,
|
|
317
|
-
typeParametersChanged: !arraysEqual(base.typeParameters, head.typeParameters)
|
|
318
|
-
};
|
|
319
|
-
}
|
|
320
|
-
function diffStringList(base, head) {
|
|
321
|
-
const added = [];
|
|
322
|
-
const removed = [];
|
|
323
|
-
const max = Math.max(base.length, head.length);
|
|
324
|
-
for (let i = 0; i < max; i++) {
|
|
325
|
-
const b = i < base.length ? base[i] : void 0;
|
|
326
|
-
const h = i < head.length ? head[i] : void 0;
|
|
327
|
-
if (b === void 0 && h !== void 0) added.push(h);
|
|
328
|
-
else if (h === void 0 && b !== void 0) removed.push(b);
|
|
329
|
-
else if (b !== h) {
|
|
330
|
-
if (b !== void 0) removed.push(b);
|
|
331
|
-
if (h !== void 0) added.push(h);
|
|
332
|
-
}
|
|
333
|
-
}
|
|
334
|
-
return {
|
|
335
|
-
added,
|
|
336
|
-
removed,
|
|
337
|
-
modified: []
|
|
338
|
-
};
|
|
339
|
-
}
|
|
340
|
-
function diffStringSet(base, head) {
|
|
341
|
-
const setB = new Set(base);
|
|
342
|
-
const setH = new Set(head);
|
|
343
|
-
const added = [];
|
|
344
|
-
const removed = [];
|
|
345
|
-
for (const h of setH) if (!setB.has(h)) added.push(h);
|
|
346
|
-
for (const b of setB) if (!setH.has(b)) removed.push(b);
|
|
347
|
-
return {
|
|
348
|
-
added,
|
|
349
|
-
removed,
|
|
350
|
-
modified: []
|
|
351
|
-
};
|
|
352
|
-
}
|
|
353
|
-
function arraysEqual(a, b) {
|
|
354
|
-
if (a.length !== b.length) return false;
|
|
355
|
-
for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
|
|
356
|
-
return true;
|
|
357
|
-
}
|
|
358
|
-
|
|
359
|
-
//#endregion
|
|
360
|
-
//#region src/signature.ts
|
|
361
|
-
/**
|
|
362
|
-
* §3.4.2 signatureSimilarity — averaged type-similarity across `inputs`, `outputs`, and
|
|
363
|
-
* `throws`. Follows diff-algorithm.md §3.4.2:
|
|
364
|
-
* - null + null → 1.0 (both symbols are signature-less; nothing to compare)
|
|
365
|
-
* - null + non-null (either side) → 0.0
|
|
366
|
-
* - both non-null: mean of three subscores
|
|
367
|
-
*
|
|
368
|
-
* Subscores:
|
|
369
|
-
* - inputs: ordered type-string equality rate (`i-th type equal` counts as 1, else 0)
|
|
370
|
-
* - outputs: same shape, but outputs is an array of type strings
|
|
371
|
-
* - throws: unordered set intersection over union
|
|
372
|
-
*
|
|
373
|
-
* Empty subarrays on both sides count as 1.0 (they are trivially equal); on one side only
|
|
374
|
-
* they count as 0.0 (asymmetric information).
|
|
375
|
-
*/
|
|
376
|
-
function signatureSimilarity(base, head) {
|
|
377
|
-
const baseSig = base ?? null;
|
|
378
|
-
const headSig = head ?? null;
|
|
379
|
-
if (baseSig === null && headSig === null) return 1;
|
|
380
|
-
if (baseSig === null || headSig === null) return 0;
|
|
381
|
-
const inputsScore = compareOrderedTypes(baseSig.inputs.map((i) => i.type), headSig.inputs.map((i) => i.type));
|
|
382
|
-
const outputsScore = compareOrderedTypes(baseSig.outputs, headSig.outputs);
|
|
383
|
-
const throwsScore = compareUnorderedSet(baseSig.throws, headSig.throws);
|
|
384
|
-
return (inputsScore + outputsScore + throwsScore) / 3;
|
|
385
|
-
}
|
|
386
|
-
function compareOrderedTypes(a, b) {
|
|
387
|
-
if (a.length === 0 && b.length === 0) return 1;
|
|
388
|
-
if (a.length !== b.length) return 0;
|
|
389
|
-
let matches = 0;
|
|
390
|
-
for (let i = 0; i < a.length; i++) if (a[i] === b[i]) matches++;
|
|
391
|
-
return matches / a.length;
|
|
392
|
-
}
|
|
393
|
-
function compareUnorderedSet(a, b) {
|
|
394
|
-
if (a.length === 0 && b.length === 0) return 1;
|
|
395
|
-
const setA = new Set(a);
|
|
396
|
-
const setB = new Set(b);
|
|
397
|
-
let intersection = 0;
|
|
398
|
-
for (const t of setA) if (setB.has(t)) intersection++;
|
|
399
|
-
const union = setA.size + setB.size - intersection;
|
|
400
|
-
return union === 0 ? 1 : intersection / union;
|
|
401
|
-
}
|
|
402
|
-
|
|
403
|
-
//#endregion
|
|
404
|
-
//#region src/similarity.ts
|
|
405
|
-
/**
|
|
406
|
-
* String similarity utilities dedicated to the diff engine. Kept in one file so the
|
|
407
|
-
* name/signature/owner formulas are auditable side by side against diff-algorithm.md §3.4.
|
|
408
|
-
*/
|
|
409
|
-
/**
|
|
410
|
-
* Tokenise a qualified name into normalised lowercase word segments. Splits on:
|
|
411
|
-
* - camelCase / PascalCase boundaries (`fooBar` → `foo`, `Bar`)
|
|
412
|
-
* - snake_case underscores (`foo_bar` → `foo`, `bar`)
|
|
413
|
-
* - dotted namespaces (`ns.Class` → `ns`, `Class`)
|
|
414
|
-
* - `::` static-method separator (`Class::method` → `Class`, `method`)
|
|
415
|
-
* - runs of digits (`get2Users` → `get`, `2`, `Users`)
|
|
416
|
-
*
|
|
417
|
-
* The result is de-duplicated so `InvoiceService.createInvoice` collapses to
|
|
418
|
-
* `["invoice", "service", "create"]` — Jaccard similarity relies on set semantics, so
|
|
419
|
-
* repeated tokens must not double-count.
|
|
420
|
-
*/
|
|
421
|
-
function tokenizeName(input) {
|
|
422
|
-
const seen = /* @__PURE__ */ new Set();
|
|
423
|
-
const out = [];
|
|
424
|
-
for (const raw of input.split(/[.:_\-\s/]+/)) {
|
|
425
|
-
if (raw.length === 0) continue;
|
|
426
|
-
for (const piece of splitCamel(raw)) {
|
|
427
|
-
const norm = piece.toLowerCase();
|
|
428
|
-
if (norm.length === 0 || seen.has(norm)) continue;
|
|
429
|
-
seen.add(norm);
|
|
430
|
-
out.push(norm);
|
|
431
|
-
}
|
|
432
|
-
}
|
|
433
|
-
return out;
|
|
434
|
-
}
|
|
435
|
-
function splitCamel(word) {
|
|
436
|
-
const chunks = [];
|
|
437
|
-
let current = "";
|
|
438
|
-
for (const ch of word) {
|
|
439
|
-
if (current === "") {
|
|
440
|
-
current = ch;
|
|
441
|
-
continue;
|
|
442
|
-
}
|
|
443
|
-
if (isCamelBoundary(current.slice(-1), ch)) {
|
|
444
|
-
chunks.push(current);
|
|
445
|
-
current = ch;
|
|
446
|
-
} else current += ch;
|
|
447
|
-
}
|
|
448
|
-
if (current.length > 0) chunks.push(current);
|
|
449
|
-
return chunks;
|
|
450
|
-
}
|
|
451
|
-
function isCamelBoundary(prev, curr) {
|
|
452
|
-
const prevLower = prev >= "a" && prev <= "z";
|
|
453
|
-
const prevUpper = prev >= "A" && prev <= "Z";
|
|
454
|
-
const prevDigit = prev >= "0" && prev <= "9";
|
|
455
|
-
const currLower = curr >= "a" && curr <= "z";
|
|
456
|
-
const currUpper = curr >= "A" && curr <= "Z";
|
|
457
|
-
const currDigit = curr >= "0" && curr <= "9";
|
|
458
|
-
if (prevLower && currUpper) return true;
|
|
459
|
-
if ((prevLower || prevUpper) && currDigit) return true;
|
|
460
|
-
if (prevDigit && (currLower || currUpper)) return true;
|
|
461
|
-
return false;
|
|
462
|
-
}
|
|
463
|
-
/**
|
|
464
|
-
* Jaccard similarity between two token multisets. Formula: |A ∩ B| / |A ∪ B|.
|
|
465
|
-
* Empty on both sides returns 1.0 (both are "no tokens", which are equivalent for the
|
|
466
|
-
* purpose of §3.4.1). Empty on one side only returns 0.0.
|
|
467
|
-
*/
|
|
468
|
-
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);
|
|
473
|
-
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;
|
|
477
|
-
}
|
|
478
|
-
/** name-token Jaccard shortcut used by nameSimilarity and ownerSimilarity call sites. */
|
|
479
|
-
function jaccardTokens(a, b) {
|
|
480
|
-
return jaccard(tokenizeName(a), tokenizeName(b));
|
|
481
|
-
}
|
|
482
|
-
/**
|
|
483
|
-
* §3.4.1 — Jaccard over the tokens of the full qualified name. The last segment is not
|
|
484
|
-
* given extra weight; the entire path contributes uniformly because the intersection is
|
|
485
|
-
* what the score should reward.
|
|
486
|
-
*/
|
|
487
|
-
function nameSimilarity(baseName, headName) {
|
|
488
|
-
return jaccardTokens(baseName, headName);
|
|
489
|
-
}
|
|
490
|
-
/**
|
|
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`.
|
|
494
|
-
*
|
|
495
|
-
* Owner extraction:
|
|
496
|
-
* - `Class::method` → `Class`
|
|
497
|
-
* - `A.B.C.method` → `A.B.C`
|
|
498
|
-
* - `topLevel` → `` (empty)
|
|
499
|
-
*
|
|
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.
|
|
503
|
-
*/
|
|
504
|
-
function ownerSimilarity(baseName, headName) {
|
|
505
|
-
const baseOwner = extractOwner(baseName);
|
|
506
|
-
const headOwner = extractOwner(headName);
|
|
507
|
-
if (baseOwner === "" && headOwner === "") return 1;
|
|
508
|
-
if (baseOwner === "" || headOwner === "") return 0;
|
|
509
|
-
return jaccardTokens(baseOwner, headOwner);
|
|
510
|
-
}
|
|
511
|
-
function extractOwner(qname) {
|
|
512
|
-
const staticIdx = qname.indexOf("::");
|
|
513
|
-
if (staticIdx >= 0) return qname.slice(0, staticIdx);
|
|
514
|
-
const lastDot = qname.lastIndexOf(".");
|
|
515
|
-
if (lastDot >= 0) return qname.slice(0, lastDot);
|
|
516
|
-
return "";
|
|
517
|
-
}
|
|
518
|
-
/** §3.4.1 tail note — used by drop-4.5 weak matcher and threshold lookup. */
|
|
519
|
-
function lastSegment(qname) {
|
|
520
|
-
const staticIdx = qname.indexOf("::");
|
|
521
|
-
if (staticIdx >= 0) return qname.slice(staticIdx + 2);
|
|
522
|
-
const lastDot = qname.lastIndexOf(".");
|
|
523
|
-
if (lastDot >= 0) return qname.slice(lastDot + 1);
|
|
524
|
-
return qname;
|
|
525
|
-
}
|
|
526
|
-
|
|
527
|
-
//#endregion
|
|
528
|
-
//#region src/match.ts
|
|
529
|
-
/** Fingerprint for the 12-hex-char "everything zero" (i.e. dropped) canonical hash. */
|
|
530
|
-
const ZERO_LOGIC_FP = "000000000000";
|
|
531
|
-
/**
|
|
532
|
-
* §3.1 — segments Symbols with identical `id` into paired matches. Runs first because it
|
|
533
|
-
* is the highest-confidence signal (no heuristics, just hash lookup).
|
|
534
|
-
*/
|
|
535
|
-
function matchStageId(base, head) {
|
|
536
|
-
const headById = /* @__PURE__ */ new Map();
|
|
537
|
-
for (const s of head) headById.set(s.id, s);
|
|
538
|
-
const matched = [];
|
|
539
|
-
const remainingBase = [];
|
|
540
|
-
const usedHead = /* @__PURE__ */ new Set();
|
|
541
|
-
for (const b of base) {
|
|
542
|
-
const h = headById.get(b.id);
|
|
543
|
-
if (h !== void 0) {
|
|
544
|
-
matched.push({
|
|
545
|
-
base: b,
|
|
546
|
-
head: h,
|
|
547
|
-
rationale: "id-match"
|
|
548
|
-
});
|
|
549
|
-
usedHead.add(b.id);
|
|
550
|
-
} else remainingBase.push(b);
|
|
551
|
-
}
|
|
552
|
-
return {
|
|
553
|
-
matched,
|
|
554
|
-
remainingBase,
|
|
555
|
-
remainingHead: head.filter((h) => !usedHead.has(h.id))
|
|
556
|
-
};
|
|
557
|
-
}
|
|
558
|
-
/**
|
|
559
|
-
* §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.
|
|
561
|
-
*
|
|
562
|
-
* The rewriter only touches the `file` portion of the id — the `<language>:` prefix and
|
|
563
|
-
* the trailing `#<qualified-name>` segment stay unchanged so a moved file with the same
|
|
564
|
-
* qualified name is picked up correctly. When a Symbol's file is not in the rename map,
|
|
565
|
-
* it is left for later stages.
|
|
566
|
-
*/
|
|
567
|
-
function matchStageGitRename(remainingBase, remainingHead, renameMap) {
|
|
568
|
-
if (renameMap === null || renameMap.size === 0) return {
|
|
569
|
-
matched: [],
|
|
570
|
-
remainingBase: [...remainingBase],
|
|
571
|
-
remainingHead: [...remainingHead]
|
|
572
|
-
};
|
|
573
|
-
const headById = /* @__PURE__ */ new Map();
|
|
574
|
-
for (const h of remainingHead) headById.set(h.id, h);
|
|
575
|
-
const matched = [];
|
|
576
|
-
const usedHead = /* @__PURE__ */ new Set();
|
|
577
|
-
const remaining = [];
|
|
578
|
-
for (const b of remainingBase) {
|
|
579
|
-
const newPath = renameMap.get(b.source.file);
|
|
580
|
-
if (newPath === void 0) {
|
|
581
|
-
remaining.push(b);
|
|
582
|
-
continue;
|
|
583
|
-
}
|
|
584
|
-
const expectedId = rewriteIdFile(b.id, b.source.file, newPath);
|
|
585
|
-
const h = expectedId === null ? void 0 : headById.get(expectedId);
|
|
586
|
-
if (h === void 0 || usedHead.has(h.id)) {
|
|
587
|
-
remaining.push(b);
|
|
588
|
-
continue;
|
|
589
|
-
}
|
|
590
|
-
matched.push({
|
|
591
|
-
base: b,
|
|
592
|
-
head: h,
|
|
593
|
-
rationale: "git-rename"
|
|
594
|
-
});
|
|
595
|
-
usedHead.add(h.id);
|
|
596
|
-
}
|
|
597
|
-
return {
|
|
598
|
-
matched,
|
|
599
|
-
remainingBase: remaining,
|
|
600
|
-
remainingHead: remainingHead.filter((h) => !usedHead.has(h.id))
|
|
601
|
-
};
|
|
602
|
-
}
|
|
603
|
-
/**
|
|
604
|
-
* Predict the id a base Symbol would carry after git moved its file. The second Symbol-id
|
|
605
|
-
* derivation in the codebase after `makeSymbolId` itself, so it goes back through the same
|
|
606
|
-
* constructor rather than re-concatenating the parts: `trySymbolId` rejects a rename target
|
|
607
|
-
* the id grammar cannot express (a backslash path, say) instead of minting an id no head
|
|
608
|
-
* Symbol can ever equal.
|
|
609
|
-
*
|
|
610
|
-
* Returns `null` for that case, and the unchanged id when no rename applies — the caller
|
|
611
|
-
* treats a null the same way it treats a lookup miss, leaving the pair for stage 3.
|
|
612
|
-
*/
|
|
613
|
-
function rewriteIdFile(id, oldPath, newPath) {
|
|
614
|
-
const colon = id.indexOf(":");
|
|
615
|
-
const hash = id.indexOf("#");
|
|
616
|
-
if (colon < 0 || hash < 0 || hash < colon) return id;
|
|
617
|
-
if (id.slice(colon + 1, hash) !== oldPath) return id;
|
|
618
|
-
return trySymbolId({
|
|
619
|
-
language: id.slice(0, colon),
|
|
620
|
-
file: newPath,
|
|
621
|
-
qualifiedName: id.slice(hash + 1)
|
|
622
|
-
});
|
|
623
|
-
}
|
|
624
|
-
/**
|
|
625
|
-
* §3.3 — group base Symbols by `fingerprint.logic` and match head Symbols whose logic
|
|
626
|
-
* fingerprint is in the map. Two disambiguation branches:
|
|
627
|
-
* - single candidate → paired with `logic-fingerprint`
|
|
628
|
-
* - multiple candidates → best `nameSimilarity` wins if ≥ 0.85; otherwise leave both
|
|
629
|
-
* sides in remaining for stage 4 to re-evaluate
|
|
630
|
-
*
|
|
631
|
-
* Dropped symbols are excluded (§3.3 tail) — their logic fingerprint is the sentinel
|
|
632
|
-
* `"000000000000"` and would collide with every other dropped Symbol in the workspace.
|
|
633
|
-
* They flow to the stage-4.5 weak matcher instead.
|
|
634
|
-
*/
|
|
635
|
-
function matchStageLogicFingerprint(remainingBase, remainingHead) {
|
|
636
|
-
const logicMap = /* @__PURE__ */ new Map();
|
|
637
|
-
const carryBase = [];
|
|
638
|
-
for (const b of remainingBase) {
|
|
639
|
-
if (b.dropped || b.fingerprint.logic === ZERO_LOGIC_FP) {
|
|
640
|
-
carryBase.push(b);
|
|
641
|
-
continue;
|
|
642
|
-
}
|
|
643
|
-
const bucket = logicMap.get(b.fingerprint.logic) ?? [];
|
|
644
|
-
bucket.push(b);
|
|
645
|
-
logicMap.set(b.fingerprint.logic, bucket);
|
|
646
|
-
}
|
|
647
|
-
const matched = [];
|
|
648
|
-
const carryHead = [];
|
|
649
|
-
const usedBaseIds = /* @__PURE__ */ new Set();
|
|
650
|
-
for (const h of remainingHead) {
|
|
651
|
-
if (h.dropped || h.fingerprint.logic === ZERO_LOGIC_FP) {
|
|
652
|
-
carryHead.push(h);
|
|
653
|
-
continue;
|
|
654
|
-
}
|
|
655
|
-
const candidates = logicMap.get(h.fingerprint.logic);
|
|
656
|
-
if (candidates === void 0 || candidates.length === 0) {
|
|
657
|
-
carryHead.push(h);
|
|
658
|
-
continue;
|
|
659
|
-
}
|
|
660
|
-
if (candidates.length === 1) {
|
|
661
|
-
const only = candidates[0];
|
|
662
|
-
if (only === void 0) continue;
|
|
663
|
-
matched.push({
|
|
664
|
-
base: only,
|
|
665
|
-
head: h,
|
|
666
|
-
rationale: "logic-fingerprint"
|
|
667
|
-
});
|
|
668
|
-
usedBaseIds.add(only.id);
|
|
669
|
-
logicMap.delete(h.fingerprint.logic);
|
|
670
|
-
continue;
|
|
671
|
-
}
|
|
672
|
-
let best = null;
|
|
673
|
-
for (const c of candidates) {
|
|
674
|
-
const score = nameSimilarity(c.name, h.name);
|
|
675
|
-
if (best === null || score > best.score) best = {
|
|
676
|
-
symbol: c,
|
|
677
|
-
score
|
|
678
|
-
};
|
|
679
|
-
}
|
|
680
|
-
if (best !== null && best.score >= .85) {
|
|
681
|
-
matched.push({
|
|
682
|
-
base: best.symbol,
|
|
683
|
-
head: h,
|
|
684
|
-
rationale: "logic-fingerprint+name-disambiguation"
|
|
685
|
-
});
|
|
686
|
-
usedBaseIds.add(best.symbol.id);
|
|
687
|
-
const remainingBucket = candidates.filter((c) => c.id !== best?.symbol.id);
|
|
688
|
-
if (remainingBucket.length === 0) logicMap.delete(h.fingerprint.logic);
|
|
689
|
-
else logicMap.set(h.fingerprint.logic, remainingBucket);
|
|
690
|
-
} else carryHead.push(h);
|
|
691
|
-
}
|
|
692
|
-
const finalBase = [...carryBase];
|
|
693
|
-
for (const bucket of logicMap.values()) for (const b of bucket) if (!usedBaseIds.has(b.id)) finalBase.push(b);
|
|
694
|
-
return {
|
|
695
|
-
matched,
|
|
696
|
-
remainingBase: finalBase,
|
|
697
|
-
remainingHead: carryHead
|
|
698
|
-
};
|
|
699
|
-
}
|
|
700
|
-
/**
|
|
701
|
-
* §3.4 — name + signature similarity with `(kind, signatureNullness)` bucket pre-filter.
|
|
702
|
-
* `signatureNullness` distinguishes symbols with no signature (`interface`, `type`,
|
|
703
|
-
* `class`) from callable ones so that a class body is never paired against a function.
|
|
704
|
-
*
|
|
705
|
-
* The composite score:
|
|
706
|
-
* 0.5 * nameSimilarity + 0.3 * signatureSimilarity + 0.2 * ownerSimilarity
|
|
707
|
-
*
|
|
708
|
-
* §3.4.3 threshold table:
|
|
709
|
-
* - 1-token name → 1.0 (unreachable → never paired; false-positive shield)
|
|
710
|
-
* - 2-token name → 0.95 (strict, avoids `getUser` vs `getUsers`)
|
|
711
|
-
* - default → 0.85
|
|
712
|
-
*
|
|
713
|
-
* §3.4.3 tail — if both sides are signature-less, we skip pairing entirely because
|
|
714
|
-
* signatureSimilarity always returns 1.0 for `null + null` and would flood the bucket with
|
|
715
|
-
* false pairings.
|
|
716
|
-
*/
|
|
717
|
-
function matchStageNameSignature(remainingBase, remainingHead) {
|
|
718
|
-
const buckets = /* @__PURE__ */ new Map();
|
|
719
|
-
for (const b of remainingBase) {
|
|
720
|
-
if (b.dropped) continue;
|
|
721
|
-
const key = bucketKey(b);
|
|
722
|
-
const bucket = buckets.get(key) ?? [];
|
|
723
|
-
bucket.push(b);
|
|
724
|
-
buckets.set(key, bucket);
|
|
725
|
-
}
|
|
726
|
-
const matched = [];
|
|
727
|
-
const remainingHeadOut = [];
|
|
728
|
-
const usedBaseIds = /* @__PURE__ */ new Set();
|
|
729
|
-
for (const h of remainingHead) {
|
|
730
|
-
if (h.dropped) {
|
|
731
|
-
remainingHeadOut.push(h);
|
|
732
|
-
continue;
|
|
733
|
-
}
|
|
734
|
-
const key = bucketKey(h);
|
|
735
|
-
const bucket = buckets.get(key);
|
|
736
|
-
if (bucket === void 0 || bucket.length === 0) {
|
|
737
|
-
remainingHeadOut.push(h);
|
|
738
|
-
continue;
|
|
739
|
-
}
|
|
740
|
-
if ((h.signature === null || h.signature === void 0) && bucket.every((c) => c.signature === null || c.signature === void 0)) {
|
|
741
|
-
remainingHeadOut.push(h);
|
|
742
|
-
continue;
|
|
743
|
-
}
|
|
744
|
-
let best = null;
|
|
745
|
-
for (const c of bucket) {
|
|
746
|
-
const score = .5 * nameSimilarity(c.name, h.name) + .3 * signatureSimilarity(c.signature ?? null, h.signature ?? null) + .2 * ownerSimilarity(c.name, h.name);
|
|
747
|
-
if (best === null || score > best.score) best = {
|
|
748
|
-
symbol: c,
|
|
749
|
-
score
|
|
750
|
-
};
|
|
751
|
-
}
|
|
752
|
-
const threshold = thresholdFor(h.name);
|
|
753
|
-
if (best !== null && best.score >= threshold) {
|
|
754
|
-
matched.push({
|
|
755
|
-
base: best.symbol,
|
|
756
|
-
head: h,
|
|
757
|
-
rationale: "name-signature"
|
|
758
|
-
});
|
|
759
|
-
usedBaseIds.add(best.symbol.id);
|
|
760
|
-
buckets.set(key, bucket.filter((c) => c.id !== best?.symbol.id));
|
|
761
|
-
} else remainingHeadOut.push(h);
|
|
762
|
-
}
|
|
763
|
-
const remainingBaseOut = [];
|
|
764
|
-
for (const b of remainingBase) {
|
|
765
|
-
if (b.dropped) {
|
|
766
|
-
remainingBaseOut.push(b);
|
|
767
|
-
continue;
|
|
768
|
-
}
|
|
769
|
-
if (!usedBaseIds.has(b.id)) remainingBaseOut.push(b);
|
|
770
|
-
}
|
|
771
|
-
return {
|
|
772
|
-
matched,
|
|
773
|
-
remainingBase: remainingBaseOut,
|
|
774
|
-
remainingHead: remainingHeadOut
|
|
775
|
-
};
|
|
776
|
-
}
|
|
777
|
-
function bucketKey(s) {
|
|
778
|
-
const sig = s.signature === null || s.signature === void 0 ? "no-sig" : "has-sig";
|
|
779
|
-
return `${s.kind}::${sig}`;
|
|
780
|
-
}
|
|
781
|
-
function thresholdFor(qname) {
|
|
782
|
-
const tokens = tokenizeName(lastSegment(qname)).length;
|
|
783
|
-
if (tokens <= 1) return 1;
|
|
784
|
-
if (tokens === 2) return .95;
|
|
785
|
-
return .85;
|
|
786
|
-
}
|
|
787
|
-
/**
|
|
788
|
-
* §3.4.5 — dropped-only weak matcher. For dropped Symbols the fingerprint is zeroed and
|
|
789
|
-
* name/signature are the only remaining signals. Score is a coarse "did the last name
|
|
790
|
-
* segment or file basename survive?" — if either half matches we pair (threshold 0.5).
|
|
791
|
-
*
|
|
792
|
-
* This is deliberately lax; diff-algorithm.md §3.4.5 already accepts that dropped Symbols live
|
|
793
|
-
* outside the main IR review surface, so occasional false pairings only affect the
|
|
794
|
-
* "Drop-rule variation" fold-out section in the Markdown projection.
|
|
795
|
-
*/
|
|
796
|
-
function matchStageDroppedWeak(remainingBase, remainingHead) {
|
|
797
|
-
const droppedBase = remainingBase.filter((s) => s.dropped);
|
|
798
|
-
const nonDroppedBase = remainingBase.filter((s) => !s.dropped);
|
|
799
|
-
const droppedHead = remainingHead.filter((s) => s.dropped);
|
|
800
|
-
const nonDroppedHead = remainingHead.filter((s) => !s.dropped);
|
|
801
|
-
const matched = [];
|
|
802
|
-
const usedBaseIds = /* @__PURE__ */ new Set();
|
|
803
|
-
const carryHead = [];
|
|
804
|
-
for (const h of droppedHead) {
|
|
805
|
-
let best = null;
|
|
806
|
-
for (const b of droppedBase) {
|
|
807
|
-
if (b.kind !== h.kind) continue;
|
|
808
|
-
if (usedBaseIds.has(b.id)) continue;
|
|
809
|
-
const nameHit = lastSegment(b.name) === lastSegment(h.name) ? 1 : 0;
|
|
810
|
-
const fileHit = basename(b.source.file) === basename(h.source.file) ? 1 : 0;
|
|
811
|
-
const score = .5 * nameHit + .5 * fileHit;
|
|
812
|
-
if (best === null || score > best.score) best = {
|
|
813
|
-
symbol: b,
|
|
814
|
-
score
|
|
815
|
-
};
|
|
816
|
-
}
|
|
817
|
-
if (best !== null && best.score >= .5) {
|
|
818
|
-
matched.push({
|
|
819
|
-
base: best.symbol,
|
|
820
|
-
head: h,
|
|
821
|
-
rationale: "dropped-weak-match"
|
|
822
|
-
});
|
|
823
|
-
usedBaseIds.add(best.symbol.id);
|
|
824
|
-
} else carryHead.push(h);
|
|
825
|
-
}
|
|
826
|
-
return {
|
|
827
|
-
matched,
|
|
828
|
-
remainingBase: [...nonDroppedBase, ...droppedBase.filter((b) => !usedBaseIds.has(b.id))],
|
|
829
|
-
remainingHead: [...nonDroppedHead, ...carryHead]
|
|
830
|
-
};
|
|
831
|
-
}
|
|
832
|
-
function basename(path) {
|
|
833
|
-
const slash = path.lastIndexOf("/");
|
|
834
|
-
return slash >= 0 ? path.slice(slash + 1) : path;
|
|
835
|
-
}
|
|
836
|
-
|
|
837
|
-
//#endregion
|
|
838
|
-
//#region src/slice.ts
|
|
839
|
-
/**
|
|
840
|
-
* Slice View clustering pass — docs/design/slice-view.md §2, §4–§8.
|
|
841
|
-
*
|
|
842
|
-
* Groups the changed-Symbol set of a diff into weakly-connected components
|
|
843
|
-
* over the union of base and head call edges. Emits a `SliceRecord[]` whose
|
|
844
|
-
* cluster ids are `"slice:" + <smallest-member Symbol id>`, both `slices[]`
|
|
845
|
-
* and each `members[]` sorted ascending.
|
|
846
|
-
*
|
|
847
|
-
* Pure function: `(changes, baseCallEdges, headCallEdges)` → `SliceRecord[]`.
|
|
848
|
-
* Determinism, idempotence, input-order insensitivity, and locality are all
|
|
849
|
-
* guaranteed — see `computeWeaklyConnectedComponents` in `@aburi/core`.
|
|
850
|
-
*
|
|
851
|
-
* Returns `[]` when no SymbolChange is Node-eligible per §4.1; callers should
|
|
852
|
-
* still serialise the empty array — the Markdown projection omits the section
|
|
853
|
-
* (§9.4 / §12.5) but the JSON always emits the key so consumers never
|
|
854
|
-
* distinguish "field absent" from "no slices" (§11.2).
|
|
855
|
-
*
|
|
856
|
-
* Every returned record has passed `assertSliceRecordInvariant` (§7.4).
|
|
857
|
-
*/
|
|
858
|
-
function computeSlices(input) {
|
|
859
|
-
const nodeIds = collectNodeIds(input.changes);
|
|
860
|
-
if (nodeIds.length === 0) return [];
|
|
861
|
-
const nodeIdSet = new Set(nodeIds);
|
|
862
|
-
return computeWeaklyConnectedComponents(nodeIds, collectEdges(input.baseCallEdges, input.headCallEdges, nodeIdSet), (id) => id).map(makeSliceRecord);
|
|
863
|
-
}
|
|
864
|
-
const SLICE_ID_PREFIX = "slice:";
|
|
865
|
-
/**
|
|
866
|
-
* §7.1 — the single place production code derives a Slice id. Everything else
|
|
867
|
-
* in `src/` either receives an id or renders one. (Tests spell the prefix out
|
|
868
|
-
* literally on purpose: an expectation written in terms of the function under
|
|
869
|
-
* test would agree with it no matter what it produced.)
|
|
870
|
-
*
|
|
871
|
-
* The cast is the one place a `SliceId` comes into existence. `SliceId` and
|
|
872
|
-
* `SymbolId` are separate brands precisely so this concatenation cannot be
|
|
873
|
-
* open-coded anywhere else: a bare `"slice:" + x` evaluates to `string`, which
|
|
874
|
-
* `SliceRecord.id` no longer accepts.
|
|
875
|
-
*/
|
|
876
|
-
function sliceIdFor(anchor) {
|
|
877
|
-
return `${SLICE_ID_PREFIX}${anchor}`;
|
|
878
|
-
}
|
|
879
|
-
/**
|
|
880
|
-
* Build one SliceRecord from an ascending-sorted component and check its own
|
|
881
|
-
* post-condition before letting it out (§7.4 layer 1).
|
|
882
|
-
*
|
|
883
|
-
* The check is not defending against untrusted input — this function builds
|
|
884
|
-
* the id itself, so the derivation clause is true by construction here and
|
|
885
|
-
* only the two clauses about `members` can actually fire. Those are the point:
|
|
886
|
-
* `members[0]` is the anchor only because `computeWeaklyConnectedComponents`
|
|
887
|
-
* returns each component sorted ascending, a guarantee that lives one layer
|
|
888
|
-
* down and is invisible from this file. If it ever stops holding, the diff
|
|
889
|
-
* would otherwise keep emitting well-formed-looking SliceRecords naming the
|
|
890
|
-
* wrong anchor. Here it fails instead.
|
|
891
|
-
*/
|
|
892
|
-
function makeSliceRecord(members) {
|
|
893
|
-
const anchor = members[0];
|
|
894
|
-
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" });
|
|
895
|
-
const record = {
|
|
896
|
-
id: sliceIdFor(anchor),
|
|
897
|
-
members: [...members]
|
|
898
|
-
};
|
|
899
|
-
assertSliceRecordInvariant(record);
|
|
900
|
-
return record;
|
|
901
|
-
}
|
|
902
|
-
/**
|
|
903
|
-
* §7.1 — the anchor of a Slice: its lexicographically smallest member.
|
|
904
|
-
*
|
|
905
|
-
* Answers from `members[0]`. `id` is derived from the anchor, so
|
|
906
|
-
* reconstructing the anchor by stripping the `"slice:"` prefix is circular at
|
|
907
|
-
* best and, for a record that broke the derivation, silently wrong: it would
|
|
908
|
-
* name a Symbol that is not in the Slice. `id` is read here only to name the
|
|
909
|
-
* offending record in the error message. Consumers that need the anchor call
|
|
910
|
-
* this; consumers that need a label keep using `id` directly.
|
|
911
|
-
*/
|
|
912
|
-
function sliceAnchor(record) {
|
|
913
|
-
const anchor = record.members[0];
|
|
914
|
-
if (anchor === void 0) {
|
|
915
|
-
const violation = emptyMembersViolation(record.id);
|
|
916
|
-
throw new DiffError(violation.message, {
|
|
917
|
-
code: "slice-invariant-violated",
|
|
918
|
-
value: violation.subject
|
|
919
|
-
});
|
|
920
|
-
}
|
|
921
|
-
return anchor;
|
|
922
|
-
}
|
|
923
|
-
/**
|
|
924
|
-
* Report which clause of the §7.1 / §8.2 invariant a value breaks, or `null`
|
|
925
|
-
* when it is a well-formed `SliceRecord`. Non-throwing counterpart of
|
|
926
|
-
* `assertSliceRecordInvariant`: the pass wants an exception, a schema
|
|
927
|
-
* validator wants a verdict it can turn into its own error.
|
|
928
|
-
*
|
|
929
|
-
* Takes `unknown` rather than `SliceRecord` deliberately. §7.4 layer 2 points
|
|
930
|
-
* this at documents written by third-party or older producers — data that has
|
|
931
|
-
* not been type-checked by definition — so anything that assumed a well-typed
|
|
932
|
-
* argument would crash on exactly the input it exists to reject.
|
|
933
|
-
*/
|
|
934
|
-
function sliceRecordViolation(value) {
|
|
935
|
-
if (typeof value !== "object" || value === null) return {
|
|
936
|
-
kind: "malformed-shape",
|
|
937
|
-
subject: "<not an object>",
|
|
938
|
-
message: `Expected a SliceRecord object; got ${value === null ? "null" : typeof value}.`
|
|
939
|
-
};
|
|
940
|
-
const { id, members } = value;
|
|
941
|
-
const subject = typeof id === "string" ? id : "<missing id>";
|
|
942
|
-
if (typeof id !== "string") return {
|
|
943
|
-
kind: "malformed-shape",
|
|
944
|
-
subject,
|
|
945
|
-
message: `SliceRecord ${subject}: id must be a string; got ${typeof id}.`
|
|
946
|
-
};
|
|
947
|
-
if (!Array.isArray(members) || members.some((member) => typeof member !== "string")) return {
|
|
948
|
-
kind: "malformed-shape",
|
|
949
|
-
subject,
|
|
950
|
-
message: `SliceRecord ${subject}: members must be an array of strings.`
|
|
951
|
-
};
|
|
952
|
-
const anchor = members[0];
|
|
953
|
-
if (anchor === void 0) return emptyMembersViolation(subject);
|
|
954
|
-
const reservedAnchor = reservedNamespaceOf(anchor);
|
|
955
|
-
if (reservedAnchor !== null) return {
|
|
956
|
-
kind: "anchor-in-reserved-namespace",
|
|
957
|
-
subject,
|
|
958
|
-
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).`
|
|
959
|
-
};
|
|
960
|
-
for (let i = 1; i < members.length; i++) {
|
|
961
|
-
const previous = members[i - 1];
|
|
962
|
-
const current = members[i];
|
|
963
|
-
if (previous < current) continue;
|
|
964
|
-
return {
|
|
965
|
-
kind: "members-unordered",
|
|
966
|
-
subject,
|
|
967
|
-
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).`
|
|
968
|
-
};
|
|
969
|
-
}
|
|
970
|
-
const expected = sliceIdFor(anchor);
|
|
971
|
-
if (id !== expected) return {
|
|
972
|
-
kind: "id-not-derived",
|
|
973
|
-
subject,
|
|
974
|
-
message: `SliceRecord id "${id}" is not derived from the anchor "${anchor}"; expected "${expected}" (slice-view.md §7.1).`
|
|
975
|
-
};
|
|
976
|
-
return null;
|
|
977
|
-
}
|
|
978
|
-
/** The reserved token an id opens with, or `null`. Shares the list `@aburi/core` enforces. */
|
|
979
|
-
function reservedNamespaceOf(id) {
|
|
980
|
-
const colon = id.indexOf(":");
|
|
981
|
-
if (colon < 0) return null;
|
|
982
|
-
const token = id.slice(0, colon);
|
|
983
|
-
return RESERVED_LANGUAGE_IDS.has(token) ? token : null;
|
|
984
|
-
}
|
|
985
|
-
/** Single source of the empty-`members[]` wording, shared with `sliceAnchor`. */
|
|
986
|
-
function emptyMembersViolation(subject) {
|
|
987
|
-
return {
|
|
988
|
-
kind: "members-empty",
|
|
989
|
-
subject,
|
|
990
|
-
message: `SliceRecord ${subject}: members[] is empty, so the Slice has no anchor (slice-view.md §11.1 requires at least one member).`
|
|
991
|
-
};
|
|
992
|
-
}
|
|
993
|
-
/**
|
|
994
|
-
* Throwing form of `sliceRecordViolation`. Raised as a coded `DiffError` so
|
|
995
|
-
* callers branch on `code` rather than parsing the message; which clause broke
|
|
996
|
-
* is `SliceRecordViolation.kind`, for callers that need to tell them apart.
|
|
997
|
-
*/
|
|
998
|
-
function assertSliceRecordInvariant(record) {
|
|
999
|
-
const violation = sliceRecordViolation(record);
|
|
1000
|
-
if (violation === null) return;
|
|
1001
|
-
throw new DiffError(violation.message, {
|
|
1002
|
-
code: "slice-invariant-violated",
|
|
1003
|
-
value: violation.subject
|
|
1004
|
-
});
|
|
1005
|
-
}
|
|
1006
|
-
/**
|
|
1007
|
-
* §4.1 Node selection: keep every SymbolChange whose status is
|
|
1008
|
-
* added / removed / changed / moved+changed / dropped-toggled. The identity
|
|
1009
|
-
* is the head-side Symbol id where present (added / changed / moved+changed /
|
|
1010
|
-
* dropped-toggled), the base-side id for removed. Pure moved and unchanged
|
|
1011
|
-
* (already stripped upstream) are excluded — §4.1 / §4.3.
|
|
1012
|
-
*
|
|
1013
|
-
* The returned array is deliberately not deduplicated: a well-formed
|
|
1014
|
-
* SymbolChange list from `buildDiff` never mentions the same Symbol id
|
|
1015
|
-
* twice, and Union-Find would coalesce any accidental duplicate anyway.
|
|
1016
|
-
*/
|
|
1017
|
-
function collectNodeIds(changes) {
|
|
1018
|
-
const ids = [];
|
|
1019
|
-
for (const change of changes) {
|
|
1020
|
-
const id = nodeIdOf(change);
|
|
1021
|
-
if (id === null) continue;
|
|
1022
|
-
ids.push(id);
|
|
1023
|
-
}
|
|
1024
|
-
return ids;
|
|
1025
|
-
}
|
|
1026
|
-
function nodeIdOf(change) {
|
|
1027
|
-
switch (change.status) {
|
|
1028
|
-
case "added": return change.symbol.id;
|
|
1029
|
-
case "removed": return change.symbol.id;
|
|
1030
|
-
case "changed":
|
|
1031
|
-
case "moved+changed":
|
|
1032
|
-
case "dropped-toggled": return change.after.id;
|
|
1033
|
-
case "moved": return null;
|
|
1034
|
-
}
|
|
1035
|
-
}
|
|
1036
|
-
/**
|
|
1037
|
-
* §5.1 Edge selection: union of base and head, restricted to edges whose
|
|
1038
|
-
* BOTH endpoints are Nodes, canonicalised to `(u, v)` with `u < v` (self-
|
|
1039
|
-
* loops implicitly dropped). Multi-edges collapse naturally inside the WCC
|
|
1040
|
-
* primitive — no explicit dedup needed.
|
|
1041
|
-
*
|
|
1042
|
-
* The union is the load-bearing rule of §5.3: a controller that called an
|
|
1043
|
-
* old service in base and a new service in head needs both edges to land
|
|
1044
|
-
* all three Symbols in a single Slice.
|
|
1045
|
-
*/
|
|
1046
|
-
function collectEdges(baseEdges, headEdges, nodeIds) {
|
|
1047
|
-
const pairs = [];
|
|
1048
|
-
for (const edge of baseEdges) appendEdgeIfBothNodes(edge, nodeIds, pairs);
|
|
1049
|
-
for (const edge of headEdges) appendEdgeIfBothNodes(edge, nodeIds, pairs);
|
|
1050
|
-
return pairs;
|
|
1051
|
-
}
|
|
1052
|
-
function appendEdgeIfBothNodes(edge, nodeIds, out) {
|
|
1053
|
-
if (!nodeIds.has(edge.from) || !nodeIds.has(edge.to)) return;
|
|
1054
|
-
out.push([edge.from, edge.to]);
|
|
1055
|
-
}
|
|
1056
|
-
|
|
1057
|
-
//#endregion
|
|
1058
|
-
//#region src/status.ts
|
|
1059
|
-
/**
|
|
1060
|
-
* §4 — determine which of the five statuses a matched pair falls into. `dropped-toggled`
|
|
1061
|
-
* has absolute priority: whenever `dropped` differs between base and head, every other
|
|
1062
|
-
* signal is ignored because the underlying fingerprint change is a consequence of the
|
|
1063
|
-
* drop-rule flip, not a genuine code edit (§4.1 rationale).
|
|
1064
|
-
*
|
|
1065
|
-
* "pathChanged" catches both physical file relocation AND in-file rename: any Symbol id
|
|
1066
|
-
* mismatch between base and head means the identifier moved, and DF9 ("method rename
|
|
1067
|
-
* (same file, same logic) → moved") relies on this. Stage-1 pairs cannot trigger the id branch
|
|
1068
|
-
* (they match by exact id), so this only affects stage-2+ pairings where the pair was
|
|
1069
|
-
* discovered via fingerprint or name/signature similarity.
|
|
1070
|
-
*/
|
|
1071
|
-
function classifyStatus(base, head) {
|
|
1072
|
-
if (base.dropped !== head.dropped) return "dropped-toggled";
|
|
1073
|
-
const pathChanged = base.source.file !== head.source.file || base.id !== head.id;
|
|
1074
|
-
const fingerprintChanged = base.fingerprint.api !== head.fingerprint.api || base.fingerprint.logic !== head.fingerprint.logic || base.fingerprint.syntax !== head.fingerprint.syntax;
|
|
1075
|
-
if (pathChanged && fingerprintChanged) return "moved+changed";
|
|
1076
|
-
if (pathChanged) return "moved";
|
|
1077
|
-
if (fingerprintChanged) return "changed";
|
|
1078
|
-
return "unchanged";
|
|
1079
|
-
}
|
|
1080
|
-
function dropDirection(head) {
|
|
1081
|
-
return head.dropped ? "to-dropped" : "to-kept";
|
|
1082
|
-
}
|
|
1083
|
-
|
|
1084
|
-
//#endregion
|
|
1085
|
-
//#region src/diff.ts
|
|
1086
|
-
const DIFF_SCHEMA = "https://aburi.dev/schema/aburi.diff.v1.json";
|
|
1087
|
-
const DEFAULT_GENERATOR = {
|
|
1088
|
-
name: "aburi",
|
|
1089
|
-
version: "0.0.0"
|
|
1090
|
-
};
|
|
1091
|
-
/**
|
|
1092
|
-
* Top-level entry: run the 5-stage matcher, classify each pair, produce array deltas,
|
|
1093
|
-
* fold in Component / Dependency diffs, and assemble the `aburi.diff.v1` JSON projection.
|
|
1094
|
-
* The function is pure; write-to-disk is delegated to `writeCanonicalDiff` so callers can
|
|
1095
|
-
* pipe the result through additional steps (Markdown projection, `--fail-on` gate) before
|
|
1096
|
-
* serialisation.
|
|
1097
|
-
*/
|
|
1098
|
-
function buildDiff(input) {
|
|
1099
|
-
assertIRShape(input.baseIR, "baseIR");
|
|
1100
|
-
assertIRShape(input.headIR, "headIR");
|
|
1101
|
-
ensureSchemasAgree(input.baseIR, input.headIR);
|
|
1102
|
-
const stage1 = matchStageId(input.baseIR.symbols, input.headIR.symbols);
|
|
1103
|
-
const stage2 = matchStageGitRename(stage1.remainingBase, stage1.remainingHead, input.gitRenames ?? null);
|
|
1104
|
-
const stage3 = matchStageLogicFingerprint(stage2.remainingBase, stage2.remainingHead);
|
|
1105
|
-
const stage4 = matchStageNameSignature(stage3.remainingBase, stage3.remainingHead);
|
|
1106
|
-
const stage4_5 = matchStageDroppedWeak(stage4.remainingBase, stage4.remainingHead);
|
|
1107
|
-
const pairs = [
|
|
1108
|
-
...stage1.matched,
|
|
1109
|
-
...stage2.matched,
|
|
1110
|
-
...stage3.matched,
|
|
1111
|
-
...stage4.matched,
|
|
1112
|
-
...stage4_5.matched
|
|
1113
|
-
];
|
|
1114
|
-
const summary = {
|
|
1115
|
-
added: 0,
|
|
1116
|
-
removed: 0,
|
|
1117
|
-
moved: 0,
|
|
1118
|
-
movedChanged: 0,
|
|
1119
|
-
changed: 0,
|
|
1120
|
-
droppedToggled: 0,
|
|
1121
|
-
unchanged: 0,
|
|
1122
|
-
droppedAdded: 0,
|
|
1123
|
-
droppedRemoved: 0,
|
|
1124
|
-
componentsAdded: 0,
|
|
1125
|
-
componentsRemoved: 0,
|
|
1126
|
-
componentsChanged: 0,
|
|
1127
|
-
depsAdded: 0,
|
|
1128
|
-
depsRemoved: 0
|
|
1129
|
-
};
|
|
1130
|
-
const symbols = [];
|
|
1131
|
-
for (const pair of pairs) {
|
|
1132
|
-
const status = classifyStatus(pair.base, pair.head);
|
|
1133
|
-
if (status === "unchanged") {
|
|
1134
|
-
summary.unchanged++;
|
|
1135
|
-
continue;
|
|
1136
|
-
}
|
|
1137
|
-
if (status === "dropped-toggled") {
|
|
1138
|
-
summary.droppedToggled++;
|
|
1139
|
-
symbols.push({
|
|
1140
|
-
status: "dropped-toggled",
|
|
1141
|
-
before: pair.base,
|
|
1142
|
-
after: pair.head,
|
|
1143
|
-
direction: dropDirection(pair.head)
|
|
1144
|
-
});
|
|
1145
|
-
continue;
|
|
1146
|
-
}
|
|
1147
|
-
if (status === "moved") {
|
|
1148
|
-
summary.moved++;
|
|
1149
|
-
symbols.push({
|
|
1150
|
-
status: "moved",
|
|
1151
|
-
before: pair.base,
|
|
1152
|
-
after: pair.head,
|
|
1153
|
-
rationale: pair.rationale
|
|
1154
|
-
});
|
|
1155
|
-
continue;
|
|
1156
|
-
}
|
|
1157
|
-
if (status === "changed") {
|
|
1158
|
-
summary.changed++;
|
|
1159
|
-
symbols.push({
|
|
1160
|
-
status: "changed",
|
|
1161
|
-
before: pair.base,
|
|
1162
|
-
after: pair.head,
|
|
1163
|
-
delta: computeSymbolDelta(pair.base, pair.head, input.delta ?? {})
|
|
1164
|
-
});
|
|
1165
|
-
continue;
|
|
1166
|
-
}
|
|
1167
|
-
summary.movedChanged++;
|
|
1168
|
-
symbols.push({
|
|
1169
|
-
status: "moved+changed",
|
|
1170
|
-
before: pair.base,
|
|
1171
|
-
after: pair.head,
|
|
1172
|
-
rationale: pair.rationale,
|
|
1173
|
-
delta: computeSymbolDelta(pair.base, pair.head, input.delta ?? {})
|
|
1174
|
-
});
|
|
1175
|
-
}
|
|
1176
|
-
const finalRemainingHead = stage4_5.remainingHead;
|
|
1177
|
-
const finalRemainingBase = stage4_5.remainingBase;
|
|
1178
|
-
for (const h of finalRemainingHead) if (h.dropped) summary.droppedAdded++;
|
|
1179
|
-
else {
|
|
1180
|
-
summary.added++;
|
|
1181
|
-
symbols.push({
|
|
1182
|
-
status: "added",
|
|
1183
|
-
symbol: h
|
|
1184
|
-
});
|
|
1185
|
-
}
|
|
1186
|
-
for (const b of finalRemainingBase) if (b.dropped) summary.droppedRemoved++;
|
|
1187
|
-
else {
|
|
1188
|
-
summary.removed++;
|
|
1189
|
-
symbols.push({
|
|
1190
|
-
status: "removed",
|
|
1191
|
-
symbol: b
|
|
1192
|
-
});
|
|
1193
|
-
}
|
|
1194
|
-
const components = diffComponents(input.baseIR.components, input.headIR.components);
|
|
1195
|
-
summary.componentsAdded = components.added.length;
|
|
1196
|
-
summary.componentsRemoved = components.removed.length;
|
|
1197
|
-
summary.componentsChanged = components.changed.length;
|
|
1198
|
-
const dependencies = diffDependencies(input.baseIR.dependencies, input.headIR.dependencies);
|
|
1199
|
-
summary.depsAdded = dependencies.added.length;
|
|
1200
|
-
summary.depsRemoved = dependencies.removed.length;
|
|
1201
|
-
symbols.sort(compareSymbolChange);
|
|
1202
|
-
const slices = computeSlices({
|
|
1203
|
-
changes: symbols,
|
|
1204
|
-
baseCallEdges: reconstructCallEdgesFromIR(input.baseIR),
|
|
1205
|
-
headCallEdges: reconstructCallEdgesFromIR(input.headIR)
|
|
1206
|
-
});
|
|
1207
|
-
return {
|
|
1208
|
-
$schema: DIFF_SCHEMA,
|
|
1209
|
-
generator: input.generator ?? DEFAULT_GENERATOR,
|
|
1210
|
-
base: input.base,
|
|
1211
|
-
head: input.head,
|
|
1212
|
-
summary,
|
|
1213
|
-
symbols,
|
|
1214
|
-
components,
|
|
1215
|
-
dependencies,
|
|
1216
|
-
slices
|
|
1217
|
-
};
|
|
1218
|
-
}
|
|
1219
|
-
/** §9.1 — refuse to diff across schema versions. */
|
|
1220
|
-
function ensureSchemasAgree(base, head) {
|
|
1221
|
-
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.`, {
|
|
1222
|
-
code: "schema-mismatch",
|
|
1223
|
-
value: base.$schema
|
|
1224
|
-
});
|
|
1225
|
-
}
|
|
1226
|
-
/**
|
|
1227
|
-
* Top-level shape check. Refuses to enter the 5-stage matcher when a caller hands in an
|
|
1228
|
-
* IR-shaped object that is missing one of the collections the matcher requires as an
|
|
1229
|
-
* array. Without this, a malformed `baseIR = { symbols: undefined, ... }` would crash
|
|
1230
|
-
* deep inside `matchStageId` with `TypeError: undefined is not iterable`, leaving the
|
|
1231
|
-
* root cause obscured. Not a full schema validation — just an entry-point smoke test.
|
|
1232
|
-
*/
|
|
1233
|
-
function assertIRShape(ir, name) {
|
|
1234
|
-
if (ir === null || typeof ir !== "object") throw new DiffError(`${name} must be an IR object; got ${typeof ir}.`, {
|
|
1235
|
-
code: "ir-shape-invalid",
|
|
1236
|
-
value: name
|
|
1237
|
-
});
|
|
1238
|
-
if (typeof ir.$schema !== "string" || ir.$schema.length === 0) throw new DiffError(`${name}.$schema must be a non-empty schema URL.`, {
|
|
1239
|
-
code: "ir-shape-invalid",
|
|
1240
|
-
value: `${name}.$schema`
|
|
1241
|
-
});
|
|
1242
|
-
for (const field of [
|
|
1243
|
-
"symbols",
|
|
1244
|
-
"components",
|
|
1245
|
-
"dependencies"
|
|
1246
|
-
]) if (!Array.isArray(ir[field])) throw new DiffError(`${name}.${field} must be an array.`, {
|
|
1247
|
-
code: "ir-shape-invalid",
|
|
1248
|
-
value: `${name}.${field}`
|
|
1249
|
-
});
|
|
1250
|
-
}
|
|
1251
|
-
/**
|
|
1252
|
-
* Deterministic ordering of the `symbols[]` output:
|
|
1253
|
-
* 1. by status (alphabetical) — pins added/changed/moved sections
|
|
1254
|
-
* 2. by the "reference" id (`after` for change/move/toggle, otherwise `symbol`)
|
|
1255
|
-
*
|
|
1256
|
-
* The result is stable byte-for-byte for equal inputs, matching the canonicalisation
|
|
1257
|
-
* guarantee the diff JSON must uphold when persisted to `out/diff.json`.
|
|
1258
|
-
*/
|
|
1259
|
-
function compareSymbolChange(a, b) {
|
|
1260
|
-
if (a.status !== b.status) return a.status < b.status ? -1 : 1;
|
|
1261
|
-
const idA = referenceId(a);
|
|
1262
|
-
const idB = referenceId(b);
|
|
1263
|
-
return idA < idB ? -1 : idA > idB ? 1 : 0;
|
|
1264
|
-
}
|
|
1265
|
-
function referenceId(change) {
|
|
1266
|
-
if (change.status === "added" || change.status === "removed") return change.symbol.id;
|
|
1267
|
-
return change.after.id;
|
|
1268
|
-
}
|
|
1269
|
-
/**
|
|
1270
|
-
* Byte-deterministic serialiser for a DiffResult. Delegates to `@aburi/core`
|
|
1271
|
-
* `serializeCanonical` so the sort order, NFC normalisation, and codepoint key sort are
|
|
1272
|
-
* shared with the IR side.
|
|
1273
|
-
*/
|
|
1274
|
-
function writeCanonicalDiff(diff, options = {}) {
|
|
1275
|
-
return serializeCanonical(diff, options);
|
|
1276
|
-
}
|
|
1277
|
-
|
|
1278
|
-
//#endregion
|
|
1279
|
-
export { DEFAULT_LINE_FUZZ, DiffError, MAX_LINE_FUZZ, MIN_LINE_FUZZ, assertSliceRecordInvariant, buildDiff, classifyStatus, computeSlices, computeSymbolDelta, diffComponents, diffDependencies, dropDirection, jaccard, jaccardTokens, lastSegment, matchStageDroppedWeak, matchStageGitRename, matchStageId, matchStageLogicFingerprint, matchStageNameSignature, nameSimilarity, ownerSimilarity, signatureSimilarity, sliceAnchor, sliceRecordViolation, tokenizeName, writeCanonicalDiff };
|
|
1280
|
-
//# sourceMappingURL=index.mjs.map
|
|
1
|
+
import{DOCUMENT_SUBJECT as e,RESERVED_LANGUAGE_IDS as t,checkDocumentShape as n,computeWeaklyConnectedComponents as r,reconstructCallEdgesFromIR as i,serializeCanonical as a,trySymbolId as o}from"@aburi/core";var s=class extends Error{code;value;violations;constructor(e,t,n){super(e,n),this.name=`DiffError`,this.code=t.code,this.value=t.value,this.violations=t.violations}};function c(e,t){let n=new Map;for(let t of e)n.set(t.id,t);let r=new Map;for(let e of t)r.set(e.id,e);let i=[],a=[],o=[];for(let[e,t]of r){let r=n.get(e);if(r===void 0){i.push(t);continue}g(r,t)||o.push({before:r,after:t,delta:{rootsChanged:!b(r.roots,t.roots),publicApiChanged:!b(r.publicApi??[],t.publicApi??[]),frameworksChanged:!b(r.frameworks??[],t.frameworks??[])}})}for(let[e,t]of n)r.has(e)||a.push(t);return x(i),x(a),o.sort((e,t)=>e.after.id<t.after.id?-1:+(e.after.id>t.after.id)),{added:i,removed:a,changed:o}}function l(e){let t=new Map;for(let n of e.symbols)t.set(n.id,n.source.file);let n=new Map;for(let t of e.stats.skippedFiles??[])n.set(t.path,t.reason);return{symbolFiles:t,lostFiles:n}}function u(e,t,n){let r=new Map;for(let t of e)r.set(m(t),t);let i=new Map;for(let e of t)i.set(m(e),e);let a=[],o=[],s=[];for(let[e,t]of i){let i=r.get(e);if(i===void 0){let e=d(t,n.head,n.base);e.length>0?s.push({dependency:t,absentFrom:`base`,lostFiles:e}):a.push(t);continue}(i.direction!==t.direction||(i.effect??null)!==(t.effect??null))&&(o.push(i),a.push(t))}for(let[e,t]of r){if(i.has(e))continue;let r=d(t,n.base,n.head);r.length>0?s.push({dependency:t,absentFrom:`head`,lostFiles:r}):o.push(t)}return a.sort(h),o.sort(h),s.sort((e,t)=>h(e.dependency,t.dependency)),{added:a,removed:o,unknown:s}}function d(e,t,n){let r=new Map;for(let i of[e.from,e.to]){let e=t.symbolFiles.get(i);if(e===void 0)continue;let a=n.lostFiles.get(e);a!==void 0&&r.set(e,a)}return[...r.entries()].map(([e,t])=>({path:e,reason:t})).sort((e,t)=>e.path<t.path?-1:+(e.path>t.path))}const f=[`from`,`to`,`via`];function p(e){return e.join(`::`)}function m(e){return p(f.map(t=>e[t]))}function h(e,t){let n=m(e),r=m(t);return n<r?-1:+(n>r)}function g(e,t){return _(e,`base`)===_(t,`head`)}function _(e,t){try{return a(v(e),{format:`compact`})}catch(n){throw new s(`${t} components[id=${e.id}] cannot be compared: ${n instanceof Error?n.message:String(n)}`,{code:`ir-shape-invalid`,value:`components[id=${e.id}]`},{cause:n})}}function v(e){let t={...e};(t.description===null||t.description===void 0)&&delete t.description;for(let e of y){let n=t[e];(n===void 0||Array.isArray(n)&&n.length===0)&&delete t[e]}return t}const y=[`publicApi`,`frameworks`];function b(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function x(e){e.sort((e,t)=>e.id<t.id?-1:+(e.id>t.id))}const S=2,ee=10,te=0;function C(e,t,n={}){let r=ne(n.lineFuzz??2),i={apiChanged:e.fingerprint.api!==t.fingerprint.api,logicChanged:e.fingerprint.logic!==t.fingerprint.logic,syntaxChanged:e.fingerprint.syntax!==t.fingerprint.syntax,componentChanged:(e.component??null)!==(t.component??null),visibilityChanged:e.visibility!==t.visibility};return i.rules=ae(e.rules,t.rules,r),i.effects=se(e.effects,t.effects),i.calls=le(e.calls,t.calls,r),i.decorators=de(e.decorators,t.decorators,r),i.signature=pe(e.signature??null,t.signature??null),i}function ne(e){if(!Number.isFinite(e)||!Number.isInteger(e))throw new s(`config.diff.lineFuzz must be an integer in [0, 10]; got ${String(e)}.`,{code:`invalid-line-fuzz`,value:String(e)});if(e<0||e>10)throw new s(`config.diff.lineFuzz must be within [0, 10]; got ${e}.`,{code:`invalid-line-fuzz`,value:String(e)});return e}function w(e,t,n,r){let i=new Set(e.map((e,t)=>t)),a=new Set(t.map((e,t)=>t)),o=new Map;for(let s of[!0,!1]){let c=(e,t)=>e.key===t.key&&Math.abs(e.line-t.line)<=r&&(!s||n(e.item,t.item));for(let[n,r]of ie(e,t,i,a,c)){i.delete(n),a.delete(r);let t=e[n];t!==void 0&&o.set(r,t)}}let s=[],c=[];for(let[e,r]of t.entries()){let t=o.get(e);t===void 0?s.push(r.item):n(t.item,r.item)||c.push(r.item)}return{added:s,removed:e.filter((e,t)=>i.has(t)).map(e=>e.item),modified:c}}const T={pairs:0,distance:0};function re(e,t){return e.pairs===t.pairs?e.distance<t.distance:e.pairs>t.pairs}function ie(e,t,n,r,i){let a=Array.from({length:e.length+1},()=>Array.from({length:t.length+1},()=>T)),o=(o,s)=>{let c=e[o],l=t[s];if(c===void 0||l===void 0||!n.has(o)||!r.has(s)||!i(c,l))return null;let u=a[o+1]?.[s+1]??T;return{pairs:u.pairs+1,distance:u.distance+Math.abs(c.line-l.line)}};for(let n=e.length-1;n>=0;n--)for(let e=t.length-1;e>=0;e--){let t=a[n+1]?.[e]??T,r=a[n]?.[e+1]??T,i=re(t,r)?t:r,s=o(n,e);s!==null&&re(s,i)&&(i=s);let c=a[n];c!==void 0&&(c[e]=i)}let s=[],c=0,l=0;for(;c<e.length&&l<t.length;){let e=a[c]?.[l]??T,t=o(c,l);if(t!==null&&t.pairs===e.pairs&&t.distance===e.distance){s.push([c,l]),c++,l++;continue}let n=a[c+1]?.[l]??T;n.pairs===e.pairs&&n.distance===e.distance?c++:l++}return s}function ae(e,t,n){let r=e=>({item:e,key:e.type,line:e.line});return w(e.map(r),t.map(r),oe,n)}function oe(e,t){return e.type===t.type&&(e.condition??null)===(t.condition??null)&&(e.what??null)===(t.what??null)&&(e.expr??null)===(t.expr??null)&&(e.loopKind??null)===(t.loopKind??null)}function se(e,t){let n=e=>({item:e,key:`${e.id}::${e.target}`,line:e.line??0});return w(e.map(n),t.map(n),ce,1/0)}function ce(e,t){return e.id===t.id&&e.target===t.target&&e.plugin===t.plugin&&e.confidence===t.confidence}function le(e,t,n){let r=e=>({item:e,key:e.target,line:e.line});return w(e.map(r),t.map(r),ue,n)}function ue(e,t){return e.target===t.target&&(e.resolved??null)===(t.resolved??null)}function de(e,t,n){let r=e=>({item:e,key:e.name,line:e.line});return w(e.map(r),t.map(r),fe,n)}function fe(e,t){if(e.name!==t.name||e.arguments.length!==t.arguments.length)return!1;for(let n=0;n<e.arguments.length;n++)if(e.arguments[n]!==t.arguments[n])return!1;return!0}function pe(e,t){if(e===null&&t===null)return null;if(e===null||t===null){let n={added:[],removed:[],modified:[]},r=e??t;if(r===null)return null;let i=e===null;return{inputs:i?{added:[...r.inputs],removed:[],modified:[]}:{added:[],removed:[...r.inputs],modified:[]},outputs:i?{added:[...r.outputs],removed:[],modified:[]}:{added:[],removed:[...r.outputs],modified:[]},throws:i?{added:[...r.throws],removed:[],modified:[]}:{added:[],removed:[...r.throws],modified:[]},asyncChanged:(e?.async??!1)!==(t?.async??!1),generatorChanged:(e?.generator??!1)!==(t?.generator??!1),typeParametersChanged:!ge(e?.typeParameters??n.added.map(String),t?.typeParameters??n.added.map(String))}}let n=(e,t)=>({item:e,key:`${t}:${e.name}`,line:t});return{inputs:w(e.inputs.map(n),t.inputs.map(n),(e,t)=>e.name===t.name&&e.type===t.type,0),outputs:me(e.outputs,t.outputs),throws:he(e.throws,t.throws),asyncChanged:e.async!==t.async,generatorChanged:e.generator!==t.generator,typeParametersChanged:!ge(e.typeParameters,t.typeParameters)}}function me(e,t){let n=[],r=[],i=Math.max(e.length,t.length);for(let a=0;a<i;a++){let i=a<e.length?e[a]:void 0,o=a<t.length?t[a]:void 0;i===void 0&&o!==void 0?n.push(o):o===void 0&&i!==void 0?r.push(i):i!==o&&(i!==void 0&&r.push(i),o!==void 0&&n.push(o))}return{added:n,removed:r,modified:[]}}function he(e,t){let n=new Set(e),r=new Set(t),i=[],a=[];for(let e of r)n.has(e)||i.push(e);for(let e of n)r.has(e)||a.push(e);return{added:i,removed:a,modified:[]}}function ge(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function E(e,t){let n=e??null,r=t??null;if(n===null&&r===null)return 1;if(n===null||r===null)return 0;let i=D(n.inputs.map(e=>e.type),r.inputs.map(e=>e.type)),a=D(n.outputs,r.outputs),o=_e(n.throws,r.throws);return(i+a+o)/3}function D(e,t){if(e.length===0&&t.length===0)return 1;if(e.length!==t.length)return 0;let n=0;for(let r=0;r<e.length;r++)e[r]===t[r]&&n++;return n/e.length}function _e(e,t){if(e.length===0&&t.length===0)return 1;let n=new Set(e),r=new Set(t),i=0;for(let e of n)r.has(e)&&i++;let a=n.size+r.size-i;return a===0?1:i/a}function O(e){let t=new Set,n=[];for(let r of e.split(/[.:_\-\s/]+/))if(r.length!==0)for(let e of ve(r)){let r=e.toLowerCase();r.length===0||t.has(r)||(t.add(r),n.push(r))}return n}function ve(e){let t=[],n=``;for(let r of e){if(n===``){n=r;continue}ye(n.slice(-1),r)?(t.push(n),n=r):n+=r}return n.length>0&&t.push(n),t}function ye(e,t){let n=e>=`a`&&e<=`z`,r=e>=`A`&&e<=`Z`,i=e>=`0`&&e<=`9`,a=t>=`a`&&t<=`z`,o=t>=`A`&&t<=`Z`;return!!(n&&o||(n||r)&&t>=`0`&&t<=`9`||i&&(a||o))}function be(e,t){return k(new Set(e),new Set(t))}function k(e,t){if(e.size===0&&t.size===0)return 1;if(e.size===0||t.size===0)return 0;let[n,r]=e.size<=t.size?[e,t]:[t,e],i=0;for(let e of n)r.has(e)&&i++;return i/(e.size+t.size-i)}function xe(e,t){return be(O(e),O(t))}const A=e=>new Set(O(e));function Se(e,t){return j(A,e,t)}function Ce(e,t){return M(A,e,t)}function we(e,t){return De(A,e,t)}function Te(e,t){if(e===t)return!0;let[n,r]=e.length<=t.length?[e,t]:[t,e];return Ee(n,r)}function Ee(e,t){return t===`${e}s`||t===`${e}es`?!0:e.endsWith(`y`)&&t===`${e.slice(0,-1)}ies`}function j(e,t,n){return k(e(t),e(n))}function M(e,t,n){return k(e(R(t)),e(R(n)))}function De(e,t,n){let r=L(t),i=L(n);return r===``&&i===``?!0:r===``||i===``?!1:r===i?!0:N(r,i,e)}function N(e,t,n){let r=e.split(`.`),i=t.split(`.`);return r.length===i.length?r.every((e,t)=>{let r=i[t];return r===void 0?!1:e===r?!0:Oe(n(e),n(r))}):!1}function Oe(e,t){if(e.size!==t.size||e.size>32)return!1;let n=[...t],r=new Map;for(let t of e)if(!P(t,n,r,new Set))return!1;return!0}function P(e,t,n,r){for(let i of t){if(r.has(i)||!Te(e,i))continue;r.add(i);let a=n.get(i);if(a===void 0||P(a,t,n,r))return n.set(i,e),!0}return!1}function ke(e,t,n){let r=e.slice(0,F(e)),i=t.slice(0,F(t));if(r===i)return!0;let a=n(r),o=n(i);if(a.size!==o.size||a.size>32)return!1;for(let e of a){let t=!1;for(let n of o)if(Te(e,n)){t=!0;break}if(!t)return!1}return!0}function F(e){let t=e.indexOf(`.`);return t<0?e.length:t}function I(){let e=new Map,t=t=>{let n=e.get(t);if(n!==void 0)return n;let r=new Set(O(t));return e.set(t,r),r},n=new Map,r=e=>{let t=n.get(e);if(t!==void 0)return t;let r=L(e);return n.set(e,r),r};return{name:(e,n)=>j(t,e,n),member:(e,n)=>M(t,e,n),ownersCompatible:(e,n)=>{let i=r(e),a=r(n);return i===a?!0:i===``||a===``||!ke(i,a,t)?!1:N(i,a,t)}}}function L(e){let t=e.indexOf(`::`);if(t>=0)return e.slice(0,t);let n=e.lastIndexOf(`.`);return n>=0?e.slice(0,n):``}function R(e){let t=e.indexOf(`::`);if(t>=0)return e.slice(t+2);let n=e.lastIndexOf(`.`);return n>=0?e.slice(n+1):e}function z(e){e.sort(Ae);let t=new Set,n=new Set,r=[];for(let i of e)t.has(i.base.id)||n.has(i.head.id)||(t.add(i.base.id),n.add(i.head.id),r.push(i));return{pairs:r,baseIds:t,headIds:n}}function Ae(e,t){return e.score===t.score?e.base.id===t.base.id?e.head.id<t.head.id?-1:+(e.head.id>t.head.id):e.base.id<t.base.id?-1:1:t.score-e.score}function B(e,t){return e.filter(e=>!t.has(e.id))}function V(e,t){let n=new Map;for(let e of t)n.set(e.id,e);let r=[],i=[],a=new Set;for(let t of e){let e=n.get(t.id);e===void 0?i.push(t):(r.push({base:t,head:e,rationale:`id-match`}),a.add(t.id))}return{matched:r,remainingBase:i,remainingHead:t.filter(e=>!a.has(e.id))}}function H(e,t,n){if(n===null||n.size===0)return{matched:[],remainingBase:[...e],remainingHead:[...t]};let r=new Map;for(let e of t)r.set(e.id,e);let i=new Map;for(let t of e){let e=n.get(t.source.file);if(e===void 0)continue;let a=Me(t.id,t.source.file,e);if(a===null)continue;let o=r.get(a);if(o===void 0)continue;let s=i.get(a);s===void 0?i.set(a,{head:o,bases:[t]}):s.bases.push(t)}let a=[],o=new Set,s=new Set;for(let{head:e,bases:t}of i.values()){let n=je(t);a.push({base:n,head:e,rationale:`git-rename`}),o.add(n.id),s.add(e.id)}return{matched:a,remainingBase:B(e,o),remainingHead:B(t,s)}}function je(e){let t=e[0];for(let n of e)n.id<t.id&&(t=n);return t}function Me(e,t,n){let r=e.indexOf(`:`),i=e.indexOf(`#`);return r<0||i<0||i<r||e.slice(r+1,i)!==t?e:o({language:e.slice(0,r),file:n,qualifiedName:e.slice(i+1)})}function U(e,t){let n=W(e),r=W(t),i=I(),a=[];for(let[e,t]of r){let r=n.get(e);r!==void 0&&a.push(...Ne(r,t,i))}let o=new Set(a.map(e=>e.base.id)),s=new Set(a.map(e=>e.head.id));return{matched:a,remainingBase:B(e,o),remainingHead:B(t,s)}}function W(e){let t=new Map;for(let n of e){if(n.dropped||n.fingerprint.logic===`000000000000`)continue;let e=t.get(n.fingerprint.logic)??[];e.push(n),t.set(n.fingerprint.logic,e)}return t}function Ne(e,t,n){let r=[...e],i=[...t],a=[];for(;r.length>0&&i.length>0;){let e=r.length===1?r[0]:void 0;if(e!==void 0){let t=Pe(e,i,n);if(t===void 0)break;a.push({base:e,head:t,rationale:`logic-fingerprint`});break}let t=[];for(let e of r)for(let r of i){let i=n.name(e.name,r.name);i>=.85&&t.push({base:e,head:r,score:i})}let o=z(t);if(o.pairs.length===0)break;for(let{base:e,head:t}of o.pairs)a.push({base:e,head:t,rationale:`logic-fingerprint+name-disambiguation`});r=B(r,o.baseIds),i=B(i,o.headIds)}return a}function Pe(e,t,n){let r;for(let i of t){let t=n.name(e.name,i.name);if(r===void 0||t>r.score){r={head:i,score:t};continue}t===r.score&&i.id<r.head.id&&(r={head:i,score:t})}return r?.head}function G(e,t){let n=new Map;for(let t of e){if(t.dropped||!J(t.name))continue;let e=Fe(t),r=n.get(e)??{members:[],byToken:new Map},i=r.members.length;r.members.push(t);for(let e of q(t.name)){let t=r.byToken.get(e)??[];t.push(i),r.byToken.set(e,t)}n.set(e,r)}let r=new Map;for(let e of n.values())r.set(e,new Int32Array(e.members.length));let i=I(),a=[],o=0;for(let e of t){if(e.dropped||e.signature===null||e.signature===void 0||!J(e.name))continue;let t=n.get(Fe(e));if(t===void 0)continue;let s=Re(e.name),c=Ie(s),l=q(e.name),u=0;for(let e of l)u+=t.byToken.get(e)?.length??0;if(u>=t.members.length){for(let n of t.members)K(n,e,i,c,s,a);continue}let d=r.get(t);if(d!==void 0){o++;for(let n of l)for(let r of t.byToken.get(n)??[]){if(d[r]===o)continue;d[r]=o;let n=t.members[r];n!==void 0&&K(n,e,i,c,s,a)}}}let s=z(a);return{matched:s.pairs.map(({base:e,head:t})=>({base:e,head:t,rationale:`name-signature`})),remainingBase:B(e,s.baseIds),remainingHead:B(t,s.headIds)}}function K(e,t,n,r,i,a){let o=n.member(e.name,t.name);if(o<r||!n.ownersCompatible(e.name,t.name))return;let s=.5*o+.3*E(e.signature??null,t.signature??null)+.2*Le;s>=i&&a.push({base:e,head:t,score:s})}function Fe(e){let t=e.signature===null||e.signature===void 0?`no-sig`:`has-sig`;return`${e.kind}::${t}`}function Ie(e){return 2*(e-.5)}function q(e){let t=O(R(e));return t.length===0?[` none`]:t}const Le=1;function Re(e){let t=O(R(e)).length;return t<=1?1:t===2?.95:.85}function J(e){return O(e).length>1}function Y(e,t){let n=e.filter(e=>e.dropped),r=t.filter(e=>e.dropped),i=[];for(let e of[Ue,We])i.push(...Ve(n,r,e));let a=ze(i);return{matched:a.map(({base:e,head:t})=>({base:e,head:t,rationale:`dropped-weak-match`})),remainingBase:B(e,new Set(a.map(e=>e.base.id))),remainingHead:B(t,new Set(a.map(e=>e.head.id)))}}function ze(e){let t=[...e].sort(Be),n=new Map,r=new Map;for(let[e,i]of t.entries())X(n,i.base.id,e),X(r,i.head.id,e);let i=e=>{let i=t[e];return i===void 0?[]:[...n.get(i.base.id)??[],...r.get(i.head.id)??[]].filter(t=>t!==e)},a=t.map(()=>!1),o=[],s=e=>{let n=e,r=!0;for(;!a[n];){a[n]=!0;let e=t[n];r&&e!==void 0&&o.push(e),r=!r;let s=i(n).find(e=>a[e]===!1);if(s===void 0)return;n=s}};for(let[e]of t.entries())!a[e]&&i(e).length<=1&&s(e);for(let[e]of t.entries())a[e]||s(e);return o}function Be(e,t){return e.base.id===t.base.id?e.head.id<t.head.id?-1:+(e.head.id>t.head.id):e.base.id<t.base.id?-1:1}function X(e,t,n){let r=e.get(t);r===void 0?e.set(t,[n]):r.push(n)}function Ve(e,t,n){let r=He(e,n),i=He(t,n),a=[];for(let[e,t]of r){let n=i.get(e);n!==void 0&&a.push({base:t,head:n})}return a}function He(e,t){let n=new Map,r=new Set;for(let i of e){let e=t(i);if(!r.has(e)){if(n.has(e)){n.delete(e),r.add(e);continue}n.set(e,i)}}return n}function Ue(e){return`${e.kind}/${R(e.name)}`}function We(e){return`${e.kind}/${Ge(e.source.file)}`}function Ge(e){let t=e.lastIndexOf(`/`);return t>=0?e.slice(t+1):e}function Ke(e){let t=$e(e.changes);if(t.length===0)return[];let n=new Set(t);return r(t,tt(e.baseCallEdges,e.headCallEdges,n),e=>e).map(Je)}function qe(e){return`slice:${e}`}function Je(e){let t=e[0];if(t===void 0)throw new s(`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`});let n={id:qe(t),members:[...e]};return Z(n),n}function Ye(e){let t=e.members[0];if(t===void 0){let t=Qe(e.id);throw new s(t.message,{code:`slice-invariant-violated`,value:t.subject})}return t}function Xe(e){if(typeof e!=`object`||!e)return{kind:`malformed-shape`,subject:`<not an object>`,message:`Expected a SliceRecord object; got ${e===null?`null`:typeof e}.`};let{id:t,members:n}=e,r=typeof t==`string`?t:`<missing id>`;if(typeof t!=`string`)return{kind:`malformed-shape`,subject:r,message:`SliceRecord ${r}: id must be a string; got ${typeof t}.`};if(!Array.isArray(n)||n.some(e=>typeof e!=`string`))return{kind:`malformed-shape`,subject:r,message:`SliceRecord ${r}: members must be an array of strings.`};let i=n[0];if(i===void 0)return Qe(r);let a=Ze(i);if(a!==null)return{kind:`anchor-in-reserved-namespace`,subject:r,message:`SliceRecord anchor "${i}" uses the reserved language token "${a}", so its Slice id would repeat the prefix (ir-schema.md §3.5, slice-view.md §7.5).`};for(let e=1;e<n.length;e++){let t=n[e-1],i=n[e];if(!(t<i))return{kind:`members-unordered`,subject:r,message:`SliceRecord ${r}: members[] is not in strictly ascending order at index ${e} ("${i}" follows "${t}"), so members[0] is not necessarily the anchor (slice-view.md §8.2 for the order, §11.1 for uniqueness).`}}let o=qe(i);return t===o?null:{kind:`id-not-derived`,subject:r,message:`SliceRecord id "${t}" is not derived from the anchor "${i}"; expected "${o}" (slice-view.md §7.1).`}}function Ze(e){let n=e.indexOf(`:`);if(n<0)return null;let r=e.slice(0,n);return t.has(r)?r:null}function Qe(e){return{kind:`members-empty`,subject:e,message:`SliceRecord ${e}: members[] is empty, so the Slice has no anchor (slice-view.md §11.1 requires at least one member).`}}function Z(e){let t=Xe(e);if(t!==null)throw new s(t.message,{code:`slice-invariant-violated`,value:t.subject})}function $e(e){let t=[];for(let n of e){let e=et(n);e!==null&&t.push(e)}return t}function et(e){switch(e.status){case`added`:return e.symbol.id;case`removed`:return e.symbol.id;case`unknown`:return e.symbol.id;case`changed`:case`moved+changed`:case`dropped-toggled`:return e.after.id;case`moved`:return null}}function tt(e,t,n){let r=[];for(let t of e)nt(t,n,r);for(let e of t)nt(e,n,r);return r}function nt(e,t,n){!t.has(e.from)||!t.has(e.to)||n.push([e.from,e.to])}function rt(e,t){if(e.dropped!==t.dropped)return`dropped-toggled`;let n=e.source.file!==t.source.file||e.id!==t.id,r=e.fingerprint.api!==t.fingerprint.api||e.fingerprint.logic!==t.fingerprint.logic||e.fingerprint.syntax!==t.fingerprint.syntax;return n&&r?`moved+changed`:n?`moved`:r?`changed`:`unchanged`}function it(e){return e.dropped?`to-dropped`:`to-kept`}const at={name:`aburi`,version:`0.0.0`};function ot(e){ut(e.baseIR,`baseIR`),ut(e.headIR,`headIR`),ct(e.baseIR,e.headIR);let t=V(e.baseIR.symbols,e.headIR.symbols),n=H(t.remainingBase,t.remainingHead,e.gitRenames??null),r=U(n.remainingBase,n.remainingHead),a=G(r.remainingBase,r.remainingHead),o=Y(a.remainingBase,a.remainingHead),s=[...t.matched,...n.matched,...r.matched,...a.matched,...o.matched],d={unknown:0,depsUnknown:0,added:0,removed:0,moved:0,movedChanged:0,changed:0,droppedToggled:0,unchanged:0,droppedAdded:0,droppedRemoved:0,componentsAdded:0,componentsRemoved:0,componentsChanged:0,depsAdded:0,depsRemoved:0},f=0,p=[];for(let t of s){let n=rt(t.base,t.head);if(n===`unchanged`){d.unchanged++;continue}if(n===`dropped-toggled`){d.droppedToggled++,p.push({status:`dropped-toggled`,before:t.base,after:t.head,direction:it(t.head)});continue}if(n===`moved`){d.moved++,p.push({status:`moved`,before:t.base,after:t.head,rationale:t.rationale});continue}if(n===`changed`){d.changed++,p.push({status:`changed`,before:t.base,after:t.head,delta:C(t.base,t.head,e.delta??{})});continue}d.movedChanged++,p.push({status:`moved+changed`,before:t.base,after:t.head,rationale:t.rationale,delta:C(t.base,t.head,e.delta??{})})}let m=o.remainingHead,h=o.remainingBase,g=l(e.baseIR),_=l(e.headIR),v=_.lostFiles,y=g.lostFiles;for(let e of m){if(e.dropped){d.droppedAdded++;continue}let t=y.get(e.source.file);if(t!==void 0){f++,p.push({status:`unknown`,symbol:e,absentFrom:`base`,reason:t});continue}d.added++,p.push({status:`added`,symbol:e})}for(let e of h){if(e.dropped){d.droppedRemoved++;continue}let t=v.get(e.source.file);if(t!==void 0){f++,p.push({status:`unknown`,symbol:e,absentFrom:`head`,reason:t});continue}d.removed++,p.push({status:`removed`,symbol:e})}let b=c(e.baseIR.components,e.headIR.components);d.componentsAdded=b.added.length,d.componentsRemoved=b.removed.length,d.componentsChanged=b.changed.length;let x=u(e.baseIR.dependencies,e.headIR.dependencies,{base:g,head:_});d.depsAdded=x.added.length,d.depsRemoved=x.removed.length,d.depsUnknown=x.unknown.length,d.unknown=f,p.sort(ht);let S=Ke({changes:p,baseCallEdges:i(e.baseIR),headCallEdges:i(e.headIR)});return{$schema:`https://aburi.kage1020.com/schema/aburi.diff.v1.json`,generator:e.generator??at,base:e.base,head:e.head,summary:d,symbols:p,components:b,dependencies:x,slices:S,notCompared:st(y,v)}}function st(e,t){let n=[];for(let[r,i]of e){let e=t.get(r);e!==void 0&&n.push({path:r,baseReason:i,headReason:e})}return n.sort((e,t)=>e.path<t.path?-1:+(e.path>t.path))}function ct(e,t){if(e.$schema!==t.$schema)throw new s(`Base IR schema "${e.$schema}" does not match head IR schema "${t.$schema}"; a diff across schema versions is not supported.`,{code:`schema-mismatch`,value:e.$schema})}const Q=e=>e.join(``),lt=[{field:`symbols`,identityFields:[`id`],keyOf:Q,noun:`id`,show:Q,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)`},{field:`components`,identityFields:[`id`],keyOf:Q,noun:`id`,show:Q,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)`},{field:`dependencies`,identityFields:f,keyOf:p,noun:`(from, to, via) triple`,show:e=>`(${e.join(`, `)})`,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)`}];function ut(e,t){let r=n(e),i=r[0];if(i!==void 0){let e=dt(t,i.subject),n=r.length-1,a=n>0?` (and ${n} more)`:``;throw new s(`${e}: ${i.message}${a}.`,{code:`ir-shape-invalid`,value:e,violations:r.map(e=>({...e,subject:dt(t,e.subject)}))})}if(e.$schema.length===0)throw $(t,`${t}: "$schema" is empty, not a schema URL.`);for(let n of lt)ft(e[n.field],`${t}.${n.field}`,n)}function dt(t,n){return n===e?t:`${t}.${n}`}function ft(e,t,n){if(!Array.isArray(e))throw $(t,`${t} must be an array.`);let r=new Map;for(let[i,a]of e.entries()){let e=`${t}[${i}]`,o=pt(a,e,n),c=n.keyOf(o),l=r.get(c);if(l===void 0){r.set(c,i);continue}let u=n.show(o);throw new s(`${e} repeats the ${n.noun} "${u}" first seen at index ${l}; ${n.consequence}.`,{code:`ir-identity-collision`,value:u})}}function pt(e,t,n){if(typeof e!=`object`||!e||Array.isArray(e))throw $(t,`${t} must be an object; got ${mt(e)}.`);let r=[];for(let i of n.identityFields){let n=e[i];if(typeof n!=`string`)throw $(`${t}.${i}`,`${t}.${i} must be a string; got ${mt(n)}.`);r.push(n)}return r}function $(e,t){return new s(t,{code:`ir-shape-invalid`,value:e})}function mt(e){return e===void 0?`undefined`:e===null?`null`:Array.isArray(e)?`an array`:`a ${typeof e}`}function ht(e,t){if(e.status!==t.status)return e.status<t.status?-1:1;let n=gt(e),r=gt(t);return n<r?-1:+(n>r)}function gt(e){return e.status===`added`||e.status===`removed`||e.status===`unknown`?e.symbol.id:e.after.id}function _t(e,t={}){return a(e,t)}export{S as DEFAULT_LINE_FUZZ,s as DiffError,ee as MAX_LINE_FUZZ,te as MIN_LINE_FUZZ,Z as assertSliceRecordInvariant,ot as buildDiff,rt as classifyStatus,Ke as computeSlices,C as computeSymbolDelta,l as dependencySideView,c as diffComponents,u as diffDependencies,it as dropDirection,be as jaccard,xe as jaccardTokens,R as lastSegment,Y as matchStageDroppedWeak,H as matchStageGitRename,V as matchStageId,U as matchStageLogicFingerprint,G as matchStageNameSignature,Ce as memberSimilarity,Se as nameSimilarity,we as ownersAreCompatible,E as signatureSimilarity,Ye as sliceAnchor,Xe as sliceRecordViolation,O as tokenizeName,_t as writeCanonicalDiff};
|