targeted-mutation 0.2.3 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/analysis.mjs CHANGED
@@ -12,6 +12,7 @@ import { inside, runVitest, runVitestAsync, withCopy } from './vitest.mjs';
12
12
  import { createProbePreloadCheck, freshProbeBinding, instrument, installProbe, rewrite } from './probe.mjs';
13
13
  import { runPlaywright } from './playwright.mjs';
14
14
  import { selectScope } from './scope.mjs';
15
+ import { createTypeContext } from './type-equivalence.mjs';
15
16
  import { checkReplay } from './lean-replay.mjs';
16
17
  import { ignoredSwaps, renderBuiltinSwitches } from './builtin-switches.mjs';
17
18
  import { inspectTrace, pendingTraceDirectory, sameObservations } from './trace-buffer.mjs';
@@ -48,11 +49,11 @@ function builtInSites(comparisons, input, file, dialect, selected, options = {})
48
49
  left: [mutant.edit[0], mutant.edit[0]], right: [mutant.edit[1], mutant.edit[1]], source: mutant.source, unobserved: true }));
49
50
  }
50
51
 
51
- function withProfileSites(comparisons, input, file, { mutators, dialect, 'exclude-rule': excludeRules }, selected) {
52
+ function withProfileSites(comparisons, input, file, { mutators, dialect, 'exclude-rule': excludeRules }, selected, typeEquivalence = null) {
52
53
  const start = candidate => (candidate.operatorEdit ?? candidate.edit)[0];
53
54
  // Without a session nothing is recorded, so the targeted or full edits run as plain source edits.
54
- const added = mutators === 'full' ? builtInSites(comparisons, input, file, dialect, selected, { excludeRules })
55
- : mutators === 'targeted' ? builtInSites(comparisons, input, file, dialect, selected, { targeted: true, excludeRules, keep: mutation => mutation.targeted !== undefined })
55
+ const added = mutators === 'full' ? builtInSites(comparisons, input, file, dialect, selected, { excludeRules, typeEquivalence })
56
+ : mutators === 'targeted' ? builtInSites(comparisons, input, file, dialect, selected, { targeted: true, excludeRules, typeEquivalence, keep: mutation => mutation.targeted !== undefined })
56
57
  : [];
57
58
  return added.length ? [...comparisons, ...added].sort((a, b) => start(a) - start(b)) : comparisons;
58
59
  }
@@ -60,7 +61,14 @@ function withProfileSites(comparisons, input, file, { mutators, dialect, 'exclud
60
61
  export function collectComparisons(root, files, options) {
61
62
  const subjects = [];
62
63
  const extraction = [];
63
- for (const { file, selected } of selectScope(root, files, options)) {
64
+ const scoped = selectScope(root, files, options);
65
+ const typeContext = options['type-check'] && ['targeted', 'full'].includes(options.mutators)
66
+ ? createTypeContext(root, scoped.map(subject => subject.file), {
67
+ tsconfig: options.tsconfig,
68
+ onWarning: options.onTypeCheckWarning,
69
+ })
70
+ : null;
71
+ for (const { file, selected } of scoped) {
64
72
  const input = readFileSync(inside(root, file));
65
73
  const { path, fallback, reason, candidates: comparisons, diagnostics } = extract(input, { file, mode: options.mode, dialect: options.dialect, logical: options.runner === 'playwright' });
66
74
  extraction.push({ file, path, reason, diagnostics, ...(fallback === undefined ? {} : { fallback }) });
@@ -69,7 +77,9 @@ export function collectComparisons(root, files, options) {
69
77
  const disabled = ignoredSwaps(input, file, { dialect: options.dialect });
70
78
  const kept = disabled.size ? comparisons.filter(candidate => !disabled.has(`${candidate.edit[0]}:${candidate.replacement}`)) : comparisons;
71
79
  if (kept.length !== comparisons.length) extraction.at(-1).ignored = comparisons.length - kept.length;
72
- const candidates = ['targeted', 'full'].includes(options.mutators) ? withProfileSites(kept, input, file, options, selected) : kept;
80
+ const candidates = ['targeted', 'full'].includes(options.mutators)
81
+ ? withProfileSites(kept, input, file, options, selected, typeContext?.forFile(file) ?? null)
82
+ : kept;
73
83
  const positions = byteLocations(input, candidates.map(candidate => (candidate.operatorEdit ?? candidate.edit)[0]));
74
84
  // A comparison is in scope when any line from its left operand to its right operand is: a threshold on its
75
85
  // own line belongs to the comparison whose operator is on the line above.
@@ -111,7 +121,7 @@ export function verdict(run, baseline) {
111
121
  }
112
122
 
113
123
  function makeAttempt(root, subjects, runner, copyExclude, probeChecks, settings = {}) {
114
- const { tracing = false, activate, trial, witness, coverageSites, synchronousTrace, collect } = settings;
124
+ const { tracing = false, activate, trial, witness, coverageSites, synchronousTrace, collect, isBaseline = false } = settings;
115
125
  const attempt = withCopy(root, (workspace, temp) => {
116
126
  const trace = tracing ? resolve(temp, 'trace.jsonl') : undefined;
117
127
  if (trace) mkdirSync(pendingTraceDirectory(trace));
@@ -141,7 +151,7 @@ function makeAttempt(root, subjects, runner, copyExclude, probeChecks, settings
141
151
  writeFileSync(path, readFileSync(inside(workspace, witness.content)), { flag: 'wx' });
142
152
  witnessFile = relative(workspace, path);
143
153
  }
144
- const result = runner(workspace, temp, { trace, active: activate, product: true, probePreload, synchronousTrace });
154
+ const result = runner(workspace, temp, { trace, active: activate, product: true, probePreload, synchronousTrace, isBaseline });
145
155
  if (!tracing && collect) {
146
156
  const path = resolve(workspace, collect);
147
157
  return { ...result, collected: existsSync(path) ? readFileSync(path, 'utf8') : '' };
@@ -163,14 +173,14 @@ export function sourceTrials(root, subjects, options) {
163
173
  ? (workspace, temp) => runPlaywright(workspace, temp, { config: options.config, projects: options.project, original: root,
164
174
  tests: options.test, ...(options.timeout ? { timeout: options.timeout * 1000 } : {}) })
165
175
  : (workspace, temp, settings) => runVitest(workspace, temp, {
166
- ...settings, config: options.config, testFiles: options.test, ...(options.timeout ? { timeout: options.timeout * 1000 } : {}) });
176
+ ...settings, config: options.config, testFiles: options.test, testProjects: options.testProjects, ...(options.timeout ? { timeout: options.timeout * 1000 } : {}) });
167
177
  return settings => makeAttempt(root, subjects, runner, options['copy-exclude'], new Map(), settings);
168
178
  }
169
179
 
170
180
  // Asynchronous Vitest plain-source runs, so independent witness checks can run side by side.
171
181
  export function sourceTrialsAsync(root, subjects, options) {
172
182
  const runner = (workspace, temp, settings) => runVitestAsync(workspace, temp, {
173
- ...settings, config: options.config, testFiles: options.test, ...(options.timeout ? { timeout: options.timeout * 1000 } : {}) });
183
+ ...settings, config: options.config, testFiles: options.test, testProjects: options.testProjects, ...(options.timeout ? { timeout: options.timeout * 1000 } : {}) });
174
184
  return settings => withCopy(root, async (workspace, temp) => {
175
185
  const { trial, witness, collect } = settings ?? {};
176
186
  for (const subject of subjects) {
@@ -432,9 +442,16 @@ function diagnose(trial, result) {
432
442
  const tests = [...observation.observed].filter(([, operands]) => operands.some(differs))
433
443
  .map(([key]) => testcase(observation.tests.get(key)));
434
444
  if (tests.length) {
435
- const example = trial.adjustment !== undefined ? observation.rows.find(row => differs(row.operands)).operands : undefined;
436
- return { kind: 'ASSERTION GAP', site: site.id, location: site.location, tests,
437
- example: example && { operands: example, ...values(...example) } };
445
+ const example = observation.rows.find(row => differs(row.operands))?.operands;
446
+ return {
447
+ kind: 'ASSERTION GAP',
448
+ site: site.id,
449
+ rule: trial.rule,
450
+ operator: site.operator,
451
+ location: site.location,
452
+ tests,
453
+ ...(example ? { example: { operands: example, ...values(...example) } } : {}),
454
+ };
438
455
  }
439
456
  const binary = observation.rows[0]?.operands;
440
457
  if (!binary) return null;
@@ -522,11 +539,12 @@ function verifyWitnessRuns(baseline, original, changed) {
522
539
  }
523
540
 
524
541
  function analyzePlaywright(root, subjects, report, options, specification) {
525
- const runner = (workspace, temp) => runPlaywright(workspace, temp, { config: options.config, projects: options.project, original: root,
526
- tests: options.test, ...(options.timeout ? { timeout: options.timeout * 1000 } : {}) });
542
+ const baselineTimeoutSeconds = options['baseline-timeout'] ?? options.timeout ?? 60;
543
+ const runner = (workspace, temp, settings) => runPlaywright(workspace, temp, { config: options.config, projects: options.project, original: root,
544
+ tests: options.test, timeout: (settings?.isBaseline ? baselineTimeoutSeconds : (options.timeout ?? 60)) * 1000 });
527
545
  const probeChecks = new Map(subjects.map(subject => [subject, createProbePreloadCheck(subject.input)]));
528
546
  const attempt = settings => makeAttempt(root, subjects, runner, options['copy-exclude'], probeChecks, settings);
529
- const baseline = attempt();
547
+ const baseline = attempt({ isBaseline: true });
530
548
  report.baseline = playwrightSummary(baseline);
531
549
  if (baseline.status !== 'passed') {
532
550
  return { ...report, evaluation: 'baseline_error',
@@ -609,19 +627,27 @@ export function prepareAnalysis(project, files, options) {
609
627
 
610
628
  const specification = options.spec ? JSON.parse(readFileSync(inside(root, options.spec), 'utf8')) : {};
611
629
  if (report.runner === 'playwright') return { report: analyzePlaywright(root, subjects, report, options, specification) };
630
+ const baselineTimeoutSeconds = options['baseline-timeout'] ?? options.timeout ?? 60;
631
+ // Keep single-worker trace ordering when --deterministic or --audit compares trace replay order index-by-index.
632
+ const baselineWorkers = (options.deterministic || options.audit) ? 1 : (options['baseline-workers'] ?? 1);
612
633
  const runner = (workspace, temp, settings) => runVitest(workspace, temp, {
613
- ...settings, config: options.config, testFiles: options.test, ...(options.timeout ? { timeout: options.timeout * 1000 } : {}),
634
+ ...settings,
635
+ config: options.config,
636
+ testFiles: options.test,
637
+ testProjects: options.testProjects,
638
+ timeout: (settings?.isBaseline ? baselineTimeoutSeconds : (options.timeout ?? 60)) * 1000,
639
+ ...(settings?.isBaseline && baselineWorkers > 1 ? { workers: baselineWorkers } : {}),
614
640
  });
615
641
  const probeChecks = new Map(subjects.map(subject => [subject, createProbePreloadCheck(subject.input)]));
616
642
  const attempt = settings => makeAttempt(root, subjects, runner, options['copy-exclude'], probeChecks, settings);
617
643
  // Beside a session, which runs the suite on its own, the recording run stands for the baseline when it passes.
618
644
  // Otherwise the plain baseline runs first, so a failing suite is reported as before.
619
- const recorded = options.traceIsBaseline ? attempt({ tracing: true }) : null;
645
+ const recorded = options.traceIsBaseline ? attempt({ tracing: true, isBaseline: true }) : null;
620
646
  // Do not re-run a plain baseline when the recording run already timed out under the same suite/limit.
621
- const plainBaseline = recorded?.status === 'passed' || recorded?.status === 'timeout' ? null : attempt();
647
+ const plainBaseline = recorded?.status === 'passed' || recorded?.status === 'timeout' ? null : attempt({ isBaseline: true });
622
648
  const baseline = plainBaseline ?? (recorded?.status === 'passed' ? { status: 'passed', tests: recorded.tests } : recorded);
623
649
  if (baseline.status !== 'passed') {
624
- const timeoutSeconds = options.timeout ?? 60;
650
+ const timeoutSeconds = baselineTimeoutSeconds;
625
651
  return { report: { ...report, evaluation: 'baseline_error', baseline: {
626
652
  status: baseline.status,
627
653
  ...(baseline.status === 'timeout' ? { timeoutSeconds } : {}),
@@ -40,7 +40,7 @@ const endSwaps = new Map([['find', 'findLast'], ['findLast', 'find'], ['findInde
40
40
  ['indexOf', 'lastIndexOf'], ['lastIndexOf', 'indexOf']]);
41
41
  const ignoredValue = { '&&': 'true', '||': 'false', '??': 'undefined' };
42
42
 
43
- export function collectMutations(text, file, { dialect, selected = () => true, shifts = false, targeted = false, excludeRules = [], ts = loadTypeScript() } = {}) {
43
+ export function collectMutations(text, file, { dialect, selected = () => true, shifts = false, targeted = false, excludeRules = [], typeEquivalence = null, ts = loadTypeScript() } = {}) {
44
44
  const excludedRuleSet = new Set((excludeRules ?? []).map(r => String(r).trim()).filter(Boolean));
45
45
  const kind = dialect === 'tsx' ? ts.ScriptKind.TSX : dialect === 'ts' ? ts.ScriptKind.TS : undefined;
46
46
  const tree = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true, kind);
@@ -250,6 +250,17 @@ export function collectMutations(text, file, { dialect, selected = () => true, s
250
250
  ((ts.isStringLiteral(inner) || ts.isNoSubstitutionTemplateLiteral(inner)) && inner.text === ''));
251
251
  };
252
252
 
253
+ const falsyLiteralLabel = node => {
254
+ const inner = strip(node);
255
+ const number = ts.isPrefixUnaryExpression(inner) && inner.operator === K.MinusToken ? inner.operand : inner;
256
+ if (inner.kind === K.FalseKeyword) return 'false';
257
+ if (ts.isIdentifier(inner) && inner.text === 'NaN') return 'NaN';
258
+ if (ts.isNumericLiteral(number) && Number(number.text) === 0) return '0';
259
+ if (ts.isBigIntLiteral(number) && /^0[box]?0*n$/i.test(number.text)) return '0n';
260
+ if ((ts.isStringLiteral(inner) || ts.isNoSubstitutionTemplateLiteral(inner)) && inner.text === '') return "''";
261
+ return undefined;
262
+ };
263
+
253
264
  const nullishLiteral = node => {
254
265
  const inner = strip(node);
255
266
  return inner.kind === K.NullKeyword ? 'null' : ts.isIdentifier(inner) && inner.text === 'undefined' ? 'undefined' : undefined;
@@ -343,24 +354,35 @@ export function collectMutations(text, file, { dialect, selected = () => true, s
343
354
  // In `typeof x === "object" && x !== null` (or reversed), `x` cannot be `undefined`, so
344
355
  // relaxing `!== null` / `=== null` to loose equality is an unreachable equivalent mutant.
345
356
  if (written[literalSide] === 'null' && isGuardedTypeofObject(node, subjectNode)) return;
357
+ const isNullishEqv = target => Boolean(typeEquivalence?.isNullishEqualityEquivalent(begin(subjectNode), subjectNode.end, target));
346
358
  if (operator.length === 3) {
347
- edit(targetedRules.nullish, 'loose', swapToken(node, token, operator.slice(0, 2)), { literalSide, differsFor: other, subject });
359
+ if (!isNullishEqv(other)) {
360
+ edit(targetedRules.nullish, 'loose', swapToken(node, token, operator.slice(0, 2)), { literalSide, differsFor: other, subject });
361
+ }
348
362
  } else {
349
363
  const strict = operator + '=';
350
- edit(targetedRules.nullish, 'strict', swapToken(node, token, strict), { literalSide, differsFor: other, subject });
351
- edit(targetedRules.nullish, 'other', literalSide ? `${left} ${strict} ${other}` : `${other} ${strict} ${right}`,
352
- { literalSide, differsFor: written[literalSide], subject });
364
+ if (!isNullishEqv(other)) {
365
+ edit(targetedRules.nullish, 'strict', swapToken(node, token, strict), { literalSide, differsFor: other, subject });
366
+ }
367
+ if (!isNullishEqv(written[literalSide])) {
368
+ edit(targetedRules.nullish, 'other', literalSide ? `${left} ${strict} ${other}` : `${other} ${strict} ${right}`,
369
+ { literalSide, differsFor: written[literalSide], subject });
370
+ }
353
371
  }
354
372
  } else if (isLogical(node) && !staysInPlace(node.right)) {
355
373
  const operand = grouped;
374
+ const rightFalsy = falsyLiteralLabel(node.right);
356
375
  const more = { thunk: true, ...(written(node.right) ? { pureRight: true } : {}) };
357
376
  edit(targetedRules.ignored, 'left', `(${left}, ${right})`, more);
358
377
  edit(targetedRules.ignored, 'right', `(${left} ${operator} (${right}, ${ignoredValue[operator]}))`, more);
359
378
  // Where only the truth is used, a written falsy fallback makes `??` and `||` the same for every value.
360
379
  if (boolean && writtenFalsy(node.right)) return;
361
- if (operator === '??') edit(targetedRules.fallback, 'or', `(${operand(node.left)} || ${operand(node.right)})`, { ...more, evidence: true });
380
+ const leftNode = strip(node.left);
381
+ if (typeEquivalence?.isNullishFallbackEquivalent(begin(leftNode), leftNode.end, rightFalsy)) return;
382
+ const fallbackMore = { ...more, ...(rightFalsy ? { rightFalsy } : {}), evidence: true };
383
+ if (operator === '??') edit(targetedRules.fallback, 'or', `(${operand(node.left)} || ${operand(node.right)})`, fallbackMore);
362
384
  // Where only the truth of the value is used, nobody writes `??` for `||`.
363
- else if (operator === '||' && !boolean) edit(targetedRules.fallback, 'nullish', `(${operand(node.left)} ?? ${operand(node.right)})`, { ...more, evidence: true });
385
+ else if (operator === '||' && !boolean) edit(targetedRules.fallback, 'nullish', `(${operand(node.left)} ?? ${operand(node.right)})`, fallbackMore);
364
386
  }
365
387
  }
366
388
 
@@ -633,8 +633,10 @@ export const targetedOrBoundary = (mutation, text) => mutation.targeted !== unde
633
633
  export function prepareBuiltinSwitches(subjects, options = {}) {
634
634
  const sources = [];
635
635
  const mutants = [];
636
+ const { typeContext, ...restOptions } = options;
636
637
  for (const { file, input, selected } of subjects) {
637
- const rendered = renderBuiltinSwitches(input, file, selected, options);
638
+ const typeEquivalence = typeContext?.forFile(file) ?? null;
639
+ const rendered = renderBuiltinSwitches(input, file, selected, { ...restOptions, typeEquivalence });
638
640
  if (!rendered.mutants.length) continue;
639
641
  if (rendered.output !== input.toString()) sources.push({ file, output: rendered.output });
640
642
  mutants.push(...rendered.mutants);
@@ -49,6 +49,7 @@ export function computeCampaignContext(targets, options = {}, root = null) {
49
49
  runner: options.runner ?? 'vitest',
50
50
  config: options.config ?? null,
51
51
  test: options.test ?? null,
52
+ ...(options.testSpecs?.length ? { testSpecs: options.testSpecs } : {}),
52
53
  lines: options.lines ?? null,
53
54
  since: options.since ?? null,
54
55
  shard: options.shard ?? null,
@@ -56,7 +57,11 @@ export function computeCampaignContext(targets, options = {}, root = null) {
56
57
  deterministic: !!options.deterministic,
57
58
  displaceThresholds: !!options['displace-thresholds'],
58
59
  excludeRules: options['exclude-rule'] ?? null,
60
+ ...(options['type-check'] ? { typeCheck: true } : {}),
61
+ ...(options.tsconfig ? { tsconfig: options.tsconfig } : {}),
59
62
  timeout: options.timeout ?? null,
63
+ ...(options['baseline-timeout'] !== undefined ? { baselineTimeout: options['baseline-timeout'] } : {}),
64
+ ...(options['baseline-workers'] !== undefined ? { baselineWorkers: options['baseline-workers'] } : {}),
60
65
  copyExclude: options['copy-exclude'] ?? null,
61
66
  isolatedTrials: !!options['isolated-trials'],
62
67
  }));
@@ -13,10 +13,14 @@ Scope (analyze):
13
13
  --undo-changes With --since: also put each change back as it was at REV and run the suite.
14
14
  A change the tests pass without is reported as UNTESTED CHANGE.
15
15
  --copy-exclude PATH Leave a project path out of the temporary copies (warns and skips if missing). Repeatable.
16
+ Also configurable via "copyExclude" in targeted-mutation.config.json.
16
17
  --copy-exclude-gitignore Also exclude gitignored paths (except node_modules) from temporary copies.
17
18
  --exclude-rule RULE Exclude a mutation rule (e.g. nullish-equality/v1). Repeatable.
19
+ --type-check Use TypeScript's type checker (when strictNullChecks is enabled) to skip
20
+ statically equivalent nullish-fallback/v1 and nullish-equality/v1 edits.
21
+ --tsconfig FILE Explicit tsconfig.json path for --type-check (defaults to nearest per file / references).
18
22
  --no-config Ignore targeted-mutation.config.{json,mjs} and package.json#targetedMutation.
19
- --progress Print lightweight progress updates to stderr.
23
+ --progress Print progress updates (copying, baseline, mutant completion) to stderr.
20
24
 
21
25
  Profiles (analyze):
22
26
  --mutators targeted|full targeted (default) edits comparison boundaries and integer thresholds
@@ -46,13 +50,21 @@ Profiles (analyze):
46
50
  Runner (analyze):
47
51
  --runner vitest|playwright Test runner (default: vitest).
48
52
  --config FILE Runner configuration file inside the project.
49
- --test FILE Run only this test file. Repeatable.
53
+ --test FILE Run only this test file or glob. Repeatable. With --related, narrows related tests.
54
+ --related Select only Vitest test files related to the target source files.
50
55
  --timeout SECONDS Time limit for one run of the suite (default: 60).
56
+ --baseline-timeout SECONDS Time limit for the baseline suite run (defaults to --timeout).
57
+ --baseline-workers N Vitest workers for the baseline run (default: 1 for focused trace; --concurrency for session).
51
58
  --project NAME Playwright project. Repeatable.
52
59
 
53
60
  Output & Baselines:
54
61
  --format text|json|jsonl|sarif
55
62
  Output format (analyze defaults to text on a terminal and json otherwise).
63
+ --verbose Include killed edits in text output (hidden by default).
64
+ --only-gaps Show only test gaps and summary in text output.
65
+ --fail-on-gaps Exit with code 2 when one or more test gaps are reported.
66
+ --json-out FILE Also write the JSON report to FILE (can be combined with --format text).
67
+ --sarif-out FILE Also write the SARIF report to FILE (can be combined with --format text).
56
68
  --baseline FILE Suppress findings already recorded in FILE.
57
69
  --write-baseline FILE Write this run's findings to FILE for future --baseline runs.
58
70
  --mode script|module extract: parse goal.
@@ -71,14 +83,30 @@ export function chooseFormat(requested, terminal) {
71
83
  // Test names and runner output come from the analyzed project and can carry terminal control sequences.
72
84
  const printable = value => String(value).replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/g, '?');
73
85
  const firstLine = value => printable(value).split('\n').find(line => line.trim())?.trim() ?? '';
74
- const at = location => location ? `${location.file}:${location.line}:${location.column}` : '(unknown location)';
86
+ const compactSnippet = (value, maxLength = 48) => {
87
+ const flat = printable(value).replace(/\s+/g, ' ').trim();
88
+ return flat.length > maxLength ? flat.slice(0, maxLength - 3) + '...' : flat;
89
+ };
90
+ const at = location => location ? `${printable(location.file)}:${location.line}:${location.column}` : '(unknown location)';
75
91
 
76
92
  function describeEdit(mutant) {
77
93
  const name = mutant.mutatorName ?? mutant.rule ?? 'edit';
78
94
  if (mutant.since !== undefined) return `${name}: ${mutant.together ? 'the changes of the file together' : firstLine(mutant.original) || '(removed lines)'} as it was at ${printable(mutant.since.slice(0, 12))}`;
79
- if (mutant.original !== undefined) return `${name}: ${firstLine(mutant.original)} -> ${firstLine(mutant.replacement)}`;
95
+ if (mutant.original !== undefined) {
96
+ const origFirst = firstLine(mutant.original);
97
+ const replFirst = firstLine(mutant.replacement);
98
+ if (origFirst === replFirst && mutant.original !== mutant.replacement) {
99
+ const rawOrig = printable(mutant.original).replace(/\s+/g, ' ').trim();
100
+ const rawRepl = printable(mutant.replacement).replace(/\s+/g, ' ').trim();
101
+ const isEmptyClause = /:\s*$/.test(rawRepl) && rawOrig.length > rawRepl.length;
102
+ const origFlat = compactSnippet(mutant.original);
103
+ const shownRepl = isEmptyClause ? `${compactSnippet(mutant.replacement, 40)} (empty)` : compactSnippet(mutant.replacement);
104
+ if (origFlat !== shownRepl) return `${name}: ${origFlat} -> ${shownRepl}`;
105
+ }
106
+ return `${name}: ${origFirst} -> ${replFirst}`;
107
+ }
80
108
  const operator = String(mutant.replacement).trim();
81
- if (mutant.operator !== undefined && /^[<>=!&|?+*\/%-]+$/.test(operator)) return `${name}: ${mutant.operator} -> ${operator}`;
109
+ if (mutant.operator !== undefined && /^[<>=!&|?+*\/%-]+$/.test(operator)) return `${name}: ${printable(mutant.operator)} -> ${operator}`;
82
110
  return `${name}: replace with ${firstLine(mutant.replacement)}`;
83
111
  }
84
112
 
@@ -87,7 +115,7 @@ function describeBaseline(baseline = {}) {
87
115
  const limit = baseline.timeoutSeconds !== undefined ? ` after ${baseline.timeoutSeconds}s` : '';
88
116
  const lines = [
89
117
  `The baseline test suite timed out${limit} before any edit.`,
90
- ' Try increasing the limit with --timeout <seconds> or narrowing the suite with --test <file|glob>.',
118
+ ' Try increasing the limit with --baseline-timeout <seconds> (or --timeout <seconds>), enabling --baseline-workers <N>, or narrowing the suite with --test <file|glob>.',
91
119
  ];
92
120
  if (baseline.output?.trim()) {
93
121
  lines.push(...printable(baseline.output).trim().split('\n').slice(-10).map(line => ` ${line}`));
@@ -106,6 +134,19 @@ function describeBaseline(baseline = {}) {
106
134
  return lines;
107
135
  }
108
136
 
137
+ function formatAssertionDetails(gap) {
138
+ const lines = [];
139
+ const shown = (gap.tests ?? []).slice(0, 3).map(test => `${printable(test.file)} > ${printable(test.name)}`);
140
+ const more = (gap.tests?.length ?? 0) - shown.length;
141
+ const where = [...shown, ...(more > 0 ? [`${more} more`] : []), ...(gap.outsideTests ? ['code outside the tests'] : [])].join('; ');
142
+ const operands = gap.example?.operands ? ` (operands ${gap.example.operands.map(printable).join(', ')})` : '';
143
+ if (where || operands) {
144
+ lines.push(` the edit gives another value in: ${where || '(unknown test)'}${operands}`);
145
+ }
146
+ lines.push(' add an assertion on what this value decides');
147
+ return lines;
148
+ }
149
+
109
150
  function describeGap(gap) {
110
151
  const lines = [`${gap.kind ?? 'GAP'} ${at(gap.location)}${gap.rule ? ` ${gap.rule}` : ''}`];
111
152
  const witness = gap.witness;
@@ -122,13 +163,20 @@ function describeGap(gap) {
122
163
  else if (gap.missing && gap.uncertain) {
123
164
  lines.push(` add ${printable(gap.missing)}, or an assertion that tells them apart: the recording cannot tell whether a test has such an input`);
124
165
  } else if (gap.missing) lines.push(` add ${printable(gap.missing)}`);
125
- else {
126
- const shown = (gap.tests ?? []).slice(0, 3).map(test => `${printable(test.file)} > ${printable(test.name)}`);
127
- const more = (gap.tests?.length ?? 0) - shown.length;
128
- const where = [...shown, ...(more > 0 ? [`${more} more`] : []), ...(gap.outsideTests ? ['code outside the tests'] : [])].join('; ');
129
- const operands = gap.example?.operands ? ` (operands ${gap.example.operands.map(printable).join(', ')})` : '';
130
- lines.push(` the edit gives another value in: ${where}${operands}`, ' add an assertion on what this value decides');
166
+ else lines.push(...formatAssertionDetails(gap));
167
+ } else if (gap.kind === 'ASSERTION GAP') {
168
+ const edit = gap.mutations?.[0];
169
+ if (edit) {
170
+ const replacement = String(edit.replacement ?? '').trim();
171
+ const detail = gap.operator !== undefined && /^[<>=!&|?+*\/%-]+$/.test(replacement)
172
+ ? `\`${printable(gap.operator)} -> ${printable(replacement)}\``
173
+ : edit.original !== undefined
174
+ ? `\`${firstLine(edit.original)}\` -> \`${firstLine(edit.replacement)}\``
175
+ : `replace with \`${firstLine(edit.replacement)}\``;
176
+ lines.push(` edit ${detail} survived`);
131
177
  }
178
+ if (gap.advice) lines.push(` ${printable(gap.advice)}`);
179
+ else lines.push(...formatAssertionDetails(gap));
132
180
  }
133
181
  if (gap.kind === 'UNTESTED CHANGE') {
134
182
  lines.push(` the tests pass with ${gap.together ? 'these changes of the file put back together as they were' : 'this change put back as it was'} at ${printable(String(gap.since).slice(0, 12))}`,
@@ -158,7 +206,31 @@ function describeGap(gap) {
158
206
  return lines;
159
207
  }
160
208
 
161
- export function renderText(report) {
209
+ const plural = (count, singular, pluralForm = singular + 's') => `${count} ${count === 1 ? singular : pluralForm}`;
210
+
211
+ export function summarizeReport(report) {
212
+ const mutants = report?.mutants ?? [];
213
+ const gaps = report?.diagnostics ?? [];
214
+ const gapSites = new Set(gaps.map(gap => gap.site).filter(Boolean));
215
+ const otherSurvivors = report?.mutators === 'full'
216
+ ? mutants.filter(mutant =>
217
+ mutant.status === 'survived' &&
218
+ !gapSites.has(mutant.id ?? mutant.site) &&
219
+ !String(mutant.mutatorName ?? mutant.rule ?? '').includes('/'))
220
+ .length
221
+ : 0;
222
+ return { edits: mutants.length, gaps: gaps.length, otherSurvivors };
223
+ }
224
+
225
+ export function formatProgressSummary(report) {
226
+ const { edits, gaps, otherSurvivors } = summarizeReport(report);
227
+ const gapPart = otherSurvivors > 0
228
+ ? `${plural(gaps, 'targeted gap')}, ${plural(otherSurvivors, 'other survivor')}`
229
+ : plural(gaps, 'gap');
230
+ return `Completed (${report.evaluation}, ${plural(edits, 'edit')}, ${gapPart}).`;
231
+ }
232
+
233
+ export function renderText(report, { verbose = false, onlyGaps = false } = {}) {
162
234
  const lines = [];
163
235
  for (const file of report.extraction ?? []) {
164
236
  if (file.path !== 'diagnostic') continue;
@@ -170,11 +242,18 @@ export function renderText(report) {
170
242
  return lines.join('\n');
171
243
  }
172
244
  const mutants = report.mutants ?? [];
173
- for (const mutant of mutants) {
174
- lines.push(`${at(mutant.location)} ${mutant.status} ${describeEdit(mutant)}`);
245
+ const isListed = report.evaluation === 'listed';
246
+ if (!onlyGaps || isListed) {
247
+ for (const mutant of mutants) {
248
+ if (!verbose && !isListed && mutant.status === 'killed') continue;
249
+ lines.push(`${at(mutant.location)} ${mutant.status} ${describeEdit(mutant)}`);
250
+ }
175
251
  }
176
252
  const gaps = report.diagnostics ?? [];
177
- if (gaps.length) lines.push('', 'Test gaps:');
253
+ if (gaps.length) {
254
+ if (lines.length) lines.push('');
255
+ lines.push('Test gaps:');
256
+ }
178
257
  for (const gap of gaps) lines.push(...describeGap(gap));
179
258
  if (lines.length) lines.push('');
180
259
  if (report.evaluation === 'no_sites') {
@@ -186,8 +265,12 @@ export function renderText(report) {
186
265
  const tally = [...counts].map(([status, count]) => `${count} ${status}`).join(', ') || 'none';
187
266
  const tests = report.baseline?.tests;
188
267
  const size = Array.isArray(tests) ? tests.length : tests;
189
- lines.push(`${report.runner}${size === undefined ? '' : `, ${size} baseline tests`}: ` +
190
- `${mutants.length} edits (${tally}), ${gaps.length} test gaps` +
268
+ const { otherSurvivors } = summarizeReport(report);
269
+ const gapSummary = otherSurvivors > 0
270
+ ? `${plural(gaps.length, 'targeted gap')} (${plural(otherSurvivors, 'other survivor')})`
271
+ : plural(gaps.length, 'test gap');
272
+ lines.push(`${report.runner}${size === undefined ? '' : `, ${plural(size, 'baseline test')}`}: ` +
273
+ `${plural(mutants.length, 'edit')} (${tally}), ${gapSummary}` +
191
274
  (report.suppressed?.baseline ? `, ${report.suppressed.baseline} suppressed by baseline` : '') +
192
275
  (report.shard ? `, shard ${report.shard.index}/${report.shard.total}` : '') +
193
276
  (report.evaluation === 'evaluated' ? '' : `, evaluation ${report.evaluation}`));
@@ -9,6 +9,7 @@ import { targetedGap } from './targeted-gaps.mjs';
9
9
  import { checkpointKeyForTrial } from './checkpoint.mjs';
10
10
  import { candidateKey } from './shard.mjs';
11
11
  import { selectScope } from './scope.mjs';
12
+ import { createTypeContext } from './type-equivalence.mjs';
12
13
  import { inside, runnerPackage, withCopy } from './vitest.mjs';
13
14
 
14
15
  const supervisor = fileURLToPath(new URL('./runner-process.mjs', import.meta.url));
@@ -50,10 +51,17 @@ export async function analyzeConventional(project, files, options) {
50
51
  }));
51
52
  const originals = new Map(targets.map(({ file, input }) => [file, input]));
52
53
  const awaitsExtras = options.extras !== undefined;
54
+ const typeContext = options['type-check']
55
+ ? createTypeContext(root, targets.map(t => t.file), {
56
+ tsconfig: options.tsconfig,
57
+ onWarning: options.onTypeCheckWarning,
58
+ })
59
+ : null;
53
60
  const { sources, mutants: prepared } = prepareBuiltinSwitches(targets, {
54
61
  dialect: options.dialect,
55
62
  shifts: awaitsExtras,
56
63
  excludeRules: options['exclude-rule'],
64
+ typeContext,
57
65
  ...(profile === 'targeted' ? { keep: targetedOrBoundary, targeted: true } : {}),
58
66
  });
59
67
  const report = {
@@ -110,6 +118,9 @@ export async function analyzeConventional(project, files, options) {
110
118
  copyFileSync(runnerSource, workerRunner);
111
119
  const manifest = resolve(temp, 'mutation-session.json');
112
120
  const output = resolve(temp, 'mutation-session.jsonl');
121
+ const runTimeoutMs = options.timeout ? options.timeout * 1000 : 60_000;
122
+ const baselineTimeoutMs = options['baseline-timeout'] ? options['baseline-timeout'] * 1000 : runTimeoutMs;
123
+ const totalRunnable = runnable.filter(mutant => !mutant.parametric).length;
113
124
  writeFileSync(manifest, JSON.stringify({
114
125
  workspace, setup, workerRunner, output, temporary: temp, awaitsExtras,
115
126
  mutants: runnable.map(({ id, parametric, targeted }) => ({
@@ -122,11 +133,14 @@ export async function analyzeConventional(project, files, options) {
122
133
  isolatedTrials: options['isolated-trials'] === true,
123
134
  concurrency: options.concurrency ?? Math.max(1, availableParallelism() - 1),
124
135
  verifyTrials: options['verify-trials'] ?? 0,
125
- ...(options.timeout ? { runTimeout: options.timeout * 1000 } : {}),
136
+ runTimeout: runTimeoutMs,
137
+ baselineTimeout: baselineTimeoutMs,
138
+ ...(options['baseline-workers'] !== undefined ? { baselineWorkers: options['baseline-workers'] } : {}),
126
139
  config: options.config === undefined ? undefined : inside(workspace, options.config),
127
140
  files: [...new Set((options.test ?? []).map(file => inside(workspace, file)))],
141
+ ...(options.testSpecs?.length ? { selectedSpecs: options.testSpecs.map(({ project, file }) => ({ project, file: inside(workspace, file) })) } : {}),
128
142
  }));
129
- const limit = 75_000 + (options.timeout ? options.timeout * 1000 : 60_000) * runnable.length;
143
+ const limit = 75_000 + baselineTimeoutMs + runTimeoutMs * runnable.length;
130
144
  // The focused analysis names its threshold edits once it has recorded the comparisons.
131
145
  // Guarded by `finished` so a late resolution never writes after `withCopy` deletes `temp`,
132
146
  // while a write error during a live session aborts the child and propagates to the caller.
@@ -151,10 +165,36 @@ export async function analyzeConventional(project, files, options) {
151
165
  }
152
166
  });
153
167
  }
168
+ let progressTimer = null;
169
+ if (options.onProgress) {
170
+ options.onProgress('Running baseline tests...');
171
+ let baselineReported = false;
172
+ let lastDone = -1;
173
+ const pollProgress = () => {
174
+ const current = readEvents(output);
175
+ if (!baselineReported) {
176
+ const base = current.find(event => event.baseline)?.baseline;
177
+ if (base?.status === 'passed') {
178
+ baselineReported = true;
179
+ options.onProgress(`Baseline passed (${base.tests} tests). Running ${totalRunnable} mutant(s)...`);
180
+ }
181
+ }
182
+ if (baselineReported && totalRunnable > 0) {
183
+ const done = current.filter(event => event.id !== undefined).length;
184
+ if (done !== lastDone && done > 0) {
185
+ lastDone = done;
186
+ options.onProgress(`Mutants: ${Math.min(done, totalRunnable)}/${totalRunnable} completed`);
187
+ }
188
+ }
189
+ };
190
+ progressTimer = setInterval(pollProgress, 1_000);
191
+ progressTimer.unref?.();
192
+ }
154
193
  let run;
155
194
  try {
156
195
  run = await superviseSession(workspace, temp, manifest, limit, sessionAbort.signal);
157
196
  } finally {
197
+ if (progressTimer) clearInterval(progressTimer);
158
198
  finished = true;
159
199
  options.signal?.removeEventListener('abort', onAbort);
160
200
  }
@@ -216,5 +256,5 @@ export async function analyzeConventional(project, files, options) {
216
256
  mutants: judged.map(({ targeted: _rule, effects: _effects, _cachedDiagnostic: _cd, ...mutant }) => mutant),
217
257
  diagnostics,
218
258
  };
219
- }, { exclude: options['copy-exclude'] });
259
+ }, { exclude: options['copy-exclude'], onProgress: options.onProgress });
220
260
  }
@@ -76,6 +76,13 @@ async function besideSession(project, files, options, run, profile, stopsSession
76
76
  ...(options.shardKeys ? { shardKeys: options.shardKeys } : {}),
77
77
  ...(options.checkpointStore ? { checkpointStore: options.checkpointStore } : {}),
78
78
  ...(options['exclude-rule'] ? { 'exclude-rule': options['exclude-rule'] } : {}),
79
+ ...(options['type-check'] ? { 'type-check': true } : {}),
80
+ ...(options.tsconfig ? { tsconfig: options.tsconfig } : {}),
81
+ ...(options.onTypeCheckWarning ? { onTypeCheckWarning: options.onTypeCheckWarning } : {}),
82
+ ...(options.onProgress ? { onProgress: options.onProgress } : {}),
83
+ ...(options['baseline-timeout'] !== undefined ? { 'baseline-timeout': options['baseline-timeout'] } : {}),
84
+ ...(options['baseline-workers'] !== undefined ? { 'baseline-workers': options['baseline-workers'] } : {}),
85
+ ...(options.testSpecs?.length ? { testSpecs: options.testSpecs } : {}),
79
86
  }).then(report => ({ report }), error => ({ error }));
80
87
  let prepared;
81
88
  try {
@@ -171,13 +171,21 @@ export function mergeProjectConfig(configObj, cliValues, cliFiles) {
171
171
  const values = { ...cliValues };
172
172
  if (values.mutators === undefined && typeof configObj.mutators === 'string') values.mutators = configObj.mutators;
173
173
  if (values.timeout === undefined && configObj.timeout !== undefined) values.timeout = String(configObj.timeout);
174
+ if (values['baseline-timeout'] === undefined && configObj.baselineTimeout !== undefined) values['baseline-timeout'] = String(configObj.baselineTimeout);
175
+ if (values['baseline-workers'] === undefined && configObj.baselineWorkers !== undefined) values['baseline-workers'] = String(configObj.baselineWorkers);
174
176
  if (values.concurrency === undefined && configObj.concurrency !== undefined) values.concurrency = String(configObj.concurrency);
175
177
  if (values.config === undefined && typeof configObj.config === 'string') values.config = configObj.config;
178
+ if (values.tsconfig === undefined && typeof configObj.tsconfig === 'string') values.tsconfig = configObj.tsconfig;
176
179
  if (values.baseline === undefined && typeof configObj.baseline === 'string') values.baseline = configObj.baseline;
177
- if (!values.test?.length && Array.isArray(configObj.tests)) values.test = configObj.tests.map(String);
180
+ if (values.related === undefined && !values.test?.length && configObj.related === true) values.related = true;
181
+ if (!values.test?.length && !values.related && Array.isArray(configObj.tests)) values.test = configObj.tests.map(String);
178
182
  if (!values['copy-exclude']?.length && Array.isArray(configObj.copyExclude)) values['copy-exclude'] = configObj.copyExclude.map(String);
179
183
  if (values['copy-exclude-gitignore'] === undefined && configObj.copyExcludeGitignore === true) values['copy-exclude-gitignore'] = true;
180
184
  if (!values['exclude-rule']?.length && Array.isArray(configObj.excludeRules)) values['exclude-rule'] = configObj.excludeRules.map(String);
185
+ if (values['type-check'] === undefined && configObj.typeCheck === true) values['type-check'] = true;
186
+ if (values['fail-on-gaps'] === undefined && configObj.failOnGaps === true) values['fail-on-gaps'] = true;
187
+ if (values.verbose === undefined && values['only-gaps'] !== true && configObj.verbose === true) values.verbose = true;
188
+ if (values['only-gaps'] === undefined && values.verbose !== true && configObj.onlyGaps === true) values['only-gaps'] = true;
181
189
  const files = cliFiles.length ? cliFiles : (Array.isArray(configObj.files) ? configObj.files.map(String) : []);
182
190
  return { files, values };
183
191
  }
package/src/shard.mjs CHANGED
@@ -2,6 +2,7 @@ import { readFileSync, realpathSync } from 'node:fs';
2
2
  import { collectComparisons } from './analysis.mjs';
3
3
  import { prepareBuiltinSwitches, targetedOrBoundary } from './builtin-switches.mjs';
4
4
  import { selectScope } from './scope.mjs';
5
+ import { createTypeContext } from './type-equivalence.mjs';
5
6
  import { inside } from './vitest.mjs';
6
7
 
7
8
  export function parseShard(spec) {
@@ -95,9 +96,16 @@ export function listCandidates(project, files, options = {}) {
95
96
  ...subject,
96
97
  input: readFileSync(inside(root, subject.file)),
97
98
  }));
99
+ const typeContext = options['type-check']
100
+ ? createTypeContext(root, targets.map(t => t.file), {
101
+ tsconfig: options.tsconfig,
102
+ onWarning: options.onTypeCheckWarning,
103
+ })
104
+ : null;
98
105
  const { mutants: prepared } = prepareBuiltinSwitches(targets, {
99
106
  dialect: options.dialect,
100
107
  excludeRules: options['exclude-rule'],
108
+ typeContext,
101
109
  ...(profile === 'targeted' ? { keep: targetedOrBoundary, targeted: true } : {}),
102
110
  });
103
111
  for (const mutant of prepared) {