targeted-mutation 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +21 -0
  3. package/README.md +111 -2
  4. package/bin/tmt-compile.mjs +46 -0
  5. package/bin/tmt.mjs +117 -0
  6. package/build/typescript-syntax/LICENSE.txt +55 -0
  7. package/build/typescript-syntax/ThirdPartyNoticeText.txt +193 -0
  8. package/build/typescript-syntax/typescript-syntax.cjs +43 -0
  9. package/docs/analysis.md +218 -0
  10. package/docs/compiler.md +462 -0
  11. package/docs/development.md +61 -0
  12. package/docs/how-it-works.svg +188 -0
  13. package/docs/l1.md +94 -0
  14. package/docs/performance.md +647 -0
  15. package/docs/releasing.md +48 -0
  16. package/package.json +49 -4
  17. package/src/analysis.mjs +689 -0
  18. package/src/assertion-session.mjs +93 -0
  19. package/src/assertion-strength.mjs +795 -0
  20. package/src/builtin-mutations.mjs +755 -0
  21. package/src/builtin-switches.mjs +642 -0
  22. package/src/change-undone.mjs +524 -0
  23. package/src/cli-output.mjs +166 -0
  24. package/src/compiler-compat.cjs +108 -0
  25. package/src/compiler-maps.cjs +60 -0
  26. package/src/compiler-routes.cjs +391 -0
  27. package/src/compiler.cjs +98 -0
  28. package/src/compiler.mjs +1 -0
  29. package/src/conventional.mjs +172 -0
  30. package/src/displacement.mjs +19 -0
  31. package/src/extract.mjs +135 -0
  32. package/src/fallback-process.mjs +14 -0
  33. package/src/in-parallel.mjs +20 -0
  34. package/src/lean-replay.mjs +39 -0
  35. package/src/operator-analysis.mjs +123 -0
  36. package/src/playwright.mjs +139 -0
  37. package/src/probe-runtime.mjs +50 -0
  38. package/src/probe.mjs +170 -0
  39. package/src/prototype.mjs +230 -0
  40. package/src/regex-mutations.mjs +102 -0
  41. package/src/runner-process.mjs +59 -0
  42. package/src/runtime-binaries.mjs +50 -0
  43. package/src/scope.mjs +202 -0
  44. package/src/source-text.mjs +49 -0
  45. package/src/standard-plan.mjs +308 -0
  46. package/src/standard-runner.mjs +185 -0
  47. package/src/standard-session.mjs +362 -0
  48. package/src/standard-setup.mjs +20 -0
  49. package/src/targeted-gaps.mjs +85 -0
  50. package/src/threshold.mjs +185 -0
  51. package/src/trace-buffer.mjs +126 -0
  52. package/src/typescript-bindings.mjs +243 -0
  53. package/src/typescript-compiler.mjs +59 -0
  54. package/src/typescript-extraction.mjs +354 -0
  55. package/src/typescript-grammar.mjs +923 -0
  56. package/src/vitest-reporter.mjs +64 -0
  57. package/src/vitest.mjs +262 -0
  58. package/src/witness-analysis.mjs +234 -0
  59. package/src/witness-contracts.mjs +110 -0
  60. package/src/witness-discovery.mjs +239 -0
  61. package/src/witness-fixtures.mjs +148 -0
  62. package/src/witness-order.mjs +83 -0
  63. package/src/witness-rules.mjs +254 -0
@@ -0,0 +1,524 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { createHash } from 'node:crypto';
3
+ import { readFileSync, realpathSync } from 'node:fs';
4
+ import { availableParallelism } from 'node:os';
5
+ import { sep } from 'node:path';
6
+ import { sourceTrials, sourceTrialsAsync, verdict } from './analysis.mjs';
7
+ import { inParallel } from './in-parallel.mjs';
8
+ import { failedTests } from './vitest-reporter.mjs';
9
+ import { selectScope } from './scope.mjs';
10
+ import { byteOffsets } from './source-text.mjs';
11
+ import { loadTypeScript } from './typescript-compiler.mjs';
12
+ import { inside } from './vitest.mjs';
13
+
14
+ // With `--since REV`, the code as it was is an edit too: each change is put back alone and the suite runs
15
+ // against it. When every test passes, no test tells the change from what was there before.
16
+ export const undoneRule = 'change-undone/v1';
17
+
18
+ const sha = source => createHash('sha256').update(source).digest('hex');
19
+
20
+ function git(root, args) {
21
+ return execFileSync('git', ['--literal-pathspecs', '-C', root, ...args], { maxBuffer: 256 * 1024 * 1024, stdio: ['ignore', 'pipe', 'pipe'] });
22
+ }
23
+
24
+ function lineStarts(bytes) {
25
+ const starts = [0];
26
+ for (let at = bytes.indexOf(10); at !== -1; at = bytes.indexOf(10, at + 1)) starts.push(at + 1);
27
+ // A last line without a line end still ends the file.
28
+ if (starts.at(-1) !== bytes.length) starts.push(bytes.length);
29
+ return starts;
30
+ }
31
+
32
+ // The changes between two versions of one file, from the headers of a patch without context. Each gives the bytes
33
+ // of the current file to replace and the bytes they replaced.
34
+ export function undoEdits(patch, old, current) {
35
+ const oldStarts = lineStarts(old);
36
+ const newStarts = lineStarts(current);
37
+ const at = (starts, line, length) => starts[Math.min(line - 1, starts.length - 1)] ?? length;
38
+ const edits = [];
39
+ for (const [, oldStart, oldCount = '1', newStart, newCount = '1'] of patch.matchAll(/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/gm)) {
40
+ const [a, b, c, d] = [oldStart, oldCount, newStart, newCount].map(Number);
41
+ // A hunk that only removes lines names the line before them on the other side.
42
+ const from = d ? at(newStarts, c, current.length) : at(newStarts, c + 1, current.length);
43
+ const to = d ? at(newStarts, c + d, current.length) : from;
44
+ const oldFrom = b ? at(oldStarts, a, old.length) : at(oldStarts, a, old.length);
45
+ const oldTo = b ? at(oldStarts, a + b, old.length) : oldFrom;
46
+ const before = b ? old.subarray(oldFrom, oldTo) : Buffer.alloc(0);
47
+ // Lines put back after a last line that has no line end must not join it.
48
+ const joins = !d && from === current.length && current.length && current.at(-1) !== 10;
49
+ edits.push({ edit: [from, to], oldSpan: [oldFrom, oldTo], replacement: joins ? Buffer.concat([Buffer.from('\n'), before]) : before,
50
+ line: d ? c : Math.min(c + 1, Math.max(1, newStarts.length - 1)), lines: [c, d ? c + d - 1 : c + 1] });
51
+ }
52
+ return edits;
53
+ }
54
+
55
+ const apply = (current, { edit, replacement }) => Buffer.concat([current.subarray(0, edit[0]), replacement, current.subarray(edit[1])]);
56
+
57
+ // The code of a source text: its syntax tree with every token as the parser read it, without comments and
58
+ // spacing. A line end that ends a statement changes the tree, a space in a regular expression or a template
59
+ // changes a token, and text between tags counts as JSX reads it, without the indentation of its lines.
60
+ function code(ts, file, text) {
61
+ const tree = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, false);
62
+ const parts = [];
63
+ (function walk(node) {
64
+ if (node.kind >= ts.SyntaxKind.FirstJSDocNode && node.kind <= ts.SyntaxKind.LastJSDocNode) return;
65
+ const children = node.getChildren(tree);
66
+ if (node.kind === ts.SyntaxKind.JsxText) {
67
+ const lines = node.text.split(/\r\n|[\n\r]/);
68
+ // Only spaces and tabs are indentation to every JSX transform; a no-break space is text.
69
+ const read = lines.map((line, index) => (index ? line.replace(/^[ \t]+/, '') : line)).map((line, index) =>
70
+ (index < lines.length - 1 ? line.replace(/[ \t]+$/, '') : line)).filter((line, index) => line || lines.length === 1 && !index).join(' ');
71
+ // Only spacing with a line end in it: JSX leaves such text out, so tags on lines of their own are no change.
72
+ if (read || lines.length === 1) parts.push(node.kind, JSON.stringify(read));
73
+ return;
74
+ }
75
+ parts.push(node.kind);
76
+ if (!children.length) parts.push(JSON.stringify(text.slice(node.getStart(tree), node.end)));
77
+ else {
78
+ parts.push('(');
79
+ for (const child of children) walk(child);
80
+ parts.push(')');
81
+ }
82
+ })(tree);
83
+ return parts.join(' ');
84
+ }
85
+
86
+ const parses = (ts, file, text) => ts.createSourceFile(file, text, ts.ScriptTarget.Latest, false).parseDiagnostics.length === 0;
87
+
88
+ function nodeSignature(ts, tree, text, node) {
89
+ const parts = [];
90
+ (function walk(inner) {
91
+ if (inner.kind >= ts.SyntaxKind.FirstJSDocNode && inner.kind <= ts.SyntaxKind.LastJSDocNode) return;
92
+ const children = inner.getChildren(tree);
93
+ parts.push(inner.kind);
94
+ if (!children.length) parts.push(JSON.stringify(text.slice(inner.getStart(tree), inner.end)));
95
+ else {
96
+ parts.push('(');
97
+ for (const child of children) walk(child);
98
+ parts.push(')');
99
+ }
100
+ })(node);
101
+ return parts.join(' ');
102
+ }
103
+
104
+ function isObjectAssignmentTarget(ts, node) {
105
+ let child = node;
106
+ let parent = child.parent;
107
+ while (parent && ts.isParenthesizedExpression(parent)) (child = parent, parent = parent.parent);
108
+ if (!parent) return false;
109
+ if (ts.isBinaryExpression(parent) && parent.left === child &&
110
+ parent.operatorToken.kind >= ts.SyntaxKind.FirstAssignment && parent.operatorToken.kind <= ts.SyntaxKind.LastAssignment) return true;
111
+ if ((ts.isForOfStatement(parent) || ts.isForInStatement(parent)) && parent.initializer === child) return true;
112
+ if (ts.isArrayLiteralExpression(parent) || ts.isSpreadElement(parent)) return isObjectAssignmentTarget(ts, parent);
113
+ if (ts.isPropertyAssignment(parent) || ts.isShorthandPropertyAssignment(parent) || ts.isSpreadAssignment(parent)) {
114
+ return isObjectAssignmentTarget(ts, parent.parent);
115
+ }
116
+ return false;
117
+ }
118
+
119
+ function flattenLogical(ts, node, kind, out = []) {
120
+ if (ts.isBinaryExpression(node) && node.operatorToken.kind === kind) {
121
+ flattenLogical(ts, node.left, kind, out);
122
+ flattenLogical(ts, node.right, kind, out);
123
+ } else {
124
+ out.push(node);
125
+ }
126
+ return out;
127
+ }
128
+
129
+ function enclosingKey(ts, node) {
130
+ const parts = [];
131
+ for (let cur = node.parent; cur; cur = cur.parent) {
132
+ if ((ts.isFunctionDeclaration(cur) || ts.isMethodDeclaration(cur) || ts.isClassDeclaration(cur)) && cur.name && ts.isIdentifier(cur.name)) {
133
+ parts.push(cur.name.text);
134
+ } else if (ts.isVariableDeclaration(cur) && ts.isIdentifier(cur.name)) {
135
+ parts.push(cur.name.text);
136
+ } else if (ts.isPropertyAssignment(cur) && ts.isIdentifier(cur.name)) {
137
+ parts.push(cur.name.text);
138
+ }
139
+ }
140
+ return parts.join('.');
141
+ }
142
+
143
+ function oldStructuresInSpan(ts, oldTree, oldText, oldBytes, span) {
144
+ const logicalExpressions = new Map();
145
+ const objectLiterals = new Map();
146
+ if (!oldTree || !span || span[0] === span[1]) return { logicalExpressions, objectLiterals };
147
+ const [from, to] = span;
148
+ const overlaps = node => oldBytes[node.getStart(oldTree)] < to && oldBytes[node.end] > from;
149
+ const pushTo = (map, key, value) => {
150
+ let list = map.get(key);
151
+ if (!list) map.set(key, list = []);
152
+ list.push(value);
153
+ };
154
+ (function visit(node) {
155
+ if (!overlaps(node)) return;
156
+ if (ts.isBinaryExpression(node) && (node.operatorToken.kind === ts.SyntaxKind.AmpersandAmpersandToken ||
157
+ node.operatorToken.kind === ts.SyntaxKind.BarBarToken)) {
158
+ const opKind = node.operatorToken.kind;
159
+ if (!ts.isBinaryExpression(node.parent) || node.parent.operatorToken.kind !== opKind) {
160
+ pushTo(logicalExpressions, enclosingKey(ts, node), { opKind, terms: flattenLogical(ts, node, opKind).map(t => nodeSignature(ts, oldTree, oldText, t)) });
161
+ }
162
+ } else if (ts.isObjectLiteralExpression(node) && !isObjectAssignmentTarget(ts, node)) {
163
+ const keys = new Set();
164
+ for (const prop of node.properties) {
165
+ if (ts.isPropertyAssignment(prop) || ts.isShorthandPropertyAssignment(prop)) {
166
+ const name = prop.name;
167
+ if (ts.isIdentifier(name) || ts.isStringLiteral(name) || ts.isNumericLiteral(name)) keys.add(name.text);
168
+ }
169
+ }
170
+ pushTo(objectLiterals, enclosingKey(ts, node), keys);
171
+ } else {
172
+ const parent = node.parent;
173
+ const isValueExpr = parent && (
174
+ (ts.isArrowFunction(parent) && parent.body === node) ||
175
+ (ts.isReturnStatement(parent) && parent.expression === node) ||
176
+ ((ts.isIfStatement(parent) || ts.isWhileStatement(parent) || ts.isDoStatement(parent)) && parent.expression === node) ||
177
+ (ts.isConditionalExpression(parent) && parent.condition === node) ||
178
+ (ts.isVariableDeclaration(parent) && parent.initializer === node) ||
179
+ (ts.isPropertyAssignment(parent) && parent.initializer === node)
180
+ );
181
+ if (isValueExpr && ts.isExpression(node) && !ts.isFunctionLike(node) && !ts.isObjectLiteralExpression(node)) {
182
+ pushTo(logicalExpressions, enclosingKey(ts, node), { opKind: null, terms: [nodeSignature(ts, oldTree, oldText, node)] });
183
+ }
184
+ }
185
+ ts.forEachChild(node, visit);
186
+ })(oldTree);
187
+ return { logicalExpressions, objectLiterals };
188
+ }
189
+
190
+ function multisetAddedIndices(oldTerms, newTermSigs) {
191
+ const remaining = new Map();
192
+ for (const sig of oldTerms) remaining.set(sig, (remaining.get(sig) ?? 0) + 1);
193
+ const added = [];
194
+ for (let i = 0; i < newTermSigs.length; i++) {
195
+ const count = remaining.get(newTermSigs[i]) ?? 0;
196
+ if (count > 0) remaining.set(newTermSigs[i], count - 1);
197
+ else added.push(i);
198
+ }
199
+ for (const count of remaining.values()) if (count > 0) return null;
200
+ return added;
201
+ }
202
+
203
+ function commaTokensOfObject(ts, tree, objNode) {
204
+ const syntaxList = objNode.getChildren(tree).find(child => child.kind === ts.SyntaxKind.SyntaxList);
205
+ if (!syntaxList) return [];
206
+ return syntaxList.getChildren(tree).filter(child => child.kind === ts.SyntaxKind.CommaToken);
207
+ }
208
+
209
+ function needsSeparatorSpace(beforeChar, afterChar) {
210
+ if (!beforeChar || !afterChar) return false;
211
+ if (/[\p{ID_Continue}$]/u.test(beforeChar) && /[\p{ID_Continue}$\\]/u.test(afterChar)) return true;
212
+ if ((beforeChar === '+' && afterChar === '+') || (beforeChar === '-' && afterChar === '-')) return true;
213
+ if (beforeChar === '/' && (afterChar === '/' || afterChar === '*')) return true;
214
+ return false;
215
+ }
216
+
217
+ function subhunkEdits(ts, file, current, text, tree, curBytes, oldTree, oldText, oldBytes, change, now, wholeCode, selected, seenCodes) {
218
+ const [from, to] = change.edit;
219
+ if (from === to) return [];
220
+ const hasOld = Boolean(change.oldSpan && change.oldSpan[0] !== change.oldSpan[1]);
221
+ const { logicalExpressions: oldLogicals, objectLiterals: oldObjects } = oldStructuresInSpan(ts, oldTree, oldText, oldBytes, change.oldSpan);
222
+ const overlaps = node => curBytes[node.getStart(tree)] < to && curBytes[node.end] > from;
223
+ const results = [];
224
+ const tryEmit = (delStartChar, delEndChar, kind, anchorNode) => {
225
+ const startLine = tree.getLineAndCharacterOfPosition(anchorNode.getStart(tree)).line + 1;
226
+ const endLine = tree.getLineAndCharacterOfPosition(anchorNode.end).line + 1;
227
+ let inScope = false;
228
+ for (let line = startLine; line <= endLine && !inScope; line++) inScope = selected(line);
229
+ if (!inScope) return;
230
+ const edit = [curBytes[delStartChar], curBytes[delEndChar]];
231
+ const sepSpace = needsSeparatorSpace(text[delStartChar - 1], text[delEndChar]);
232
+ const replacement = sepSpace ? Buffer.from(' ') : Buffer.alloc(0);
233
+ const undone = apply(current, { edit, replacement }).toString();
234
+ if (!parses(ts, file, undone)) return;
235
+ const undoneCode = code(ts, file, undone);
236
+ if (undoneCode === now || undoneCode === wholeCode || seenCodes.has(undoneCode)) return;
237
+ seenCodes.add(undoneCode);
238
+ results.push({ edit, replacement, line: startLine, lines: [startLine, endLine], parses: true, subhunk: kind });
239
+ };
240
+ (function visit(node) {
241
+ if (!overlaps(node)) return;
242
+ if (ts.isBinaryExpression(node) && (node.operatorToken.kind === ts.SyntaxKind.AmpersandAmpersandToken ||
243
+ node.operatorToken.kind === ts.SyntaxKind.BarBarToken)) {
244
+ const opKind = node.operatorToken.kind;
245
+ if (!ts.isBinaryExpression(node.parent) || node.parent.operatorToken.kind !== opKind) {
246
+ const terms = flattenLogical(ts, node, opKind);
247
+ if (terms.length >= 2) {
248
+ const termSigs = terms.map(t => nodeSignature(ts, tree, text, t));
249
+ const scopedOld = oldLogicals.get(enclosingKey(ts, node)) ?? [];
250
+ let addedIndices = null;
251
+ if (!hasOld) {
252
+ addedIndices = terms.map((_, idx) => idx);
253
+ } else if (scopedOld.length === 1) {
254
+ const oldExpr = scopedOld[0];
255
+ if (oldExpr.opKind === null || oldExpr.opKind === opKind) {
256
+ const diff = multisetAddedIndices(oldExpr.terms, termSigs);
257
+ if (diff && diff.length > 0) addedIndices = diff;
258
+ }
259
+ }
260
+ if (addedIndices) {
261
+ for (const i of addedIndices) {
262
+ const term = terms[i];
263
+ if (!overlaps(term)) continue;
264
+ const delStart = i === 0 ? term.getStart(tree) : terms[i - 1].end;
265
+ const delEnd = i === 0 ? terms[1].getStart(tree) : term.end;
266
+ tryEmit(delStart, delEnd, 'logical-term', term);
267
+ }
268
+ }
269
+ }
270
+ }
271
+ } else if (ts.isObjectLiteralExpression(node) && !isObjectAssignmentTarget(ts, node)) {
272
+ const scopedOldObjs = oldObjects.get(enclosingKey(ts, node)) ?? [];
273
+ // Only decompose added properties when we can match against at most one old object literal in the same scope
274
+ // (avoiding cross-object shadowing) or when the hunk is a pure addition.
275
+ if (!hasOld || scopedOldObjs.length === 1) {
276
+ const oldKeys = hasOld ? scopedOldObjs[0] : new Set();
277
+ const props = node.properties;
278
+ const commas = commaTokensOfObject(ts, tree, node);
279
+ for (let i = 0; i < props.length; i++) {
280
+ const prop = props[i];
281
+ if ((!ts.isPropertyAssignment(prop) && !ts.isShorthandPropertyAssignment(prop)) || !overlaps(prop)) continue;
282
+ const name = prop.name;
283
+ if (!ts.isIdentifier(name) && !ts.isStringLiteral(name) && !ts.isNumericLiteral(name)) continue;
284
+ if (oldKeys.has(name.text)) continue;
285
+ const propStart = prop.getStart(tree);
286
+ const afterLimit = i + 1 < props.length ? props[i + 1].getStart(tree) : node.end - 1;
287
+ const trailingComma = commas.find(c => c.getStart(tree) >= prop.end && c.end <= afterLimit);
288
+ if (trailingComma) {
289
+ tryEmit(propStart, trailingComma.end, 'object-property', prop);
290
+ } else if (i > 0) {
291
+ const prevEnd = props[i - 1].end;
292
+ const prevComma = commas.find(c => c.getStart(tree) >= prevEnd && c.end <= propStart);
293
+ if (prevComma) tryEmit(prevComma.getStart(tree), prop.end, 'object-property', prop);
294
+ } else {
295
+ tryEmit(propStart, prop.end, 'object-property', prop);
296
+ }
297
+ }
298
+ }
299
+ }
300
+ ts.forEachChild(node, visit);
301
+ })(tree);
302
+ return results;
303
+ }
304
+
305
+ // The trials for one file: every change in scope that changes code, put back alone, plus AST sub-hunks for
306
+ // added `&&`/`||` terms and added object properties, and all hunks together where one does not parse alone.
307
+ export function planUndo(file, old, current, patch, selected = () => true, ts = loadTypeScript()) {
308
+ const text = current.toString();
309
+ const now = code(ts, file, text);
310
+ const tree = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true);
311
+ const sound = tree.parseDiagnostics.length === 0;
312
+ const oldText = old.toString();
313
+ const oldTree = sound ? ts.createSourceFile(file, oldText, ts.ScriptTarget.Latest, true) : null;
314
+ const oldSound = oldTree && oldTree.parseDiagnostics.length === 0;
315
+ const curBytes = sound ? byteOffsets(text) : null;
316
+ const oldBytes = oldSound ? byteOffsets(oldText) : null;
317
+ const trials = [];
318
+ const seenCodes = new Set();
319
+ for (const change of undoEdits(patch, old, current)) {
320
+ let inScope = false;
321
+ for (let line = change.lines[0]; line <= change.lines[1] && !inScope; line++) inScope = selected(line);
322
+ if (!inScope) continue;
323
+ const undone = apply(current, change).toString();
324
+ const wholeCode = code(ts, file, undone);
325
+ if (wholeCode === now) continue;
326
+ seenCodes.add(wholeCode);
327
+ trials.push({ ...change, parses: !sound || parses(ts, file, undone) });
328
+ if (sound) {
329
+ trials.push(...subhunkEdits(ts, file, current, text, tree, curBytes, oldSound ? oldTree : null, oldText, oldBytes, change, now, wholeCode, selected, seenCodes));
330
+ }
331
+ }
332
+ const wholeHunks = trials.filter(trial => !trial.subhunk);
333
+ if (wholeHunks.length > 1 && wholeHunks.some(trial => !trial.parses)) {
334
+ const all = [...wholeHunks].sort((a, b) => b.edit[0] - a.edit[0]).reduce(apply, current);
335
+ trials.push({ edit: [0, current.length], replacement: all, line: wholeHunks[0].line, together: true, parses: !sound || parses(ts, file, all.toString()) });
336
+ }
337
+ return trials;
338
+ }
339
+
340
+ function locate(current, offset) {
341
+ const before = current.subarray(0, offset);
342
+ let line = 1;
343
+ let start = 0;
344
+ for (let at = before.indexOf(10); at !== -1; at = before.indexOf(10, at + 1)) (line++, start = at + 1);
345
+ return { line, column: before.subarray(start).toString().length + 1 };
346
+ }
347
+
348
+ function prepareUndoPlan(project, files, options) {
349
+ const root = realpathSync(project);
350
+ if (options.since === undefined) throw new Error('--undo-changes requires --since REV');
351
+ let revision;
352
+ try {
353
+ revision = git(root, ['rev-parse', '--verify', '--end-of-options', options.since + '^{commit}']).toString().trim();
354
+ } catch {
355
+ throw new Error(`Cannot resolve Git revision: ${options.since}`);
356
+ }
357
+ const fromGit = path => sep === '/' ? path : path.replaceAll('/', sep);
358
+ const changed = new Set(git(root, ['diff', '--name-only', '-z', '--relative', '--no-ext-diff', '--no-renames', revision, '--']).toString().split('\0').map(fromGit));
359
+ const subjects = [];
360
+ const trials = [];
361
+ const fileHunks = new Map();
362
+ for (const { file, selected } of selectScope(root, files, { lines: options.lines, 'copy-exclude': options['copy-exclude'] })) {
363
+ if (!changed.has(file)) continue;
364
+ const pathspec = sep === '/' ? file : file.replaceAll(sep, '/');
365
+ let old;
366
+ try {
367
+ // As a checkout of the revision would write it: with the line ends the attributes of the path ask for.
368
+ old = git(root, ['cat-file', '--filters', `${revision}:./${pathspec}`]);
369
+ } catch {
370
+ // The file is new since the revision: there is nothing to put back.
371
+ continue;
372
+ }
373
+ const input = readFileSync(inside(root, file));
374
+ const patch = git(root, ['diff', '--relative', '--no-ext-diff', '--no-textconv', '--no-color', '--no-renames', '--unified=0', revision, '--', pathspec]).toString('latin1');
375
+ const planned = planUndo(file, old, input, patch, selected);
376
+ if (!planned.length) continue;
377
+ subjects.push({ file, input, digest: sha(input), sites: [] });
378
+ const singleHunks = planned.filter(trial => !trial.together && !trial.subhunk);
379
+ fileHunks.set(file, { input, hunks: singleHunks, hasTogether: planned.some(trial => trial.together) });
380
+ for (const trial of planned) {
381
+ const location = { file, ...locate(input, trial.edit[0]), start: trial.edit[0], end: trial.edit[1] };
382
+ trials.push({ ...trial, site: { id: sha(JSON.stringify([file, undoneRule, trial.edit, sha(trial.replacement)])).slice(0, 16), location },
383
+ replacement: trial.replacement.toString(), original: input.subarray(...trial.edit).toString() });
384
+ }
385
+ }
386
+ return { root, revision, subjects, trials, fileHunks };
387
+ }
388
+
389
+ function classifyUndoOutcome(trial, result, baseline, options, revision) {
390
+ const mutant = { site: trial.site.id, location: trial.site.location, rule: undoneRule, original: trial.original, edit: trial.edit,
391
+ replacement: trial.replacement, since: revision, ...(trial.together ? { together: true } : {}),
392
+ ...(trial.subhunk ? { subhunk: trial.subhunk } : {}) };
393
+ if (!trial.parses) {
394
+ return { mutant: { ...mutant, status: 'unsupported', statusReason: 'Put back alone, this change does not parse' }, unloadable: false, diagnostic: null, incomplete: false };
395
+ }
396
+ // Only genuine module load failures (not post-load unhandled rejections or suite hook errors) count as `load_error`.
397
+ // Rather than falsely reporting an unloadable single hunk as killed by tests, report `load_error` and fall back to
398
+ // reverting all in-scope hunks of the file together when multiple hunks exist.
399
+ const loadErrors = Array.isArray(result.moduleErrors)
400
+ ? result.moduleErrors
401
+ : (result.errors?.length > 0 && Array.isArray(result.tests) && result.tests.length < baseline.tests.length ? result.errors : []);
402
+ const unloadable = options.runner !== 'playwright' && result.status === 'error' && loadErrors.length > 0 && Array.isArray(result.tests);
403
+ const status = unloadable ? 'load_error' : verdict(result, baseline);
404
+ const entry = { ...mutant, status, evidence: 'reexecuted',
405
+ ...(unloadable ? { statusReason: 'The suite did not load: ' + String(loadErrors[0]).split('\n')[0] } : {}),
406
+ ...(status === 'killed' ? { tests: result.tests.filter(test => test.status === 'failed').map(({ id, project, file, name }) => ({ id, project, file, name })) } : {}) };
407
+ const diagnostic = status === 'survived'
408
+ ? { kind: 'UNTESTED CHANGE', site: trial.site.id, location: trial.site.location, rule: undoneRule, since: revision,
409
+ ...(trial.together ? { together: true } : {}), ...(trial.subhunk ? { subhunk: trial.subhunk } : {}),
410
+ mutations: [{ rule: undoneRule, edit: trial.edit, replacement: trial.replacement, evidence: 'reexecuted' }] }
411
+ : null;
412
+ return { mutant: entry, unloadable, diagnostic, incomplete: status === 'error' };
413
+ }
414
+
415
+ function buildTogetherTrials(needsTogether, fileHunks) {
416
+ if (!needsTogether.size) return [];
417
+ const ts = loadTypeScript();
418
+ const extra = [];
419
+ for (const file of needsTogether) {
420
+ const info = fileHunks.get(file);
421
+ if (!info || info.hasTogether || info.hunks.length < 2) continue;
422
+ const all = [...info.hunks].sort((a, b) => b.edit[0] - a.edit[0]).reduce(apply, info.input);
423
+ const edit = [0, info.input.length];
424
+ const location = { file, ...locate(info.input, info.hunks[0].edit[0]), start: edit[0], end: edit[1] };
425
+ extra.push({
426
+ edit, replacement: all.toString(), original: info.input.toString(), together: true,
427
+ parses: !parses(ts, file, info.input.toString()) || parses(ts, file, all.toString()),
428
+ site: { id: sha(JSON.stringify([file, undoneRule, edit, sha(all)])).slice(0, 16), location },
429
+ });
430
+ }
431
+ return extra;
432
+ }
433
+
434
+ export function analyzeUndoneChanges(project, files, options, run = { sourceTrials }) {
435
+ const { root, revision, subjects, trials, fileHunks } = prepareUndoPlan(project, files, options);
436
+ const report = { mutants: [], diagnostics: [], evaluation: 'no_sites', since: revision };
437
+ if (!trials.length) return report;
438
+ const attempt = run.sourceTrials(root, subjects, options);
439
+ const baseline = options.existingBaseline?.plain === true && options.existingBaseline.status === 'passed' && Array.isArray(options.existingBaseline.tests)
440
+ ? options.existingBaseline : attempt();
441
+ if (baseline.status !== 'passed') {
442
+ return { ...report, evaluation: 'baseline_error',
443
+ baseline: { status: baseline.status, output: baseline.output, errors: baseline.errors, failedTests: failedTests(baseline) } };
444
+ }
445
+ report.evaluation = 'evaluated';
446
+ // A file the suite runs as a test is not the program: its assertions stay as they are in every trial.
447
+ const testFiles = new Set(baseline.tests.map(entry => entry.file));
448
+ const needsTogether = new Set();
449
+ const recordOutcome = (trial, result) => {
450
+ const { mutant, unloadable, diagnostic, incomplete } = classifyUndoOutcome(trial, result, baseline, options, revision);
451
+ if (unloadable && !trial.together) needsTogether.add(trial.site.location.file);
452
+ report.mutants.push(mutant);
453
+ if (incomplete) report.evaluation = 'incomplete';
454
+ if (diagnostic) report.diagnostics.push(diagnostic);
455
+ };
456
+ for (const trial of trials) {
457
+ if (testFiles.has(trial.site.location.file)) continue;
458
+ recordOutcome(trial, trial.parses ? attempt({ trial }) : null);
459
+ }
460
+ for (const trial of buildTogetherTrials(needsTogether, fileHunks)) {
461
+ recordOutcome(trial, trial.parses ? attempt({ trial }) : null);
462
+ }
463
+ return report;
464
+ }
465
+
466
+ const defaultUndoAsyncRun = { sourceTrialsAsync };
467
+
468
+ export async function analyzeUndoneChangesAsync(project, files, options, run = defaultUndoAsyncRun) {
469
+ // Playwright runs via synchronous `sourceTrials`; never route Playwright undo trials into Vitest's `sourceTrialsAsync`.
470
+ if (options.runner === 'playwright' && run === defaultUndoAsyncRun) {
471
+ return analyzeUndoneChanges(project, files, options, { sourceTrials });
472
+ }
473
+ const { root, revision, subjects, trials, fileHunks } = prepareUndoPlan(project, files, options);
474
+ const report = { mutants: [], diagnostics: [], evaluation: 'no_sites', since: revision };
475
+ if (!trials.length) return report;
476
+ const runnerFactory = run.sourceTrialsAsync ?? run.sourceTrials;
477
+ const attempt = runnerFactory(root, subjects, options);
478
+ const baseline = options.existingBaseline?.plain === true && options.existingBaseline.status === 'passed' && Array.isArray(options.existingBaseline.tests)
479
+ ? options.existingBaseline : await attempt();
480
+ if (baseline.status !== 'passed') {
481
+ return { ...report, evaluation: 'baseline_error',
482
+ baseline: { status: baseline.status, output: baseline.output, errors: baseline.errors, failedTests: failedTests(baseline) } };
483
+ }
484
+ report.evaluation = 'evaluated';
485
+ const testFiles = new Set(baseline.tests.map(entry => entry.file));
486
+ const active = trials.filter(trial => !testFiles.has(trial.site.location.file));
487
+ const concurrency = options.runner === 'playwright' ? 1 : (options.concurrency ?? Math.max(1, Math.min(8, availableParallelism() - 1)));
488
+ const results = new Array(active.length);
489
+ await inParallel(active.map((trial, index) => ({ trial, index })), concurrency, async ({ trial, index }) => {
490
+ results[index] = trial.parses ? await attempt({ trial }) : null;
491
+ });
492
+ const needsTogether = new Set();
493
+ for (let i = 0; i < active.length; i++) {
494
+ const { mutant, unloadable, diagnostic, incomplete } = classifyUndoOutcome(active[i], results[i], baseline, options, revision);
495
+ if (unloadable && !active[i].together) needsTogether.add(active[i].site.location.file);
496
+ report.mutants.push(mutant);
497
+ if (incomplete) report.evaluation = 'incomplete';
498
+ if (diagnostic) report.diagnostics.push(diagnostic);
499
+ }
500
+ const togetherTrials = buildTogetherTrials(needsTogether, fileHunks);
501
+ const togetherResults = new Array(togetherTrials.length);
502
+ await inParallel(togetherTrials.map((trial, index) => ({ trial, index })), concurrency, async ({ trial, index }) => {
503
+ togetherResults[index] = trial.parses ? await attempt({ trial }) : null;
504
+ });
505
+ for (let i = 0; i < togetherTrials.length; i++) {
506
+ const { mutant, diagnostic, incomplete } = classifyUndoOutcome(togetherTrials[i], togetherResults[i], baseline, options, revision);
507
+ report.mutants.push(mutant);
508
+ if (incomplete) report.evaluation = 'incomplete';
509
+ if (diagnostic) report.diagnostics.push(diagnostic);
510
+ }
511
+ return report;
512
+ }
513
+
514
+ // Adds the undone changes to the report of the profile that ran beside them.
515
+ export function withUndoneChanges(report, undone) {
516
+ if (report.evaluation === 'baseline_error') return report;
517
+ if (undone.evaluation === 'baseline_error') return { ...report, evaluation: 'baseline_error', baseline: undone.baseline };
518
+ if (undone.evaluation === 'no_sites') return { ...report, changesSince: undone.since };
519
+ return {
520
+ ...report, changesSince: undone.since,
521
+ evaluation: report.evaluation === 'incomplete' || undone.evaluation === 'incomplete' ? 'incomplete' : 'evaluated',
522
+ mutants: [...report.mutants, ...undone.mutants], diagnostics: [...report.diagnostics, ...undone.diagnostics],
523
+ };
524
+ }