targeted-mutation 0.1.0 → 0.2.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/README.md +8 -2
- package/bin/tmt.mjs +88 -30
- package/docs/analysis.md +1 -1
- package/package.json +5 -5
- package/src/analysis.mjs +53 -13
- package/src/baseline.mjs +184 -0
- package/src/builtin-mutations.mjs +56 -1
- package/src/builtin-switches.mjs +4 -3
- package/src/checkpoint.mjs +173 -0
- package/src/cli-output.mjs +32 -3
- package/src/conventional.mjs +54 -6
- package/src/enclosing-suppression.mjs +48 -0
- package/src/operator-analysis.mjs +49 -10
- package/src/project-config.mjs +183 -0
- package/src/reachability.mjs +335 -0
- package/src/sarif.mjs +156 -0
- package/src/shard.mjs +137 -0
- package/src/standard-plan.mjs +6 -1
- package/src/weakened-tests.mjs +178 -0
- package/src/witness-analysis.mjs +1 -1
- package/src/witness-discovery.mjs +10 -10
- package/src/witness-fixtures.mjs +4 -3
- package/src/witness-rules.mjs +129 -1
package/README.md
CHANGED
|
@@ -59,10 +59,16 @@ The tool copies the project to a temporary directory and runs the project's own
|
|
|
59
59
|
npx targeted-mutation analyze # every source file in the current project (default: targeted)
|
|
60
60
|
npx targeted-mutation analyze . src/cart.ts # selected files
|
|
61
61
|
npx targeted-mutation analyze --lines src/cart.ts:10-40
|
|
62
|
-
npx targeted-mutation analyze --since origin/main # edits on lines changed since a revision
|
|
62
|
+
npx targeted-mutation analyze --since origin/main # edits on lines changed since a revision (also flags weakened tests)
|
|
63
63
|
npx targeted-mutation analyze --since origin/main --undo-changes # also: which changes do the tests pass without?
|
|
64
64
|
npx targeted-mutation analyze --suggest-assertions # also: the exact value a weak assertion should compare with
|
|
65
65
|
npx targeted-mutation analyze --mutators full # full built-in StrykerJS-compatible mutation set (no StrykerJS required)
|
|
66
|
+
npx targeted-mutation analyze --list --shard 0/4 # preview candidates for CI shard 0 of 4 without running tests
|
|
67
|
+
npx targeted-mutation analyze --format sarif # emit SARIF 2.1.0 for GitHub Code Scanning (or --format jsonl)
|
|
68
|
+
npx targeted-mutation analyze --write-baseline tmt-baseline.json # save stable finding IDs
|
|
69
|
+
npx targeted-mutation analyze --baseline tmt-baseline.json # suppress already-recorded findings
|
|
70
|
+
npx targeted-mutation analyze --checkpoint .tmt-checkpoint.jsonl # resume interrupted runs safely
|
|
71
|
+
npx targeted-mutation analyze --exclude-rule nullish-equality/v1 --copy-exclude-gitignore --test 'src/lib/**/*.test.ts'
|
|
66
72
|
```
|
|
67
73
|
|
|
68
74
|
`tmts` is a short alias for the same command. `targeted-mutation --help` lists every option.
|
|
@@ -91,7 +97,7 @@ On a terminal the report is text. When the output is piped or redirected it is J
|
|
|
91
97
|
| `--mutators full` | Comparison boundaries (and constant-RHS integer thresholds on Vitest), plus the complete built-in mutation set: every StrykerJS mutator (arithmetic, equality, logical, conditional, boolean, string, array, object, block, arrow function, assignment, unary, update, method, optional chaining, regular expression and call removal). Needs no extra package. Runs in one switched session on Vitest 4, or one source rewrite per mutation with Playwright. |
|
|
92
98
|
| `--witnesses` | Value substitutions such as a neighbouring field, the first or last index, or a sort key, each confirmed by a test that tells them apart. Reports `No edit sites` when a file has no such pattern. |
|
|
93
99
|
|
|
94
|
-
`// Stryker disable
|
|
100
|
+
`// Stryker disable`, `// Stryker restore`, and `// tmt:ignore <reason>` (same-line or standalone line above) comments exclude mutations in both the `targeted` and `full` profiles, with the reason recorded on each ignored mutation.
|
|
95
101
|
|
|
96
102
|
On Vitest 4 the mutations are decided inside running Vitest workers, several at a time, with a control run after each one. `--concurrency N` sets the number of workers, `--verify-trials N` re-runs a sample of those decisions in fresh Vitest runs, and `--isolated-trials` starts a fresh Vitest run for every mutation instead; see [How mutations run on Vitest](docs/analysis.md#how-mutations-run-on-vitest).
|
|
97
103
|
|
package/bin/tmt.mjs
CHANGED
|
@@ -29,7 +29,17 @@ try {
|
|
|
29
29
|
config: { type: 'string' },
|
|
30
30
|
test: { type: 'string', multiple: true },
|
|
31
31
|
'copy-exclude': { type: 'string', multiple: true },
|
|
32
|
+
'copy-exclude-gitignore': { type: 'boolean' },
|
|
33
|
+
'exclude-rule': { type: 'string', multiple: true },
|
|
34
|
+
'no-config': { type: 'boolean' },
|
|
35
|
+
progress: { type: 'boolean' },
|
|
32
36
|
format: { type: 'string' },
|
|
37
|
+
baseline: { type: 'string' },
|
|
38
|
+
'write-baseline': { type: 'string' },
|
|
39
|
+
list: { type: 'boolean' },
|
|
40
|
+
shard: { type: 'string' },
|
|
41
|
+
sharding: { type: 'string' },
|
|
42
|
+
checkpoint: { type: 'string' },
|
|
33
43
|
help: { type: 'boolean', short: 'h' },
|
|
34
44
|
version: { type: 'boolean', short: 'v' },
|
|
35
45
|
},
|
|
@@ -46,61 +56,109 @@ try {
|
|
|
46
56
|
console.log(JSON.stringify(result, null, 2));
|
|
47
57
|
if (result.path === 'diagnostic') process.exitCode = 1;
|
|
48
58
|
} else if (command === 'analyze') {
|
|
49
|
-
const [project = '.', ...
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
const
|
|
54
|
-
if (
|
|
59
|
+
const [project = '.', ...rawFiles] = positionals;
|
|
60
|
+
const { gitignoredCopyExclusions, loadProjectConfig, mergeProjectConfig, validateAndExpandInputs } = await import('../src/project-config.mjs');
|
|
61
|
+
const loadedConfig = values['no-config'] ? null : await loadProjectConfig(project, { allowCodeConfig: !values.list });
|
|
62
|
+
const merged = mergeProjectConfig(loadedConfig?.config, values, rawFiles);
|
|
63
|
+
const runValues = merged.values;
|
|
64
|
+
if (runValues.runner !== undefined && !['vitest', 'playwright'].includes(runValues.runner)) throw new Error('Expected --runner vitest|playwright');
|
|
65
|
+
if (runValues.runner === 'playwright' && runValues['displace-thresholds']) throw new Error('--displace-thresholds requires Vitest');
|
|
66
|
+
if (runValues.mutators !== undefined && !['targeted', 'full'].includes(runValues.mutators)) throw new Error('Expected --mutators targeted|full');
|
|
67
|
+
const session = runValues.runner !== 'playwright' && !runValues.witnesses && !runValues.audit;
|
|
68
|
+
if ((runValues['isolated-trials'] || runValues['verify-trials'] !== undefined) && !session) {
|
|
55
69
|
throw new Error('--isolated-trials and --verify-trials apply to Vitest sessions, which --witnesses, --audit and Playwright do not use');
|
|
56
70
|
}
|
|
57
|
-
if (
|
|
71
|
+
if (runValues.concurrency !== undefined && !session && !runValues.witnesses) {
|
|
58
72
|
throw new Error('--concurrency applies to Vitest sessions and to --witnesses, not to --audit or Playwright');
|
|
59
73
|
}
|
|
60
|
-
if (
|
|
74
|
+
if (runValues['undo-changes'] && (runValues.since === undefined || runValues.witnesses)) {
|
|
61
75
|
throw new Error('--undo-changes requires --since REV and does not apply to --witnesses');
|
|
62
76
|
}
|
|
63
|
-
if (
|
|
77
|
+
if (runValues['suggest-assertions'] && (runValues.runner === 'playwright' || runValues.witnesses)) {
|
|
64
78
|
throw new Error('--suggest-assertions applies to the targeted and full profiles on Vitest');
|
|
65
79
|
}
|
|
66
|
-
if (
|
|
67
|
-
if (!/^[1-9]\d{0,4}$/.test(
|
|
68
|
-
|
|
80
|
+
if (runValues.timeout !== undefined) {
|
|
81
|
+
if (!/^[1-9]\d{0,4}$/.test(runValues.timeout)) throw new Error('Expected --timeout to be a number of seconds');
|
|
82
|
+
runValues.timeout = Number(runValues.timeout);
|
|
69
83
|
}
|
|
70
|
-
if (
|
|
71
|
-
if (!/^\d{1,6}$/.test(
|
|
72
|
-
|
|
84
|
+
if (runValues['verify-trials'] !== undefined) {
|
|
85
|
+
if (!/^\d{1,6}$/.test(runValues['verify-trials'])) throw new Error('Expected --verify-trials to be a count');
|
|
86
|
+
runValues['verify-trials'] = Number(runValues['verify-trials']);
|
|
73
87
|
}
|
|
74
|
-
if (
|
|
75
|
-
if (!/^[1-9]\d{0,3}$/.test(
|
|
76
|
-
|
|
88
|
+
if (runValues.concurrency !== undefined) {
|
|
89
|
+
if (!/^[1-9]\d{0,3}$/.test(runValues.concurrency)) throw new Error('Expected --concurrency to be a positive integer');
|
|
90
|
+
runValues.concurrency = Number(runValues.concurrency);
|
|
77
91
|
}
|
|
78
|
-
|
|
92
|
+
if (runValues['exclude-rule']?.length) {
|
|
93
|
+
runValues['exclude-rule'] = runValues['exclude-rule'].flatMap(entry => entry.split(',')).map(s => s.trim()).filter(Boolean);
|
|
94
|
+
}
|
|
95
|
+
const format = chooseFormat(runValues.format, process.stdout.isTTY === true);
|
|
96
|
+
const { parseShard, parseShardingStrategy, listCandidates } = await import('../src/shard.mjs');
|
|
97
|
+
const shard = parseShard(runValues.shard);
|
|
98
|
+
const sharding = parseShardingStrategy(runValues.sharding);
|
|
99
|
+
const { loadBaseline, writeBaseline, applyBaseline } = await import('../src/baseline.mjs');
|
|
100
|
+
const baselineIds = runValues.baseline ? loadBaseline(runValues.baseline) : null;
|
|
101
|
+
// Validate project paths and expand any globs before copying the project to a temporary directory.
|
|
102
|
+
const validated = validateAndExpandInputs(project, merged.files, runValues);
|
|
103
|
+
const files = validated.files;
|
|
104
|
+
if (validated.tests) runValues.test = validated.tests;
|
|
105
|
+
if (runValues['copy-exclude-gitignore']) {
|
|
106
|
+
const ignoredExclusions = gitignoredCopyExclusions(validated.root);
|
|
107
|
+
if (ignoredExclusions.length) {
|
|
108
|
+
runValues['copy-exclude'] = [...new Set([...(runValues['copy-exclude'] ?? []), ...ignoredExclusions])];
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
const logProgress = runValues.progress ? message => process.stderr.write(`[tmt] ${message}\n`) : () => {};
|
|
79
112
|
enablePreparedTypeScript();
|
|
80
113
|
let result;
|
|
81
|
-
if (
|
|
82
|
-
|
|
83
|
-
|
|
114
|
+
if (runValues.list) {
|
|
115
|
+
result = listCandidates(project, files, { ...runValues, mutators: runValues.mutators ?? 'targeted', shard: runValues.shard, sharding });
|
|
116
|
+
} else if (runValues.witnesses) {
|
|
117
|
+
if (runValues.runner === 'playwright' || runValues.mutators !== undefined ||
|
|
118
|
+
runValues.deterministic || runValues.project || runValues.audit || runValues['displace-thresholds']) throw new Error('--witnesses runs its own Vitest source trials');
|
|
119
|
+
logProgress('Running witness analysis...');
|
|
84
120
|
const { analyzeWitnesses } = await import('../src/witness-analysis.mjs');
|
|
85
|
-
result = await analyzeWitnesses(project, files,
|
|
121
|
+
result = await analyzeWitnesses(project, files, runValues);
|
|
86
122
|
} else {
|
|
123
|
+
logProgress(`Analyzing ${files.length ? `${files.length} file(s)` : 'project'} (${runValues.mutators ?? 'targeted'})...`);
|
|
87
124
|
const { analyzeOperators } = await import('../src/operator-analysis.mjs');
|
|
88
|
-
result = await analyzeOperators(project, files, { ...
|
|
125
|
+
result = await analyzeOperators(project, files, { ...runValues, mutators: runValues.mutators ?? 'targeted', shard, sharding });
|
|
89
126
|
}
|
|
90
|
-
if (!
|
|
127
|
+
if (!runValues.witnesses && !runValues.list) {
|
|
91
128
|
const { strengthenAssertions, withoutSourceEdits } = await import('../src/assertion-strength.mjs');
|
|
92
|
-
if (
|
|
129
|
+
if (runValues['suggest-assertions'] && result.evaluation === 'evaluated') result = await strengthenAssertions(realpathSync(project), result, runValues);
|
|
93
130
|
withoutSourceEdits(result);
|
|
94
131
|
}
|
|
95
|
-
if (
|
|
132
|
+
if (runValues['undo-changes'] && !runValues.list) {
|
|
96
133
|
const { analyzeUndoneChangesAsync, withUndoneChanges } = await import('../src/change-undone.mjs');
|
|
97
134
|
const { baselineRunSymbol } = await import('../src/analysis.mjs');
|
|
98
135
|
if (result.evaluation !== 'baseline_error') {
|
|
99
|
-
result = withUndoneChanges(result, await analyzeUndoneChangesAsync(project, files, { ...
|
|
136
|
+
result = withUndoneChanges(result, await analyzeUndoneChangesAsync(project, files, { ...runValues, existingBaseline: result[baselineRunSymbol] }));
|
|
100
137
|
}
|
|
101
138
|
}
|
|
102
|
-
if (
|
|
103
|
-
|
|
139
|
+
if (runValues.since && !runValues.list && !runValues.witnesses && result.evaluation === 'evaluated') {
|
|
140
|
+
const { detectWeakenedTests } = await import('../src/weakened-tests.mjs');
|
|
141
|
+
result = await detectWeakenedTests(project, result, runValues);
|
|
142
|
+
}
|
|
143
|
+
if (!runValues.list && runValues['write-baseline'] && result.evaluation !== 'baseline_error') {
|
|
144
|
+
writeBaseline(runValues['write-baseline'], result.diagnostics ?? []);
|
|
145
|
+
}
|
|
146
|
+
if (!runValues.list && baselineIds) {
|
|
147
|
+
result = applyBaseline(result, baselineIds);
|
|
148
|
+
}
|
|
149
|
+
logProgress(`Completed (${result.evaluation}, ${(result.mutants ?? []).length} edits, ${(result.diagnostics ?? []).length} gaps).`);
|
|
150
|
+
if (format === 'json') {
|
|
151
|
+
console.log(JSON.stringify(result, null, 2));
|
|
152
|
+
} else if (format === 'jsonl') {
|
|
153
|
+
const { renderJsonl } = await import('../src/sarif.mjs');
|
|
154
|
+
console.log(renderJsonl(result));
|
|
155
|
+
} else if (format === 'sarif') {
|
|
156
|
+
const { renderSarif } = await import('../src/sarif.mjs');
|
|
157
|
+
const version = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
|
|
158
|
+
console.log(JSON.stringify(renderSarif(result, { version }), null, 2));
|
|
159
|
+
} else {
|
|
160
|
+
console.log(renderText(result));
|
|
161
|
+
}
|
|
104
162
|
if (['baseline_error', 'incomplete'].includes(result.evaluation) || result.extraction.some(file => file.path === 'diagnostic')) process.exitCode = 1;
|
|
105
163
|
} else if (command === 'prototype' && positionals.length === 2) {
|
|
106
164
|
enablePreparedTypeScript();
|
package/docs/analysis.md
CHANGED
|
@@ -203,7 +203,7 @@ npx targeted-mutation analyze fixtures/witnesses src/text-order.ts --witnesses -
|
|
|
203
203
|
npx targeted-mutation analyze fixtures/witnesses src/contracts.ts --witnesses --test test/contracts.test.ts
|
|
204
204
|
```
|
|
205
205
|
|
|
206
|
-
The automatic rules handle same-type safe integer arguments and numeric fields of an inline object type in an ordered comparison, `indexOf` versus `lastIndexOf` on numeric arrays, any versus all bits in a nonnegative 31-bit mask,
|
|
206
|
+
The automatic rules handle same-type safe integer arguments and numeric fields of an inline object type in an ordered comparison, `indexOf` versus `lastIndexOf` on numeric arrays, any versus all bits in a nonnegative 31-bit mask, one extra element in a `slice(0, count).reduce(...)` sum, integer rounding-order bugs (`Math.floor((a * b) / c)` / `Math.trunc((a * b) / c)` vs dividing before multiplying), and omitted parameters in composite keys (template literals and `[...].join(...)`). They use direct Vitest calls with literal arguments and a scalar `toBe` assertion as seeds. Calls may appear inside nested `describe` or `suite` blocks with literal titles. JavaScript named exports can use JSDoc parameter annotations, and the numeric-array `indexOf` rule can use an unannotated function with literal numeric fixtures. A finding includes a minimized single-literal edit where the observed assertion still holds for the original implementation. Otherwise it can verify a separate assertion in the selected test file. Automatic expectations come from the original implementation. The automatic search evaluates up to 32 eligible rewrites and four one-edit proposals per surviving rewrite.
|
|
207
207
|
|
|
208
208
|
`witnessSearch` reports scoped single-rule source candidates, how many matched passing test seeds, how many were evaluated, and how many hit the evaluation cap. `unmatched` is null when a diagnostic or a failed baseline prevented matching. A matched seed can lack a supported distinguishing edit. Paired and public-state witness plans have separate evaluation results.
|
|
209
209
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "targeted-mutation",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
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.
|
|
47
|
-
"@targeted-mutation/tmt-darwin-x64": "0.
|
|
48
|
-
"@targeted-mutation/tmt-linux-arm64": "0.
|
|
49
|
-
"@targeted-mutation/tmt-linux-x64": "0.
|
|
46
|
+
"@targeted-mutation/tmt-darwin-arm64": "0.2.0",
|
|
47
|
+
"@targeted-mutation/tmt-darwin-x64": "0.2.0",
|
|
48
|
+
"@targeted-mutation/tmt-linux-arm64": "0.2.0",
|
|
49
|
+
"@targeted-mutation/tmt-linux-x64": "0.2.0"
|
|
50
50
|
}
|
|
51
51
|
}
|
package/src/analysis.mjs
CHANGED
|
@@ -4,6 +4,8 @@ import { dirname, relative, resolve, sep } from 'node:path';
|
|
|
4
4
|
import { byteLocations, byteOffsets, extract, sourceDialect } from './extract.mjs';
|
|
5
5
|
import { comparisonThresholdSites } from './prototype.mjs';
|
|
6
6
|
import { marginGaps, thresholdGaps } from './threshold.mjs';
|
|
7
|
+
import { extractLoopCounterNonNegative, extractReachability, filterReachableThresholdGap, isBoundaryReachable } from './reachability.mjs';
|
|
8
|
+
import { checkpointKeyForTrial } from './checkpoint.mjs';
|
|
7
9
|
import { shiftedReplacement, tightenComparison } from './displacement.mjs';
|
|
8
10
|
import { failedTests } from './vitest-reporter.mjs';
|
|
9
11
|
import { inside, runVitest, runVitestAsync, withCopy } from './vitest.mjs';
|
|
@@ -46,11 +48,11 @@ function builtInSites(comparisons, input, file, dialect, selected, options = {})
|
|
|
46
48
|
left: [mutant.edit[0], mutant.edit[0]], right: [mutant.edit[1], mutant.edit[1]], source: mutant.source, unobserved: true }));
|
|
47
49
|
}
|
|
48
50
|
|
|
49
|
-
function withProfileSites(comparisons, input, file, { mutators, dialect }, selected) {
|
|
51
|
+
function withProfileSites(comparisons, input, file, { mutators, dialect, 'exclude-rule': excludeRules }, selected) {
|
|
50
52
|
const start = candidate => (candidate.operatorEdit ?? candidate.edit)[0];
|
|
51
53
|
// Without a session nothing is recorded, so the targeted or full edits run as plain source edits.
|
|
52
|
-
const added = mutators === 'full' ? builtInSites(comparisons, input, file, dialect, selected)
|
|
53
|
-
: mutators === 'targeted' ? builtInSites(comparisons, input, file, dialect, selected, { targeted: true, keep: mutation => mutation.targeted !== undefined })
|
|
54
|
+
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 })
|
|
54
56
|
: [];
|
|
55
57
|
return added.length ? [...comparisons, ...added].sort((a, b) => start(a) - start(b)) : comparisons;
|
|
56
58
|
}
|
|
@@ -289,24 +291,36 @@ export function planFocusedTrials(subjects, trace, baseline, specification, disp
|
|
|
289
291
|
const callable = callableThreshold(subject, site, observation, specification, lookupThreshold);
|
|
290
292
|
const constant = constantThreshold(site, observation, callable);
|
|
291
293
|
const margin = variableMargin(site, observation, constant);
|
|
292
|
-
|
|
294
|
+
const lhsText = site.left ? subject.input.subarray(...site.left).toString('utf8') : '';
|
|
295
|
+
const charOffset = site.location?.start !== undefined
|
|
296
|
+
? subject.input.subarray(0, site.location.start).toString('utf8').length
|
|
297
|
+
: 0;
|
|
298
|
+
const reachability = extractReachability(lhsText) ??
|
|
299
|
+
extractLoopCounterNonNegative(subject.input.toString('utf8'), charOffset, lhsText);
|
|
300
|
+
if (constant) {
|
|
301
|
+
constant.reachability = reachability;
|
|
302
|
+
thresholdRequests.push(constant);
|
|
303
|
+
}
|
|
293
304
|
if (margin) marginRequests.push(margin);
|
|
294
|
-
sites.push({ subject, site, observation, tightened, callable, constant, margin });
|
|
305
|
+
sites.push({ subject, site, observation, tightened, callable, constant, margin, reachability });
|
|
295
306
|
}
|
|
296
307
|
}
|
|
297
308
|
const gaps = thresholdGaps(thresholdRequests.map(({ operator, value, inputs, min, max }) => ({
|
|
298
309
|
operator, threshold: value, observations: inputs, min, max,
|
|
299
310
|
})));
|
|
300
|
-
thresholdRequests.forEach((entry, index) => {
|
|
311
|
+
thresholdRequests.forEach((entry, index) => {
|
|
312
|
+
entry.gap = filterReachableThresholdGap(gaps[index], entry.reachability, entry.value, entry.operator, entry.inputs);
|
|
313
|
+
});
|
|
301
314
|
const mGaps = marginGaps(marginRequests.map(({ operator, pairs }) => ({ operator, pairs })));
|
|
302
315
|
marginRequests.forEach((entry, index) => { entry.gap = mGaps[index]; });
|
|
303
316
|
|
|
304
317
|
const trials = [];
|
|
305
|
-
for (const { subject, site, observation, tightened, callable, constant, margin } of sites) {
|
|
318
|
+
for (const { subject, site, observation, tightened, callable, constant, margin, reachability } of sites) {
|
|
306
319
|
if (callable && constant) callable.gap = constant.gap;
|
|
307
320
|
const boundary = {
|
|
308
321
|
site, edit: site.edit, replacement: site.replacement, source: site.source, rule: site.rule,
|
|
309
322
|
observation, threshold: callable, thresholdGap: constant?.gap ?? null, marginGap: margin?.gap ?? null,
|
|
323
|
+
reachability,
|
|
310
324
|
};
|
|
311
325
|
trials.push(boundary);
|
|
312
326
|
let thresholdAdjustment;
|
|
@@ -424,6 +438,11 @@ function diagnose(trial, result) {
|
|
|
424
438
|
}
|
|
425
439
|
const binary = observation.rows[0]?.operands;
|
|
426
440
|
if (!binary) return null;
|
|
441
|
+
const isConstantRhs = observation.rows.every(row => row.operands[1] === binary[1]);
|
|
442
|
+
if (isConstantRhs && trial.rule === site.rule && trial.reachability &&
|
|
443
|
+
!isBoundaryReachable(trial.reachability, binary[1], observation.rows.map(row => row.operands[0]))) {
|
|
444
|
+
return null;
|
|
445
|
+
}
|
|
427
446
|
const gap = trial.rule === 'comparison-threshold/v1' ? trial.thresholdGap : null;
|
|
428
447
|
const mGap = trial.rule === 'comparison-margin/v1' ? trial.marginGap : null;
|
|
429
448
|
const input = gap?.witness ?? (mGap ? binary[1] + mGap.witness : binary[1] + (trial.adjustment ?? 0));
|
|
@@ -519,6 +538,9 @@ function analyzePlaywright(root, subjects, report, options, specification) {
|
|
|
519
538
|
report.instrumented = { status: 'unavailable', reason: 'browser-observations-unavailable' };
|
|
520
539
|
for (const subject of subjects) {
|
|
521
540
|
for (const site of subject.sites) {
|
|
541
|
+
if (options.shardKeys && !options.shardKeys.has(
|
|
542
|
+
`${site.location.file}:${site.location.start}:${site.location.end}:${site.rule}:${site.replacement}`,
|
|
543
|
+
)) continue;
|
|
522
544
|
const trial = { site, edit: site.edit, replacement: site.replacement, source: site.source };
|
|
523
545
|
const mutant = attempt({ trial });
|
|
524
546
|
const result = {
|
|
@@ -595,10 +617,16 @@ export function prepareAnalysis(project, files, options) {
|
|
|
595
617
|
// Beside a session, which runs the suite on its own, the recording run stands for the baseline when it passes.
|
|
596
618
|
// Otherwise the plain baseline runs first, so a failing suite is reported as before.
|
|
597
619
|
const recorded = options.traceIsBaseline ? attempt({ tracing: true }) : null;
|
|
598
|
-
|
|
599
|
-
const
|
|
620
|
+
// 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();
|
|
622
|
+
const baseline = plainBaseline ?? (recorded?.status === 'passed' ? { status: 'passed', tests: recorded.tests } : recorded);
|
|
600
623
|
if (baseline.status !== 'passed') {
|
|
601
|
-
|
|
624
|
+
const timeoutSeconds = options.timeout ?? 60;
|
|
625
|
+
return { report: { ...report, evaluation: 'baseline_error', baseline: {
|
|
626
|
+
status: baseline.status,
|
|
627
|
+
...(baseline.status === 'timeout' ? { timeoutSeconds } : {}),
|
|
628
|
+
output: baseline.output, errors: baseline.errors, failedTests: failedTests(baseline),
|
|
629
|
+
} } };
|
|
602
630
|
}
|
|
603
631
|
report.baseline = { status: 'passed', tests: baseline.tests.length };
|
|
604
632
|
if (plainBaseline) {
|
|
@@ -618,7 +646,12 @@ export function prepareAnalysis(project, files, options) {
|
|
|
618
646
|
else if (coverageSites.size) coverage = indexFocusedCoverage(replay.trace, coverageSites);
|
|
619
647
|
}
|
|
620
648
|
|
|
621
|
-
const
|
|
649
|
+
const rawTrials = planFocusedTrials(subjects, trace, baseline, specification, options['displace-thresholds']);
|
|
650
|
+
const trials = options.shardKeys
|
|
651
|
+
? rawTrials.filter(trial => options.shardKeys.has(
|
|
652
|
+
`${trial.site.location.file}:${trial.site.location.start}:${trial.site.location.end}:${trial.site.rule}:${trial.site.replacement}`,
|
|
653
|
+
))
|
|
654
|
+
: rawTrials;
|
|
622
655
|
const skips = leanSkips(trials, baseline, !!options.deterministic, coverage);
|
|
623
656
|
return { root, report, options, attempt, baseline, traced, trace, trials, skips };
|
|
624
657
|
}
|
|
@@ -670,18 +703,25 @@ export function completeAnalysis({ root, report, options, attempt, baseline, tra
|
|
|
670
703
|
// The runner broke down in this trial, which is neither a kill nor a survivor: the analysis is not complete.
|
|
671
704
|
if (result.status === 'error') report.evaluation = 'incomplete';
|
|
672
705
|
const gap = diagnose(trial, result);
|
|
706
|
+
if (options.checkpointStore) {
|
|
707
|
+
options.checkpointStore.record(checkpointKeyForTrial(result), result, gap ?? undefined);
|
|
708
|
+
}
|
|
673
709
|
if (gap) {
|
|
674
710
|
if (options.audit && gap.suggestedTest) gap.verification = verifyVitestWitness(root, attempt, baseline, trial, gap);
|
|
675
711
|
const duplicate = trial.adjustment === undefined && report.diagnostics.find(other => other.site === gap.site && other.kind === gap.kind &&
|
|
676
712
|
(gap.kind === 'ASSERTION GAP' || gap.witness.operands.every((value, index) => value === other.witness.operands[index])));
|
|
713
|
+
const mutationEntry = {
|
|
714
|
+
rule: result.rule, edit: result.edit, replacement: result.replacement, evidence: result.evidence,
|
|
715
|
+
...(result.original !== undefined ? { original: result.original } : {}),
|
|
716
|
+
};
|
|
677
717
|
if (duplicate) {
|
|
678
718
|
if (gap.tests) {
|
|
679
719
|
const existing = new Set(duplicate.tests.map(identity));
|
|
680
720
|
duplicate.tests.push(...gap.tests.filter(test => !existing.has(identity(test))));
|
|
681
721
|
}
|
|
682
|
-
duplicate.mutations.push(
|
|
722
|
+
duplicate.mutations.push(mutationEntry);
|
|
683
723
|
} else {
|
|
684
|
-
report.diagnostics.push({ ...gap, mutations: [
|
|
724
|
+
report.diagnostics.push({ ...gap, mutations: [mutationEntry] });
|
|
685
725
|
}
|
|
686
726
|
}
|
|
687
727
|
}
|
package/src/baseline.mjs
ADDED
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { readFileSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { loadTypeScript } from './typescript-compiler.mjs';
|
|
4
|
+
|
|
5
|
+
const BASELINE_VERSION = 2;
|
|
6
|
+
const TMT_IGNORE_RE = /^\s*tmt:ignore(?:\s+(.*))?$/i;
|
|
7
|
+
|
|
8
|
+
function computeLineStarts(text) {
|
|
9
|
+
const starts = [0];
|
|
10
|
+
for (let i = 0; i < text.length; i++) {
|
|
11
|
+
if (text.charCodeAt(i) === 10) starts.push(i + 1);
|
|
12
|
+
}
|
|
13
|
+
return starts;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function lineOfOffset(starts, offset) {
|
|
17
|
+
let low = 0;
|
|
18
|
+
let high = starts.length - 1;
|
|
19
|
+
while (low < high) {
|
|
20
|
+
const mid = (low + high + 1) >> 1;
|
|
21
|
+
if (starts[mid] <= offset) low = mid;
|
|
22
|
+
else high = mid - 1;
|
|
23
|
+
}
|
|
24
|
+
return low;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
// Parse `// tmt:ignore [reason]` and `/* tmt:ignore [reason] */` comments using the TypeScript AST
|
|
28
|
+
// so occurrences inside template literals, strings, or after regex literals are handled accurately.
|
|
29
|
+
export function tmtIgnoreLines(text, ts = loadTypeScript(), file = 'source.tsx') {
|
|
30
|
+
const ignored = new Map();
|
|
31
|
+
if (!/tmt:ignore/i.test(text)) return ignored;
|
|
32
|
+
|
|
33
|
+
const starts = computeLineStarts(text);
|
|
34
|
+
const sf = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true);
|
|
35
|
+
const seenRanges = new Set();
|
|
36
|
+
|
|
37
|
+
const handleRange = range => {
|
|
38
|
+
const key = `${range.pos}:${range.end}`;
|
|
39
|
+
if (seenRanges.has(key)) return;
|
|
40
|
+
seenRanges.add(key);
|
|
41
|
+
const raw = range.kind === ts.SyntaxKind.SingleLineCommentTrivia
|
|
42
|
+
? text.slice(range.pos + 2, range.end)
|
|
43
|
+
: text.slice(range.pos + 2, range.end - 2);
|
|
44
|
+
const match = TMT_IGNORE_RE.exec(raw.trim());
|
|
45
|
+
if (!match) return;
|
|
46
|
+
const reason = (match[1] ?? '').trim() || 'Ignored using tmt:ignore';
|
|
47
|
+
const startLine = lineOfOffset(starts, range.pos);
|
|
48
|
+
const endLine = lineOfOffset(starts, Math.max(range.pos, range.end - 1));
|
|
49
|
+
const linePrefix = text.slice(starts[startLine], range.pos);
|
|
50
|
+
const nextLineStart = endLine + 1 < starts.length ? starts[endLine + 1] : text.length;
|
|
51
|
+
const lineSuffix = text.slice(range.end, nextLineStart).replace(/\r?\n$/, '');
|
|
52
|
+
const standalone = linePrefix.trim().length === 0 && lineSuffix.trim().length === 0;
|
|
53
|
+
const targetLine = standalone ? endLine + 1 : endLine;
|
|
54
|
+
ignored.set(targetLine, reason);
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
const inspectPosition = pos => {
|
|
58
|
+
for (const range of ts.getLeadingCommentRanges(text, pos) ?? []) handleRange(range);
|
|
59
|
+
for (const range of ts.getTrailingCommentRanges(text, pos) ?? []) handleRange(range);
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
(function walk(node) {
|
|
63
|
+
inspectPosition(node.pos);
|
|
64
|
+
inspectPosition(node.end);
|
|
65
|
+
ts.forEachChild(node, walk);
|
|
66
|
+
})(sf);
|
|
67
|
+
|
|
68
|
+
return ignored;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function normalizePosixPath(file) {
|
|
72
|
+
return String(file ?? '').replaceAll('\\', '/');
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function normalizeCodeSnippet(diagnostic) {
|
|
76
|
+
const raw = diagnostic.expression ??
|
|
77
|
+
diagnostic.mutations?.[0]?.original ??
|
|
78
|
+
(diagnostic.mutations?.length
|
|
79
|
+
? diagnostic.mutations.map(m => `${m.rule ?? ''}:${m.replacement ?? ''}`).join('|')
|
|
80
|
+
: diagnostic.rule ?? '');
|
|
81
|
+
return String(raw).replace(/\s+/g, ' ').trim();
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// Stable finding key without line numbers so findings survive edits and line moves.
|
|
85
|
+
export function findingKeyBase(diagnostic) {
|
|
86
|
+
const kind = String(diagnostic.kind ?? 'GAP');
|
|
87
|
+
const file = normalizePosixPath(diagnostic.location?.file);
|
|
88
|
+
const rule = String(diagnostic.rule ?? diagnostic.mutations?.[0]?.rule ?? '');
|
|
89
|
+
const code = normalizeCodeSnippet(diagnostic);
|
|
90
|
+
return JSON.stringify([kind, file, rule, code]);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export function findingId(diagnostic, occurrence = 0) {
|
|
94
|
+
const payload = JSON.stringify([findingKeyBase(diagnostic), occurrence]);
|
|
95
|
+
return `tmt-${createHash('sha256').update(payload).digest('hex').slice(0, 16)}`;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// Assign deterministic stable IDs to diagnostics, preserving any pre-assigned findingId
|
|
99
|
+
// (so SARIF/JSONL output after baseline filtering never re-numbers remaining findings).
|
|
100
|
+
export function annotateFindingIds(diagnostics) {
|
|
101
|
+
const counts = new Map();
|
|
102
|
+
return (diagnostics ?? []).map(diagnostic => {
|
|
103
|
+
if (typeof diagnostic?.findingId === 'string' && diagnostic.findingId.length > 0) {
|
|
104
|
+
return diagnostic;
|
|
105
|
+
}
|
|
106
|
+
const base = findingKeyBase(diagnostic);
|
|
107
|
+
const occurrence = counts.get(base) ?? 0;
|
|
108
|
+
counts.set(base, occurrence + 1);
|
|
109
|
+
const id = findingId(diagnostic, occurrence);
|
|
110
|
+
return { ...diagnostic, findingId: id };
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export function serializeBaseline(diagnostics) {
|
|
115
|
+
const annotated = annotateFindingIds(diagnostics);
|
|
116
|
+
return {
|
|
117
|
+
version: BASELINE_VERSION,
|
|
118
|
+
findings: annotated.map(item => ({
|
|
119
|
+
id: item.findingId,
|
|
120
|
+
kind: item.kind ?? 'GAP',
|
|
121
|
+
file: normalizePosixPath(item.location?.file),
|
|
122
|
+
rule: item.rule ?? item.mutations?.[0]?.rule ?? undefined,
|
|
123
|
+
code: normalizeCodeSnippet(item),
|
|
124
|
+
})),
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
export function parseBaseline(text, label = 'baseline') {
|
|
129
|
+
let data;
|
|
130
|
+
try {
|
|
131
|
+
data = JSON.parse(text);
|
|
132
|
+
} catch (error) {
|
|
133
|
+
throw new Error(`Invalid baseline JSON in ${label}: ${error.message}`);
|
|
134
|
+
}
|
|
135
|
+
if (Array.isArray(data)) {
|
|
136
|
+
if (!data.every(entry => typeof entry === 'string')) {
|
|
137
|
+
throw new Error(`Invalid legacy baseline array in ${label}`);
|
|
138
|
+
}
|
|
139
|
+
return new Set(data);
|
|
140
|
+
}
|
|
141
|
+
if (!data || typeof data !== 'object' || data.version !== BASELINE_VERSION || !Array.isArray(data.findings)) {
|
|
142
|
+
throw new Error(`Unsupported baseline format in ${label}: expected version ${BASELINE_VERSION}`);
|
|
143
|
+
}
|
|
144
|
+
const ids = new Set();
|
|
145
|
+
for (const entry of data.findings) {
|
|
146
|
+
const id = typeof entry === 'string' ? entry : entry?.id;
|
|
147
|
+
if (typeof id !== 'string' || !id.length) {
|
|
148
|
+
throw new Error(`Invalid baseline entry in ${label}`);
|
|
149
|
+
}
|
|
150
|
+
ids.add(id);
|
|
151
|
+
}
|
|
152
|
+
return ids;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
export function loadBaseline(path) {
|
|
156
|
+
return parseBaseline(readFileSync(path, 'utf8'), path);
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
export function writeBaseline(path, diagnostics) {
|
|
160
|
+
const payload = serializeBaseline(diagnostics);
|
|
161
|
+
writeFileSync(path, JSON.stringify(payload, null, 2) + '\n', 'utf8');
|
|
162
|
+
return payload;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
export function applyBaseline(report, baselineIds) {
|
|
166
|
+
const annotated = annotateFindingIds(report.diagnostics ?? []);
|
|
167
|
+
if (!baselineIds || !baselineIds.size) {
|
|
168
|
+
return { ...report, diagnostics: annotated };
|
|
169
|
+
}
|
|
170
|
+
const kept = [];
|
|
171
|
+
const suppressedIds = [];
|
|
172
|
+
for (const diagnostic of annotated) {
|
|
173
|
+
if (baselineIds.has(diagnostic.findingId)) suppressedIds.push(diagnostic.findingId);
|
|
174
|
+
else kept.push(diagnostic);
|
|
175
|
+
}
|
|
176
|
+
return {
|
|
177
|
+
...report,
|
|
178
|
+
diagnostics: kept,
|
|
179
|
+
suppressed: {
|
|
180
|
+
baseline: suppressedIds.length,
|
|
181
|
+
ids: suppressedIds,
|
|
182
|
+
},
|
|
183
|
+
};
|
|
184
|
+
}
|