@plannotator/sem-jiff 0.0.0-stage → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/CHANGELOG.md +77 -0
  2. package/LICENSE-APACHE +191 -0
  3. package/LICENSE-MIT +21 -0
  4. package/README.md +122 -2
  5. package/THIRD-PARTY-NOTICES +367 -0
  6. package/dist/candidate.d.ts +14 -0
  7. package/dist/candidate.js +1 -0
  8. package/dist/classifier.d.ts +25 -0
  9. package/dist/classifier.js +32 -0
  10. package/dist/copy-wasm-bin.d.ts +2 -0
  11. package/dist/copy-wasm-bin.js +11 -0
  12. package/dist/copy-wasm.d.ts +3 -0
  13. package/dist/copy-wasm.js +43 -0
  14. package/dist/coverage.d.ts +7 -0
  15. package/dist/coverage.js +43 -0
  16. package/dist/edits.d.ts +10 -0
  17. package/dist/edits.js +230 -0
  18. package/dist/extract.d.ts +5 -0
  19. package/dist/extract.js +24 -0
  20. package/dist/grammars.d.ts +22 -0
  21. package/dist/grammars.js +37 -0
  22. package/dist/index.d.ts +79 -0
  23. package/dist/index.js +581 -0
  24. package/dist/inline.d.ts +21 -0
  25. package/dist/inline.js +959 -0
  26. package/dist/languages.d.ts +2 -0
  27. package/dist/languages.js +28 -0
  28. package/dist/linediff.d.ts +28 -0
  29. package/dist/linediff.js +205 -0
  30. package/dist/opinions.d.ts +84 -0
  31. package/dist/opinions.js +201 -0
  32. package/dist/pairing.d.ts +10 -0
  33. package/dist/pairing.js +269 -0
  34. package/dist/parse.d.ts +119 -0
  35. package/dist/parse.js +1293 -0
  36. package/dist/pierre-types.d.ts +101 -0
  37. package/dist/pierre-types.js +5 -0
  38. package/dist/runtime.d.ts +48 -0
  39. package/dist/runtime.js +60 -0
  40. package/dist/structure.d.ts +23 -0
  41. package/dist/structure.js +1111 -0
  42. package/dist/summary.d.ts +19 -0
  43. package/dist/summary.js +15 -0
  44. package/dist/symbol-types.d.ts +18 -0
  45. package/dist/symbol-types.js +1 -0
  46. package/dist/symbols.d.ts +6 -0
  47. package/dist/symbols.js +458 -0
  48. package/dist/syntax.d.ts +69 -0
  49. package/dist/syntax.js +450 -0
  50. package/dist/textdiff.d.ts +15 -0
  51. package/dist/textdiff.js +64 -0
  52. package/dist/textmoves.d.ts +8 -0
  53. package/dist/textmoves.js +143 -0
  54. package/package.json +108 -4
  55. package/src/candidate.ts +10 -0
  56. package/src/grammars.ts +44 -0
  57. package/src/opinions.ts +271 -0
  58. package/wasm/SHA256SUMS +12 -0
  59. package/wasm/tree-sitter-c_sharp.wasm +0 -0
  60. package/wasm/tree-sitter-go.wasm +0 -0
  61. package/wasm/tree-sitter-java.wasm +0 -0
  62. package/wasm/tree-sitter-kotlin.wasm +0 -0
  63. package/wasm/tree-sitter-php.wasm +0 -0
  64. package/wasm/tree-sitter-python.wasm +0 -0
  65. package/wasm/tree-sitter-ruby.wasm +0 -0
  66. package/wasm/tree-sitter-rust.wasm +0 -0
  67. package/wasm/tree-sitter-swift.wasm +0 -0
  68. package/wasm/tree-sitter-tsx.wasm +0 -0
  69. package/wasm/tree-sitter-typescript.wasm +0 -0
  70. package/wasm/web-tree-sitter.wasm +0 -0
package/dist/index.js ADDED
@@ -0,0 +1,581 @@
1
+ // Entry point: two versions of a file in, semantic operations out (the operation types).
2
+ import { detectExtracted } from "./extract.js";
3
+ import { DEFAULT_INLINE_OPTIONS, detectInlined } from "./inline.js";
4
+ import { LANGUAGES, withTrees } from "./parse.js";
5
+ import { detectStructure } from "./structure.js";
6
+ import { uncoveredChanges } from "./coverage.js";
7
+ import { endLine, startLine } from "./syntax.js";
8
+ import { detectEdits, replacementsFromBlocks } from "./edits.js";
9
+ import { alignedLineDiff, diffLines, toPatch, unchangedLinePairs } from "./linediff.js";
10
+ import { computeTextDiff, WORK_PER_SECOND } from "./textdiff.js";
11
+ import { detectTextMoves } from "./textmoves.js";
12
+ import { attachSymbols } from "./symbols.js";
13
+ export { languageForPath } from "./languages.js";
14
+ export { configure } from "./runtime.js";
15
+ export { reviewSummary, READ_KINDS, SKIM_KINDS } from "./summary.js";
16
+ import { flags, rule, trial } from "./runtime.js";
17
+ import { OpinionKeyError } from "./opinions.js";
18
+ const DEFAULT_MAX_CHARS = 2_000_000;
19
+ const DEFAULT_TIME_BUDGET_MS = Number.POSITIVE_INFINITY;
20
+ /**
21
+ * The operation types allow each line to belong to at most one operation per side.
22
+ * Operations earlier in the list win; later ones keep their spans but lose
23
+ * the lines already taken.
24
+ */
25
+ function assignLines(ops) {
26
+ const taken = { old: new Set(), new: new Set() };
27
+ return ops.map((op) => {
28
+ const lines = { old: [], new: [] };
29
+ for (const side of ['old', 'new']) {
30
+ for (const r of op.lines[side]) {
31
+ let start = -1;
32
+ for (let l = r.start; l <= r.end + 1; l++) {
33
+ const free = l <= r.end && !taken[side].has(l);
34
+ if (free && start < 0)
35
+ start = l;
36
+ if (!free && start >= 0) {
37
+ lines[side].push({ ...r, start, end: l - 1 });
38
+ start = -1;
39
+ }
40
+ }
41
+ for (let l = r.start; l <= r.end; l++)
42
+ taken[side].add(l);
43
+ }
44
+ lines[side].sort((a, b) => a.start - b.start);
45
+ }
46
+ return { ...op, lines };
47
+ });
48
+ }
49
+ /**
50
+ * A plain edit is worth showing only if it still owns a non-blank line (blank lines
51
+ * around moves are noise), or a blank line inside a multi-line string, where it is
52
+ * part of the string's value.
53
+ */
54
+ function ownsText(op, oldLines, newLines, inString) {
55
+ const any = (ranges, lines, keep) => ranges.some((r) => lines.slice(r.start - 1, r.end).some((l, i) => l.trim() !== '' || keep.has(r.start + i)));
56
+ return any(op.lines.old, oldLines, inString.old) || any(op.lines.new, newLines, inString.new);
57
+ }
58
+ /**
59
+ * Changed lines that differ only in their indentation, anywhere (also inside
60
+ * nested functions and callbacks, which are not declarations): formatting.
61
+ * Not in Python, where indentation is meaning, nor inside multi-line strings.
62
+ */
63
+ function reindented(blocks, oldLines, newLines, inString, language) {
64
+ if (language === 'python')
65
+ return [];
66
+ const out = [];
67
+ for (const b of blocks) {
68
+ if (!b.old || !b.new || b.old.end - b.old.start !== b.new.end - b.new.start)
69
+ continue;
70
+ let ok = false;
71
+ for (let i = 0; i <= b.old.end - b.old.start; i++) {
72
+ const lo = b.old.start + i;
73
+ const ln = b.new.start + i;
74
+ const x = oldLines[lo - 1] ?? '';
75
+ const y = newLines[ln - 1] ?? '';
76
+ if (x.trim() !== y.trim() || inString.old.has(lo) || inString.new.has(ln)) {
77
+ ok = false;
78
+ break;
79
+ }
80
+ if (x.trim())
81
+ ok = true;
82
+ }
83
+ if (!ok)
84
+ continue;
85
+ const pair = { old: { start: b.old.start, end: b.old.end }, new: { start: b.new.start, end: b.new.end } };
86
+ out.push({
87
+ type: 'reformatted',
88
+ spans: [
89
+ {
90
+ role: 'root',
91
+ relation: 'mapped',
92
+ old: [{ start: { line: pair.old.start, character: 0 }, end: { line: pair.old.end + 1, character: 0 } }],
93
+ new: [{ start: { line: pair.new.start, character: 0 }, end: { line: pair.new.end + 1, character: 0 } }],
94
+ linePairs: [pair],
95
+ },
96
+ ],
97
+ lines: { old: [{ ...pair.old, spanIndex: 0 }], new: [{ ...pair.new, spanIndex: 0 }] },
98
+ });
99
+ }
100
+ return out;
101
+ }
102
+ /**
103
+ * Keep every operation inside the real lines. Half-written code can put a node past
104
+ * the end (the parser supplies a missing `}` there), and an emptied file has no
105
+ * line 1. An edit left without new lines is a deletion; an operation left with
106
+ * nothing is dropped. Indices into the list shift, so this runs on the final list.
107
+ */
108
+ function withinFile(ops, oldCount, newCount) {
109
+ const count = { old: oldCount, new: newCount };
110
+ const out = [];
111
+ for (const op of ops) {
112
+ const lines = { old: [], new: [] };
113
+ for (const side of ['old', 'new']) {
114
+ for (const r of op.lines[side]) {
115
+ const otherCount = count[side === 'old' ? 'new' : 'old'];
116
+ // Against an empty file there is no line to attach to: the `{ empty: true }` attachment.
117
+ if (r.attachment && 'line' in r.attachment && otherCount === 0)
118
+ r.attachment = { empty: true };
119
+ else if (r.attachment && 'line' in r.attachment && r.attachment.line > otherCount)
120
+ r.attachment = { line: otherCount, edge: 'after' };
121
+ const end = Math.min(r.end, count[side]);
122
+ if (r.start <= end)
123
+ lines[side].push({ ...r, end });
124
+ }
125
+ }
126
+ if (!lines.old.length && !lines.new.length)
127
+ continue;
128
+ const pairsInside = op.spans.every((sp) => !('linePairs' in sp) || (sp.linePairs ?? []).every((p) => p.old.end <= count.old && p.new.end <= count.new && p.old.start <= p.old.end && p.new.start <= p.new.end));
129
+ if (pairsInside && lines.old.length === op.lines.old.length && lines.new.length === op.lines.new.length && lines.old.every((l, i) => l.end === op.lines.old[i].end) && lines.new.every((l, i) => l.end === op.lines.new[i].end)) {
130
+ out.push(op);
131
+ continue;
132
+ }
133
+ const clip = (rs, side) => rs?.filter((r) => r.start.line <= count[side]).map((r) => (r.end.line > count[side] + 1 ? { ...r, end: { line: count[side] + 1, character: 0 } } : r));
134
+ const spans = op.spans.map((sp) => {
135
+ const x = sp;
136
+ const pairs = 'linePairs' in sp ? { linePairs: (sp.linePairs ?? []).filter((p) => p.old.end <= count.old && p.new.end <= count.new && p.old.start <= p.old.end && p.new.start <= p.new.end) } : {};
137
+ return { ...sp, ...(x.old ? { old: clip(x.old, 'old') } : {}), ...(x.new ? { new: clip(x.new, 'new') } : {}), ...pairs };
138
+ });
139
+ if (op.type === 'edited' && !lines.new.length) {
140
+ const attach = newCount ? { line: newCount, edge: 'after' } : { empty: true };
141
+ const r = { start: { line: lines.old[0].start, character: 0 }, end: { line: lines.old.at(-1).end + 1, character: 0 } };
142
+ out.push({ type: 'deleted', spans: [{ role: 'root', relation: 'removed', old: [r] }], lines: { old: lines.old.map((l) => ({ start: l.start, end: l.end, spanIndex: 0, attachment: attach })), new: [] } });
143
+ continue;
144
+ }
145
+ out.push({ ...op, spans, lines });
146
+ }
147
+ return out;
148
+ }
149
+ /** Deepest bracket nesting in the text (strings and comments included: an estimate). */
150
+ function nestingDepth(text) {
151
+ let depth = 0;
152
+ let max = 0;
153
+ for (let i = 0; i < text.length; i++) {
154
+ const c = text.charCodeAt(i);
155
+ if (c === 123 || c === 40 || c === 91)
156
+ max = Math.max(max, ++depth);
157
+ else if (c === 125 || c === 41 || c === 93)
158
+ depth = Math.max(0, depth - 1);
159
+ }
160
+ return max;
161
+ }
162
+ /** Minified or bundled: some line over 1,000 characters and an average over 200. */
163
+ function minified(text) {
164
+ const lines = text.split('\n');
165
+ return lines.some((l) => l.length > 1000) && text.length / lines.length > 200;
166
+ }
167
+ /** Lines strictly inside multi-line string literals (template strings, raw strings, text blocks...). */
168
+ function stringInteriors(root, language) {
169
+ const out = new Set();
170
+ const lines = language === 'php' ? root.text.split('\n') : [];
171
+ const walk = (n) => {
172
+ // PHP's HTML around `<?php ... ?>` is output: every line holding some of it, even one space, is kept as written.
173
+ if (language === 'php' && n.type === 'text') {
174
+ for (let row = n.startPosition.row; row <= n.endPosition.row; row++) {
175
+ const from = row === n.startPosition.row ? n.startPosition.column : 0;
176
+ const to = Math.min(row === n.endPosition.row ? n.endPosition.column : Infinity, (lines[row] ?? '').length);
177
+ if (to > from)
178
+ out.add(row + 1);
179
+ }
180
+ return;
181
+ }
182
+ if (n.endPosition.row === n.startPosition.row)
183
+ return;
184
+ // Ruby's multi-line regexes and backtick commands keep their whitespace too.
185
+ if ((/string|template|text_block|heredoc|nowdoc/.test(n.type) || (language === 'ruby' && /^(regex|subshell)$/.test(n.type))) && !/content|fragment/.test(n.type)) {
186
+ // Rust drops the leading whitespace of a line continued with a backslash
187
+ // ("...\\\n more"), so re-indenting that line leaves the string as it was.
188
+ const lines = n.text.split('\n');
189
+ const continued = (k) => language === 'rust' && n.type === 'string_literal' && /(^|[^\\])(\\\\)*\\$/.test(lines[k - 1] ?? '');
190
+ for (let l = startLine(n) + 1; l <= endLine(n); l++)
191
+ if (!continued(l - startLine(n)))
192
+ out.add(l);
193
+ return;
194
+ }
195
+ for (const c of n.children)
196
+ if (c)
197
+ walk(c);
198
+ };
199
+ walk(root);
200
+ return out;
201
+ }
202
+ const candidateKey = (c) => [c.kind, c.helper, c.caller, c.code.helper, c.code.caller, c.code.callerNew].join('\u0000');
203
+ function fnv(text, seed) {
204
+ let h = seed >>> 0;
205
+ for (let i = 0; i < text.length; i++)
206
+ h = Math.imul(h ^ text.charCodeAt(i), 0x01000193) >>> 0;
207
+ return h.toString(16).padStart(8, '0');
208
+ }
209
+ /** A stable id for a candidate: the same code always gets the same id. */
210
+ export function candidateId(c) {
211
+ const key = candidateKey(c);
212
+ return fnv(key, 0x811c9dc5) + fnv(key, 0x050c5d1f);
213
+ }
214
+ function opinionState(e) {
215
+ if (e instanceof OpinionKeyError)
216
+ return e.status === 402 ? 'noCredit' : 'refusedKey';
217
+ return 'failed';
218
+ }
219
+ /**
220
+ * A move with edits must still be mostly the same code. Two blocks sharing under a fifth of their
221
+ * tokens are different code that happens to sit in the same place (an import paired with another
222
+ * import, a function whose body was replaced and kept only its name): their lines are plain changes.
223
+ * Audited on real commits: below 0.2, 4 of 22 wrong labels and 0 of 240 correct ones.
224
+ */
225
+ const MOVED_WITH_EDIT_MIN_SIMILARITY = 0.2;
226
+ function alike(op, oldLines, newLines) {
227
+ const words = (lines, rs) => rs.flatMap((r) => lines.slice(r.start - 1, r.end)).join('\n').match(/[A-Za-z_$][\w$]*|\d+|\S/g) ?? [];
228
+ const a = words(oldLines, op.lines.old);
229
+ const b = words(newLines, op.lines.new);
230
+ const count = new Map();
231
+ for (const x of a)
232
+ count.set(x, (count.get(x) ?? 0) + 1);
233
+ let common = 0;
234
+ for (const y of b) {
235
+ const n = count.get(y) ?? 0;
236
+ if (n > 0) {
237
+ common++;
238
+ count.set(y, n - 1);
239
+ }
240
+ }
241
+ return (2 * common) / (a.length + b.length || 1) >= MOVED_WITH_EDIT_MIN_SIMILARITY;
242
+ }
243
+ /**
244
+ * A move whose lines sit in a different context afterwards (another namespace, past a visibility
245
+ * line) changes what the code means: it is an edit, so the move is dropped and its lines stay plain changes.
246
+ */
247
+ function contextChanged(op, cfg, oldRoot, newRoot, oldLines, newLines, at = cfg.contextAt) {
248
+ if (!at)
249
+ return false;
250
+ // One context on each side, the same: the rule for languages without contextRuns (PHP, Ruby).
251
+ if (!cfg.contextRuns) {
252
+ const set = (root, lines, ranges) => {
253
+ const out = new Set();
254
+ for (const r of ranges)
255
+ for (let l = r.start; l <= r.end; l++)
256
+ if ((lines[l - 1] ?? '').trim())
257
+ out.add(at(root, l));
258
+ return out;
259
+ };
260
+ const b = set(oldRoot, oldLines, op.lines.old);
261
+ const a = set(newRoot, newLines, op.lines.new);
262
+ return b.size !== 1 || a.size !== 1 || [...b][0] !== [...a][0];
263
+ }
264
+ // Each range's contexts in line order, runs collapsed: a whole class moved with its companion
265
+ // object (or with its doc comment above it) reads the same sequence on both sides.
266
+ const contexts = (root, lines, ranges) => ranges.map((r) => {
267
+ const out = [];
268
+ for (let l = r.start; l <= r.end; l++) {
269
+ if (!(lines[l - 1] ?? '').trim())
270
+ continue;
271
+ const c = at(root, l);
272
+ if (out.at(-1) !== c)
273
+ out.push(c);
274
+ }
275
+ return out.join('\u0000');
276
+ });
277
+ const before = contexts(oldRoot, oldLines, op.lines.old);
278
+ const after = contexts(newRoot, newLines, op.lines.new);
279
+ return before.length !== after.length || before.some((c, i) => c !== after[i]);
280
+ }
281
+ /**
282
+ * Extends each move (moved, movedWithEdit, one range per side) over the blank lines directly above and below it on
283
+ * that side, when they are changed lines no other operation owns and not inside a multi-line string. The root span
284
+ * and its line pair follow the range, so the move draws them as its own. Nothing else changes.
285
+ */
286
+ function attachBlankSeparators(ops, changed, inString, oldLines, newLines) {
287
+ const owned = { old: new Set(), new: new Set() };
288
+ for (const op of ops)
289
+ for (const side of ['old', 'new'])
290
+ for (const l of op.lines[side])
291
+ for (let n = l.start; n <= l.end; n++)
292
+ owned[side].add(n);
293
+ for (const op of ops) {
294
+ if (op.type !== 'moved' && op.type !== 'movedWithEdit')
295
+ continue;
296
+ for (const side of ['old', 'new']) {
297
+ if (op.lines[side].length !== 1)
298
+ continue;
299
+ const r = op.lines[side][0];
300
+ const lines = side === 'old' ? oldLines : newLines;
301
+ const free = (n) => n >= 1 && n <= lines.length && !(lines[n - 1] ?? '').trim() && changed[side].has(n) && !owned[side].has(n) && !inString[side].has(n);
302
+ let start = r.start;
303
+ let end = r.end;
304
+ while (free(start - 1))
305
+ owned[side].add(--start);
306
+ while (free(end + 1))
307
+ owned[side].add(++end);
308
+ if (start === r.start && end === r.end)
309
+ continue;
310
+ r.start = start;
311
+ r.end = end;
312
+ const root = op.spans[r.spanIndex];
313
+ if (root && root.role === 'root' && 'linePairs' in root) {
314
+ const ranges = root[side];
315
+ if (ranges?.length === 1)
316
+ ranges[0] = { start: { line: start, character: 0 }, end: { line: end + 1, character: 0 } };
317
+ const pair = root.linePairs?.length === 1 ? root.linePairs[0] : undefined;
318
+ if (pair)
319
+ pair[side] = { start, end };
320
+ }
321
+ }
322
+ }
323
+ }
324
+ export async function semanticDiffFile(language, oldText, newText, name = 'file', options = {}) {
325
+ const cfg = LANGUAGES[language];
326
+ const started = performance.now();
327
+ // Bring-your-own-model second opinion: the engine is synchronous, the model is not. Collect the
328
+ // candidates first, ask once, then run the diff with the answers looked up.
329
+ let opinion;
330
+ let report;
331
+ const acceptedAnswers = new Map();
332
+ const early = [];
333
+ const skipAll = oldText.length + newText.length > (options.maxChars ?? DEFAULT_MAX_CHARS) || minified(oldText) || minified(newText) || nestingDepth(oldText) > 80 || nestingDepth(newText) > 80;
334
+ if (options.secondOpinion && !skipAll) {
335
+ const t0 = performance.now();
336
+ try {
337
+ const asked = [];
338
+ const collect = { ...DEFAULT_INLINE_OPTIONS, secondOpinion: (c) => (asked.push({ ...c, file: name }), false) };
339
+ await withTrees(language, oldText, newText, (a, b) => {
340
+ detectInlined(a.rootNode, b.rootNode, oldText, cfg, collect);
341
+ detectExtracted(a.rootNode, b.rootNode, newText, cfg, collect);
342
+ });
343
+ const rejected = new Set(options.rejectedCandidates ?? []);
344
+ // A held-back extract or inline is never shown: no model is asked about it.
345
+ const held = (c) => rule('HOLD_BACK') && !!cfg.holdBack?.has(c.kind === 'extract' ? 'extractedFunction' : 'inlinedFunction');
346
+ const toAsk = asked.filter((c) => !rejected.has(candidateId(c)) && !held(c));
347
+ const answers = toAsk.length ? await options.secondOpinion(toAsk) : [];
348
+ toAsk.forEach((c, i) => {
349
+ const a = answers[i];
350
+ const accept = typeof a === 'boolean' ? a : a?.accept === true;
351
+ if (accept)
352
+ acceptedAnswers.set(candidateKey(c), { c, a: typeof a === 'object' ? a : undefined });
353
+ });
354
+ opinion = (c) => acceptedAnswers.has(candidateKey(c));
355
+ report = { state: 'ok', asked: toAsk.length, answered: answers.length, accepted: acceptedAnswers.size, links: [] };
356
+ early.push({ pass: 'second-opinion', ms: performance.now() - t0, status: 'ok', reason: `${toAsk.length} asked, ${acceptedAnswers.size} accepted` });
357
+ }
358
+ catch (e) {
359
+ report = { state: opinionState(e), asked: 0, answered: 0, accepted: 0, links: [], reason: String(e instanceof Error ? e.message : e).slice(0, 200) };
360
+ early.push({ pass: 'second-opinion', ms: performance.now() - t0, status: 'failed', reason: String(e).slice(0, 200) });
361
+ }
362
+ }
363
+ const inlineOptions = opinion ? { ...DEFAULT_INLINE_OPTIONS, secondOpinion: opinion } : DEFAULT_INLINE_OPTIONS;
364
+ const result = await withTrees(language, oldText, newText, (a, b) => {
365
+ // Order matters: earlier passes own the lines they explain (see assignLines).
366
+ // Inline explains a whole helper's disappearance; declaration moves explain
367
+ // whole functions; text moves cover statement blocks moved anywhere else.
368
+ // Minified code has mangled names and one statement per line of thousands of
369
+ // characters: claims about extracted or inlined functions mean nothing there.
370
+ // Very deep nesting (generated code, fuzz input) makes per-statement work grow with depth.
371
+ // Last resort: a semantic pass that fails on some input (a stack overflow on a
372
+ // pathological tree) costs only its own findings; the file still gets a plain diff.
373
+ // Guardrails: a very large file, or one that has used up its time budget, gets a plain diff
374
+ // for the remaining passes instead of holding up the review. Every pass reports what it did.
375
+ const diagnostics = [...early];
376
+ const tooBig = oldText.length + newText.length > (options.maxChars ?? DEFAULT_MAX_CHARS);
377
+ const budget = options.timeBudgetMs ?? DEFAULT_TIME_BUDGET_MS;
378
+ const run = (pass, f, fallback, skip) => {
379
+ const reason = skip ?? (tooBig ? 'file too large' : performance.now() - started > budget ? 'time budget used up' : undefined);
380
+ if (reason) {
381
+ diagnostics.push({ pass, ms: 0, status: 'skipped', reason });
382
+ return fallback;
383
+ }
384
+ const t0 = performance.now();
385
+ try {
386
+ const out = f();
387
+ diagnostics.push({ pass, ms: performance.now() - t0, status: 'ok' });
388
+ return out;
389
+ }
390
+ catch (e) {
391
+ if (flags.reasons())
392
+ console.error('[semantic] pass failed:', e);
393
+ diagnostics.push({ pass, ms: performance.now() - t0, status: 'failed', reason: String(e).slice(0, 200) });
394
+ return fallback;
395
+ }
396
+ };
397
+ const noInline = minified(oldText) || minified(newText) ? 'minified code' : nestingDepth(oldText) > 80 || nestingDepth(newText) > 80 ? 'nesting too deep' : undefined;
398
+ const inlined = run('inline-extract', () => [...detectInlined(a.rootNode, b.rootNode, oldText, cfg, inlineOptions), ...detectExtracted(a.rootNode, b.rootNode, newText, cfg, inlineOptions)], [], noInline);
399
+ // Trial DUP_TIEBREAK: the structure pass breaks ties between duplicates by the line diff's unchanged lines.
400
+ const keptLines = trial('DUP_TIEBREAK') ? unchangedLinePairs(alignedLineDiff(a.rootNode, b.rootNode, cfg, diffLines(oldText), diffLines(newText)), diffLines(oldText).length) : undefined;
401
+ const structure = run('structure', () => detectStructure(a.rootNode, b.rootNode, cfg, keptLines), { operations: [], folds: [], paired: [], wordsChanged: new Set() });
402
+ const textDiff = computeTextDiff(oldText, newText, 0.4 * WORK_PER_SECOND);
403
+ const text = run('text-moves', () => detectTextMoves(textDiff, oldText, newText), { operations: [], folds: [] });
404
+ // A text move is redundant when every non-blank line it moves is already explained.
405
+ const oldLines = oldText.split('\n');
406
+ const newLines = newText.split('\n');
407
+ const inString = { old: stringInteriors(a.rootNode, language), new: stringInteriors(b.rootNode, language) };
408
+ const explained = new Set();
409
+ for (const o of [...inlined, ...structure.operations])
410
+ for (const l of o.lines.old)
411
+ for (let n = l.start; n <= l.end; n++)
412
+ explained.add(n);
413
+ // A declaration the structure pass paired is placed by it: a text move that
414
+ // carries whole declarations it kept in place sees the same swap from the
415
+ // other side (A and B swapped: structure moves B, the text diff moves A).
416
+ const covered = (op) => {
417
+ const whole = new Set();
418
+ for (const d of structure.paired)
419
+ if (op.lines.old.some((l) => l.start <= d.start && d.end <= l.end))
420
+ for (let n = d.start; n <= d.end; n++)
421
+ whole.add(n);
422
+ return op.lines.old.every((l) => {
423
+ for (let n = l.start; n <= l.end; n++)
424
+ if ((oldLines[n - 1] ?? '').trim() !== '' && !explained.has(n) && !whole.has(n))
425
+ return false;
426
+ return true;
427
+ });
428
+ };
429
+ // A statement-block move comes from VS Code's diff, but the UI draws our own
430
+ // line diff. Where the two disagree (an equal swap, a block crossing a function
431
+ // boundary) the move would claim lines the patch shows as unchanged: drop it.
432
+ const dOld = diffLines(oldText);
433
+ const dNew = diffLines(newText);
434
+ const blocks = alignedLineDiff(a.rootNode, b.rootNode, cfg, dOld, dNew);
435
+ const changed = { old: new Set(), new: new Set() };
436
+ for (const bl of blocks) {
437
+ if (bl.old)
438
+ for (let l = bl.old.start; l <= bl.old.end; l++)
439
+ changed.old.add(l);
440
+ if (bl.new)
441
+ for (let l = bl.new.start; l <= bl.new.end; l++)
442
+ changed.new.add(l);
443
+ }
444
+ const agrees = (op) => ['old', 'new'].every((side) => op.lines[side].every((r) => {
445
+ const lines = side === 'old' ? oldLines : newLines;
446
+ for (let l = r.start; l <= r.end; l++)
447
+ if ((lines[l - 1] ?? '').trim() && !changed[side].has(l))
448
+ return false;
449
+ return true;
450
+ }));
451
+ const textKept = text.operations.map((op, i) => ({ op, i })).filter(({ op }) => !covered(op) && agrees(op));
452
+ // Plain edits go last: they describe only what no semantic pass explained.
453
+ const explainedOps = [...inlined, ...structure.operations, ...textKept.map((t) => t.op), ...reindented(blocks, oldLines, newLines, inString, language)];
454
+ // Trial DROP_UNTOUCHED_MOVE: a structure move none of whose non-blank lines, on either side, is a changed line
455
+ // claims nothing the patch shows (the code only shifted against neighbours that were added or removed, or it
456
+ // sits where it was under a changed container header): drop it, before it takes any line from the passes after it.
457
+ const untouchedMoves = new Set();
458
+ if (trial('DROP_UNTOUCHED_MOVE'))
459
+ structure.operations.forEach((op, k) => {
460
+ if (op.type !== 'moved' && op.type !== 'movedWithEdit')
461
+ return;
462
+ const touched = ['old', 'new'].some((side) => op.lines[side].some((r) => {
463
+ const lines = side === 'old' ? oldLines : newLines;
464
+ for (let l = r.start; l <= r.end; l++)
465
+ if ((lines[l - 1] ?? '').trim() && changed[side].has(l))
466
+ return true;
467
+ return false;
468
+ }));
469
+ if (!touched)
470
+ untouchedMoves.add(inlined.length + k);
471
+ });
472
+ // The dropped move keeps its place in the list (folds refer to operations by index) but owns no line.
473
+ for (const i of untouchedMoves)
474
+ explainedOps[i] = { ...explainedOps[i], lines: { old: [], new: [] } };
475
+ const assigned = assignLines([...explainedOps, ...detectEdits(replacementsFromBlocks(blocks, oldText, newText), oldText, newText)]);
476
+ // Drop operations left with nothing to show: semantic ones that lost every
477
+ // line to an earlier pass (e.g. the same extract found from a second call
478
+ // site), and plain edits that own only blank lines.
479
+ const finalIndex = new Map();
480
+ const operations = [];
481
+ assigned.forEach((op, i) => {
482
+ // A move, rename or formatting change relates lines on both sides: one that lost
483
+ // either side to an earlier pass is no longer true (the safety net below then
484
+ // marks the lines it still had as plain changes).
485
+ const twoSided = op.type === 'moved' || op.type === 'movedWithEdit' || op.type === 'renamed' || op.type === 'reformatted';
486
+ const keep = i < explainedOps.length
487
+ ? twoSided
488
+ ? op.lines.old.length > 0 && op.lines.new.length > 0
489
+ : op.lines.old.length + op.lines.new.length > 0
490
+ : ownsText(op, oldLines, newLines, inString);
491
+ if (!keep || (op.type === 'movedWithEdit' && !alike(op, oldLines, newLines)))
492
+ return;
493
+ // A claim the language holds back: the safety net below marks its lines as plain changes.
494
+ if (rule('HOLD_BACK') && cfg.holdBack?.has(op.type))
495
+ return;
496
+ // Formatting whose words changed (a docstring reworded, not just rewrapped) is an edit: its lines show as
497
+ // plain changes. Dropped here, not in the structure pass, so no other pass sees a difference.
498
+ if (rule('REFORMAT_WORDS') && i >= inlined.length && structure.wordsChanged.has(i - inlined.length))
499
+ return;
500
+ // Lines that now sit in another context (wrapped into Ruby's `class << self`, under a new `private`) are
501
+ // not just laid out differently either.
502
+ // A move that changes the position of an item whose order means something (a constructor parameter) is an edit.
503
+ if ((op.type === 'moved' || op.type === 'movedWithEdit') && contextChanged(op, cfg, a.rootNode, b.rootNode, oldLines, newLines, cfg.positionAt))
504
+ return;
505
+ if ((op.type === 'moved' || op.type === 'movedWithEdit' || op.type === 'reformatted') && contextChanged(op, cfg, a.rootNode, b.rootNode, oldLines, newLines))
506
+ return;
507
+ finalIndex.set(i, operations.length);
508
+ operations.push(op);
509
+ });
510
+ // Trial ATTACH_BLANK: a blank separator line left beside a moved block (removed with it, or added with it) is part
511
+ // of the move, not a change of its own.
512
+ if (trial('ATTACH_BLANK'))
513
+ attachBlankSeparators(operations, changed, inString, oldLines, newLines);
514
+ operations.push(...uncoveredChanges(blocks, oldText, newText, operations, inString));
515
+ const structureOffset = inlined.length;
516
+ const textOffset = structureOffset + structure.operations.length;
517
+ const textIndex = new Map(textKept.map(({ i }, k) => [i, textOffset + k]));
518
+ const regionOps = [
519
+ ...structure.folds.flatMap((r) => r.operations.map((i) => i + structureOffset)),
520
+ ...text.folds.flatMap((r) => r.operations.filter((i) => textIndex.has(i)).map((i) => textIndex.get(i))),
521
+ ].flatMap((i) => (finalIndex.has(i) ? [finalIndex.get(i)] : []));
522
+ // Fold rows follow the lines each move finally owns.
523
+ const semanticFolds = regionOps
524
+ .flatMap((index) => operations[index].lines.old.map((l) => ({
525
+ old: { start: l.start, end: l.end },
526
+ operations: [index],
527
+ counts: { moved: l.end - l.start + 1, edited: 0, removed: 0 },
528
+ })))
529
+ .sort((x, y) => x.old.start - y.old.start);
530
+ const semanticOperations = withinFile(operations, dOld.length, dNew.length);
531
+ // The declaration each operation is about (docs/symbols.md). Additive: a failure here only costs the symbols.
532
+ try {
533
+ attachSymbols(semanticOperations, a.rootNode, b.rootNode, oldText, newText, cfg);
534
+ }
535
+ catch (e) {
536
+ if (flags.reasons())
537
+ console.error('[semantic] symbols failed:', e);
538
+ for (const op of semanticOperations)
539
+ delete op.symbol;
540
+ }
541
+ return { semanticOperations, semanticFolds, patch: toPatch(name, blocks, dOld, dNew), diagnostics };
542
+ });
543
+ if (!report)
544
+ return result;
545
+ return { ...result, secondOpinion: { ...report, links: linksFor(result.semanticOperations, acceptedAnswers, oldText, newText) } };
546
+ }
547
+ function linksFor(operations, accepted, oldText, newText) {
548
+ if (accepted.size === 0)
549
+ return [];
550
+ const oldLines = oldText.split('\n');
551
+ const newLines = newText.split('\n');
552
+ const textOf = (lines, ranges) => ranges.flatMap((r) => lines.slice(r.start - 1, r.end)).join('\n');
553
+ const left = [...accepted.values()];
554
+ const links = [];
555
+ operations.forEach((op, operationIndex) => {
556
+ if (op.type !== 'extractedFunction' && op.type !== 'inlinedFunction')
557
+ return;
558
+ const kind = op.type === 'extractedFunction' ? 'extract' : 'inline';
559
+ const text = kind === 'extract' ? textOf(newLines, op.lines.new) : textOf(oldLines, op.lines.old);
560
+ const at = left.findIndex(({ c }) => c.kind === kind && new RegExp(`\\b${c.helper.split('.').pop().replace(/[$]/g, '\\$')}\\s*[(<=:]`).test(text));
561
+ if (at < 0)
562
+ return;
563
+ const { c, a } = left.splice(at, 1)[0];
564
+ links.push({
565
+ operationIndex,
566
+ candidateId: candidateId(c),
567
+ kind,
568
+ helper: c.helper,
569
+ caller: c.caller,
570
+ band: a?.band,
571
+ score: a?.score ?? 1,
572
+ model: a?.model ?? 'second opinion',
573
+ question: a?.question ?? '',
574
+ answer: a?.answer ?? 'moved',
575
+ });
576
+ });
577
+ return links;
578
+ }
579
+ export async function semanticDiff(language, oldText, newText) {
580
+ return (await semanticDiffFile(language, oldText, newText)).semanticOperations;
581
+ }
@@ -0,0 +1,21 @@
1
+ import type { Node } from 'web-tree-sitter';
2
+ import { type LanguageConfig } from './parse.js';
3
+ import { type Candidate } from './runtime.js';
4
+ import type { SemanticDiffOperation } from './pierre-types.js';
5
+ export interface InlineOptions {
6
+ /** Minimum token similarity for a helper statement to count as moved. */
7
+ statementSimilarity: number;
8
+ /** Minimum share of the helper's tokens that must reappear in the caller. */
9
+ coverage: number;
10
+ /** Set by extract detection, which runs this check with the versions swapped. */
11
+ mirrored?: boolean;
12
+ /**
13
+ * Let the learned check (`classifier.ts`) accept candidates the rules reject. Off by default:
14
+ * it added finds on practice projects it had not seen, but none on the held-out sets.
15
+ */
16
+ learned?: boolean;
17
+ /** Per-diff second opinion (takes precedence over `configure({ secondOpinion })`). */
18
+ secondOpinion?: (candidate: Candidate) => boolean;
19
+ }
20
+ export declare const DEFAULT_INLINE_OPTIONS: InlineOptions;
21
+ export declare function detectInlined(oldRoot: Node, newRoot: Node, oldText: string, cfg: LanguageConfig, options?: InlineOptions): SemanticDiffOperation[];