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,64 @@
1
+ import { writeFileSync } from 'node:fs';
2
+ import { relative } from 'node:path';
3
+
4
+ const primitive = value => ['string', 'number', 'boolean'].includes(typeof value) || value === null ? value : undefined;
5
+
6
+ export function snapshotVitestRun(root, modules, unhandled, reason) {
7
+ const errors = [...unhandled];
8
+ const moduleErrors = [];
9
+ const tests = [];
10
+ const files = [];
11
+ for (const module of modules) {
12
+ const file = relative(root, module.moduleId);
13
+ files.push(file);
14
+ const moduleTests = [...module.children.allTests()];
15
+ const loadErrors = module.errors();
16
+ const diag = module.diagnostic?.();
17
+ // File-level `beforeAll` / `afterAll` failures also appear in `module.errors()`, even in 0-test files,
18
+ // but only after collection completed (`collectDuration > 0`, `task.result.hooks`, or collected tests).
19
+ if (loadErrors.length && moduleTests.length === 0 && !module.task?.result?.hooks && !(diag && diag.collectDuration > 0)) {
20
+ moduleErrors.push(...loadErrors);
21
+ }
22
+ errors.push(...loadErrors);
23
+ for (const suite of module.children.allSuites()) errors.push(...suite.errors());
24
+ for (const test of moduleTests) {
25
+ const result = test.result();
26
+ tests.push({
27
+ id: test.id, file,
28
+ project: test.project.name, name: test.fullName, status: result.state,
29
+ failures: result.errors?.map(error => error.message) ?? [],
30
+ assertions: result.errors?.filter(error => error.name === 'AssertionError')
31
+ .map(({ actual, expected, message }) => ({ actual: primitive(actual), expected: primitive(expected), message })),
32
+ timeout: result.errors?.some(error => /^(?:Hook|Test) timed out in \d+ms\.\nIf this is a long-running/.test(error.message ?? '')) ?? false,
33
+ retry: test.options.retry ?? 0, repeats: test.options.repeats ?? 0,
34
+ concurrent: test.options.concurrent ?? false,
35
+ });
36
+ }
37
+ }
38
+ return { tests, modules: files, errors: errors.map(error => error.message), moduleErrors: moduleErrors.map(error => error.message), reason };
39
+ }
40
+
41
+ // How long each test and each test file's collection took, for ordering later work by cost.
42
+ export function timeVitestRun(modules) {
43
+ const tests = {};
44
+ const collection = {};
45
+ for (const module of modules) {
46
+ collection[JSON.stringify([module.project.name, module.moduleId])] = module.diagnostic()?.collectDuration ?? 0;
47
+ for (const test of module.children.allTests()) tests[test.id] = test.diagnostic()?.duration ?? 0;
48
+ }
49
+ return { tests, collection };
50
+ }
51
+
52
+ // A baseline report names what failed so the suite can be fixed without a second run.
53
+ export function failedTests(run, limit = 20) {
54
+ return (run.tests ?? []).filter(test => test.status === 'failed').slice(0, limit).map(test => ({
55
+ file: test.file, name: test.name, failures: (test.failures ?? []).slice(0, 5).map(failure => String(failure).slice(0, 2000)),
56
+ }));
57
+ }
58
+
59
+ export default class TmtReporter {
60
+ onTestRunEnd(modules, unhandled, reason) {
61
+ const run = snapshotVitestRun(process.env.TMT_WORKSPACE, modules, unhandled, reason);
62
+ writeFileSync(process.env.TMT_REPORT, JSON.stringify(run));
63
+ }
64
+ }
package/src/vitest.mjs ADDED
@@ -0,0 +1,262 @@
1
+ import { spawn, spawnSync } from 'node:child_process';
2
+ import { constants, cpSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, readlinkSync, realpathSync, rmSync, statSync, symlinkSync, unlinkSync } from 'node:fs';
3
+ import { createRequire } from 'node:module';
4
+ import { tmpdir } from 'node:os';
5
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
6
+ import { fileURLToPath } from 'node:url';
7
+
8
+ const reporter = fileURLToPath(new URL('./vitest-reporter.mjs', import.meta.url));
9
+ const supervisor = fileURLToPath(new URL('./runner-process.mjs', import.meta.url));
10
+ const toolDependencies = [
11
+ { name: 'vitest', bin: 'vitest.mjs', command: 'vitest' },
12
+ { name: '@playwright/test', bin: 'cli.js', command: 'playwright' },
13
+ { name: 'typescript' },
14
+ ];
15
+ const excluded = new Set(['.git', '.worktree', '.worktrees', 'docs.local', 'node_modules', 'reports', '.stryker-tmp']);
16
+ const toolRequire = createRequire(import.meta.url);
17
+
18
+ export function resolveOptional(require, id) {
19
+ try {
20
+ return require.resolve(id);
21
+ } catch (error) {
22
+ if (error.code !== 'MODULE_NOT_FOUND') throw error;
23
+ }
24
+ }
25
+
26
+ export function runnerPackage(root, runner) {
27
+ const name = runner === 'vitest' ? 'vitest' : '@playwright/test';
28
+ const manifest = resolveOptional(createRequire(resolve(root, 'package.json')), name + '/package.json');
29
+ if (!manifest) {
30
+ const label = runner === 'vitest' ? 'Vitest' : 'Playwright';
31
+ throw new Error(`Install ${label} in the project or its workspace: npm install -D ${name}`);
32
+ }
33
+ return manifest;
34
+ }
35
+
36
+ export function inside(root, path) {
37
+ const target = realpathSync(resolve(root, path));
38
+ const fromRoot = relative(root, target);
39
+ if (fromRoot === '..' || fromRoot.startsWith('..' + sep) || isAbsolute(fromRoot)) {
40
+ throw new Error(`Path escapes the project: ${path}`);
41
+ }
42
+ return target;
43
+ }
44
+
45
+ export function resolveCopyExclusions(source, exclude = []) {
46
+ return exclude.map(path => {
47
+ const candidate = resolve(source, path);
48
+ const fromRoot = relative(source, candidate);
49
+ if (!fromRoot || isAbsolute(path) || isAbsolute(fromRoot) || fromRoot === '..' || fromRoot.startsWith('..' + sep)) {
50
+ throw new Error(`Copy exclusion must be inside the project: ${path}`);
51
+ }
52
+ const components = fromRoot.split(sep);
53
+ const dependency = components.indexOf('node_modules');
54
+ if (dependency === 0) throw new Error(`Copy exclusion cannot target node_modules: ${path}`);
55
+ if (dependency > 0 && dependency !== components.length - 1) {
56
+ throw new Error(`Copy exclusion cannot target node_modules contents: ${path}`);
57
+ }
58
+ if (!existsSync(candidate)) throw new Error(`Copy exclusion does not exist: ${path}`);
59
+ const parent = dirname(candidate);
60
+ if (realpathSync(parent) !== parent) throw new Error(`Copy exclusion must not traverse a symbolic link: ${path}`);
61
+ return candidate;
62
+ });
63
+ }
64
+
65
+ export function copyPathIsExcluded(source, path, exclusions) {
66
+ return relative(source, path).split(sep).some(part => excluded.has(part)) ||
67
+ exclusions.some(exclusion => path === exclusion || path.startsWith(exclusion + sep));
68
+ }
69
+
70
+ function linkInstalledModules(source, root, projectModules, installed, tools) {
71
+ const mergedDirectories = new Set(tools.map(({ name }) => dirname(name)));
72
+ const entries = readdirSync(projectModules, { withFileTypes: true }).flatMap(entry =>
73
+ (entry.isDirectory() && entry.name.startsWith('@') || mergedDirectories.has(entry.name))
74
+ ? readdirSync(resolve(projectModules, entry.name), { withFileTypes: true })
75
+ .map(child => ({ entry: child, name: join(entry.name, child.name) }))
76
+ : [{ entry, name: entry.name }]);
77
+ const modules = entries.map(({ entry, name }) => {
78
+ const original = resolve(projectModules, name);
79
+ const target = entry.isSymbolicLink() && existsSync(original) ? realpathSync(original) : null;
80
+ const within = target === null ? '..' : relative(source, target);
81
+ const local = within !== '..' && !within.startsWith('..' + sep) && !isAbsolute(within) &&
82
+ !within.split(sep).includes('node_modules');
83
+ return { name, target: local ? resolve(root, within) : original, local };
84
+ });
85
+ if (!tools.length && !modules.some(module => module.local)) {
86
+ symlinkSync(projectModules, installed, 'dir');
87
+ return;
88
+ }
89
+ linkModules(installed, [...modules, ...tools]);
90
+ }
91
+
92
+ function linkModules(installed, modules) {
93
+ for (const { name, target, type } of modules) {
94
+ const destination = resolve(installed, name);
95
+ mkdirSync(dirname(destination), { recursive: true });
96
+ symlinkSync(target, destination, type);
97
+ }
98
+ }
99
+
100
+ function toolLinks(source, projectModules, hasLocalModules) {
101
+ const projectRequire = createRequire(resolve(source, 'package.json'));
102
+ const links = [];
103
+ const canLink = name => {
104
+ const destination = resolve(projectModules, name);
105
+ const parent = dirname(destination);
106
+ return (!lstatSync(parent, { throwIfNoEntry: false }) || statSync(parent, { throwIfNoEntry: false })?.isDirectory()) &&
107
+ !lstatSync(destination, { throwIfNoEntry: false });
108
+ };
109
+ for (const { name, bin, command } of toolDependencies) {
110
+ if (!canLink(name)) continue;
111
+ const id = name + '/package.json';
112
+ const manifest = resolveOptional(projectRequire, id) ?? (!hasLocalModules ? resolveOptional(toolRequire, id) : undefined);
113
+ if (!manifest) continue;
114
+ const target = dirname(manifest);
115
+ links.push({ name, target, type: 'dir' });
116
+ if (bin && canLink(join('.bin', command))) {
117
+ links.push({ name: join('.bin', command), target: resolve(target, bin), type: 'file' });
118
+ }
119
+ }
120
+ return links;
121
+ }
122
+
123
+ function rebaseCopiedLinks(source, workspace) {
124
+ for (const entry of readdirSync(workspace, { withFileTypes: true, recursive: true })) {
125
+ if (!entry.isSymbolicLink()) continue;
126
+ const path = resolve(entry.parentPath, entry.name);
127
+ const target = resolve(entry.parentPath, readlinkSync(path));
128
+ let within = relative(source, target);
129
+ const outside = value => isAbsolute(value) || value === '..' || value.startsWith('..' + sep);
130
+ if (outside(within) && existsSync(target)) within = relative(source, realpathSync(target));
131
+ if (outside(within)) continue;
132
+ unlinkSync(path);
133
+ symlinkSync(resolve(workspace, within), path);
134
+ }
135
+ }
136
+
137
+ export function withCopy(project, action, { exclude = [] } = {}) {
138
+ const source = realpathSync(project);
139
+ const exclusions = resolveCopyExclusions(source, exclude);
140
+ const temp = realpathSync(mkdtempSync(resolve(tmpdir(), 'tmt-')));
141
+ const remove = () => rmSync(temp, { recursive: true, force: true });
142
+ let pending = false;
143
+ try {
144
+ const root = resolve(temp, 'project');
145
+ const moduleTrees = [];
146
+ cpSync(source, root, {
147
+ recursive: true,
148
+ // Copy-on-write where the file system offers it (APFS, Btrfs, XFS); an ordinary copy elsewhere.
149
+ mode: constants.COPYFILE_FICLONE,
150
+ filter(path) {
151
+ if (path !== source && basename(path) === 'node_modules' && !exclusions.includes(path) &&
152
+ !copyPathIsExcluded(source, dirname(path), exclusions) &&
153
+ statSync(path, { throwIfNoEntry: false })?.isDirectory()) moduleTrees.push(path);
154
+ return !copyPathIsExcluded(source, path, exclusions);
155
+ },
156
+ });
157
+ rebaseCopiedLinks(source, root);
158
+ const projectModules = resolve(source, 'node_modules');
159
+ const hasLocalModules = moduleTrees.includes(projectModules);
160
+ const tools = toolLinks(source, projectModules, hasLocalModules);
161
+ for (const modules of moduleTrees) {
162
+ linkInstalledModules(source, root, modules, resolve(root, relative(source, modules)), modules === projectModules ? tools : []);
163
+ }
164
+ if (!hasLocalModules) linkModules(resolve(root, 'node_modules'), tools);
165
+ const result = action(root, temp);
166
+ // An action that is still running keeps its copy until it settles.
167
+ pending = typeof result?.then === 'function';
168
+ return pending ? result.finally(remove) : result;
169
+ } finally {
170
+ if (!pending) remove();
171
+ }
172
+ }
173
+
174
+ // How one Vitest run is started, shared by the blocking and the concurrent form.
175
+ function vitestCommand(root, temp, { trace, config, testFiles = [], product = false, active, probePreload, synchronousTrace, timeout = 60_000 } = {}) {
176
+ const vitest = resolve(dirname(runnerPackage(root, 'vitest')), 'vitest.mjs');
177
+ const testsToRun = [...new Set(testFiles.map(file => inside(root, file)))];
178
+ const configuration = config === undefined ? [] : ['--config', inside(root, config)];
179
+ const report = resolve(temp, 'vitest.json');
180
+ rmSync(report, { force: true });
181
+ const cache = resolve(temp, 'vite-cache');
182
+ mkdirSync(cache, { recursive: true });
183
+ return { report, testsToRun, product, args: [
184
+ supervisor, resolve(temp, 'vitest.pid'), String(timeout),
185
+ vitest, 'run', '--maxWorkers=1', '--maxConcurrency=1', '--no-file-parallelism', '--no-cache',
186
+ ...configuration, ...(product ? ['--reporter', reporter] : ['--reporter=json', '--outputFile', report]),
187
+ ...testsToRun,
188
+ ], options: {
189
+ cwd: root,
190
+ env: {
191
+ ...process.env, CI: 'true', VITE_CACHE_DIR: cache, TMT_WORKSPACE: root, TMT_REPORT: report,
192
+ TMT_TRACE: trace ?? '', TMT_ACTIVE_SITE: active ?? '', TMT_TRACE_SYNC: synchronousTrace ? '1' : '',
193
+ ...(probePreload ? { NODE_OPTIONS: [process.env.NODE_OPTIONS, '--require=' + JSON.stringify(probePreload)]
194
+ .filter(Boolean).join(' ') } : {}),
195
+ },
196
+ encoding: 'utf8',
197
+ timeout: timeout + 5000,
198
+ maxBuffer: 4 * 1024 * 1024,
199
+ } };
200
+ }
201
+
202
+ function vitestOutcome(root, { report, testsToRun, product }, result) {
203
+ if (result.status === 124 || result.error?.code === 'ETIMEDOUT') return { status: 'timeout', output: result.stderr ?? '' };
204
+ if (result.error || !existsSync(report)) {
205
+ return { status: 'error', output: result.error?.message ?? (result.stderr + result.stdout) };
206
+ }
207
+ const data = JSON.parse(readFileSync(report, 'utf8'));
208
+ if (product) {
209
+ if (testsToRun.length) {
210
+ const expected = new Set(testsToRun.map(file => relative(root, file)));
211
+ const actual = new Set(data.modules);
212
+ const missing = [...expected].filter(file => !actual.has(file));
213
+ const unexpected = [...actual].filter(file => !expected.has(file));
214
+ if (missing.length || unexpected.length) {
215
+ return { status: 'error', output: `Vitest test selection mismatch (missing: ${missing.join(', ') || 'none'}; unexpected: ${unexpected.join(', ') || 'none'})`,
216
+ errors: data.errors };
217
+ }
218
+ }
219
+ const failed = data.tests.filter(test => test.status === 'failed');
220
+ const complete = data.reason === 'passed' || data.reason === 'failed';
221
+ const status = failed.some(test => test.timeout) ? 'timeout'
222
+ : !complete || data.errors.length ? 'error'
223
+ : result.status === 1 && failed.length ? 'failed'
224
+ : result.status === 0 && data.tests.some(test => test.status === 'passed') && !failed.length ? 'passed' : 'error';
225
+ return { status, tests: data.tests, errors: data.errors, moduleErrors: data.moduleErrors ?? [], output: result.stderr + result.stdout };
226
+ }
227
+ const tests = data.testResults.flatMap(file => file.assertionResults.map(assertion => ({
228
+ file: relative(root, file.name),
229
+ name: assertion.fullName,
230
+ status: assertion.status,
231
+ failures: assertion.failureMessages,
232
+ })));
233
+ const failed = tests.filter(test => test.status === 'failed');
234
+ const status = result.status === 0 && data.success && data.numPassedTests > 0 ? 'passed'
235
+ : result.status === 1 && !data.success && failed.length > 0 &&
236
+ data.testResults.every(file => file.status !== 'failed' || file.assertionResults.some(test => test.status === 'failed'))
237
+ ? 'failed' : 'error';
238
+ return { status, tests, output: result.stderr + result.stdout };
239
+ }
240
+
241
+ export function runVitest(root, temp, settings) {
242
+ const command = vitestCommand(root, temp, settings);
243
+ return vitestOutcome(root, command, spawnSync(process.execPath, command.args, command.options));
244
+ }
245
+
246
+ // The same run without blocking, so several project copies can run their suites side by side.
247
+ export async function runVitestAsync(root, temp, settings) {
248
+ const command = vitestCommand(root, temp, settings);
249
+ const result = await new Promise(settle => {
250
+ const child = spawn(process.execPath, command.args, { ...command.options, stdio: ['ignore', 'pipe', 'pipe'] });
251
+ const output = { stdout: '', stderr: '' };
252
+ for (const stream of ['stdout', 'stderr']) {
253
+ child[stream].setEncoding('utf8');
254
+ child[stream].on('data', chunk => { if (output[stream].length < command.options.maxBuffer) output[stream] += chunk; });
255
+ }
256
+ let failure;
257
+ child.once('error', error => { failure = error; });
258
+ child.once('close', (status, signal) => settle({ status, signal, ...output,
259
+ error: failure ?? (signal && status === null ? Object.assign(new Error('Vitest did not finish in time'), { code: 'ETIMEDOUT' }) : undefined) }));
260
+ });
261
+ return vitestOutcome(root, command, result);
262
+ }
@@ -0,0 +1,234 @@
1
+ import { isUtf8 } from 'node:buffer';
2
+ import { createHash, randomUUID } from 'node:crypto';
3
+ import { appendFileSync, existsSync, readFileSync, realpathSync, writeFileSync } from 'node:fs';
4
+ import { isAbsolute, relative, resolve, sep } from 'node:path';
5
+ import { verdict } from './analysis.mjs';
6
+ import { selectScope } from './scope.mjs';
7
+ import { failedTests } from './vitest-reporter.mjs';
8
+ import { availableParallelism } from 'node:os';
9
+ import { inParallel } from './in-parallel.mjs';
10
+ import { inside, runVitestAsync, withCopy } from './vitest.mjs';
11
+ import { parseSource, discoverWitnessRules } from './witness-rules.mjs';
12
+ import { fixtureCalls, witnessProposals } from './witness-fixtures.mjs';
13
+ import { prepareContracts, evaluateContracts } from './witness-contracts.mjs';
14
+ import { parseSortConstraints } from './witness-order.mjs';
15
+ import { discoverySources, discoverContracts } from './witness-discovery.mjs';
16
+
17
+ const candidateLimit = 32;
18
+ const proposalLimit = 4;
19
+ const distinct = (rows, name, file) => rows.filter(test => test.name === name && test.file === file);
20
+ const key = test => JSON.stringify([test.project, test.file, test.id, test.name]);
21
+
22
+ export function applyTextEdits(source, edits) {
23
+ let last = source.length;
24
+ for (const edit of edits.toSorted((a, b) => b.start - a.start)) {
25
+ if (edit.start < 0 || edit.end < edit.start || edit.end > last || source.slice(edit.start, edit.end) !== edit.original) {
26
+ throw new Error('A witness source edit no longer matches its snapshot');
27
+ }
28
+ source = source.slice(0, edit.start) + edit.replacement + source.slice(edit.end);
29
+ last = edit.start;
30
+ }
31
+ return source;
32
+ }
33
+
34
+ // One run of the suite in its own copy of the project. Copies are independent, so attempts can run side by side.
35
+ function runAttempt(root, options, snapshots, edits = [], append, capture = false) {
36
+ return withCopy(root, async (workspace, temp) => {
37
+ for (const [file, expected] of snapshots) {
38
+ const current = readFileSync(inside(workspace, file));
39
+ if (!isUtf8(current) || current.toString() !== expected) throw new Error(`Source changed during analysis: ${file}`);
40
+ }
41
+ for (const file of new Set([...edits.map(edit => edit.file), ...(append ? [append.file] : [])])) {
42
+ const path = inside(workspace, file);
43
+ const source = readFileSync(path, 'utf8');
44
+ if (source !== snapshots.get(file)) throw new Error(`Source changed during analysis: ${file}`);
45
+ writeFileSync(path, applyTextEdits(source, edits.filter(edit => edit.file === file)));
46
+ }
47
+ if (append) appendFileSync(inside(workspace, append.file), append.source);
48
+ const result = await runVitestAsync(workspace, temp, { product: true, config: options.config, testFiles: options.test,
49
+ ...(options.timeout ? { timeout: options.timeout * 1000 } : {}) });
50
+ if (capture && result.status === 'passed') {
51
+ for (const file of new Set(result.tests.map(test => test.file))) {
52
+ const bytes = readFileSync(inside(workspace, file));
53
+ if (isUtf8(bytes) && !snapshots.has(file)) snapshots.set(file, bytes.toString());
54
+ }
55
+ }
56
+ return result;
57
+ }, { exclude: options['copy-exclude'] });
58
+ }
59
+
60
+ export function isExpectedFailure(run, baseline, target, original, alternate, marker) {
61
+ if (verdict(run, baseline) !== 'killed') return false;
62
+ const failed = run.tests.filter(test => test.status === 'failed');
63
+ if (failed.length !== 1 || key(failed[0]) !== key(target)) return false;
64
+ const [error] = failed[0].assertions ?? [];
65
+ return failed[0].failures.length === 1 && failed[0].assertions?.length === 1 &&
66
+ error.message?.startsWith(marker + ':') &&
67
+ (Object.is(error.actual, alternate) && Object.is(error.expected, original) ||
68
+ error.actual === String(alternate) && error.expected === String(original));
69
+ }
70
+
71
+ async function verifyProposal(attempt, baseline, candidate, proposal, snapshots) {
72
+ const { fixture, rewrite, original, mutant } = proposal;
73
+ const suffix = randomUUID().replaceAll('-', '');
74
+ const marker = 'TMT witness ' + suffix;
75
+ if (rewrite) {
76
+ const target = distinct(baseline.tests, fixture.name, fixture.file)[0];
77
+ const edit = { ...rewrite, file: fixture.file };
78
+ const tagged = { file: fixture.file, start: fixture.expectEnd, end: fixture.expectEnd, original: '', replacement: ', ' + JSON.stringify(marker) };
79
+ const originalRun = await attempt([edit, tagged]);
80
+ if (verdict(originalRun, baseline) !== 'survived') return null;
81
+ const changed = await attempt([candidate.edit, edit, tagged]);
82
+ if (isExpectedFailure(changed, baseline, target, original, mutant, marker)) {
83
+ const source = snapshots.get(edit.file);
84
+ const fixtureEdit = { ...edit, start: Buffer.byteLength(source.slice(0, edit.start)), end: Buffer.byteLength(source.slice(0, edit.end)) };
85
+ return { fixtureEdit, verification: { status: 'confirmed', original: 'passed', rewrite: 'failed' } };
86
+ }
87
+ return null;
88
+ }
89
+
90
+ const name = marker;
91
+ const expression = `__tmtCall_${suffix}(${proposal.arguments.map(value => JSON.stringify(value)).join(', ')})${fixture.suffix}`;
92
+ const append = { file: fixture.file, source: `
93
+ import { expect as __tmtExpect_${suffix}, it as __tmtIt_${suffix} } from 'vitest';
94
+ import { ${candidate.name} as __tmtCall_${suffix} } from ${JSON.stringify(fixture.module)};
95
+ __tmtIt_${suffix}(${JSON.stringify(name)}, () => __tmtExpect_${suffix}(${expression}, ${JSON.stringify(marker)}).toBe(${JSON.stringify(original)}));
96
+ ` };
97
+ return await verifyAppend(attempt, baseline, [candidate.edit], append, marker, original, mutant)
98
+ ? { verification: { status: 'confirmed', original: 'passed', rewrite: 'failed' } } : null;
99
+ }
100
+
101
+ async function verifyAppend(attempt, baseline, edits, append, marker, original, mutant) {
102
+ const originalRun = await attempt([], append);
103
+ if (originalRun.status !== 'passed' || originalRun.tests.length !== baseline.tests.length + 1) return false;
104
+ const [target, extra] = distinct(originalRun.tests, marker, append.file);
105
+ if (!target || extra || target.status !== 'passed' ||
106
+ verdict({ ...originalRun, tests: originalRun.tests.filter(test => test !== target) }, baseline) !== 'survived') return false;
107
+ return isExpectedFailure(await attempt(edits, append), originalRun, target, original, mutant, marker);
108
+ }
109
+
110
+ export async function analyzeWitnesses(project, files, options) {
111
+ const root = realpathSync(project);
112
+ const specification = options.spec ? JSON.parse(readFileSync(inside(root, options.spec), 'utf8')) : {};
113
+ if (!specification || typeof specification !== 'object' || Array.isArray(specification)) throw new Error('Expected a witness specification object');
114
+ const constraints = parseSortConstraints(specification).map(entry => {
115
+ const file = resolve(root, entry.file);
116
+ const path = relative(root, existsSync(file) ? inside(root, entry.file) : file);
117
+ if (!path || isAbsolute(entry.file) || isAbsolute(path) || path === '..' || path.startsWith('..' + sep)) {
118
+ throw new Error(`Sort constraint must name a project-relative source file: ${entry.file}`);
119
+ }
120
+ return { ...entry, file: path };
121
+ });
122
+ const boundConstraints = new Set();
123
+ const snapshots = new Map();
124
+ const candidates = [];
125
+ const sources = [];
126
+ const extraction = [];
127
+ const selectedFiles = selectScope(root, files, options);
128
+ for (const { file, selected } of selectedFiles) {
129
+ const input = readFileSync(inside(root, file));
130
+ if (!isUtf8(input)) {
131
+ extraction.push({ file, path: 'diagnostic', reason: 'invalid-utf8' });
132
+ continue;
133
+ }
134
+ const source = input.toString();
135
+ const tree = parseSource(file, source);
136
+ snapshots.set(file, source);
137
+ const rules = discoverWitnessRules(tree, constraints.filter(entry => entry.file === file));
138
+ for (const rule of rules) for (const entry of rule.constraints ?? []) boundConstraints.add(entry);
139
+ sources.push(discoverySources(tree, selected));
140
+ extraction.push({ file, path: tree.parseDiagnostics.length ? 'diagnostic' : 'typescript' });
141
+ for (const rule of rules) {
142
+ const start = rule.node.getStart(tree);
143
+ const end = rule.node.getEnd();
144
+ const pos = tree.getLineAndCharacterOfPosition(start);
145
+ const last = tree.getLineAndCharacterOfPosition(end - 1).line;
146
+ if (Array.from({ length: last - pos.line + 1 }, (_, index) => pos.line + index + 1).some(line => !selected(line))) continue;
147
+ const edit = { file, start, end, original: source.slice(start, end), replacement: rule.replacement };
148
+ const location = { file, line: pos.line + 1, column: pos.character + 1,
149
+ start: Buffer.byteLength(source.slice(0, start)), end: Buffer.byteLength(source.slice(0, end)) };
150
+ const id = createHash('sha256').update(JSON.stringify([file, source, start, rule.rule, rule.replacement])).digest('hex');
151
+ candidates.push({ ...rule, id, edit, location });
152
+ }
153
+ }
154
+ const selectedPaths = new Set(selectedFiles.map(({ file }) => file));
155
+ const unmatched = constraints.find(entry => selectedPaths.has(entry.file) && !boundConstraints.has(entry));
156
+ if (unmatched) throw new Error(`Sort constraints do not match a supported export: ${unmatched.file} / ${unmatched.function}`);
157
+
158
+ const witnessSearch = { candidates: candidates.length, matched: 0, unmatched: candidates.length ? null : 0, evaluated: 0, omitted: 0 };
159
+ const report = { schemaVersion: 1, runner: 'vitest', profile: 'witnesses', extraction, witnessSearch,
160
+ mutants: [], diagnostics: [], evaluation: 'no_sites' };
161
+ if (options.config || options.test?.length || options['copy-exclude']?.length) {
162
+ report.selection = { config: options.config, tests: options.test, copyExclude: options['copy-exclude'] };
163
+ }
164
+ const selection = new Map(selectedFiles.map(({ file, selected }) => [file, selected]));
165
+ const plans = Object.hasOwn(specification, 'witnessPlans') ? prepareContracts(specification, selection, snapshots) : [];
166
+ const discoveryPossible = sources.some(source => source.stores.length) ||
167
+ ['encoder', 'decoder'].every(kind => sources.some(source => source.endpoints.some(endpoint => endpoint.kind === kind)));
168
+ if ((!candidates.length && !plans.length && !discoveryPossible) || extraction.some(entry => entry.path === 'diagnostic')) return report;
169
+ const attempt = (edits, append) => runAttempt(root, options, snapshots, edits, append);
170
+ const baseline = await runAttempt(root, options, snapshots, [], undefined, true);
171
+ // Each candidate, and each contract after them, is tried in copies of its own, several at a time.
172
+ // The report keeps the candidates' order whatever order they finish in.
173
+ const concurrency = options.concurrency ?? Math.max(1, Math.min(8, availableParallelism() - 1));
174
+ if (baseline.status !== 'passed') return { ...report, evaluation: 'baseline_error',
175
+ baseline: { status: baseline.status, errors: baseline.errors, output: baseline.output, failedTests: failedTests(baseline) } };
176
+ report.baseline = { status: 'passed', tests: baseline.tests.length };
177
+ const testFiles = new Set(baseline.tests.map(test => test.file));
178
+ const fixtureSources = [...testFiles].flatMap(file => {
179
+ const source = snapshots.get(file);
180
+ if (source === undefined) return [];
181
+ return [{ file, tree: parseSource(file, source) }];
182
+ });
183
+ const prepared = candidates.filter(candidate => !testFiles.has(candidate.location.file)).flatMap(candidate => {
184
+ const fixtures = fixtureSources.flatMap(({ tree, file }) => fixtureCalls(tree, file, candidate, candidate.location.file, root))
185
+ .filter(fixture => {
186
+ const keys = distinct(baseline.tests, fixture.name, fixture.file);
187
+ return keys.length === 1 && keys[0].status === 'passed' && !keys[0].retry && !keys[0].repeats;
188
+ });
189
+ if (fixtures.length) witnessSearch.matched++;
190
+ const proposals = witnessProposals(candidate, fixtures);
191
+ return proposals.length ? [{ candidate, fixtures, proposals }] : [];
192
+ });
193
+ report.evaluation = 'evaluated';
194
+ witnessSearch.unmatched = candidates.length - witnessSearch.matched;
195
+ witnessSearch.evaluated = Math.min(prepared.length, candidateLimit);
196
+ witnessSearch.omitted = Math.max(0, prepared.length - candidateLimit);
197
+
198
+ const tried = await inParallel(prepared.slice(0, candidateLimit), concurrency, async ({ candidate, fixtures, proposals }) => {
199
+ const { id, location, rule, edit } = candidate;
200
+ const outcome = verdict(await attempt([edit]), baseline);
201
+ const mutant = { id, location, rule, edit: [location.start, location.end], original: edit.original,
202
+ replacement: edit.replacement, status: outcome, evidence: 'reexecuted' };
203
+ if (outcome !== 'survived') return { mutant };
204
+ for (const proposal of proposals.slice(0, proposalLimit)) {
205
+ const verified = await verifyProposal(attempt, baseline, candidate, proposal, snapshots);
206
+ if (!verified) continue;
207
+ const { fixture, original, mutant: changed } = proposal;
208
+ return { mutant, diagnostic: {
209
+ kind: 'INPUT GAP', site: id, rule, location,
210
+ witness: { arguments: proposal.arguments, original, mutant: changed, expectation: 'original' },
211
+ observedOutcomes: candidate.outcome ? [...new Set(fixtures
212
+ .map(seed => candidate.outcome(seed.args.map(arg => arg.value), seed.expected)).filter(Boolean))].sort() : undefined,
213
+ seed: { file: fixture.file, test: fixture.name },
214
+ suggestedTest: `expect(${fixture.bindingName}(${proposal.arguments.map(value => JSON.stringify(value)).join(', ')})${fixture.suffix}).toBe(${JSON.stringify(original)})`,
215
+ constraints: candidate.constraints,
216
+ ...verified,
217
+ } };
218
+ }
219
+ return { mutant };
220
+ });
221
+ for (const { mutant, diagnostic } of tried) {
222
+ report.mutants.push(mutant);
223
+ if (diagnostic) report.diagnostics.push(diagnostic);
224
+ }
225
+ const automatic = discoverContracts(fixtureSources, baseline, sources, { project: root }).filter(plan => !plans.some(explicit =>
226
+ explicit.testFile === plan.testFile && explicit.seedTest === plan.seedTest &&
227
+ explicit.edits.length === plan.edits.length && explicit.edits.every(edit => plan.edits.some(other =>
228
+ edit.file === other.file && edit.line === other.line && edit.original === other.original && edit.replacement === other.replacement))));
229
+ const discovered = prepareContracts({ witnessPlans: automatic }, selection, snapshots, { discovered: true });
230
+ await evaluateContracts([...plans, ...discovered], attempt, baseline, snapshots, verifyAppend, report, concurrency);
231
+ // A trial the runner could not finish is neither a kill nor a survivor.
232
+ if (report.mutants.some(mutant => mutant.status === 'error')) report.evaluation = 'incomplete';
233
+ return report;
234
+ }