targeted-mutation 0.3.0 → 0.4.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.
@@ -0,0 +1,117 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 960 448" width="960" height="448" role="img" aria-label="Value-space blind spot and RIPR diagnosis in Targeted Mutation Testing">
2
+ <defs>
3
+ <style>
4
+ .heading { font-family: 'Virgil', 'Segoe Print', 'Bradley Hand', 'Chalkboard SE', cursive, sans-serif; font-size: 16.5px; font-weight: 700; }
5
+ .label { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; font-size: 12.5px; font-weight: 700; }
6
+ .body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; font-size: 12px; }
7
+ .small { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; font-size: 11px; }
8
+ .code { font-family: ui-monospace, 'SFMono-Regular', Menlo, Monaco, Consolas, monospace; font-size: 12px; }
9
+ .code-sm { font-family: ui-monospace, 'SFMono-Regular', Menlo, Monaco, Consolas, monospace; font-size: 11px; }
10
+ </style>
11
+ <pattern id="hatch-red" width="8" height="8" patternUnits="userSpaceOnUse" patternTransform="rotate(45)">
12
+ <line x1="0" y1="0" x2="0" y2="8" stroke="#ffa8a8" stroke-width="2" />
13
+ </pattern>
14
+ <marker id="arrow-gray" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="6.5" markerHeight="6.5" orient="auto-start-reverse">
15
+ <path d="M 0 1.5 L 8.5 5 L 0 8.5 z" fill="#64748b"/>
16
+ </marker>
17
+ <marker id="arrow-purple" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="6.5" markerHeight="6.5" orient="auto-start-reverse">
18
+ <path d="M 0 1.5 L 8.5 5 L 0 8.5 z" fill="#6741d9"/>
19
+ </marker>
20
+ <marker id="arrow-red" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="6.5" markerHeight="6.5" orient="auto-start-reverse">
21
+ <path d="M 0 1.5 L 8.5 5 L 0 8.5 z" fill="#e03131"/>
22
+ </marker>
23
+ <marker id="arrow-orange" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="6.5" markerHeight="6.5" orient="auto-start-reverse">
24
+ <path d="M 0 1.5 L 8.5 5 L 0 8.5 z" fill="#d9480f"/>
25
+ </marker>
26
+ </defs>
27
+
28
+ <!-- Clean card background for GitHub light & dark themes -->
29
+ <rect x="0" y="0" width="960" height="448" rx="14" fill="#ffffff"/>
30
+ <rect x="1" y="1" width="958" height="446" rx="13" fill="none" stroke="#e9ecef" stroke-width="1.5"/>
31
+
32
+ <!-- ====================================================================== -->
33
+ <!-- PANEL 1: Value-space blind spot -->
34
+ <!-- ====================================================================== -->
35
+ <rect x="24" y="22" width="912" height="202" rx="12" fill="#f8fafc" stroke="#e2e8f0" stroke-width="1.5"/>
36
+ <text x="44" y="48" class="heading" fill="#1e293b">1. Value-space blind spot</text>
37
+ <text x="276" y="48" class="code" fill="#475569">yen &gt;= 5000</text>
38
+ <text x="372" y="48" class="small" fill="#64748b">(tests pass 4800 and 5000)</text>
39
+
40
+ <!-- Conventional row -->
41
+ <text x="44" y="88" class="label" fill="#495057">Conventional</text>
42
+ <rect x="164" y="68" width="286" height="32" rx="8" fill="#ebfbee" stroke="#2f9e44" stroke-width="1.4"/>
43
+ <text x="307" y="88" text-anchor="middle" class="code-sm" fill="#1b4332">&gt; 5000, &lt; 5000, true / false</text>
44
+ <line x1="450" y1="84" x2="488" y2="84" stroke="#64748b" stroke-width="1.5" marker-end="url(#arrow-gray)"/>
45
+ <rect x="494" y="68" width="128" height="32" rx="8" fill="#ebfbee" stroke="#2f9e44" stroke-width="1.4"/>
46
+ <text x="558" y="88" text-anchor="middle" class="label" fill="#2b8a3e">100% killed</text>
47
+ <text x="640" y="88" class="small" fill="#c92a2a" font-weight="700">misses yen &gt;= 4999</text>
48
+
49
+ <!-- Targeted row (number line) -->
50
+ <text x="44" y="160" class="label" fill="#5f3dc4">Targeted</text>
51
+ <rect x="164" y="114" width="748" height="94" rx="10" fill="#ffffff" stroke="#d0bfff" stroke-width="1.4"/>
52
+
53
+ <!-- Unpinned interval [4801..4999] -->
54
+ <rect x="278" y="148" width="388" height="22" rx="4" fill="#fff5f5" stroke="#ffa8a8" stroke-width="1.2"/>
55
+ <rect x="278" y="148" width="388" height="22" rx="4" fill="url(#hatch-red)" opacity="0.7"/>
56
+ <text x="472" y="139" text-anchor="middle" class="small" fill="#c92a2a" font-weight="700">unpinned thresholds [4801 .. 4999]</text>
57
+
58
+ <!-- Axis -->
59
+ <line x1="196" y1="159" x2="884" y2="159" stroke="#495057" stroke-width="1.8" marker-end="url(#arrow-gray)"/>
60
+
61
+ <!-- 4800 -->
62
+ <circle cx="258" cy="159" r="6" fill="#1971c2" stroke="#ffffff" stroke-width="2"/>
63
+ <text x="258" y="136" text-anchor="middle" class="small" fill="#1864ab">false</text>
64
+ <text x="258" y="185" text-anchor="middle" class="code" fill="#1864ab">4800</text>
65
+
66
+ <!-- 4999 -->
67
+ <polygon points="666,151 674,159 666,167 658,159" fill="#6741d9" stroke="#ffffff" stroke-width="1.5"/>
68
+ <text x="666" y="185" text-anchor="middle" class="code" fill="#5f3dc4" font-weight="700">4999</text>
69
+ <text x="666" y="200" text-anchor="middle" class="code-sm" fill="#5f3dc4">synthesizes yen &gt;= 4999 (1 witness closes 4801..4999)</text>
70
+
71
+ <!-- 5000 -->
72
+ <circle cx="766" cy="159" r="6" fill="#2f9e44" stroke="#ffffff" stroke-width="2"/>
73
+ <text x="766" y="136" text-anchor="middle" class="small" fill="#2b8a3e">true</text>
74
+ <text x="766" y="185" text-anchor="middle" class="code" fill="#2b8a3e">5000</text>
75
+
76
+ <!-- ====================================================================== -->
77
+ <!-- PANEL 2: RIPR diagnosis -->
78
+ <!-- ====================================================================== -->
79
+ <rect x="24" y="240" width="912" height="186" rx="12" fill="#f8fafc" stroke="#e2e8f0" stroke-width="1.5"/>
80
+ <text x="44" y="266" class="heading" fill="#1e293b">2. RIPR diagnosis</text>
81
+ <text x="202" y="266" class="small" fill="#64748b">why a mutant survived</text>
82
+
83
+ <!-- Conventional row -->
84
+ <text x="44" y="305" class="label" fill="#495057">Conventional</text>
85
+ <rect x="164" y="284" width="92" height="34" rx="8" fill="#ffffff" stroke="#adb5bd" stroke-width="1.4"/>
86
+ <text x="210" y="305" text-anchor="middle" class="body" fill="#495057">Reach</text>
87
+ <line x1="256" y1="301" x2="292" y2="301" stroke="#64748b" stroke-width="1.5" marker-end="url(#arrow-gray)"/>
88
+
89
+ <rect x="298" y="284" width="280" height="34" rx="8" fill="#f1f3f5" stroke="#868e96" stroke-width="1.4" stroke-dasharray="5 3"/>
90
+ <text x="438" y="305" text-anchor="middle" class="body" fill="#64748b">Infect -&gt; Propagate -&gt; Reveal (black box)</text>
91
+ <line x1="578" y1="301" x2="618" y2="301" stroke="#64748b" stroke-width="1.5" marker-end="url(#arrow-gray)"/>
92
+
93
+ <rect x="624" y="284" width="288" height="34" rx="8" fill="#f8f9fa" stroke="#868e96" stroke-width="1.5"/>
94
+ <text x="768" y="305" text-anchor="middle" class="code" fill="#495057"><tspan font-weight="700">survived</tspan> (manual triage)</text>
95
+
96
+ <!-- Targeted row -->
97
+ <text x="44" y="376" class="label" fill="#5f3dc4">Targeted</text>
98
+ <rect x="164" y="355" width="92" height="34" rx="8" fill="#e7f5ff" stroke="#1971c2" stroke-width="1.4"/>
99
+ <text x="210" y="376" text-anchor="middle" class="body" fill="#1864ab">Reach</text>
100
+ <line x1="256" y1="372" x2="292" y2="372" stroke="#6741d9" stroke-width="1.5" marker-end="url(#arrow-purple)"/>
101
+
102
+ <rect x="298" y="350" width="144" height="44" rx="8" fill="#f3f0ff" stroke="#6741d9" stroke-width="1.6"/>
103
+ <text x="370" y="369" text-anchor="middle" class="label" fill="#5f3dc4">Operand Probe</text>
104
+ <text x="370" y="385" text-anchor="middle" class="small" fill="#3b2c68">Infect observed?</text>
105
+
106
+ <!-- Upper branch: INPUT GAP -->
107
+ <path d="M 442 362 L 472 362 L 472 348 L 618 348" fill="none" stroke="#e03131" stroke-width="1.6" marker-end="url(#arrow-red)"/>
108
+ <text x="545" y="342" text-anchor="middle" class="small" fill="#c92a2a" font-weight="700">No (agreed)</text>
109
+ <rect x="624" y="331" width="288" height="34" rx="8" fill="#fff5f5" stroke="#e03131" stroke-width="1.5"/>
110
+ <text x="768" y="352" text-anchor="middle" class="body" fill="#691b1b"><tspan class="label" fill="#c92a2a">INPUT GAP</tspan> · exact missing input</text>
111
+
112
+ <!-- Lower branch: ASSERTION GAP -->
113
+ <path d="M 442 382 L 472 382 L 472 396 L 618 396" fill="none" stroke="#d9480f" stroke-width="1.6" marker-end="url(#arrow-orange)"/>
114
+ <text x="545" y="390" text-anchor="middle" class="small" fill="#d9480f" font-weight="700">Yes in T, passed</text>
115
+ <rect x="624" y="379" width="288" height="34" rx="8" fill="#fff4e6" stroke="#d9480f" stroke-width="1.5"/>
116
+ <text x="768" y="400" text-anchor="middle" class="body" fill="#6e2b07"><tspan class="label" fill="#d9480f">ASSERTION GAP</tspan> · weak test T</text>
117
+ </svg>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "targeted-mutation",
3
- "version": "0.3.0",
3
+ "version": "0.4.1",
4
4
  "description": "Find the tests a JavaScript or TypeScript suite is missing by trying small, targeted source edits against it.",
5
5
  "keywords": [
6
6
  "mutation-testing",
@@ -43,9 +43,9 @@
43
43
  "NOTICE"
44
44
  ],
45
45
  "optionalDependencies": {
46
- "@targeted-mutation/tmt-darwin-arm64": "0.3.0",
47
- "@targeted-mutation/tmt-darwin-x64": "0.3.0",
48
- "@targeted-mutation/tmt-linux-arm64": "0.3.0",
49
- "@targeted-mutation/tmt-linux-x64": "0.3.0"
46
+ "@targeted-mutation/tmt-darwin-arm64": "0.4.1",
47
+ "@targeted-mutation/tmt-darwin-x64": "0.4.1",
48
+ "@targeted-mutation/tmt-linux-arm64": "0.4.1",
49
+ "@targeted-mutation/tmt-linux-x64": "0.4.1"
50
50
  }
51
51
  }
package/src/analysis.mjs CHANGED
@@ -63,7 +63,10 @@ export function collectComparisons(root, files, options) {
63
63
  const extraction = [];
64
64
  const scoped = selectScope(root, files, options);
65
65
  const typeContext = options['type-check'] && ['targeted', 'full'].includes(options.mutators)
66
- ? createTypeContext(root, scoped.map(subject => subject.file))
66
+ ? createTypeContext(root, scoped.map(subject => subject.file), {
67
+ tsconfig: options.tsconfig,
68
+ onWarning: options.onTypeCheckWarning,
69
+ })
67
70
  : null;
68
71
  for (const { file, selected } of scoped) {
69
72
  const input = readFileSync(inside(root, file));
@@ -118,7 +121,7 @@ export function verdict(run, baseline) {
118
121
  }
119
122
 
120
123
  function makeAttempt(root, subjects, runner, copyExclude, probeChecks, settings = {}) {
121
- const { tracing = false, activate, trial, witness, coverageSites, synchronousTrace, collect } = settings;
124
+ const { tracing = false, activate, trial, witness, coverageSites, synchronousTrace, collect, isBaseline = false } = settings;
122
125
  const attempt = withCopy(root, (workspace, temp) => {
123
126
  const trace = tracing ? resolve(temp, 'trace.jsonl') : undefined;
124
127
  if (trace) mkdirSync(pendingTraceDirectory(trace));
@@ -148,7 +151,7 @@ function makeAttempt(root, subjects, runner, copyExclude, probeChecks, settings
148
151
  writeFileSync(path, readFileSync(inside(workspace, witness.content)), { flag: 'wx' });
149
152
  witnessFile = relative(workspace, path);
150
153
  }
151
- 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 });
152
155
  if (!tracing && collect) {
153
156
  const path = resolve(workspace, collect);
154
157
  return { ...result, collected: existsSync(path) ? readFileSync(path, 'utf8') : '' };
@@ -439,9 +442,16 @@ function diagnose(trial, result) {
439
442
  const tests = [...observation.observed].filter(([, operands]) => operands.some(differs))
440
443
  .map(([key]) => testcase(observation.tests.get(key)));
441
444
  if (tests.length) {
442
- const example = trial.adjustment !== undefined ? observation.rows.find(row => differs(row.operands)).operands : undefined;
443
- return { kind: 'ASSERTION GAP', site: site.id, location: site.location, tests,
444
- 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
+ };
445
455
  }
446
456
  const binary = observation.rows[0]?.operands;
447
457
  if (!binary) return null;
@@ -529,11 +539,12 @@ function verifyWitnessRuns(baseline, original, changed) {
529
539
  }
530
540
 
531
541
  function analyzePlaywright(root, subjects, report, options, specification) {
532
- const runner = (workspace, temp) => runPlaywright(workspace, temp, { config: options.config, projects: options.project, original: root,
533
- 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 });
534
545
  const probeChecks = new Map(subjects.map(subject => [subject, createProbePreloadCheck(subject.input)]));
535
546
  const attempt = settings => makeAttempt(root, subjects, runner, options['copy-exclude'], probeChecks, settings);
536
- const baseline = attempt();
547
+ const baseline = attempt({ isBaseline: true });
537
548
  report.baseline = playwrightSummary(baseline);
538
549
  if (baseline.status !== 'passed') {
539
550
  return { ...report, evaluation: 'baseline_error',
@@ -616,19 +627,27 @@ export function prepareAnalysis(project, files, options) {
616
627
 
617
628
  const specification = options.spec ? JSON.parse(readFileSync(inside(root, options.spec), 'utf8')) : {};
618
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);
619
633
  const runner = (workspace, temp, settings) => runVitest(workspace, temp, {
620
- ...settings, config: options.config, testFiles: options.test, testProjects: options.testProjects, ...(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 } : {}),
621
640
  });
622
641
  const probeChecks = new Map(subjects.map(subject => [subject, createProbePreloadCheck(subject.input)]));
623
642
  const attempt = settings => makeAttempt(root, subjects, runner, options['copy-exclude'], probeChecks, settings);
624
643
  // Beside a session, which runs the suite on its own, the recording run stands for the baseline when it passes.
625
644
  // Otherwise the plain baseline runs first, so a failing suite is reported as before.
626
- const recorded = options.traceIsBaseline ? attempt({ tracing: true }) : null;
645
+ const recorded = options.traceIsBaseline ? attempt({ tracing: true, isBaseline: true }) : null;
627
646
  // Do not re-run a plain baseline when the recording run already timed out under the same suite/limit.
628
- const plainBaseline = recorded?.status === 'passed' || recorded?.status === 'timeout' ? null : attempt();
647
+ const plainBaseline = recorded?.status === 'passed' || recorded?.status === 'timeout' ? null : attempt({ isBaseline: true });
629
648
  const baseline = plainBaseline ?? (recorded?.status === 'passed' ? { status: 'passed', tests: recorded.tests } : recorded);
630
649
  if (baseline.status !== 'passed') {
631
- const timeoutSeconds = options.timeout ?? 60;
650
+ const timeoutSeconds = baselineTimeoutSeconds;
632
651
  return { report: { ...report, evaluation: 'baseline_error', baseline: {
633
652
  status: baseline.status,
634
653
  ...(baseline.status === 'timeout' ? { timeoutSeconds } : {}),
@@ -371,7 +371,11 @@ export function collectMutations(text, file, { dialect, selected = () => true, s
371
371
  }
372
372
  } else if (isLogical(node) && !staysInPlace(node.right)) {
373
373
  const operand = grouped;
374
- const rightFalsy = falsyLiteralLabel(node.right);
374
+ const rightNode = strip(node.right);
375
+ const rawRightFalsy = falsyLiteralLabel(node.right);
376
+ const rightFalsy = rawRightFalsy === 'NaN' && typeEquivalence?.hasLocalNaNBinding?.(begin(rightNode), rightNode.end)
377
+ ? undefined
378
+ : rawRightFalsy;
375
379
  const more = { thunk: true, ...(written(node.right) ? { pureRight: true } : {}) };
376
380
  edit(targetedRules.ignored, 'left', `(${left}, ${right})`, more);
377
381
  edit(targetedRules.ignored, 'right', `(${left} ${operator} (${right}, ${ignoredValue[operator]}))`, more);
@@ -379,7 +383,8 @@ export function collectMutations(text, file, { dialect, selected = () => true, s
379
383
  if (boolean && writtenFalsy(node.right)) return;
380
384
  const leftNode = strip(node.left);
381
385
  if (typeEquivalence?.isNullishFallbackEquivalent(begin(leftNode), leftNode.end, rightFalsy)) return;
382
- const fallbackMore = { ...more, ...(rightFalsy ? { rightFalsy } : {}), evidence: true };
386
+ const possibleFalsy = typeEquivalence?.possibleNullishFallbackFalsy?.(begin(leftNode), leftNode.end) ?? null;
387
+ const fallbackMore = { ...more, ...(rightFalsy ? { rightFalsy } : {}), ...(possibleFalsy?.length ? { possibleFalsy } : {}), evidence: true };
383
388
  if (operator === '??') edit(targetedRules.fallback, 'or', `(${operand(node.left)} || ${operand(node.right)})`, fallbackMore);
384
389
  // Where only the truth of the value is used, nobody writes `??` for `||`.
385
390
  else if (operator === '||' && !boolean) edit(targetedRules.fallback, 'nullish', `(${operand(node.left)} ?? ${operand(node.right)})`, fallbackMore);
@@ -58,7 +58,10 @@ export function computeCampaignContext(targets, options = {}, root = null) {
58
58
  displaceThresholds: !!options['displace-thresholds'],
59
59
  excludeRules: options['exclude-rule'] ?? null,
60
60
  ...(options['type-check'] ? { typeCheck: true } : {}),
61
+ ...(options.tsconfig ? { tsconfig: options.tsconfig } : {}),
61
62
  timeout: options.timeout ?? null,
63
+ ...(options['baseline-timeout'] !== undefined ? { baselineTimeout: options['baseline-timeout'] } : {}),
64
+ ...(options['baseline-workers'] !== undefined ? { baselineWorkers: options['baseline-workers'] } : {}),
62
65
  copyExclude: options['copy-exclude'] ?? null,
63
66
  isolatedTrials: !!options['isolated-trials'],
64
67
  }));
@@ -13,12 +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.
18
19
  --type-check Use TypeScript's type checker (when strictNullChecks is enabled) to skip
19
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).
20
22
  --no-config Ignore targeted-mutation.config.{json,mjs} and package.json#targetedMutation.
21
- --progress Print lightweight progress updates to stderr.
23
+ --progress Print progress updates (copying, baseline, mutant completion) to stderr.
22
24
 
23
25
  Profiles (analyze):
24
26
  --mutators targeted|full targeted (default) edits comparison boundaries and integer thresholds
@@ -48,14 +50,19 @@ Profiles (analyze):
48
50
  Runner (analyze):
49
51
  --runner vitest|playwright Test runner (default: vitest).
50
52
  --config FILE Runner configuration file inside the project.
51
- --test FILE Run only this test file. Repeatable.
53
+ --test FILE Run only this test file or glob. Repeatable. With --related, narrows related tests.
52
54
  --related Select only Vitest test files related to the target source files.
53
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).
54
58
  --project NAME Playwright project. Repeatable.
55
59
 
56
60
  Output & Baselines:
57
61
  --format text|json|jsonl|sarif
58
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.
59
66
  --json-out FILE Also write the JSON report to FILE (can be combined with --format text).
60
67
  --sarif-out FILE Also write the SARIF report to FILE (can be combined with --format text).
61
68
  --baseline FILE Suppress findings already recorded in FILE.
@@ -76,14 +83,30 @@ export function chooseFormat(requested, terminal) {
76
83
  // Test names and runner output come from the analyzed project and can carry terminal control sequences.
77
84
  const printable = value => String(value).replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/g, '?');
78
85
  const firstLine = value => printable(value).split('\n').find(line => line.trim())?.trim() ?? '';
79
- 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)';
80
91
 
81
92
  function describeEdit(mutant) {
82
93
  const name = mutant.mutatorName ?? mutant.rule ?? 'edit';
83
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))}`;
84
- 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
+ }
85
108
  const operator = String(mutant.replacement).trim();
86
- if (mutant.operator !== undefined && /^[<>=!&|?+*\/%-]+$/.test(operator)) return `${name}: ${mutant.operator} -> ${operator}`;
109
+ if (mutant.operator !== undefined && /^[<>=!&|?+*\/%-]+$/.test(operator)) return `${name}: ${printable(mutant.operator)} -> ${operator}`;
87
110
  return `${name}: replace with ${firstLine(mutant.replacement)}`;
88
111
  }
89
112
 
@@ -92,7 +115,7 @@ function describeBaseline(baseline = {}) {
92
115
  const limit = baseline.timeoutSeconds !== undefined ? ` after ${baseline.timeoutSeconds}s` : '';
93
116
  const lines = [
94
117
  `The baseline test suite timed out${limit} before any edit.`,
95
- ' 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>.',
96
119
  ];
97
120
  if (baseline.output?.trim()) {
98
121
  lines.push(...printable(baseline.output).trim().split('\n').slice(-10).map(line => ` ${line}`));
@@ -111,6 +134,19 @@ function describeBaseline(baseline = {}) {
111
134
  return lines;
112
135
  }
113
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
+
114
150
  function describeGap(gap) {
115
151
  const lines = [`${gap.kind ?? 'GAP'} ${at(gap.location)}${gap.rule ? ` ${gap.rule}` : ''}`];
116
152
  const witness = gap.witness;
@@ -127,13 +163,20 @@ function describeGap(gap) {
127
163
  else if (gap.missing && gap.uncertain) {
128
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`);
129
165
  } else if (gap.missing) lines.push(` add ${printable(gap.missing)}`);
130
- else {
131
- const shown = (gap.tests ?? []).slice(0, 3).map(test => `${printable(test.file)} > ${printable(test.name)}`);
132
- const more = (gap.tests?.length ?? 0) - shown.length;
133
- const where = [...shown, ...(more > 0 ? [`${more} more`] : []), ...(gap.outsideTests ? ['code outside the tests'] : [])].join('; ');
134
- const operands = gap.example?.operands ? ` (operands ${gap.example.operands.map(printable).join(', ')})` : '';
135
- 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`);
136
177
  }
178
+ if (gap.advice) lines.push(` ${printable(gap.advice)}`);
179
+ else lines.push(...formatAssertionDetails(gap));
137
180
  }
138
181
  if (gap.kind === 'UNTESTED CHANGE') {
139
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))}`,
@@ -187,7 +230,7 @@ export function formatProgressSummary(report) {
187
230
  return `Completed (${report.evaluation}, ${plural(edits, 'edit')}, ${gapPart}).`;
188
231
  }
189
232
 
190
- export function renderText(report) {
233
+ export function renderText(report, { verbose = false, onlyGaps = false } = {}) {
191
234
  const lines = [];
192
235
  for (const file of report.extraction ?? []) {
193
236
  if (file.path !== 'diagnostic') continue;
@@ -199,11 +242,18 @@ export function renderText(report) {
199
242
  return lines.join('\n');
200
243
  }
201
244
  const mutants = report.mutants ?? [];
202
- for (const mutant of mutants) {
203
- 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
+ }
204
251
  }
205
252
  const gaps = report.diagnostics ?? [];
206
- if (gaps.length) lines.push('', 'Test gaps:');
253
+ if (gaps.length) {
254
+ if (lines.length) lines.push('');
255
+ lines.push('Test gaps:');
256
+ }
207
257
  for (const gap of gaps) lines.push(...describeGap(gap));
208
258
  if (lines.length) lines.push('');
209
259
  if (report.evaluation === 'no_sites') {
@@ -51,7 +51,12 @@ export async function analyzeConventional(project, files, options) {
51
51
  }));
52
52
  const originals = new Map(targets.map(({ file, input }) => [file, input]));
53
53
  const awaitsExtras = options.extras !== undefined;
54
- const typeContext = options['type-check'] ? createTypeContext(root, targets.map(t => t.file)) : null;
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;
55
60
  const { sources, mutants: prepared } = prepareBuiltinSwitches(targets, {
56
61
  dialect: options.dialect,
57
62
  shifts: awaitsExtras,
@@ -113,6 +118,9 @@ export async function analyzeConventional(project, files, options) {
113
118
  copyFileSync(runnerSource, workerRunner);
114
119
  const manifest = resolve(temp, 'mutation-session.json');
115
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;
116
124
  writeFileSync(manifest, JSON.stringify({
117
125
  workspace, setup, workerRunner, output, temporary: temp, awaitsExtras,
118
126
  mutants: runnable.map(({ id, parametric, targeted }) => ({
@@ -125,12 +133,15 @@ export async function analyzeConventional(project, files, options) {
125
133
  isolatedTrials: options['isolated-trials'] === true,
126
134
  concurrency: options.concurrency ?? Math.max(1, availableParallelism() - 1),
127
135
  verifyTrials: options['verify-trials'] ?? 0,
128
- ...(options.timeout ? { runTimeout: options.timeout * 1000 } : {}),
136
+ runTimeout: runTimeoutMs,
137
+ baselineTimeout: baselineTimeoutMs,
138
+ ...(options['baseline-workers'] !== undefined ? { baselineWorkers: options['baseline-workers'] } : {}),
139
+ ...(options.progressIntervalMs !== undefined ? { progressIntervalMs: options.progressIntervalMs } : {}),
129
140
  config: options.config === undefined ? undefined : inside(workspace, options.config),
130
141
  files: [...new Set((options.test ?? []).map(file => inside(workspace, file)))],
131
142
  ...(options.testSpecs?.length ? { selectedSpecs: options.testSpecs.map(({ project, file }) => ({ project, file: inside(workspace, file) })) } : {}),
132
143
  }));
133
- const limit = 75_000 + (options.timeout ? options.timeout * 1000 : 60_000) * runnable.length;
144
+ const limit = 75_000 + baselineTimeoutMs + runTimeoutMs * runnable.length;
134
145
  // The focused analysis names its threshold edits once it has recorded the comparisons.
135
146
  // Guarded by `finished` so a late resolution never writes after `withCopy` deletes `temp`,
136
147
  // while a write error during a live session aborts the child and propagates to the caller.
@@ -155,10 +166,62 @@ export async function analyzeConventional(project, files, options) {
155
166
  }
156
167
  });
157
168
  }
169
+ let progressTimer = null;
170
+ if (options.onProgress) {
171
+ const progressIntervalMs = options.progressIntervalMs ?? 5_000;
172
+ const pollIntervalMs = Math.min(1_000, Math.max(50, Math.floor(progressIntervalMs / 2)));
173
+ const baselineStartedAt = Date.now();
174
+ let baselineDoneAt = baselineStartedAt;
175
+ let lastReportAt = baselineStartedAt;
176
+ options.onProgress('Running baseline tests...');
177
+ let baselineReported = false;
178
+ let lastDone = -1;
179
+ const pollProgress = () => {
180
+ const now = Date.now();
181
+ const current = readEvents(output);
182
+ if (!baselineReported) {
183
+ const base = current.find(event => event.baseline)?.baseline;
184
+ if (base?.status === 'passed') {
185
+ baselineReported = true;
186
+ baselineDoneAt = now;
187
+ lastReportAt = now;
188
+ options.onProgress(`Baseline passed (${base.tests} tests). Running ${totalRunnable} mutant(s)...`);
189
+ } else if (now - lastReportAt >= progressIntervalMs) {
190
+ lastReportAt = now;
191
+ const elapsed = Math.max(1, Math.round((now - baselineStartedAt) / 1000));
192
+ options.onProgress(`Running baseline tests... (${elapsed}s elapsed)`);
193
+ }
194
+ }
195
+ if (baselineReported && totalRunnable > 0) {
196
+ const sessionComplete = current.some(event => event.complete === true);
197
+ const recordedDone = current.filter(event => event.id !== undefined).length;
198
+ let latestProgress = 0;
199
+ for (const event of current) {
200
+ if (typeof event.progress?.completed === 'number' && event.progress.completed > latestProgress) {
201
+ latestProgress = event.progress.completed;
202
+ }
203
+ }
204
+ const provisionalCap = Math.max(0, totalRunnable - 1);
205
+ const done = Math.min(totalRunnable, Math.max(recordedDone, Math.min(latestProgress, provisionalCap)));
206
+ if (done > lastDone && done > 0) {
207
+ lastDone = done;
208
+ lastReportAt = now;
209
+ options.onProgress(`Mutants: ${done}/${totalRunnable} completed`);
210
+ } else if (!sessionComplete && now - lastReportAt >= progressIntervalMs) {
211
+ lastReportAt = now;
212
+ const elapsed = Math.max(1, Math.round((now - baselineDoneAt) / 1000));
213
+ options.onProgress(`Mutants: ${Math.max(0, done)}/${totalRunnable} completed (${elapsed}s elapsed)`);
214
+ }
215
+ }
216
+ };
217
+ progressTimer = setInterval(pollProgress, pollIntervalMs);
218
+ progressTimer.unref?.();
219
+ }
158
220
  let run;
159
221
  try {
160
222
  run = await superviseSession(workspace, temp, manifest, limit, sessionAbort.signal);
161
223
  } finally {
224
+ if (progressTimer) clearInterval(progressTimer);
162
225
  finished = true;
163
226
  options.signal?.removeEventListener('abort', onAbort);
164
227
  }
@@ -220,5 +283,5 @@ export async function analyzeConventional(project, files, options) {
220
283
  mutants: judged.map(({ targeted: _rule, effects: _effects, _cachedDiagnostic: _cd, ...mutant }) => mutant),
221
284
  diagnostics,
222
285
  };
223
- }, { exclude: options['copy-exclude'] });
286
+ }, { exclude: options['copy-exclude'], onProgress: options.onProgress, reuseCopy: options.reusableCopy });
224
287
  }
@@ -77,7 +77,14 @@ async function besideSession(project, files, options, run, profile, stopsSession
77
77
  ...(options.checkpointStore ? { checkpointStore: options.checkpointStore } : {}),
78
78
  ...(options['exclude-rule'] ? { 'exclude-rule': options['exclude-rule'] } : {}),
79
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'] } : {}),
80
85
  ...(options.testSpecs?.length ? { testSpecs: options.testSpecs } : {}),
86
+ ...(options.reusableCopy ? { reusableCopy: options.reusableCopy } : {}),
87
+ ...(options.progressIntervalMs !== undefined ? { progressIntervalMs: options.progressIntervalMs } : {}),
81
88
  }).then(report => ({ report }), error => ({ error }));
82
89
  let prepared;
83
90
  try {
@@ -171,8 +171,11 @@ 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
180
  if (values.related === undefined && !values.test?.length && configObj.related === true) values.related = true;
178
181
  if (!values.test?.length && !values.related && Array.isArray(configObj.tests)) values.test = configObj.tests.map(String);
@@ -180,6 +183,9 @@ export function mergeProjectConfig(configObj, cliValues, cliFiles) {
180
183
  if (values['copy-exclude-gitignore'] === undefined && configObj.copyExcludeGitignore === true) values['copy-exclude-gitignore'] = true;
181
184
  if (!values['exclude-rule']?.length && Array.isArray(configObj.excludeRules)) values['exclude-rule'] = configObj.excludeRules.map(String);
182
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;
183
189
  const files = cliFiles.length ? cliFiles : (Array.isArray(configObj.files) ? configObj.files.map(String) : []);
184
190
  return { files, values };
185
191
  }
package/src/shard.mjs CHANGED
@@ -96,7 +96,12 @@ export function listCandidates(project, files, options = {}) {
96
96
  ...subject,
97
97
  input: readFileSync(inside(root, subject.file)),
98
98
  }));
99
- const typeContext = options['type-check'] ? createTypeContext(root, targets.map(t => t.file)) : null;
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;
100
105
  const { mutants: prepared } = prepareBuiltinSwitches(targets, {
101
106
  dialect: options.dialect,
102
107
  excludeRules: options['exclude-rule'],