crossexamdev 0.2.0 → 0.3.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 +7 -2
- package/bin/crossexam.js +88 -4
- package/package.json +1 -1
- package/src/claims.js +138 -120
- package/src/github.js +93 -69
- package/src/mcp.js +198 -109
- package/src/mutate.js +443 -0
- package/src/report.js +194 -99
- package/src/sandbox.js +627 -0
- package/src/strength.js +628 -0
package/src/strength.js
ADDED
|
@@ -0,0 +1,628 @@
|
|
|
1
|
+
// Test strength: would the repo's tests notice if the changed code were wrong?
|
|
2
|
+
//
|
|
3
|
+
// Plants deterministic defects (mutate.js) in the lines an agent changed, runs
|
|
4
|
+
// the repo's own test command against each one inside an isolated copy
|
|
5
|
+
// (sandbox.js), and reports which defects the tests caught and which survived.
|
|
6
|
+
//
|
|
7
|
+
// This is a quality dimension, kept apart from factual verification: a
|
|
8
|
+
// "tests pass" claim can be verified (they did pass) and still be weak
|
|
9
|
+
// evidence (they would also have passed with a bug in place).
|
|
10
|
+
|
|
11
|
+
import { spawnSync } from 'node:child_process';
|
|
12
|
+
import fs from 'node:fs';
|
|
13
|
+
import os from 'node:os';
|
|
14
|
+
import path from 'node:path';
|
|
15
|
+
import { fileURLToPath } from 'node:url';
|
|
16
|
+
import { excerpt, judgeRun } from './evidence.js';
|
|
17
|
+
import { detectCommands, loadConfig } from './live.js';
|
|
18
|
+
import { JS_EXT, TEST_FILE, applyMutant, classifyFile, explain, generateMutants, prioritize } from './mutate.js';
|
|
19
|
+
import { allowlistedEnv, chooseIsolation, clampLimits, createCopy, describeIsolation, fingerprint, gitState, git as gitRead, isInside, projectFiles, runIsolated, scrubbedEnv, sha, sweepStaleCopies } from './sandbox.js';
|
|
20
|
+
|
|
21
|
+
export const STATUS = /** @type {const} */ ({
|
|
22
|
+
KILLED: 'MUTATION_KILLED',
|
|
23
|
+
SURVIVED: 'MUTATION_SURVIVED',
|
|
24
|
+
INVALID: 'MUTATION_INVALID',
|
|
25
|
+
UNRESOLVED: 'MUTATION_UNRESOLVED',
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
const VERSION = (() => {
|
|
29
|
+
try {
|
|
30
|
+
return JSON.parse(fs.readFileSync(path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'package.json'), 'utf8')).version;
|
|
31
|
+
} catch {
|
|
32
|
+
return '0';
|
|
33
|
+
}
|
|
34
|
+
})();
|
|
35
|
+
|
|
36
|
+
// Output that means the mutant broke compilation, not behaviour.
|
|
37
|
+
// Case-sensitive on purpose: vitest prints assertion failures as
|
|
38
|
+
// "Error: expected 5 to be 7", which must count as a kill, not a compile error.
|
|
39
|
+
const INVALID_SIG = /\bSyntaxError\b|Transform failed|\bUnexpected token\b|ERROR: Expected "[^"\n]*" but found|\berror TS\d{3,5}\b|Failed to parse source|\bParseError\b|is not a valid (?:JavaScript|TypeScript)/;
|
|
40
|
+
|
|
41
|
+
const git = gitRead; // read-only subcommands, GIT_OPTIONAL_LOCKS=0
|
|
42
|
+
const tryGit = (cwd, args) => {
|
|
43
|
+
try {
|
|
44
|
+
return git(cwd, args);
|
|
45
|
+
} catch {
|
|
46
|
+
return null;
|
|
47
|
+
}
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
/** Pick the comparison base when none was given. */
|
|
51
|
+
export function resolveBase(cwd, base) {
|
|
52
|
+
if (base) return { base, label: `vs ${base}` };
|
|
53
|
+
if (process.env.GITHUB_BASE_REF) {
|
|
54
|
+
const mb = tryGit(cwd, ['merge-base', 'HEAD', `origin/${process.env.GITHUB_BASE_REF}`]);
|
|
55
|
+
if (mb) return { base: mb.trim(), label: `vs origin/${process.env.GITHUB_BASE_REF}` };
|
|
56
|
+
}
|
|
57
|
+
const dirty = tryGit(cwd, ['status', '--porcelain', '--', '.']);
|
|
58
|
+
if (dirty === null) return { base: null, label: 'not a git repository' };
|
|
59
|
+
if (dirty.trim()) return { base: 'HEAD', label: 'uncommitted changes vs HEAD' };
|
|
60
|
+
if (tryGit(cwd, ['rev-parse', '--verify', '--quiet', 'HEAD~1'])) return { base: 'HEAD~1', label: 'last commit (HEAD~1..HEAD)' };
|
|
61
|
+
// A shallow clone (CI's default fetch-depth: 1) has no parent to diff
|
|
62
|
+
// against; falling through to "initial commit" would mutate every file.
|
|
63
|
+
if ((tryGit(cwd, ['rev-parse', '--is-shallow-repository']) || '').trim() === 'true') {
|
|
64
|
+
return { base: null, label: 'shallow clone: no base to compare against (use fetch-depth: 0, or pass --base)' };
|
|
65
|
+
}
|
|
66
|
+
// A repo with a single commit: that commit is the change.
|
|
67
|
+
const empty = tryGit(cwd, ['hash-object', '-t', 'tree', process.platform === 'win32' ? 'NUL' : '/dev/null']);
|
|
68
|
+
if (empty && tryGit(cwd, ['rev-parse', '--verify', '--quiet', 'HEAD'])) return { base: empty.trim(), label: 'initial commit' };
|
|
69
|
+
return { base: null, label: 'no commits yet' };
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Changed lines per file, relative to cwd. null = every line (new or explicitly named file). */
|
|
73
|
+
export function changedLines(cwd, base) {
|
|
74
|
+
const out = new Map();
|
|
75
|
+
if (!base) return out;
|
|
76
|
+
const diff = tryGit(cwd, ['diff', '-U0', '--no-color', '--no-ext-diff', '--relative', base, '--']) || '';
|
|
77
|
+
let file = null;
|
|
78
|
+
for (const line of diff.split('\n')) {
|
|
79
|
+
if (line.startsWith('+++ ')) {
|
|
80
|
+
file = line === '+++ /dev/null' ? null : line.slice(6).trim();
|
|
81
|
+
if (file && !out.has(file)) out.set(file, new Set());
|
|
82
|
+
continue;
|
|
83
|
+
}
|
|
84
|
+
const h = line.match(/^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/);
|
|
85
|
+
if (h && file) {
|
|
86
|
+
const start = Number(h[1]);
|
|
87
|
+
const n = h[2] === undefined ? 1 : Number(h[2]);
|
|
88
|
+
for (let i = 0; i < n; i++) out.get(file).add(start + i);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
for (const f of (tryGit(cwd, ['ls-files', '-o', '--exclude-standard']) || '').split('\n').filter(Boolean)) out.set(f, null);
|
|
92
|
+
for (const [f, set] of out) if (set && !set.size) out.delete(f);
|
|
93
|
+
return out;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** Test files that import a changed module or mention a changed function. */
|
|
97
|
+
export function associatedTests(cwd, files, fnNames) {
|
|
98
|
+
const tests = projectFiles(cwd).filter((f) => TEST_FILE.test(f) && JS_EXT.test(f));
|
|
99
|
+
const names = [...new Set(fnNames)].filter((n) => n && n.length >= 4);
|
|
100
|
+
const mods = files.map((f) => {
|
|
101
|
+
const base = path.basename(f).replace(/\.[^.]+$/, '');
|
|
102
|
+
const key = base === 'index' ? path.basename(path.dirname(f)) : base;
|
|
103
|
+
return { f, re: new RegExp(`['"\`][^'"\`\\n]*[/.]${key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(?:\\.[cm]?[jt]sx?)?['"\`]`) };
|
|
104
|
+
});
|
|
105
|
+
const nameRe = names.length ? new RegExp(`\\b(?:${names.map((n) => n.replace(/[$]/g, '\\$')).join('|')})\\b`) : null;
|
|
106
|
+
const hits = [];
|
|
107
|
+
for (const t of tests.slice(0, 3000)) {
|
|
108
|
+
let text;
|
|
109
|
+
try {
|
|
110
|
+
text = fs.readFileSync(path.join(cwd, t), 'utf8');
|
|
111
|
+
} catch {
|
|
112
|
+
continue;
|
|
113
|
+
}
|
|
114
|
+
if (text.length > 1 << 20) continue;
|
|
115
|
+
const imports = mods.filter((m) => m.re.test(text)).map((m) => m.f);
|
|
116
|
+
const mentions = nameRe ? [...new Set(text.match(new RegExp(nameRe.source, 'g')) || [])] : [];
|
|
117
|
+
if (imports.length || mentions.length) hits.push({ file: t, imports, mentions });
|
|
118
|
+
}
|
|
119
|
+
return { tests, associated: hits };
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// ---------- cache ----------
|
|
123
|
+
|
|
124
|
+
function cacheFile(cwd) {
|
|
125
|
+
let real = cwd;
|
|
126
|
+
try {
|
|
127
|
+
real = fs.realpathSync(cwd);
|
|
128
|
+
} catch {}
|
|
129
|
+
return path.join(process.env.CROSSEXAM_HOME || path.join(os.homedir(), '.crossexam'), 'mutation-cache', sha(real.toLowerCase()).slice(0, 16) + '.json');
|
|
130
|
+
}
|
|
131
|
+
function loadCache(cwd) {
|
|
132
|
+
try {
|
|
133
|
+
return JSON.parse(fs.readFileSync(cacheFile(cwd), 'utf8'));
|
|
134
|
+
} catch {
|
|
135
|
+
return { entries: {} };
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
function saveCache(cwd, cache) {
|
|
139
|
+
try {
|
|
140
|
+
const keys = Object.keys(cache.entries);
|
|
141
|
+
if (keys.length > 5000) for (const k of keys.sort((a, b) => cache.entries[a].at.localeCompare(cache.entries[b].at)).slice(0, keys.length - 5000)) delete cache.entries[k];
|
|
142
|
+
const f = cacheFile(cwd);
|
|
143
|
+
fs.mkdirSync(path.dirname(f), { recursive: true });
|
|
144
|
+
fs.writeFileSync(f, JSON.stringify(cache));
|
|
145
|
+
} catch {
|
|
146
|
+
/* the cache is an optimisation */
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// ---------- the run ----------
|
|
151
|
+
|
|
152
|
+
const HARD = { max: 500, budgetSeconds: 3600, mutantTimeoutSeconds: 600 };
|
|
153
|
+
const clampNum = (v, lo, hi, d) => {
|
|
154
|
+
const n = Number(v);
|
|
155
|
+
return Number.isFinite(n) ? Math.min(Math.max(n, lo), hi) : d;
|
|
156
|
+
};
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* @param {{
|
|
160
|
+
* cwd: string, base?: string, files?: string[], max?: number, budgetSeconds?: number,
|
|
161
|
+
* isolation?: 'auto'|'bwrap'|'sandbox-exec'|'docker'|'none', allowUnsandboxed?: boolean,
|
|
162
|
+
* testCommand?: string, cache?: boolean,
|
|
163
|
+
* onProgress?: (e: {phase: string, i?: number, total?: number, mutant?: object, status?: string, ms?: number}) => void
|
|
164
|
+
* }} opts
|
|
165
|
+
*/
|
|
166
|
+
export async function assessStrength(opts) {
|
|
167
|
+
const t0 = Date.now();
|
|
168
|
+
const cwd = path.resolve(opts.cwd || process.cwd());
|
|
169
|
+
const config = loadConfig(cwd);
|
|
170
|
+
const mc = config.mutation || {};
|
|
171
|
+
const max = clampNum(opts.max ?? mc.maxMutants, 0, HARD.max, 25);
|
|
172
|
+
const budgetMs = clampNum(opts.budgetSeconds ?? mc.budgetSeconds, 1, HARD.budgetSeconds, 300) * 1000;
|
|
173
|
+
const limits = clampLimits(mc.limits);
|
|
174
|
+
const notes = [];
|
|
175
|
+
const testCommand = opts.testCommand || mc.testCommand || detectCommands(cwd, config).tests?.command || null;
|
|
176
|
+
|
|
177
|
+
// Isolation is decided first, and a repository's own config can't weaken it.
|
|
178
|
+
const allowUnsandboxed = opts.allowUnsandboxed === true || process.env.CROSSEXAM_ALLOW_UNSANDBOXED === '1';
|
|
179
|
+
const iso = chooseIsolation({ requested: opts.isolation || mc.isolation || 'auto', allowUnsandboxed, fromRepoConfig: !opts.isolation && !!mc.isolation });
|
|
180
|
+
notes.push(...iso.notes);
|
|
181
|
+
|
|
182
|
+
// 1. Scope: which lines changed. Named files must stay inside the repo.
|
|
183
|
+
let scope;
|
|
184
|
+
let baseInfo;
|
|
185
|
+
const skipped = [];
|
|
186
|
+
if (opts.files?.length) {
|
|
187
|
+
scope = new Map();
|
|
188
|
+
for (const f of opts.files) {
|
|
189
|
+
const abs = path.resolve(cwd, f);
|
|
190
|
+
const rel = path.relative(cwd, abs).split(path.sep).join('/');
|
|
191
|
+
let st = null;
|
|
192
|
+
try {
|
|
193
|
+
st = fs.lstatSync(abs);
|
|
194
|
+
} catch {}
|
|
195
|
+
if (rel.startsWith('..') || path.isAbsolute(rel) || !isInside(cwd, abs)) skipped.push({ file: String(f), reason: 'outside the repository: refused' });
|
|
196
|
+
else if (st?.isSymbolicLink()) skipped.push({ file: rel, reason: 'a symbolic link: refused' });
|
|
197
|
+
else scope.set(rel, null);
|
|
198
|
+
}
|
|
199
|
+
baseInfo = { base: null, label: `named files (${opts.files.length})` };
|
|
200
|
+
} else {
|
|
201
|
+
baseInfo = resolveBase(cwd, opts.base || mc.base);
|
|
202
|
+
scope = changedLines(cwd, baseInfo.base);
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
const files = [];
|
|
206
|
+
for (const [f, lines] of scope) {
|
|
207
|
+
const cls = classifyFile(f);
|
|
208
|
+
const abs = path.join(cwd, f);
|
|
209
|
+
if (!cls.ok) {
|
|
210
|
+
if (!cls.quiet) skipped.push({ file: f, reason: cls.reason });
|
|
211
|
+
} else if (!fs.existsSync(abs)) skipped.push({ file: f, reason: 'deleted' });
|
|
212
|
+
else if (fs.lstatSync(abs).isSymbolicLink() || !isInside(cwd, abs)) skipped.push({ file: f, reason: 'a symbolic link: refused' });
|
|
213
|
+
else files.push({ file: f, lines, language: cls.language });
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
// 2–4. Mutants, functions, associated tests.
|
|
217
|
+
const all = [];
|
|
218
|
+
const originals = new Map();
|
|
219
|
+
for (const f of files) {
|
|
220
|
+
const src = fs.readFileSync(path.join(cwd, f.file), 'utf8');
|
|
221
|
+
originals.set(f.file, src);
|
|
222
|
+
const ms = generateMutants(f.file, src, f.lines);
|
|
223
|
+
f.sha256 = sha(src);
|
|
224
|
+
f.changedLines = f.lines ? f.lines.size : src.split('\n').length;
|
|
225
|
+
f.mutants = ms.length;
|
|
226
|
+
all.push(...ms);
|
|
227
|
+
}
|
|
228
|
+
const queue = prioritize(all);
|
|
229
|
+
const fnNames = [...new Set(all.map((m) => m.function).filter(Boolean))];
|
|
230
|
+
const { tests, associated } = associatedTests(cwd, files.map((f) => f.file), fnNames);
|
|
231
|
+
|
|
232
|
+
const report = {
|
|
233
|
+
kind: 'crossexam.mutation/v1',
|
|
234
|
+
version: VERSION,
|
|
235
|
+
generatedAt: new Date().toISOString(),
|
|
236
|
+
cwd: tildify(cwd),
|
|
237
|
+
repo: repoName(cwd),
|
|
238
|
+
scope: baseInfo.label,
|
|
239
|
+
base: baseInfo.base,
|
|
240
|
+
isolation: iso.method ? describeIsolation(iso.method, { ...limits, timeoutMs: 0 }) : { method: null, sandboxed: false },
|
|
241
|
+
testCommand,
|
|
242
|
+
files: files.map(({ file, language, changedLines, mutants, sha256 }) => ({ file, language, changedLines, mutants, sha256 })),
|
|
243
|
+
skippedFiles: skipped,
|
|
244
|
+
associatedTests: associated,
|
|
245
|
+
baseline: null,
|
|
246
|
+
mutants: [],
|
|
247
|
+
functions: [],
|
|
248
|
+
summary: null,
|
|
249
|
+
headline: null,
|
|
250
|
+
rating: 'inconclusive',
|
|
251
|
+
blocker: null,
|
|
252
|
+
remaining: 0,
|
|
253
|
+
workingTreeUntouched: null,
|
|
254
|
+
execution: { repository: repoName(cwd), mutantsGenerated: all.length, mutantsPlanned: queue.length, testRuns: 0, staleCopiesRemoved: 0, cleanup: { status: 'not needed' } },
|
|
255
|
+
notes,
|
|
256
|
+
};
|
|
257
|
+
const block = (text) => {
|
|
258
|
+
report.blocker = text;
|
|
259
|
+
notes.unshift(text);
|
|
260
|
+
};
|
|
261
|
+
const finish = () => {
|
|
262
|
+
summarise(report, t0);
|
|
263
|
+
report.execution.durationMs = Date.now() - t0;
|
|
264
|
+
return report;
|
|
265
|
+
};
|
|
266
|
+
|
|
267
|
+
if (!files.length) {
|
|
268
|
+
block(scope.size ? 'No changed JavaScript or TypeScript source to mutate (only tests, config, other languages, or refused paths).' : `Nothing changed (${baseInfo.label}).`);
|
|
269
|
+
return finish();
|
|
270
|
+
}
|
|
271
|
+
if (!queue.length) {
|
|
272
|
+
block('The changed lines contain no operators crossexam mutates yet (comparisons, conditions, arithmetic, booleans, logic).');
|
|
273
|
+
return finish();
|
|
274
|
+
}
|
|
275
|
+
if (!testCommand) {
|
|
276
|
+
block('No test command found. Add one to crossexam.json: {"mutation": {"testCommand": "npm test"}} or {"commands": {"tests": "…"}}.');
|
|
277
|
+
report.remaining = queue.length;
|
|
278
|
+
return finish();
|
|
279
|
+
}
|
|
280
|
+
if (!iso.method) {
|
|
281
|
+
block(iso.refused);
|
|
282
|
+
report.remaining = queue.length;
|
|
283
|
+
return finish();
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
// 5. A disposable copy; prove the working tree and git state are left alone.
|
|
287
|
+
report.execution.staleCopiesRemoved = sweepStaleCopies(cwd).length;
|
|
288
|
+
const watch = [...new Set([...projectFiles(cwd)])];
|
|
289
|
+
const before = fingerprint(cwd, watch);
|
|
290
|
+
const gitBefore = gitState(cwd);
|
|
291
|
+
const removedEnv = iso.method === 'none' ? scrubbedEnv().removed : allowlistedEnv().removed;
|
|
292
|
+
if (removedEnv.length) notes.push(`${removedEnv.length} environment variable${removedEnv.length === 1 ? ' was' : 's were'} withheld from the test runs${iso.method === 'none' ? ' (credential-like names)' : ' (sandboxed runs get an allowlist only)'}.`);
|
|
293
|
+
opts.onProgress?.({ phase: 'copy', isolation: report.isolation });
|
|
294
|
+
const copy = createCopy(cwd, { linkDeps: iso.method !== 'docker' });
|
|
295
|
+
if (copy.skippedLinks.length) notes.push(`${copy.skippedLinks.length} tracked symbolic link${copy.skippedLinks.length === 1 ? '' : 's'} pointing outside the repository ${copy.skippedLinks.length === 1 ? 'was' : 'were'} not copied: ${copy.skippedLinks.slice(0, 3).join(', ')}.`);
|
|
296
|
+
const onSig = () => {
|
|
297
|
+
copy.dispose();
|
|
298
|
+
process.exit(130);
|
|
299
|
+
};
|
|
300
|
+
process.once('SIGINT', onSig);
|
|
301
|
+
process.once('SIGTERM', onSig);
|
|
302
|
+
const run = (command, timeoutMs) => {
|
|
303
|
+
report.execution.testRuns++;
|
|
304
|
+
return runIsolated(command, { copy, cwd: copy.dir, timeoutMs, method: iso.method, limits, docker: mc.docker || {} });
|
|
305
|
+
};
|
|
306
|
+
|
|
307
|
+
try {
|
|
308
|
+
// 6. Baseline: a red suite can't detect anything.
|
|
309
|
+
opts.onProgress?.({ phase: 'baseline' });
|
|
310
|
+
const baseTimeout = clampNum(config.timeoutSeconds, 10, HARD.mutantTimeoutSeconds, 300) * 1000;
|
|
311
|
+
report.isolation.limits.timeoutSeconds = Math.round(baseTimeout / 1000);
|
|
312
|
+
const b = await run(testCommand, baseTimeout);
|
|
313
|
+
const bj = judgeRun({ ...b, command: testCommand });
|
|
314
|
+
report.baseline = { exitCode: b.exitCode, ms: b.ms, timedOut: b.timedOut, excerpt: b.exitCode === 0 ? '' : redact(excerpt(b.output)) };
|
|
315
|
+
if (b.exitCode !== 0 || b.timedOut) {
|
|
316
|
+
const sandboxHint = iso.method !== 'none' ? ' Inside the sandbox there is no network, no home directory and no credentials; a suite that needs them fails here.' : '';
|
|
317
|
+
block(b.timedOut ? `The unmutated test suite timed out after ${Math.round(baseTimeout / 1000)}s, so no mutant could be judged.` : `The unmutated test suite fails (\`${testCommand}\` exited ${b.exitCode}), so no mutant could be judged.${sandboxHint}`);
|
|
318
|
+
report.remaining = queue.length;
|
|
319
|
+
return finish();
|
|
320
|
+
}
|
|
321
|
+
const exitOnly = bj.status === 'fail'; // noisy-but-passing suites: trust the exit code alone
|
|
322
|
+
const baselineInvalid = INVALID_SIG.test(b.output);
|
|
323
|
+
const perTimeout = Math.min(Math.max(b.ms * 3 + 5000, 10000), clampNum(mc.mutantTimeoutSeconds, 5, HARD.mutantTimeoutSeconds, 120) * 1000);
|
|
324
|
+
report.isolation.limits.timeoutSeconds = Math.round(perTimeout / 1000);
|
|
325
|
+
const deadline = t0 + budgetMs;
|
|
326
|
+
|
|
327
|
+
// 7–8. Run each mutant.
|
|
328
|
+
const useCache = opts.cache !== false && mc.cache !== false;
|
|
329
|
+
const cache = useCache ? loadCache(cwd) : { entries: {} };
|
|
330
|
+
const testHash = sha(tests.map((t) => `${t}:${before[t] ?? ''}`).join('|'));
|
|
331
|
+
let executed = 0;
|
|
332
|
+
let i = 0;
|
|
333
|
+
for (const m of queue) {
|
|
334
|
+
i++;
|
|
335
|
+
const src = originals.get(m.file);
|
|
336
|
+
const key = sha([VERSION, testCommand, iso.method, sha(src), m.id, m.replacement, testHash].join('\0'));
|
|
337
|
+
const hit = cache.entries[key];
|
|
338
|
+
if (hit) {
|
|
339
|
+
report.mutants.push(record(m, hit.status, hit.why, hit.ms, true));
|
|
340
|
+
opts.onProgress?.({ phase: 'mutant', i, total: queue.length, mutant: m, status: hit.status, cached: true });
|
|
341
|
+
continue;
|
|
342
|
+
}
|
|
343
|
+
if (executed >= max || Date.now() + perTimeout > deadline) {
|
|
344
|
+
report.remaining++;
|
|
345
|
+
continue;
|
|
346
|
+
}
|
|
347
|
+
executed++;
|
|
348
|
+
const target = path.join(copy.dir, m.file);
|
|
349
|
+
// The copy is crossexam's own: refuse to write anywhere else, even if a
|
|
350
|
+
// test replaced a folder in the copy with a link while it ran.
|
|
351
|
+
if (!isInside(copy.root, path.dirname(target)) || (fs.existsSync(target) && fs.lstatSync(target).isSymbolicLink())) {
|
|
352
|
+
throw new Error(`Refusing to write ${m.file}: its path in the copy now leads outside the copy.`);
|
|
353
|
+
}
|
|
354
|
+
const mutated = applyMutant(src, m);
|
|
355
|
+
let status;
|
|
356
|
+
let why;
|
|
357
|
+
let ms = 0;
|
|
358
|
+
try {
|
|
359
|
+
fs.writeFileSync(target, mutated);
|
|
360
|
+
if (/\.[cm]?js$/i.test(m.file)) {
|
|
361
|
+
// Parse only, never execute: node --check compiles and exits.
|
|
362
|
+
const chk = spawnSync(process.execPath, ['--check', target], { encoding: 'utf8', windowsHide: true, timeout: 15000, env: { PATH: process.env.PATH, SystemRoot: process.env.SystemRoot } });
|
|
363
|
+
if (chk.status !== 0) {
|
|
364
|
+
status = STATUS.INVALID;
|
|
365
|
+
why = 'the mutant is not valid syntax';
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
if (!status) {
|
|
369
|
+
const r = await run(testCommand, perTimeout);
|
|
370
|
+
ms = r.ms;
|
|
371
|
+
if (r.spawnError) [status, why] = [STATUS.UNRESOLVED, `could not start the tests: ${r.spawnError}`];
|
|
372
|
+
else if (r.timedOut) [status, why] = [STATUS.UNRESOLVED, `timed out after ${Math.round(perTimeout / 1000)}s (the defect may loop forever); not counted as caught`];
|
|
373
|
+
else if (r.signal) [status, why] = [STATUS.UNRESOLVED, `the test process was killed by ${r.signal} (a resource limit); not counted as caught`];
|
|
374
|
+
else {
|
|
375
|
+
const failed = exitOnly ? r.exitCode !== 0 : r.exitCode !== 0 || judgeRun({ ...r, command: testCommand }).status === 'fail';
|
|
376
|
+
if (failed && !baselineInvalid && INVALID_SIG.test(r.output)) [status, why] = [STATUS.INVALID, 'the mutant did not compile or load'];
|
|
377
|
+
else if (failed) [status, why] = [STATUS.KILLED, redact(firstFailure(r))];
|
|
378
|
+
else [status, why] = [STATUS.SURVIVED, explain(m)];
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
} finally {
|
|
382
|
+
// Restore and prove it, before the next mutant touches anything.
|
|
383
|
+
fs.writeFileSync(target, src);
|
|
384
|
+
if (sha(fs.readFileSync(target, 'utf8')) !== sha(src)) throw new Error(`Could not restore ${m.file} in the isolated copy; stopping.`);
|
|
385
|
+
}
|
|
386
|
+
if (status !== STATUS.UNRESOLVED) cache.entries[key] = { status, why, ms, at: new Date().toISOString() };
|
|
387
|
+
report.mutants.push(record(m, status, why, ms, false));
|
|
388
|
+
opts.onProgress?.({ phase: 'mutant', i, total: queue.length, mutant: m, status, ms });
|
|
389
|
+
}
|
|
390
|
+
if (useCache) saveCache(cwd, cache);
|
|
391
|
+
if (report.remaining) notes.push(`${report.remaining} more mutant${report.remaining === 1 ? '' : 's'} not run this time (--max ${max} / --budget ${Math.round(budgetMs / 1000)}s). Run again to continue: finished mutants are cached.`);
|
|
392
|
+
} finally {
|
|
393
|
+
process.removeListener('SIGINT', onSig);
|
|
394
|
+
process.removeListener('SIGTERM', onSig);
|
|
395
|
+
const cleaned = copy.dispose();
|
|
396
|
+
report.execution.cleanup = cleaned.removed ? { status: 'removed' } : { status: 'incomplete', path: cleaned.path, reason: cleaned.reason };
|
|
397
|
+
if (!cleaned.removed) notes.push(`The temporary copy could not be fully removed (${cleaned.reason}). It is at ${cleaned.path}; nothing in it is linked to your repo's files except read-only dependency links.`);
|
|
398
|
+
const after = fingerprint(cwd, watch);
|
|
399
|
+
const gitAfter = gitState(cwd);
|
|
400
|
+
const treeSame = watch.every((f) => before[f] === after[f]);
|
|
401
|
+
const gitSame = ['head', 'refs', 'stash', 'status'].every((k) => gitBefore[k] === gitAfter[k]);
|
|
402
|
+
report.workingTreeUntouched = treeSame && gitSame;
|
|
403
|
+
report.execution.gitUnchanged = gitSame;
|
|
404
|
+
if (!report.workingTreeUntouched) notes.push('The working tree or git state changed during the run. crossexam only writes inside its temporary copy, so something else (an editor, a watcher, the agent) changed it.');
|
|
405
|
+
}
|
|
406
|
+
return finish();
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
const tildify = (p) => {
|
|
410
|
+
const h = os.homedir();
|
|
411
|
+
return p.toLowerCase().startsWith(h.toLowerCase()) ? '~' + p.slice(h.length) : p;
|
|
412
|
+
};
|
|
413
|
+
|
|
414
|
+
// Values that look like secrets never leave in a report.
|
|
415
|
+
const SECRET_PATTERNS = [
|
|
416
|
+
/\b(?:sk|pk|rk)_(?:live|test)_[0-9A-Za-z]{10,}/g,
|
|
417
|
+
/\bsk-[A-Za-z0-9_-]{20,}/g,
|
|
418
|
+
/\bgh[pousr]_[A-Za-z0-9]{30,}/g,
|
|
419
|
+
/\bgithub_pat_[A-Za-z0-9_]{30,}/g,
|
|
420
|
+
/\bAKIA[0-9A-Z]{16}\b/g,
|
|
421
|
+
/\bxox[baprs]-[A-Za-z0-9-]{10,}/g,
|
|
422
|
+
/\bAIza[0-9A-Za-z_-]{35}\b/g,
|
|
423
|
+
/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z ]*PRIVATE KEY-----|$)/g,
|
|
424
|
+
/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/g,
|
|
425
|
+
];
|
|
426
|
+
const SECRET_ASSIGN = /((?:password|passwd|secret|token|api[_-]?key|access[_-]?key|private[_-]?key|client[_-]?secret)["']?\s*[:=]\s*)(["'`])([^"'`\n]{6,})\2/gi;
|
|
427
|
+
export function redact(s) {
|
|
428
|
+
if (typeof s !== 'string' || !s) return s;
|
|
429
|
+
let out = s;
|
|
430
|
+
for (const re of SECRET_PATTERNS) out = out.replace(re, '[redacted]');
|
|
431
|
+
return out.replace(SECRET_ASSIGN, (_, k, q) => `${k}${q}[redacted]${q}`);
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
/** A report without code lines, for sharing outside the team. */
|
|
435
|
+
export function withoutSource(report) {
|
|
436
|
+
return {
|
|
437
|
+
...report,
|
|
438
|
+
baseline: report.baseline ? { ...report.baseline, excerpt: '' } : null,
|
|
439
|
+
mutants: report.mutants.map(({ before, after, ...m }) => ({ ...m, before: undefined, after: undefined, why: m.status === STATUS.KILLED ? '' : m.why })),
|
|
440
|
+
};
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
function record(m, status, why, ms, cached) {
|
|
444
|
+
return {
|
|
445
|
+
id: m.id,
|
|
446
|
+
file: m.file,
|
|
447
|
+
line: m.line,
|
|
448
|
+
col: m.col,
|
|
449
|
+
function: m.function,
|
|
450
|
+
functionLine: m.functionLine,
|
|
451
|
+
operator: m.operator,
|
|
452
|
+
original: m.original,
|
|
453
|
+
replacement: m.replacement,
|
|
454
|
+
before: redact(m.before),
|
|
455
|
+
after: redact(m.after),
|
|
456
|
+
status,
|
|
457
|
+
why,
|
|
458
|
+
ms,
|
|
459
|
+
cached,
|
|
460
|
+
};
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
function firstFailure(r) {
|
|
464
|
+
const j = judgeRun({ ...r, command: '' });
|
|
465
|
+
const ex = excerpt(r.output, 240).split('\n').find((l) => /fail|error|assert|expected|✗|×|not ok/i.test(l));
|
|
466
|
+
return (ex ? ex.trim() : j.why).slice(0, 200);
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
const repoName = (cwd) => {
|
|
470
|
+
const url = tryGit(cwd, ['config', '--get', 'remote.origin.url']);
|
|
471
|
+
const m = url && url.trim().match(/[:/]([^/:]+\/[^/]+?)(?:\.git)?$/);
|
|
472
|
+
return m ? m[1] : path.basename(cwd);
|
|
473
|
+
};
|
|
474
|
+
|
|
475
|
+
// ---------- summary ----------
|
|
476
|
+
|
|
477
|
+
// Survivors that say the most about missing tests come first.
|
|
478
|
+
const WEIGHT = { 'negate-condition': 6, boundary: 5, equality: 5, logical: 4, 'remove-not': 4, boolean: 3, arithmetic: 3, update: 2 };
|
|
479
|
+
|
|
480
|
+
function summarise(report, t0) {
|
|
481
|
+
const n = (s) => report.mutants.filter((m) => m.status === s).length;
|
|
482
|
+
const killed = n(STATUS.KILLED);
|
|
483
|
+
const survived = n(STATUS.SURVIVED);
|
|
484
|
+
const invalid = n(STATUS.INVALID);
|
|
485
|
+
const unresolved = n(STATUS.UNRESOLVED);
|
|
486
|
+
const attempted = report.mutants.length;
|
|
487
|
+
const judged = killed + survived;
|
|
488
|
+
report.summary = {
|
|
489
|
+
attempted,
|
|
490
|
+
valid: attempted - invalid,
|
|
491
|
+
killed,
|
|
492
|
+
survived,
|
|
493
|
+
invalid,
|
|
494
|
+
unresolved,
|
|
495
|
+
remaining: report.remaining,
|
|
496
|
+
score: judged ? Math.round((killed / judged) * 1000) / 1000 : null,
|
|
497
|
+
ms: Date.now() - t0,
|
|
498
|
+
cachedResults: report.mutants.filter((m) => m.cached).length,
|
|
499
|
+
};
|
|
500
|
+
|
|
501
|
+
const fns = new Map();
|
|
502
|
+
for (const m of report.mutants) {
|
|
503
|
+
const k = `${m.file}#${m.function ?? ''}`;
|
|
504
|
+
if (!fns.has(k)) fns.set(k, { file: m.file, name: m.function, line: m.functionLine ?? m.line, killed: 0, survived: 0, invalid: 0, unresolved: 0 });
|
|
505
|
+
const f = fns.get(k);
|
|
506
|
+
f[{ [STATUS.KILLED]: 'killed', [STATUS.SURVIVED]: 'survived', [STATUS.INVALID]: 'invalid', [STATUS.UNRESOLVED]: 'unresolved' }[m.status]]++;
|
|
507
|
+
}
|
|
508
|
+
report.functions = [...fns.values()]
|
|
509
|
+
.map((f) => ({ ...f, score: f.killed + f.survived ? Math.round((f.killed / (f.killed + f.survived)) * 1000) / 1000 : null }))
|
|
510
|
+
.sort((a, b) => b.survived - a.survived || (a.score ?? 1) - (b.score ?? 1) || a.file.localeCompare(b.file));
|
|
511
|
+
|
|
512
|
+
// Rating: only when there's enough to go on.
|
|
513
|
+
const s = report.summary.score;
|
|
514
|
+
report.rating = judged < 3 ? 'inconclusive' : s >= 0.8 ? 'strong' : s >= 0.6 ? 'moderate' : 'weak';
|
|
515
|
+
|
|
516
|
+
const survivors = report.mutants.filter((m) => m.status === STATUS.SURVIVED);
|
|
517
|
+
if (survivors.length) {
|
|
518
|
+
const worstFn = report.functions[0];
|
|
519
|
+
const pick = survivors
|
|
520
|
+
.filter((m) => m.file === worstFn.file && m.function === worstFn.name)
|
|
521
|
+
.sort((a, b) => (WEIGHT[b.operator] || 0) - (WEIGHT[a.operator] || 0) || a.line - b.line)[0];
|
|
522
|
+
const where = pick.function ? `\`${pick.function}\` (${pick.file}:${pick.line})` : `${pick.file}:${pick.line}`;
|
|
523
|
+
report.headline = {
|
|
524
|
+
tone: report.rating === 'strong' ? 'note' : 'warn',
|
|
525
|
+
text: `${survived} of ${judged} planted defects went unnoticed by the tests. Biggest gap: ${where}: ${pick.why.replace(/^In [^,]+, /, '').replace(/\.$/, '')}.`,
|
|
526
|
+
mutant: pick.id,
|
|
527
|
+
};
|
|
528
|
+
} else if (judged) {
|
|
529
|
+
report.headline = { tone: 'good', text: `The tests caught all ${killed} planted defect${killed === 1 ? '' : 's'} in the changed code.`, mutant: null };
|
|
530
|
+
} else {
|
|
531
|
+
report.headline = { tone: report.blocker ? 'warn' : 'note', text: report.blocker || 'No mutant could be judged.', mutant: null };
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
/** A compact block to attach to a verified "tests pass" claim: a separate dimension, never a verdict. */
|
|
536
|
+
export function qualityOf(report) {
|
|
537
|
+
const s = report.summary;
|
|
538
|
+
return {
|
|
539
|
+
dimension: 'test-strength',
|
|
540
|
+
rating: report.rating,
|
|
541
|
+
score: s.score,
|
|
542
|
+
killed: s.killed,
|
|
543
|
+
survived: s.survived,
|
|
544
|
+
invalid: s.invalid,
|
|
545
|
+
unresolved: s.unresolved,
|
|
546
|
+
headline: report.headline?.text ?? null,
|
|
547
|
+
warning: report.rating === 'weak' || report.rating === 'moderate' ? report.headline?.text ?? null : null,
|
|
548
|
+
};
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
// ---------- exports ----------
|
|
552
|
+
|
|
553
|
+
export function toCsv(report) {
|
|
554
|
+
const head = ['mutant_id', 'repo', 'file', 'line', 'function', 'operator', 'original', 'replacement', 'status', 'ms', 'cached', 'explanation'];
|
|
555
|
+
const esc = (v) => `"${String(v ?? '').replace(/"/g, '""').replace(/\r?\n/g, ' ')}"`;
|
|
556
|
+
const rows = report.mutants.map((m) => [m.id, report.repo, m.file, m.line, m.function ?? '', m.operator, m.original, m.replacement, m.status, m.ms, m.cached, m.why].map(esc).join(','));
|
|
557
|
+
return [head.join(','), ...rows].join('\n') + '\n';
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
/** What goes into ~/.crossexam/ledger.jsonl, so history can show test strength per agent and repo. */
|
|
561
|
+
export function ledgerRecord(report, { agent = 'unknown', claim = null, source = 'cli' } = {}) {
|
|
562
|
+
return {
|
|
563
|
+
type: 'mutation',
|
|
564
|
+
at: report.generatedAt,
|
|
565
|
+
agent,
|
|
566
|
+
repo: report.repo,
|
|
567
|
+
source,
|
|
568
|
+
claim,
|
|
569
|
+
scope: report.scope,
|
|
570
|
+
testCommand: report.testCommand,
|
|
571
|
+
rating: report.rating,
|
|
572
|
+
...report.summary,
|
|
573
|
+
survivors: report.mutants.filter((m) => m.status === STATUS.SURVIVED).slice(0, 20).map((m) => ({ id: m.id, function: m.function, operator: m.operator })),
|
|
574
|
+
};
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
// ---------- history ----------
|
|
578
|
+
|
|
579
|
+
/**
|
|
580
|
+
* Test strength over time, from the ledger. Kept beside, never blended into,
|
|
581
|
+
* the factual false-done rates: an agent can be honest and still ship weak tests.
|
|
582
|
+
*/
|
|
583
|
+
export function strengthHistory({ since = 0, agent, repo, file = path.join(process.env.CROSSEXAM_HOME || path.join(os.homedir(), '.crossexam'), 'ledger.jsonl') } = {}) {
|
|
584
|
+
let lines = [];
|
|
585
|
+
try {
|
|
586
|
+
lines = fs.readFileSync(file, 'utf8').split('\n');
|
|
587
|
+
} catch {
|
|
588
|
+
return null;
|
|
589
|
+
}
|
|
590
|
+
const runs = [];
|
|
591
|
+
for (const l of lines) {
|
|
592
|
+
if (!l.includes('"type":"mutation"')) continue;
|
|
593
|
+
try {
|
|
594
|
+
const r = JSON.parse(l);
|
|
595
|
+
if (r.type !== 'mutation' || !(r.killed + r.survived)) continue;
|
|
596
|
+
if (since && Date.parse(r.at) < since) continue;
|
|
597
|
+
if ((agent && r.agent !== agent) || (repo && r.repo !== repo)) continue;
|
|
598
|
+
runs.push(r);
|
|
599
|
+
} catch {
|
|
600
|
+
/* a torn line from a crash: skip it */
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
if (!runs.length) return null;
|
|
604
|
+
const group = (key) => {
|
|
605
|
+
const m = {};
|
|
606
|
+
for (const r of runs) {
|
|
607
|
+
const k = r[key] || 'unknown';
|
|
608
|
+
m[k] ??= { runs: 0, killed: 0, survived: 0, weakRuns: 0 };
|
|
609
|
+
m[k].runs++;
|
|
610
|
+
m[k].killed += r.killed;
|
|
611
|
+
m[k].survived += r.survived;
|
|
612
|
+
if (r.rating === 'weak') m[k].weakRuns++;
|
|
613
|
+
}
|
|
614
|
+
for (const v of Object.values(m)) v.score = Math.round((v.killed / (v.killed + v.survived)) * 1000) / 1000;
|
|
615
|
+
return m;
|
|
616
|
+
};
|
|
617
|
+
const killed = runs.reduce((a, r) => a + r.killed, 0);
|
|
618
|
+
const survived = runs.reduce((a, r) => a + r.survived, 0);
|
|
619
|
+
return {
|
|
620
|
+
runs: runs.length,
|
|
621
|
+
killed,
|
|
622
|
+
survived,
|
|
623
|
+
score: Math.round((killed / (killed + survived)) * 1000) / 1000,
|
|
624
|
+
byAgent: group('agent'),
|
|
625
|
+
byRepo: group('repo'),
|
|
626
|
+
recent: runs.slice(-20).reverse().map(({ at, agent, repo, rating, score, killed, survived, source, claim }) => ({ at, agent, repo, rating, score, killed, survived, source, claim })),
|
|
627
|
+
};
|
|
628
|
+
}
|