targeted-mutation 0.0.0-stage → 0.1.1

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 +149 -0
  62. package/src/witness-order.mjs +83 -0
  63. package/src/witness-rules.mjs +254 -0
@@ -0,0 +1,689 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { appendFileSync, existsSync, mkdirSync, readFileSync, realpathSync, writeFileSync } from 'node:fs';
3
+ import { dirname, relative, resolve, sep } from 'node:path';
4
+ import { byteLocations, byteOffsets, extract, sourceDialect } from './extract.mjs';
5
+ import { comparisonThresholdSites } from './prototype.mjs';
6
+ import { marginGaps, thresholdGaps } from './threshold.mjs';
7
+ import { shiftedReplacement, tightenComparison } from './displacement.mjs';
8
+ import { failedTests } from './vitest-reporter.mjs';
9
+ import { inside, runVitest, runVitestAsync, withCopy } from './vitest.mjs';
10
+ import { createProbePreloadCheck, freshProbeBinding, instrument, installProbe, rewrite } from './probe.mjs';
11
+ import { runPlaywright } from './playwright.mjs';
12
+ import { selectScope } from './scope.mjs';
13
+ import { checkReplay } from './lean-replay.mjs';
14
+ import { ignoredSwaps, renderBuiltinSwitches } from './builtin-switches.mjs';
15
+ import { inspectTrace, pendingTraceDirectory, sameObservations } from './trace-buffer.mjs';
16
+
17
+ export const baselineRunSymbol = Symbol.for('targeted-mutation-ts/baseline-run');
18
+
19
+ const sha = source => createHash('sha256').update(source).digest('hex');
20
+ const identity = test => JSON.stringify([test.project, test.file, test.id]);
21
+ const testcase = ({ id, project, file, name }) => ({ id, project, file, name });
22
+ const literalKey = { '<': 'ltLiteral', '<=': 'leLiteral', '>': 'gtLiteral', '>=': 'geLiteral' };
23
+ const shiftKey = { '<': 'ltShift', '<=': 'leShift', '>': 'gtShift', '>=': 'geShift' };
24
+
25
+ function compare(operator, left, right) {
26
+ switch (operator) {
27
+ case '<': return left < right;
28
+ case '<=': return left <= right;
29
+ case '>': return left > right;
30
+ case '>=': return left >= right;
31
+ }
32
+ }
33
+
34
+ // The Playwright extraction reports a logical operator with an operand-dropping edit (`jsx-disabled-drop-left/v1`).
35
+ // The complete built-in set as plain source edits, for runners that cannot use runtime switches.
36
+ // A comparison boundary or JSX disabled left-drop that the focused analysis already edits is left to it.
37
+ function builtInSites(comparisons, input, file, dialect, selected, options = {}) {
38
+ const focused = new Set(comparisons.map(candidate => `${candidate.edit[0]}:${candidate.replacement}`));
39
+ const droppedLeft = new Set(comparisons.filter(candidate => candidate.rule === 'jsx-disabled-drop-left/v1')
40
+ .map(candidate => `${candidate.edit[0]}:${candidate.edit[1]}`));
41
+ return renderBuiltinSwitches(input, file, selected, { dialect, ...options }).mutants
42
+ .filter(mutant => mutant.status === undefined &&
43
+ !(mutant.operatorSwap && focused.has(mutant.operatorSwap.join(':'))) &&
44
+ !(mutant.targeted?.form === 'left' && droppedLeft.has(`${mutant.edit[0]}:${mutant.edit[1]}`)))
45
+ .map(mutant => ({ rule: mutant.mutatorName, original: mutant.original, replacement: mutant.replacement, edit: mutant.edit,
46
+ left: [mutant.edit[0], mutant.edit[0]], right: [mutant.edit[1], mutant.edit[1]], source: mutant.source, unobserved: true }));
47
+ }
48
+
49
+ function withProfileSites(comparisons, input, file, { mutators, dialect }, selected) {
50
+ const start = candidate => (candidate.operatorEdit ?? candidate.edit)[0];
51
+ // Without a session nothing is recorded, so the targeted or full edits run as plain source edits.
52
+ const added = mutators === 'full' ? builtInSites(comparisons, input, file, dialect, selected)
53
+ : mutators === 'targeted' ? builtInSites(comparisons, input, file, dialect, selected, { targeted: true, keep: mutation => mutation.targeted !== undefined })
54
+ : [];
55
+ return added.length ? [...comparisons, ...added].sort((a, b) => start(a) - start(b)) : comparisons;
56
+ }
57
+
58
+ export function collectComparisons(root, files, options) {
59
+ const subjects = [];
60
+ const extraction = [];
61
+ for (const { file, selected } of selectScope(root, files, options)) {
62
+ const input = readFileSync(inside(root, file));
63
+ const { path, fallback, reason, candidates: comparisons, diagnostics } = extract(input, { file, mode: options.mode, dialect: options.dialect, logical: options.runner === 'playwright' });
64
+ extraction.push({ file, path, reason, diagnostics, ...(fallback === undefined ? {} : { fallback }) });
65
+ if (path === 'diagnostic') continue;
66
+ // A boundary under a `// Stryker disable` comment is not edited by any profile.
67
+ const disabled = ignoredSwaps(input, file, { dialect: options.dialect });
68
+ const kept = disabled.size ? comparisons.filter(candidate => !disabled.has(`${candidate.edit[0]}:${candidate.replacement}`)) : comparisons;
69
+ if (kept.length !== comparisons.length) extraction.at(-1).ignored = comparisons.length - kept.length;
70
+ const candidates = ['targeted', 'full'].includes(options.mutators) ? withProfileSites(kept, input, file, options, selected) : kept;
71
+ const positions = byteLocations(input, candidates.map(candidate => (candidate.operatorEdit ?? candidate.edit)[0]));
72
+ // A comparison is in scope when any line from its left operand to its right operand is: a threshold on its
73
+ // own line belongs to the comparison whose operator is on the line above.
74
+ const reach = candidates.map(candidate => {
75
+ const [start, end] = candidate.operatorEdit ?? candidate.edit;
76
+ return [Math.min(start, candidate.left?.[0] ?? start), Math.max(start, (candidate.right?.[1] ?? end) - 1)];
77
+ });
78
+ // The lookup takes offsets in ascending order, and nested comparisons overlap.
79
+ const offsets = [...new Set(reach.flat())].sort((a, b) => a - b);
80
+ const located = byteLocations(input, offsets);
81
+ const lineAt = new Map(offsets.map((offset, index) => [offset, located[index * 2]]));
82
+ let digest;
83
+ const sites = candidates.flatMap((candidate, index) => {
84
+ const [start, end] = candidate.operatorEdit ?? candidate.edit;
85
+ const location = { file, line: positions[index * 2], column: positions[index * 2 + 1], start, end };
86
+ let inScope = false;
87
+ for (let line = lineAt.get(reach[index][0]); line <= lineAt.get(reach[index][1]) && !inScope; line++) inScope = selected(line);
88
+ if (!inScope) return [];
89
+ digest ??= sha(input);
90
+ return [{ ...candidate, location, id: sha(JSON.stringify([
91
+ file, digest, options.mode ?? 'module', options.dialect ?? sourceDialect(file),
92
+ candidate,
93
+ ])) }];
94
+ });
95
+ if (sites.length) subjects.push({ file, input, sites, digest });
96
+ }
97
+ return { subjects, extraction };
98
+ }
99
+
100
+ export function verdict(run, baseline) {
101
+ if (!['passed', 'failed'].includes(run.status)) return run.status;
102
+ const baselineTests = new Map(baseline.tests.map(test => [identity(test), test]));
103
+ if (run.tests.length !== baselineTests.size || run.tests.some(test => {
104
+ const original = baselineTests.get(identity(test));
105
+ return !original || original.name !== test.name || original.browser !== test.browser ||
106
+ (original.status === 'passed' ? !['failed', 'passed'].includes(test.status) : original.status !== test.status);
107
+ })) return 'unstable';
108
+ return run.status === 'passed' ? 'survived' : 'killed';
109
+ }
110
+
111
+ function makeAttempt(root, subjects, runner, copyExclude, probeChecks, settings = {}) {
112
+ const { tracing = false, activate, trial, witness, coverageSites, synchronousTrace, collect } = settings;
113
+ const attempt = withCopy(root, (workspace, temp) => {
114
+ const trace = tracing ? resolve(temp, 'trace.jsonl') : undefined;
115
+ if (trace) mkdirSync(pendingTraceDirectory(trace));
116
+ const files = subjects.map(subject => ({ subject, file: inside(workspace, subject.file) }));
117
+ const preloaded = tracing ? new Set(files.filter(({ file, subject }) => probeChecks.get(subject)(workspace, file))) : null;
118
+ const binding = preloaded?.size ? freshProbeBinding([...preloaded].map(({ subject }) => subject.input)) : undefined;
119
+ const probePreload = tracing ? installProbe(workspace, binding) : undefined;
120
+ for (const entry of files) {
121
+ const { subject, file } = entry;
122
+ if (sha(readFileSync(file)) !== subject.digest) throw new Error(`Source changed during analysis: ${subject.file}`);
123
+ const observable = tracing ? subject.sites.filter(site => !site.unobserved) : [];
124
+ if (observable.length) writeFileSync(file, instrument(workspace, subject.file, subject.input, observable,
125
+ preloaded.has(entry) ? binding : undefined, coverageSites));
126
+ else if (!tracing && trial?.site.location.file === subject.file) writeFileSync(file, rewrite(subject.input, trial.source?.edit ?? trial.edit, trial.source?.replacement ?? trial.replacement));
127
+ }
128
+ let witnessFile;
129
+ if (witness?.rewrite) {
130
+ // A test file with one of its calls wrapped, to record what the call gives where the test makes it.
131
+ writeFileSync(inside(workspace, witness.rewrite.file), witness.rewrite.content);
132
+ } else if (witness?.appendTo) {
133
+ const path = inside(workspace, witness.appendTo);
134
+ appendFileSync(path, witness.source);
135
+ witnessFile = relative(workspace, path);
136
+ } else if (witness) {
137
+ const folder = inside(workspace, witness.directory);
138
+ const path = resolve(folder, witness.name);
139
+ writeFileSync(path, readFileSync(inside(workspace, witness.content)), { flag: 'wx' });
140
+ witnessFile = relative(workspace, path);
141
+ }
142
+ const result = runner(workspace, temp, { trace, active: activate, product: true, probePreload, synchronousTrace });
143
+ if (!tracing && collect) {
144
+ const path = resolve(workspace, collect);
145
+ return { ...result, collected: existsSync(path) ? readFileSync(path, 'utf8') : '' };
146
+ }
147
+ if (!tracing) return { ...result, witnessFile, witnessName: witness?.testName };
148
+ const { rows, overlap } = inspectTrace(trace);
149
+ return { ...result, trace: rows, overlap, synchronousTrace };
150
+ }, { exclude: copyExclude });
151
+ if (attempt.overlap && !synchronousTrace && ['passed', 'failed'].includes(attempt.status)) {
152
+ return makeAttempt(root, subjects, runner, copyExclude, probeChecks, { ...settings, synchronousTrace: true });
153
+ }
154
+ return attempt;
155
+ }
156
+
157
+ // Runs of the suite against plain source edits, for analyses that record nothing: `attempt()` is the baseline
158
+ // and `attempt({ trial })` one edit, each in a fresh copy of the project.
159
+ export function sourceTrials(root, subjects, options) {
160
+ const runner = options.runner === 'playwright'
161
+ ? (workspace, temp) => runPlaywright(workspace, temp, { config: options.config, projects: options.project, original: root,
162
+ tests: options.test, ...(options.timeout ? { timeout: options.timeout * 1000 } : {}) })
163
+ : (workspace, temp, settings) => runVitest(workspace, temp, {
164
+ ...settings, config: options.config, testFiles: options.test, ...(options.timeout ? { timeout: options.timeout * 1000 } : {}) });
165
+ return settings => makeAttempt(root, subjects, runner, options['copy-exclude'], new Map(), settings);
166
+ }
167
+
168
+ // Asynchronous Vitest plain-source runs, so independent witness checks can run side by side.
169
+ export function sourceTrialsAsync(root, subjects, options) {
170
+ const runner = (workspace, temp, settings) => runVitestAsync(workspace, temp, {
171
+ ...settings, config: options.config, testFiles: options.test, ...(options.timeout ? { timeout: options.timeout * 1000 } : {}) });
172
+ return settings => withCopy(root, async (workspace, temp) => {
173
+ const { trial, witness, collect } = settings ?? {};
174
+ for (const subject of subjects) {
175
+ const file = inside(workspace, subject.file);
176
+ if (sha(readFileSync(file)) !== subject.digest) throw new Error(`Source changed during analysis: ${subject.file}`);
177
+ if (trial?.site.location.file === subject.file) writeFileSync(file, rewrite(subject.input, trial.source?.edit ?? trial.edit, trial.source?.replacement ?? trial.replacement));
178
+ }
179
+ if (witness?.rewrite) writeFileSync(inside(workspace, witness.rewrite.file), witness.rewrite.content);
180
+ const result = await runner(workspace, temp, { product: true });
181
+ if (collect) {
182
+ const path = resolve(workspace, collect);
183
+ return { ...result, collected: existsSync(path) ? readFileSync(path, 'utf8') : '' };
184
+ }
185
+ return result;
186
+ }, { exclude: options['copy-exclude'] });
187
+ }
188
+
189
+ function indexObservations(trace, baseline) {
190
+ const tests = new Map(baseline.tests.filter(test => test.status === 'passed').map(test => [identity(test), test]));
191
+ const bySite = new Map();
192
+ const loaded = new Set();
193
+ for (const row of trace ?? []) {
194
+ if (typeof row?.site === 'string') {
195
+ let rows = bySite.get(row.site);
196
+ if (!rows) bySite.set(row.site, rows = []);
197
+ rows.push(row);
198
+ }
199
+ if (Array.isArray(row?.loaded)) for (const site of row.loaded) loaded.add(site);
200
+ }
201
+ return { tests, bySite, loaded };
202
+ }
203
+
204
+ function matchObservations(site, { tests, bySite, loaded }) {
205
+ const rows = bySite.get(site.id) ?? [];
206
+ const observed = new Map();
207
+ let complete = rows.length > 0;
208
+ for (const row of rows) {
209
+ const key = row.identity ? identity(row.identity) : null;
210
+ if (!tests.has(key) || !Array.isArray(row.operands) || row.operands.length !== 2 ||
211
+ !row.operands.every(Number.isSafeInteger) || row.operator !== site.operator ||
212
+ compare(site.operator, ...row.operands) !== row.result) {
213
+ complete = false;
214
+ } else {
215
+ if (!observed.has(key)) observed.set(key, []);
216
+ observed.get(key).push(row.operands);
217
+ }
218
+ }
219
+ return { observed, rows, complete, tests, loaded: loaded.has(site.id) };
220
+ }
221
+
222
+ function thresholdLookup(subject) {
223
+ let offsets;
224
+ let byOperator;
225
+ return site => {
226
+ if (!byOperator) {
227
+ const source = subject.input.toString();
228
+ offsets = byteOffsets(source);
229
+ byOperator = new Map();
230
+ for (const { operator, ...entry } of comparisonThresholdSites(source, subject.file)) {
231
+ let entries = byOperator.get(operator);
232
+ if (!entries) byOperator.set(operator, entries = new Map());
233
+ const left = offsets[entry.from];
234
+ if (!entries.has(left)) entries.set(left, entry);
235
+ }
236
+ }
237
+ const entry = byOperator.get(site.operator)?.get(site.left[0]);
238
+ if (entry && offsets[entry.literalFrom] === site.right[0] && offsets[entry.literalTo] === site.right[1]) return entry;
239
+ return null;
240
+ };
241
+ }
242
+
243
+ function callableThreshold(subject, site, observations, specification, lookupThreshold) {
244
+ if (!observations.complete ||
245
+ !/^-?\s*\d+$/.test(subject.input.subarray(...site.right).toString())) return null;
246
+ const meta = lookupThreshold(site);
247
+ if (!meta || observations.rows.some(row => row.operands[1] !== meta.threshold)) return null;
248
+ const contract = Object.hasOwn(specification, meta.functionName) ? specification[meta.functionName] : null;
249
+ const specified = contract?.operator === site.operator && contract.threshold === meta.threshold &&
250
+ typeof contract.rationale === 'string' && contract.rationale.trim().length > 0;
251
+ const inputs = observations.rows.map(row => row.operands[0]);
252
+ return { meta, gap: null, specified, inputs, contract };
253
+ }
254
+
255
+ function constantThreshold(site, observation, callable) {
256
+ if (!observation.complete || !observation.rows.length || !['<', '<=', '>', '>='].includes(site.operator)) return null;
257
+ const value = observation.rows[0].operands[1];
258
+ if (observation.rows.some(row => row.operands[1] !== value)) return null;
259
+ const inputs = observation.rows.map(row => row.operands[0]);
260
+ return {
261
+ operator: site.operator,
262
+ value,
263
+ inputs,
264
+ min: callable?.specified ? callable.contract.min : undefined,
265
+ max: callable?.specified ? callable.contract.max : undefined,
266
+ gap: null,
267
+ };
268
+ }
269
+
270
+ function variableMargin(site, observation, constant) {
271
+ if (constant || !observation.complete || !observation.rows.length || !['<', '<=', '>', '>='].includes(site.operator)) return null;
272
+ const pairs = observation.rows.map(row => row.operands);
273
+ return { operator: site.operator, pairs, gap: null };
274
+ }
275
+
276
+ const isBoundaryEquivalentShift = (operator, threshold, alternate) =>
277
+ (operator === '>=' || operator === '<') ? alternate === threshold + 1 : alternate === threshold - 1;
278
+
279
+ export function planFocusedTrials(subjects, trace, baseline, specification, displaceThresholds) {
280
+ const sites = [];
281
+ const thresholdRequests = [];
282
+ const marginRequests = [];
283
+ const observations = indexObservations(trace, baseline);
284
+ for (const subject of subjects) {
285
+ const lookupThreshold = thresholdLookup(subject);
286
+ for (const site of subject.sites) {
287
+ const observation = matchObservations(site, observations);
288
+ const tightened = tightenComparison(subject.input, site, observation, displaceThresholds);
289
+ const callable = callableThreshold(subject, site, observation, specification, lookupThreshold);
290
+ const constant = constantThreshold(site, observation, callable);
291
+ const margin = variableMargin(site, observation, constant);
292
+ if (constant) thresholdRequests.push(constant);
293
+ if (margin) marginRequests.push(margin);
294
+ sites.push({ subject, site, observation, tightened, callable, constant, margin });
295
+ }
296
+ }
297
+ const gaps = thresholdGaps(thresholdRequests.map(({ operator, value, inputs, min, max }) => ({
298
+ operator, threshold: value, observations: inputs, min, max,
299
+ })));
300
+ thresholdRequests.forEach((entry, index) => { entry.gap = gaps[index]; });
301
+ const mGaps = marginGaps(marginRequests.map(({ operator, pairs }) => ({ operator, pairs })));
302
+ marginRequests.forEach((entry, index) => { entry.gap = mGaps[index]; });
303
+
304
+ const trials = [];
305
+ for (const { subject, site, observation, tightened, callable, constant, margin } of sites) {
306
+ if (callable && constant) callable.gap = constant.gap;
307
+ const boundary = {
308
+ site, edit: site.edit, replacement: site.replacement, source: site.source, rule: site.rule,
309
+ observation, threshold: callable, thresholdGap: constant?.gap ?? null, marginGap: margin?.gap ?? null,
310
+ };
311
+ trials.push(boundary);
312
+ let thresholdAdjustment;
313
+ if (constant?.gap) {
314
+ const { alternate } = constant.gap;
315
+ const rhsText = subject.input.subarray(...site.right).toString();
316
+ const isLiteral = /^-?\s*\d+$/.test(rhsText) && Number(rhsText.replace(/\s+/g, '')) === constant.value;
317
+ if (isLiteral && isBoundaryEquivalentShift(site.operator, constant.value, alternate)) {
318
+ boundary.equivalentOnSafeIntegers = [`${site.operator} ${alternate}`];
319
+ } else {
320
+ thresholdAdjustment = alternate - constant.value;
321
+ const replacement = isLiteral ? String(alternate) : shiftedReplacement(subject.input, site, thresholdAdjustment);
322
+ trials.push({
323
+ site, edit: site.right, replacement, rule: 'comparison-threshold/v1', observation,
324
+ adjustment: thresholdAdjustment, thresholdValue: constant.value, isLiteralThreshold: isLiteral,
325
+ thresholdGap: constant.gap, threshold: callable,
326
+ });
327
+ }
328
+ }
329
+ let marginAdjustment;
330
+ if (margin?.gap) {
331
+ const { alternate } = margin.gap;
332
+ if (!isBoundaryEquivalentShift(site.operator, 0, alternate)) {
333
+ marginAdjustment = alternate;
334
+ trials.push({
335
+ site, edit: site.right, replacement: shiftedReplacement(subject.input, site, alternate),
336
+ rule: 'comparison-margin/v1', observation, adjustment: alternate, marginGap: margin.gap,
337
+ });
338
+ }
339
+ }
340
+ if (tightened && tightened.adjustment !== thresholdAdjustment && tightened.adjustment !== marginAdjustment) {
341
+ trials.push({ ...tightened, threshold: callable });
342
+ }
343
+ }
344
+ return trials;
345
+ }
346
+
347
+ function sitesForIndependentCoverage(subjects, trace, baseline) {
348
+ const index = indexObservations(trace, baseline);
349
+ const sites = new Set();
350
+ for (const { sites: candidates } of subjects) {
351
+ for (const site of candidates) {
352
+ const observation = matchObservations(site, index);
353
+ if (observation.complete && observation.observed.size < index.tests.size) sites.add(site.id);
354
+ }
355
+ }
356
+ return sites;
357
+ }
358
+
359
+ function indexFocusedCoverage(trace, sites) {
360
+ const coverage = new Map();
361
+ for (const row of trace) {
362
+ if (!sites.has(row?.hit)) continue;
363
+ let counts = coverage.get(row.hit);
364
+ if (!counts) coverage.set(row.hit, counts = new Map());
365
+ const key = row.identity ? identity(row.identity) : null;
366
+ counts.set(key, (counts.get(key) ?? 0) + 1);
367
+ }
368
+ return coverage;
369
+ }
370
+
371
+ export function matchesFocusedCoverage(observed, counts) {
372
+ if (!observed.size || counts?.size !== observed.size) return false;
373
+ for (const [test, hits] of counts) {
374
+ if (observed.get(test)?.length !== hits) return false;
375
+ }
376
+ return true;
377
+ }
378
+
379
+ function leanSkips(trials, baseline, deterministic, coverage) {
380
+ if (!deterministic || baseline.tests.some(test => test.retry || test.repeats || test.concurrent)) return new Set();
381
+ const requests = [];
382
+ const indices = [];
383
+ for (const [index, trial] of trials.entries()) {
384
+ const { site, rule, observation } = trial;
385
+ if (!observation.complete) continue;
386
+ if (observation.observed.size !== observation.tests.size &&
387
+ !matchesFocusedCoverage(observation.observed, coverage.get(site.id))) continue;
388
+ const literal = rule === 'comparison-threshold/v1' && trial.isLiteralThreshold === true;
389
+ const margin = rule === 'comparison-margin/v1' && Number.isSafeInteger(trial.adjustment);
390
+ if (!literal && !margin && rule !== site.rule) continue;
391
+ indices.push(index);
392
+ requests.push({
393
+ candidate: site.id, traceCandidate: site.id, complete: true, deterministic,
394
+ original: site.operator,
395
+ replacement: literal ? { [literalKey[site.operator]]: Number(trial.replacement) }
396
+ : margin ? { [shiftKey[site.operator]]: trial.adjustment }
397
+ : trial.replacement,
398
+ observations: observation.rows.map(row => row.operands),
399
+ });
400
+ }
401
+ const accepted = checkReplay(requests);
402
+ return new Set(indices.filter((_, position) => accepted?.[position] === true));
403
+ }
404
+
405
+ function diagnose(trial, result) {
406
+ if (result.status !== 'survived' || !trial.observation.complete) return null;
407
+ const { site, threshold, observation } = trial;
408
+ function values(lhs, rhs) {
409
+ const original = compare(site.operator, lhs, rhs);
410
+ const mutant = trial.adjustment !== undefined ? compare(site.operator, lhs, rhs + trial.adjustment)
411
+ : compare(trial.replacement, lhs, rhs);
412
+ return { original, mutant };
413
+ }
414
+ const differs = ([lhs, rhs]) => {
415
+ const { original, mutant } = values(lhs, rhs);
416
+ return original !== mutant;
417
+ };
418
+ const tests = [...observation.observed].filter(([, operands]) => operands.some(differs))
419
+ .map(([key]) => testcase(observation.tests.get(key)));
420
+ if (tests.length) {
421
+ const example = trial.adjustment !== undefined ? observation.rows.find(row => differs(row.operands)).operands : undefined;
422
+ return { kind: 'ASSERTION GAP', site: site.id, location: site.location, tests,
423
+ example: example && { operands: example, ...values(...example) } };
424
+ }
425
+ const binary = observation.rows[0]?.operands;
426
+ if (!binary) return null;
427
+ const gap = trial.rule === 'comparison-threshold/v1' ? trial.thresholdGap : null;
428
+ const mGap = trial.rule === 'comparison-margin/v1' ? trial.marginGap : null;
429
+ const input = gap?.witness ?? (mGap ? binary[1] + mGap.witness : binary[1] + (trial.adjustment ?? 0));
430
+ const comparison = values(input, binary[1]);
431
+ const expected = gap?.expected ?? mGap?.expected ?? comparison.original;
432
+ const mutant = gap?.mutant ?? mGap?.mutant ?? comparison.mutant;
433
+ const constantThreshold = threshold && threshold.meta.threshold === binary[1];
434
+ const specified = constantThreshold && threshold.specified &&
435
+ input >= (threshold.contract.min ?? Number.MIN_SAFE_INTEGER) && input <= (threshold.contract.max ?? Number.MAX_SAFE_INTEGER);
436
+ return {
437
+ kind: 'INPUT GAP', site: site.id, location: site.location,
438
+ ...(mGap ? { rule: 'comparison-margin/v1' } : {}),
439
+ witness: {
440
+ input: constantThreshold ? input : undefined, operands: [input, binary[1]],
441
+ ...(mGap ? { margin: mGap.witness } : {}),
442
+ original: expected, mutant,
443
+ expectation: specified ? 'specification' : constantThreshold ? 'original' : 'hypothetical-operands',
444
+ },
445
+ observedInputs: constantThreshold ? [...new Set(threshold.inputs)].sort((a, b) => a - b) : undefined,
446
+ suggestedTest: constantThreshold ? `expect(${threshold.meta.functionName}(${input})).toBe(${expected})` : undefined,
447
+ feasibleThresholds: gap?.interval ?? trial.thresholdGap?.interval ?? (constantThreshold ? threshold.gap?.interval : undefined),
448
+ ...(mGap || trial.marginGap ? { feasibleMargins: (mGap ?? trial.marginGap).interval } : {}),
449
+ };
450
+ }
451
+
452
+ function verifyVitestWitness(root, attempt, baseline, trial, gap) {
453
+ const testFile = baseline.tests.find(test => test.status === 'passed').file;
454
+ try {
455
+ inside(root, testFile);
456
+ } catch {
457
+ return { baselineWithWitness: 'unconfirmed', rewriteWithWitness: 'unconfirmed' };
458
+ }
459
+ const target = relative(dirname(testFile), trial.site.location.file).split(sep).join('/');
460
+ const modulePath = target.startsWith('../') ? target : './' + target;
461
+ const key = trial.site.id.slice(0, 20);
462
+ const testName = 'TMT generated threshold witness ' + key;
463
+ const { functionName } = trial.threshold.meta;
464
+ const { input, original } = gap.witness;
465
+ const witness = {
466
+ appendTo: testFile, testName,
467
+ source: `
468
+ import { expect as __tmtExpect_${key}, it as __tmtIt_${key} } from 'vitest';
469
+ import { ${functionName} as __tmtSubject_${key} } from ${JSON.stringify(modulePath)};
470
+ __tmtIt_${key}(${JSON.stringify(testName)}, () => __tmtExpect_${key}(__tmtSubject_${key}(${input})).toBe(${original}));
471
+ `,
472
+ };
473
+ const originalRun = attempt({ witness });
474
+ const changedRun = attempt({ witness, trial });
475
+ return verifyWitnessRuns(baseline, originalRun, changedRun);
476
+ }
477
+
478
+ function playwrightSummary(run) {
479
+ return { attempt: run.attempt, runnerPid: run.runnerPid, serverPid: run.serverPid, status: run.status,
480
+ tests: run.tests?.map(test => ({ ...testcase(test), browser: test.browser, worker: test.worker, status: test.status })) };
481
+ }
482
+
483
+ function witnessCases(baseline, run) {
484
+ const isWitness = test => test.file === run.witnessFile && (!run.witnessName || test.name === run.witnessName);
485
+ const witnesses = run.tests?.filter(isWitness);
486
+ const original = run.tests?.filter(test => !isWitness(test));
487
+ if (!witnesses?.length || original.some(test => !['passed', 'skipped'].includes(test.status)) ||
488
+ verdict({ status: 'passed', tests: original }, baseline) !== 'survived') return [];
489
+ return witnesses;
490
+ }
491
+
492
+ function verifyWitnessRuns(baseline, original, changed) {
493
+ const passed = witnessCases(baseline, original);
494
+ const failed = witnessCases(baseline, changed);
495
+ const baselineAccepted = original.status === 'passed' && passed.length > 0 && passed.every(test => test.status === 'passed');
496
+ const matching = baselineAccepted && changed.status === 'failed' && failed.length === passed.length &&
497
+ failed.some(test => test.status === 'failed') &&
498
+ verdict({ status: 'failed', tests: failed }, { tests: passed }) === 'killed';
499
+ return {
500
+ baselineWithWitness: baselineAccepted ? 'passed' : 'unconfirmed',
501
+ rewriteWithWitness: matching ? 'failed' : 'unconfirmed',
502
+ };
503
+ }
504
+
505
+ function analyzePlaywright(root, subjects, report, options, specification) {
506
+ const runner = (workspace, temp) => runPlaywright(workspace, temp, { config: options.config, projects: options.project, original: root,
507
+ tests: options.test, ...(options.timeout ? { timeout: options.timeout * 1000 } : {}) });
508
+ const probeChecks = new Map(subjects.map(subject => [subject, createProbePreloadCheck(subject.input)]));
509
+ const attempt = settings => makeAttempt(root, subjects, runner, options['copy-exclude'], probeChecks, settings);
510
+ const baseline = attempt();
511
+ report.baseline = playwrightSummary(baseline);
512
+ if (baseline.status !== 'passed') {
513
+ return { ...report, evaluation: 'baseline_error',
514
+ baseline: { ...report.baseline, output: baseline.output, errors: baseline.errors, failedTests: failedTests(baseline) } };
515
+ }
516
+
517
+ report.evaluation = 'evaluated';
518
+ Object.defineProperty(report, baselineRunSymbol, { value: { status: baseline.status, tests: baseline.tests, plain: true }, enumerable: false });
519
+ report.instrumented = { status: 'unavailable', reason: 'browser-observations-unavailable' };
520
+ for (const subject of subjects) {
521
+ for (const site of subject.sites) {
522
+ const trial = { site, edit: site.edit, replacement: site.replacement, source: site.source };
523
+ const mutant = attempt({ trial });
524
+ const result = {
525
+ site: site.id, location: site.location, rule: site.rule, operator: site.operator, original: site.original, edit: site.edit,
526
+ replacement: site.replacement, status: verdict(mutant, baseline), evidence: 'reexecuted', run: playwrightSummary(mutant),
527
+ };
528
+ if (result.status === 'killed') result.tests = mutant.tests.filter(test => test.status === 'failed').map(testcase);
529
+ if (options.audit) {
530
+ const replay = attempt({ trial });
531
+ const replayed = verdict(replay, baseline);
532
+ const agrees = ['killed', 'survived'].includes(replayed) && replayed === result.status;
533
+ result.audit = { status: agrees ? 'agreed' : 'mismatch', source: replayed, run: playwrightSummary(replay) };
534
+ if (!agrees && ['killed', 'survived'].includes(result.status)) result.status = 'unstable';
535
+ }
536
+ report.mutants.push(result);
537
+ if (result.status === 'error') report.evaluation = 'incomplete';
538
+
539
+ const match = Array.isArray(specification.playwright) && specification.playwright.find(entry =>
540
+ entry.file === subject.file && entry.operator === site.operator && entry.rule === site.rule &&
541
+ (entry.line === undefined || entry.line === site.location.line));
542
+ if (result.status === 'survived' && match?.witness && typeof match.requirement === 'string') {
543
+ const witness = {
544
+ content: match.witness, name: 'tmt-witness-' + randomUUID() + '.spec.ts',
545
+ directory: match.witnessDirectory ?? dirname(baseline.tests.find(test => test.status === 'passed').file),
546
+ };
547
+ const original = attempt({ witness });
548
+ const changed = attempt({ witness, trial });
549
+ report.diagnostics.push({
550
+ kind: 'SURVIVED', site: site.id, location: site.location, requirement: match.requirement, suggestedTestFile: match.witness,
551
+ verification: verifyWitnessRuns(baseline, original, changed),
552
+ });
553
+ }
554
+ }
555
+ }
556
+ return report;
557
+ }
558
+
559
+ function definitive(status) {
560
+ return status === 'killed' || status === 'survived';
561
+ }
562
+
563
+ export function focusedAuditStatus(source, probe, predicted, status) {
564
+ if (!definitive(source)) return 'inconclusive';
565
+ if ((predicted && source !== 'survived') || (definitive(probe) && source !== probe)) return 'mismatch';
566
+ if (source === status && (probe === null ? predicted : definitive(probe))) return 'agreed';
567
+ return 'inconclusive';
568
+ }
569
+
570
+ // The whole focused analysis in one call.
571
+ export function analyze(project, files, options) {
572
+ const prepared = prepareAnalysis(project, files, options);
573
+ return prepared.trials ? completeAnalysis(prepared) : prepared.report;
574
+ }
575
+
576
+ // Everything up to the planned trials: extraction, the baseline and the recorded comparisons.
577
+ // Returns { report } when the analysis already ended there.
578
+ export function prepareAnalysis(project, files, options) {
579
+ const root = realpathSync(project);
580
+ const { subjects, extraction } = collectComparisons(root, files, options);
581
+ const report = { schemaVersion: 1, runner: options.runner ?? 'vitest', extraction, mutants: [], diagnostics: [], evaluation: 'no_sites' };
582
+ if (['targeted', 'full'].includes(options.mutators)) report.mutators = options.mutators;
583
+ if (options.config !== undefined || options.test?.length || options['copy-exclude']?.length) {
584
+ report.selection = { config: options.config, tests: options.test, copyExclude: options['copy-exclude'] };
585
+ }
586
+ if (!subjects.length) return { report };
587
+
588
+ const specification = options.spec ? JSON.parse(readFileSync(inside(root, options.spec), 'utf8')) : {};
589
+ if (report.runner === 'playwright') return { report: analyzePlaywright(root, subjects, report, options, specification) };
590
+ const runner = (workspace, temp, settings) => runVitest(workspace, temp, {
591
+ ...settings, config: options.config, testFiles: options.test, ...(options.timeout ? { timeout: options.timeout * 1000 } : {}),
592
+ });
593
+ const probeChecks = new Map(subjects.map(subject => [subject, createProbePreloadCheck(subject.input)]));
594
+ const attempt = settings => makeAttempt(root, subjects, runner, options['copy-exclude'], probeChecks, settings);
595
+ // Beside a session, which runs the suite on its own, the recording run stands for the baseline when it passes.
596
+ // Otherwise the plain baseline runs first, so a failing suite is reported as before.
597
+ const recorded = options.traceIsBaseline ? attempt({ tracing: true }) : null;
598
+ const plainBaseline = recorded?.status === 'passed' ? null : attempt();
599
+ const baseline = plainBaseline ?? { status: 'passed', tests: recorded.tests };
600
+ if (baseline.status !== 'passed') {
601
+ return { report: { ...report, evaluation: 'baseline_error', baseline: { status: baseline.status, output: baseline.output, errors: baseline.errors, failedTests: failedTests(baseline) } } };
602
+ }
603
+ report.baseline = { status: 'passed', tests: baseline.tests.length };
604
+ if (plainBaseline) {
605
+ Object.defineProperty(report, baselineRunSymbol, { value: { status: plainBaseline.status, tests: plainBaseline.tests, plain: true }, enumerable: false });
606
+ }
607
+
608
+ const traced = recorded?.status === 'passed' ? recorded : attempt({ tracing: true });
609
+ const tracedStatus = verdict(traced, baseline);
610
+ report.instrumented = { status: tracedStatus === 'survived' ? 'passed' : tracedStatus };
611
+ let trace = tracedStatus === 'survived' ? traced.trace : null;
612
+ let coverage = new Map();
613
+ if (trace && (options.deterministic || options.audit)) {
614
+ const coverageSites = options.deterministic ? sitesForIndependentCoverage(subjects, trace, baseline) : new Set();
615
+ const replay = attempt({ tracing: true, coverageSites, synchronousTrace: traced.synchronousTrace });
616
+ report.instrumented.stable = verdict(replay, baseline) === 'survived' && sameObservations(trace, replay.trace);
617
+ if (!report.instrumented.stable) trace = null;
618
+ else if (coverageSites.size) coverage = indexFocusedCoverage(replay.trace, coverageSites);
619
+ }
620
+
621
+ const trials = planFocusedTrials(subjects, trace, baseline, specification, options['displace-thresholds']);
622
+ const skips = leanSkips(trials, baseline, !!options.deterministic, coverage);
623
+ return { root, report, options, attempt, baseline, traced, trace, trials, skips };
624
+ }
625
+
626
+ // Runs the planned trials. `settled` answers a trial that another run already decided: it returns
627
+ // { status, tests } for the same edit, or nothing when this analysis has to run the edit itself.
628
+ export function completeAnalysis({ root, report, options, attempt, baseline, traced, trace, trials, skips }, settled = () => undefined) {
629
+ report.evaluation = 'evaluated';
630
+
631
+ for (const [index, trial] of trials.entries()) {
632
+ const predicted = skips.has(index);
633
+ const { site } = trial;
634
+ const result = {
635
+ site: site.id, location: site.location, rule: trial.rule, operator: site.operator, original: site.original,
636
+ edit: trial.edit, replacement: trial.replacement, equivalentOnSafeIntegers: trial.equivalentOnSafeIntegers,
637
+ status: predicted ? 'survived' : 'unevaluated', evidence: predicted ? 'predicted' : 'reexecuted',
638
+ };
639
+ let audit;
640
+ if (!predicted || options.audit) {
641
+ const known = options.audit ? undefined : settled(trial);
642
+ const source = known ? null : attempt({ trial });
643
+ const actual = known ? known.status : verdict(source, baseline);
644
+ if (!predicted) {
645
+ result.status = actual;
646
+ if (actual === 'killed') result.tests = known ? known.tests : source.tests.filter(test => test.status === 'failed').map(testcase);
647
+ }
648
+
649
+ if (options.audit) {
650
+ const focused = trial.rule === site.rule && trace && trial.observation.rows.length
651
+ ? attempt({ tracing: true, activate: site.id, synchronousTrace: traced.synchronousTrace }) : null;
652
+ const activation = focused?.trace?.some(row => row.site === site.id && row.operator === site.replacement);
653
+ audit = { source: actual, probe: focused ? (activation ? verdict(focused, baseline) : 'unevaluated') : null };
654
+ }
655
+ }
656
+
657
+ // Operator edits are never traced, so reach is unknown and a surviving run stands as survived.
658
+ if (result.status === 'survived' && !site.unobserved &&
659
+ (report.instrumented.stable === false || trial.observation.rows.length === 0)) {
660
+ result.sourceVerdict = 'survived';
661
+ result.status = report.instrumented.stable === false ? 'unstable'
662
+ : trial.observation.loaded ? 'unreached' : 'unevaluated';
663
+ }
664
+ if (audit) {
665
+ const status = focusedAuditStatus(audit.source, audit.probe, predicted, result.status);
666
+ result.audit = { status, ...audit };
667
+ if (status === 'mismatch') result.status = 'unstable';
668
+ }
669
+ report.mutants.push(result);
670
+ // The runner broke down in this trial, which is neither a kill nor a survivor: the analysis is not complete.
671
+ if (result.status === 'error') report.evaluation = 'incomplete';
672
+ const gap = diagnose(trial, result);
673
+ if (gap) {
674
+ if (options.audit && gap.suggestedTest) gap.verification = verifyVitestWitness(root, attempt, baseline, trial, gap);
675
+ const duplicate = trial.adjustment === undefined && report.diagnostics.find(other => other.site === gap.site && other.kind === gap.kind &&
676
+ (gap.kind === 'ASSERTION GAP' || gap.witness.operands.every((value, index) => value === other.witness.operands[index])));
677
+ if (duplicate) {
678
+ if (gap.tests) {
679
+ const existing = new Set(duplicate.tests.map(identity));
680
+ duplicate.tests.push(...gap.tests.filter(test => !existing.has(identity(test))));
681
+ }
682
+ duplicate.mutations.push({ rule: result.rule, edit: result.edit, replacement: result.replacement, evidence: result.evidence });
683
+ } else {
684
+ report.diagnostics.push({ ...gap, mutations: [{ rule: result.rule, edit: result.edit, replacement: result.replacement, evidence: result.evidence }] });
685
+ }
686
+ }
687
+ }
688
+ return report;
689
+ }