crossexamdev 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/mutate.js CHANGED
@@ -5,6 +5,8 @@
5
5
  // out (same length, newlines kept), so an operator never fires inside text and
6
6
  // every offset in the masked copy is also an offset in the original.
7
7
 
8
+ import { createHash } from 'node:crypto';
9
+
8
10
  export const CODE_EXT = /\.(?:py|go|rs|java|kt|kts|rb|swift|cs|php|c|cc|cpp|h|hpp|scala|ex|exs|dart|vue|svelte|lua|r|jl)$/i;
9
11
  export const JS_EXT = /\.(?:[cm]?jsx?|[cm]?tsx?)$/i;
10
12
  export const TEST_FILE = /(?:^|[\\/])(?:__tests__|__mocks__|tests?|spec|e2e|fixtures?)[\\/]|[._-](?:test|spec)\.[cm]?[jt]sx?$/i;
@@ -319,7 +321,59 @@ export const OPERATORS = [
319
321
  ];
320
322
 
321
323
  const NEGATE = { id: 'negate-condition', label: 'condition', why: 'neither branch of this condition is pinned down by a test' };
322
- export const OPERATOR_WHY = Object.fromEntries([...OPERATORS, NEGATE].map((o) => [o.id, o.why]));
324
+
325
+ /*
326
+ * Behavioural defects: the ways real changes go wrong, not just a flipped
327
+ * token. Found by pattern on the masked source (so never inside strings or
328
+ * comments), and labelled as such: a name like `requireAdmin` or `retries`
329
+ * is what marks the code, not a type checker.
330
+ */
331
+ export const BEHAVIOURS = [
332
+ { id: 'commit-to-rollback', category: 'transactions', why: 'nothing checks that the work is actually committed' },
333
+ { id: 'drop-rollback', category: 'transactions', why: 'nothing checks that a failure undoes the partial writes' },
334
+ { id: 'bypass-auth', category: 'authorization', why: 'no test proves that a caller without permission is turned away' },
335
+ { id: 'drop-auth-check', category: 'authorization', why: 'no test proves that a caller without permission is turned away' },
336
+ { id: 'retry-once', category: 'retries', why: 'nothing tests what happens when the first attempt fails' },
337
+ { id: 'no-backoff', category: 'retries', why: 'nothing checks the wait between attempts' },
338
+ { id: 'off-by-one', category: 'boundaries', why: 'no test checks the first or the last item' },
339
+ { id: 'drop-await', category: 'concurrency', why: 'nothing checks that this finishes before the code moves on' },
340
+ { id: 'drop-lock', category: 'concurrency', why: 'nothing exercises two of these running at the same time' },
341
+ { id: 'all-settled', category: 'concurrency', why: 'nothing checks that one failed task fails the whole batch' },
342
+ ];
343
+
344
+ export const OPERATOR_WHY = Object.fromEntries([...OPERATORS, NEGATE, ...BEHAVIOURS].map((o) => [o.id, o.why]));
345
+
346
+ /** What kind of defect an operator plants. */
347
+ export const CATEGORY = {
348
+ boundary: 'boundaries',
349
+ equality: 'logic',
350
+ logical: 'logic',
351
+ 'remove-not': 'logic',
352
+ 'negate-condition': 'logic',
353
+ boolean: 'logic',
354
+ arithmetic: 'arithmetic',
355
+ update: 'arithmetic',
356
+ ...Object.fromEntries(BEHAVIOURS.map((b) => [b.id, b.category])),
357
+ };
358
+ /** Categories that describe behaviour rather than syntax. */
359
+ export const BEHAVIOURAL_CATEGORIES = new Set(['transactions', 'authorization', 'retries', 'concurrency']);
360
+ export const isBehavioural = (op) => BEHAVIOURAL_CATEGORIES.has(CATEGORY[op]) || op === 'off-by-one';
361
+
362
+ // Names that mark code as being about access, retries or array positions.
363
+ const AUTH_WORDS = /\b(?:auth\w*|Auth\w*|authori[sz]\w*|permi\w*|can[A-Z]\w*|isAdmin|is[A-Z]\w*(?:Admin|Owner|Member|Allowed|Authori[sz]ed)|admin\w*|owner\w*|roles?|scopes?|allowed\w*|forbidden|unauthori[sz]ed|session|currentUser|acl|policy|access\w*)\b/;
364
+ const AUTH_CALL = /^(?:require|assert|ensure|check|verify|enforce|authori[sz]e|guard|can|must)\w*$/i;
365
+ const AUTH_NAME = /auth|perm|role|admin|owner|access|scope|login|session|can[A-Z]|allowed|policy|acl/i;
366
+ const RETRY_WORDS = /\b(?:[a-z]*[Rr]etr(?:y|ies|ied)[A-Za-z]*|[a-z]*[Aa]ttempts?[A-Za-z]*|(?:max|num)?[Tt]ries|[a-z]*[Bb]ackoff[A-Za-z]*)\b/;
367
+ const INDEX_WORDS = /\b(?:length|index|idx|count|size|limit|offset|page|end|start|last|first|len|total|cursor)\b/i;
368
+ const DELAY_CALL = /\b(sleep|delay|wait|pause|backoff\w*|setTimeout)\s*\(/g;
369
+
370
+ /** The whole line as one statement (no block, no control flow), or null. */
371
+ function lineStatement(mline) {
372
+ const lead = mline.match(/^\s*/)[0].length;
373
+ const body = mline.slice(lead).replace(/\s+$/, '');
374
+ if (!body || /[{}]/.test(body) || /^(?:if|for|while|switch|return|throw|else|case|default|const|let|var|function|class|try|catch|finally|do)\b/.test(body)) return null;
375
+ return [lead, lead + body.length];
376
+ }
323
377
 
324
378
  // Lines where an operator-looking token isn't an operator.
325
379
  const NOT_CODE_LINE = /^\s*(?:import\b|export\s+(?:\*|\{[^}]*\}\s+from)|\/\/|\*|type\s+\w+\s*=|interface\b|@)/;
@@ -397,10 +451,86 @@ export function generateMutants(file, src, lines) {
397
451
  if (!cond.trim() || /^\s*!\s*(?:[\w$.]+|\([^()]*\))\s*$/.test(cond)) continue;
398
452
  push(NEGATE.id, open + 1, close, `!(${cond})`);
399
453
  }
454
+ behaviouralMutants(mline, a, masked, src, push);
400
455
  }
401
456
  return mutants;
402
457
  }
403
458
 
459
+ /** Realistic defects on one line: transactions, access checks, retries, positions, concurrency. */
460
+ function behaviouralMutants(mline, a, masked, src, push) {
461
+ const stmt = lineStatement(mline);
462
+
463
+ // transactions: commit becomes rollback; a rollback disappears
464
+ for (const m of mline.matchAll(/\.(commit)\s*\(/g)) push('commit-to-rollback', a + m.index + 1, a + m.index + 1 + 6, 'rollback');
465
+ if (stmt && /\.\s*rollback\s*\(/.test(mline)) push('drop-rollback', a + stmt[0], a + stmt[1], 'void 0;');
466
+
467
+ // authorization: a guard that turns callers away never fires
468
+ for (const m of mline.matchAll(/\bif\s*\(/g)) {
469
+ const open = a + m.index + m[0].length - 1;
470
+ const close = matchClose(masked, open);
471
+ if (close < 0) continue;
472
+ const cond = masked.slice(open + 1, close);
473
+ if (!AUTH_WORDS.test(cond)) continue;
474
+ // only guards: the branch leaves (throw, return, a 4xx response, next(err))
475
+ if (!/^\s*(?:\{\s*)?(?:throw\b|return\b|res(?:ponse)?\.status\s*\(\s*4\d\d|next\s*\(\s*[\w$])/.test(masked.slice(close + 1, close + 200))) continue;
476
+ push('bypass-auth', open + 1, close, 'false');
477
+ }
478
+ // ...or a guard call (`await requireAdmin(user)`) is dropped
479
+ if (stmt) {
480
+ const call = mline.slice(stmt[0], stmt[1]).match(/^(?:await\s+)?(?:[\w$]+\.)*([\w$]+)\s*\(/);
481
+ if (call && AUTH_CALL.test(call[1]) && AUTH_NAME.test(call[1])) push('drop-auth-check', a + stmt[0], a + stmt[1], 'void 0;');
482
+ }
483
+
484
+ // retries: only one attempt, or no wait between attempts
485
+ if (RETRY_WORDS.test(mline)) {
486
+ for (const m of mline.matchAll(/(?<=\s)(<=?)\s+([\w$.]+)/g)) {
487
+ if (m[2] === '1' || m[2] === '0') continue;
488
+ const at = a + m.index + m[0].length - m[2].length;
489
+ push('retry-once', at, at + m[2].length, m[1] === '<=' ? '0' : '1');
490
+ }
491
+ }
492
+ for (const m of mline.matchAll(DELAY_CALL)) {
493
+ const open = a + m.index + m[0].length - 1;
494
+ const close = matchClose(masked, open);
495
+ if (close < 0) continue;
496
+ const inner = src.slice(open + 1, close);
497
+ // setTimeout(fn, ms): the delay is the last argument; sleep(ms): the only one
498
+ let from = open + 1;
499
+ if (m[1] === 'setTimeout') {
500
+ const comma = masked.slice(open + 1, close).lastIndexOf(',');
501
+ if (comma < 0) continue;
502
+ from = open + 1 + comma + 1;
503
+ }
504
+ const arg = src.slice(from, close);
505
+ if (!arg.trim() || /^\s*0\s*$/.test(arg) || (m[1] !== 'setTimeout' && inner.includes(','))) continue;
506
+ const lead = arg.match(/^\s*/)[0].length;
507
+ push('no-backoff', from + lead, close, '0');
508
+ }
509
+
510
+ // positions: an index or length loses its -1 / +1
511
+ if (INDEX_WORDS.test(mline)) {
512
+ for (const m of mline.matchAll(/(?<=[\w$\])])(\s[+-]\s1)(?![\w$.])/g)) push('off-by-one', a + m.index, a + m.index + m[1].length, '');
513
+ }
514
+
515
+ // concurrency: an await is dropped, a lock is skipped, Promise.all stops failing fast
516
+ for (const m of mline.matchAll(/(?<!for\s)\bawait\s+(?=[\w$([])/g)) push('drop-await', a + m.index, a + m.index + m[0].length, '');
517
+ if (stmt && /\.(?:acquire|lock|runExclusive|waitForUnlock)\s*\(|\b(?:acquireLock|lock)\s*\(/.test(mline) && !/\.release\s*\(|\bunlock\s*\(/.test(mline)) push('drop-lock', a + stmt[0], a + stmt[1], 'void 0;');
518
+ for (const m of mline.matchAll(/\bPromise\.(all)\s*\(/g)) {
519
+ const at = a + m.index + 'Promise.'.length;
520
+ push('all-settled', at, at + 3, 'allSettled');
521
+ }
522
+ }
523
+
524
+ /**
525
+ * A stable id for a mutant that outlives line shifts: the same change to the
526
+ * same code in the same function gets the same fingerprint, so a triage
527
+ * decision, or an agent's fix, carries over between runs.
528
+ */
529
+ export function mutantFingerprint(m) {
530
+ const firstLine = String(m.before ?? '').split('\n')[0].replace(/\s+/g, ' ').trim();
531
+ return createHash('sha256').update([m.file, m.function ?? '', m.operator, m.original ?? '', m.replacement ?? '', firstLine].join('\u0000')).digest('hex').slice(0, 32);
532
+ }
533
+
404
534
  /**
405
535
  * Pick which mutants to run: spread across functions first, then operators,
406
536
  * so a cap still touches every changed function. Deterministic.
@@ -416,7 +546,8 @@ export function prioritize(mutants) {
416
546
  }
417
547
  // Within a function: round-robin across operators.
418
548
  const queues = [...byFn.values()].map((ops) => {
419
- const lists = [...ops.values()];
549
+ // behavioural defects first, so a capped run still reaches them
550
+ const lists = [...ops.entries()].sort((x, y) => Number(isBehavioural(y[0])) - Number(isBehavioural(x[0]))).map(([, l]) => l);
420
551
  const q = [];
421
552
  for (let i = 0; lists.some((l) => l.length > i); i++) for (const l of lists) if (l[i]) q.push(l[i]);
422
553
  return q;
@@ -433,7 +564,15 @@ export function applyMutant(src, m) {
433
564
  /** One sentence on what a surviving mutant says about the tests. */
434
565
  export function explain(m) {
435
566
  const where = m.function ? `\`${m.function}\`` : 'top-level code';
436
- const change = m.operator === 'negate-condition' ? `inverting \`${clip(m.original)}\`` : m.operator === 'remove-not' ? `dropping the \`!\`` : `\`${m.original}\` → \`${m.replacement}\``;
567
+ const change =
568
+ m.operator === 'negate-condition' ? `inverting \`${clip(m.original)}\``
569
+ : m.operator === 'remove-not' ? 'dropping the `!`'
570
+ : m.replacement === 'void 0;' ? `removing \`${clip(m.original)}\``
571
+ : m.operator === 'bypass-auth' ? `skipping the check \`${clip(m.original)}\``
572
+ : m.operator === 'drop-await' ? `dropping the \`await\` in \`${clip(m.before)}\``
573
+ : m.operator === 'off-by-one' ? `dropping \`${m.original.trim()}\``
574
+ : m.operator === 'no-backoff' ? `waiting 0 instead of \`${clip(m.original)}\``
575
+ : `\`${m.original}\` → \`${m.replacement}\``;
437
576
  return `In ${where}, ${change} still passed every test: ${OPERATOR_WHY[m.operator]}.`;
438
577
  }
439
578
 
@@ -0,0 +1,208 @@
1
+ // Prove a fix: do the tests fail without it and pass with it?
2
+ //
3
+ // "Fixed the refund rounding bug" and a green suite say nothing on their own:
4
+ // the suite may have passed before the fix too. crossexam takes the change
5
+ // into an isolated copy, runs the tests with it (they must pass), then puts
6
+ // the non-test files back the way they were at the base, keeps the new and
7
+ // changed tests, and runs them again (they must fail). Only a fix the tests
8
+ // can tell apart from no fix is proven. The working tree is never touched.
9
+
10
+ import fs from 'node:fs';
11
+ import path from 'node:path';
12
+ import { excerpt, judgeRun } from './evidence.js';
13
+ import { detectCommands, loadConfig } from './live.js';
14
+ import { TEST_FILE } from './mutate.js';
15
+ import { redact, tildify } from './redact.js';
16
+ import { allowlistedEnv, chooseIsolation, clampLimits, createCopy, describeIsolation, fingerprint, git, gitState, isInside, projectFiles, runIsolated, scrubbedEnv, sweepStaleCopies } from './sandbox.js';
17
+ import { resolveBase } from './strength.js';
18
+
19
+ export const FIX = /** @type {const} */ ({
20
+ PROVEN: 'proven', // fails without the fix, passes with it, on an assertion
21
+ LOAD_ONLY: 'load-only', // fails without the fix only because the tests can't load without the new code
22
+ UNPROVEN: 'unproven', // passes with and without the fix: the tests can't tell
23
+ BROKEN: 'broken', // fails even with the fix
24
+ INCONCLUSIVE: 'inconclusive', // could not be judged (no base, no tests, no sandbox, timeouts)
25
+ });
26
+
27
+ // Output that means the tests could not load the code, rather than that an
28
+ // expectation failed: an import of something only the fix adds, a parse error.
29
+ const LOAD_SIG =
30
+ /\bSyntaxError\b|\bdoes not provide an export named\b|\bCannot find module\b|\bERR_MODULE_NOT_FOUND\b|\bModule not found\b|\bis not exported\b|\berror TS\d{3,5}\b|\bModuleNotFoundError\b|\bImportError\b|\bis not a function\b|\bis not defined\b/;
31
+
32
+ const tryGit = (cwd, args) => {
33
+ try {
34
+ return git(cwd, args);
35
+ } catch {
36
+ return null;
37
+ }
38
+ };
39
+
40
+ /** Files changed since base, split into tests and everything else. Paths relative to cwd. */
41
+ export function splitChange(cwd, base) {
42
+ const out = { tests: [], source: [] };
43
+ const seen = new Set();
44
+ const add = (status, file) => {
45
+ if (!file || seen.has(file)) return;
46
+ seen.add(file);
47
+ (TEST_FILE.test(file) ? out.tests : out.source).push({ file, status });
48
+ };
49
+ for (const line of (tryGit(cwd, ['diff', '--name-status', '--no-renames', '--relative', base, '--']) || '').split('\n')) {
50
+ const m = line.match(/^([ADMT])\t(.+)$/);
51
+ if (m) add(m[1], m[2]);
52
+ }
53
+ for (const f of (tryGit(cwd, ['ls-files', '-o', '--exclude-standard']) || '').split('\n').filter(Boolean)) add('A', f);
54
+ return out;
55
+ }
56
+
57
+ const clampNum = (v, lo, hi, d) => {
58
+ const n = Number(v);
59
+ return Number.isFinite(n) ? Math.min(Math.max(n, lo), hi) : d;
60
+ };
61
+
62
+ /**
63
+ * @param {{
64
+ * cwd: string, base?: string, testCommand?: string, claim?: string,
65
+ * isolation?: 'auto'|'bwrap'|'sandbox-exec'|'docker'|'none', allowUnsandboxed?: boolean,
66
+ * timeoutSeconds?: number, onProgress?: (e: {phase: string}) => void
67
+ * }} opts
68
+ */
69
+ export async function proveFix(opts) {
70
+ const t0 = Date.now();
71
+ const cwd = path.resolve(opts.cwd || process.cwd());
72
+ const config = loadConfig(cwd);
73
+ const mc = config.mutation || {};
74
+ const notes = [];
75
+ const testCommand = opts.testCommand || mc.testCommand || detectCommands(cwd, config).tests?.command || null;
76
+ const allowUnsandboxed = opts.allowUnsandboxed === true || process.env.CROSSEXAM_ALLOW_UNSANDBOXED === '1';
77
+ const iso = chooseIsolation({ requested: opts.isolation || mc.isolation || 'auto', allowUnsandboxed, fromRepoConfig: !opts.isolation && !!mc.isolation });
78
+ notes.push(...iso.notes);
79
+ const limits = clampLimits(mc.limits);
80
+ const timeoutMs = clampNum(opts.timeoutSeconds ?? config.timeoutSeconds, 10, 600, 300) * 1000;
81
+
82
+ const baseInfo = resolveBase(cwd, opts.base);
83
+ // Pin the base to a commit, so a later re-check compares against the same thing.
84
+ const baseSha = baseInfo.base ? (tryGit(cwd, ['rev-parse', '--verify', '--quiet', `${baseInfo.base}^{commit}`]) || '').trim() || baseInfo.base : null;
85
+ const change = baseSha ? splitChange(cwd, baseSha) : { tests: [], source: [] };
86
+
87
+ const report = {
88
+ kind: 'crossexam.prove-fix/v1',
89
+ generatedAt: new Date().toISOString(),
90
+ cwd: tildify(cwd),
91
+ repo: path.basename(cwd),
92
+ claim: opts.claim ?? null,
93
+ scope: baseInfo.label,
94
+ base: baseSha,
95
+ testCommand,
96
+ isolation: iso.method ? describeIsolation(iso.method, { ...limits, timeoutMs }) : { method: null, sandboxed: false },
97
+ change: { source: change.source.map((f) => f.file), tests: change.tests.map((f) => f.file) },
98
+ withFix: null,
99
+ withoutFix: null,
100
+ verdict: FIX.INCONCLUSIVE,
101
+ headline: '',
102
+ workingTreeUntouched: null,
103
+ notes,
104
+ };
105
+ const done = (verdict, headline) => {
106
+ report.verdict = verdict;
107
+ report.headline = headline;
108
+ report.durationMs = Date.now() - t0;
109
+ return report;
110
+ };
111
+
112
+ if (!baseSha) return done(FIX.INCONCLUSIVE, `No base to compare against (${baseInfo.label}). Pass --base <ref>.`);
113
+ if (!change.source.length) {
114
+ return done(FIX.INCONCLUSIVE, change.tests.length ? 'Only tests changed, so there is no fix to take out.' : `Nothing changed (${baseInfo.label}).`);
115
+ }
116
+ if (!testCommand) return done(FIX.INCONCLUSIVE, 'No test command found. Pass --test-command, or add {"commands": {"tests": "…"}} to crossexam.json.');
117
+ if (!iso.method) return done(FIX.INCONCLUSIVE, iso.refused);
118
+ if (!change.tests.length) notes.push('No test was added or changed with the fix, so it is judged by the tests that were already there.');
119
+
120
+ sweepStaleCopies(cwd);
121
+ const watch = projectFiles(cwd);
122
+ const before = fingerprint(cwd, watch);
123
+ const gitBefore = gitState(cwd);
124
+ const removedEnv = iso.method === 'none' ? scrubbedEnv().removed : allowlistedEnv().removed;
125
+ if (removedEnv.length) notes.push(`${removedEnv.length} environment variable${removedEnv.length === 1 ? ' was' : 's were'} withheld from the test runs.`);
126
+ const copy = createCopy(cwd, { linkDeps: iso.method !== 'docker' });
127
+ const onSig = () => {
128
+ copy.dispose();
129
+ process.exit(130);
130
+ };
131
+ process.once('SIGINT', onSig);
132
+ process.once('SIGTERM', onSig);
133
+ const run = async (label) => {
134
+ opts.onProgress?.({ phase: label });
135
+ const r = await runIsolated(testCommand, { copy, cwd: copy.dir, timeoutMs, method: iso.method, limits, docker: mc.docker || {} });
136
+ const failed = r.exitCode !== 0 || judgeRun({ ...r, command: testCommand }).status === 'fail';
137
+ return { exitCode: r.exitCode, ms: r.ms, timedOut: !!r.timedOut, spawnError: r.spawnError || null, signal: r.signal || null, failed, output: r.output || '', excerpt: redact(excerpt(r.output || '')) };
138
+ };
139
+ const unrunnable = (r) => (r.spawnError ? `could not start the tests: ${r.spawnError}` : r.timedOut ? `timed out after ${Math.round(timeoutMs / 1000)}s` : r.signal ? `killed by ${r.signal} (a resource limit)` : null);
140
+
141
+ try {
142
+ // 1. With the fix: the suite has to pass, or there's nothing to prove.
143
+ const withFix = await run('with-fix');
144
+ report.withFix = { exitCode: withFix.exitCode, ms: withFix.ms, passed: !withFix.failed, excerpt: withFix.failed ? withFix.excerpt : '' };
145
+ const w = unrunnable(withFix);
146
+ if (w) return done(FIX.INCONCLUSIVE, `The tests could not be judged with the fix: ${w}.`);
147
+ if (withFix.failed) {
148
+ const sandboxHint = iso.method !== 'none' ? ' Inside the sandbox there is no network, home directory or credentials; a suite that needs them fails here.' : '';
149
+ return done(FIX.BROKEN, `The tests fail even with the fix (\`${testCommand}\` exited ${withFix.exitCode}).${sandboxHint}`);
150
+ }
151
+
152
+ // 2. Take the fix out: every non-test file back to the base; tests stay as they are now.
153
+ for (const { file, status } of change.source) {
154
+ const target = path.join(copy.dir, file);
155
+ if (!isInside(copy.root, path.dirname(target)) || (fs.existsSync(target) && fs.lstatSync(target).isSymbolicLink())) {
156
+ throw new Error(`Refusing to write ${file}: its path in the copy leads outside the copy.`);
157
+ }
158
+ if (status === 'A') {
159
+ fs.rmSync(target, { force: true });
160
+ continue;
161
+ }
162
+ const old = tryGit(cwd, ['show', `${baseSha}:./${file}`]);
163
+ if (old === null) throw new Error(`Could not read ${file} at ${baseSha.slice(0, 12)}.`);
164
+ fs.mkdirSync(path.dirname(target), { recursive: true });
165
+ fs.writeFileSync(target, old);
166
+ }
167
+
168
+ // 3. Without the fix: the tests have to notice.
169
+ const without = await run('without-fix');
170
+ report.withoutFix = { exitCode: without.exitCode, ms: without.ms, passed: !without.failed, excerpt: without.failed ? without.excerpt : '' };
171
+ const wo = unrunnable(without);
172
+ if (wo) return done(FIX.INCONCLUSIVE, `The tests could not be judged without the fix: ${wo}.`);
173
+ if (!without.failed) {
174
+ return done(FIX.UNPROVEN, `The tests pass with the fix and without it, so nothing shows the bug existed or that the fix removes it. Add a test that fails on the old code.`);
175
+ }
176
+ if (LOAD_SIG.test(without.output)) {
177
+ return done(FIX.LOAD_ONLY, 'Without the fix the tests fail only because they cannot load (they use something the fix added). That proves the new code exists, not that it fixes the bug. Add a test that runs the old code path and fails on it.');
178
+ }
179
+ return done(FIX.PROVEN, 'The tests fail without the fix and pass with it.');
180
+ } finally {
181
+ process.removeListener('SIGINT', onSig);
182
+ process.removeListener('SIGTERM', onSig);
183
+ const cleaned = copy.dispose();
184
+ if (!cleaned.removed) notes.push(`The temporary copy could not be fully removed (${cleaned.reason}). It is at ${cleaned.path}.`);
185
+ const after = fingerprint(cwd, watch);
186
+ const gitAfter = gitState(cwd);
187
+ report.workingTreeUntouched = watch.every((f) => before[f] === after[f]) && ['head', 'refs', 'stash', 'status'].every((k) => gitBefore[k] === gitAfter[k]);
188
+ 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 changed it.');
189
+ }
190
+ }
191
+
192
+ /** A finding for a fix the tests can't tell apart from no fix. */
193
+ export function fixFinding(r) {
194
+ if (r.verdict !== FIX.UNPROVEN && r.verdict !== FIX.LOAD_ONLY) return null;
195
+ return {
196
+ id: `fix-${String(r.base).slice(0, 10)}-${r.change.source.length}`,
197
+ type: 'fix',
198
+ severity: 'high',
199
+ verdict: r.verdict,
200
+ claim: r.claim,
201
+ base: r.base,
202
+ files: r.change.source,
203
+ reason: r.headline,
204
+ ask: 'Add or change a test so it fails on the code as it was before your fix and passes with it. Do not weaken the fix to make it pass.',
205
+ recheck: 'crossexam takes the fix out again in an isolated copy and runs your tests with and without it',
206
+ status: 'open',
207
+ };
208
+ }
package/src/redact.js ADDED
@@ -0,0 +1,59 @@
1
+ // Keeping secrets and local paths out of anything crossexam writes or shares.
2
+ import os from 'node:os';
3
+
4
+ // Values that look like secrets never leave in a report.
5
+ const SECRET_PATTERNS = [
6
+ /\b(?:sk|pk|rk)_(?:live|test)_[0-9A-Za-z]{10,}/g,
7
+ /\bsk-[A-Za-z0-9_-]{20,}/g,
8
+ /\bgh[pousr]_[A-Za-z0-9]{30,}/g,
9
+ /\bgithub_pat_[A-Za-z0-9_]{30,}/g,
10
+ /\bAKIA[0-9A-Z]{16}\b/g,
11
+ /\bxox[baprs]-[A-Za-z0-9-]{10,}/g,
12
+ /\bAIza[0-9A-Za-z_-]{35}\b/g,
13
+ /-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z ]*PRIVATE KEY-----|$)/g,
14
+ /\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/g,
15
+ ];
16
+ const SECRET_ASSIGN = /((?:password|passwd|secret|token|api[_-]?key|access[_-]?key|private[_-]?key|client[_-]?secret)["']?\s*[:=]\s*)(["'`])([^"'`\n]{6,})\2/gi;
17
+
18
+ export function redact(s) {
19
+ if (typeof s !== 'string' || !s) return s;
20
+ let out = s;
21
+ for (const re of SECRET_PATTERNS) out = out.replace(re, '[redacted]');
22
+ return out.replace(SECRET_ASSIGN, (_, k, q) => `${k}${q}[redacted]${q}`);
23
+ }
24
+
25
+ /** A path under the home folder, written from `~`. */
26
+ export function tildify(p) {
27
+ const h = os.homedir();
28
+ return typeof p === 'string' && p.toLowerCase().startsWith(h.toLowerCase()) ? '~' + p.slice(h.length) : p;
29
+ }
30
+
31
+ const escapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
32
+
33
+ // Absolute paths that would say something about the machine: drive letters,
34
+ // home folders, temp folders, CI workspaces.
35
+ const ABSOLUTE = /(?:\b[A-Za-z]:[\\/]|(?<![\w.~])\/(?:home|Users|root|tmp|private|var|opt|mnt|srv|github|runner|workspace|builds)\/)[^\s'"`<>|)]*/g;
36
+
37
+ /**
38
+ * Make text safe to leave this machine: paths inside `root` become relative,
39
+ * the home folder becomes `~`, any other absolute path becomes `[path]`, and
40
+ * secret-looking values are redacted.
41
+ */
42
+ export function scrubText(s, root) {
43
+ if (typeof s !== 'string' || !s) return s;
44
+ let out = s;
45
+ if (root) {
46
+ // both slash styles; Windows paths compare case-insensitively
47
+ const variants = new Set([root, root.replace(/\\/g, '/'), root.replace(/\//g, '\\')]);
48
+ for (const v of variants) {
49
+ if (v.length < 2) continue;
50
+ out = out.replace(new RegExp(escapeRe(v) + '[\\\\/]?', process.platform === 'win32' || /^[A-Za-z]:/.test(v) ? 'gi' : 'g'), '');
51
+ }
52
+ }
53
+ const home = os.homedir();
54
+ for (const v of new Set([home, home.replace(/\\/g, '/')])) {
55
+ if (v.length > 3) out = out.replace(new RegExp(escapeRe(v), 'gi'), '~');
56
+ }
57
+ out = out.replace(ABSOLUTE, '[path]');
58
+ return redact(out);
59
+ }
@@ -0,0 +1,154 @@
1
+ // Reliability intelligence: how reliably each agent produces working software,
2
+ // built only from evidence crossexam recorded itself (~/.crossexam/ledger.jsonl):
3
+ // claims verdicts on what agents said (verify, the MCP tool, the Claude Code hook)
4
+ // strength how many planted defects their tests caught (mutate, verify --mutate, MCP)
5
+ // fixes whether their corrections closed findings on independent re-checks
6
+ // The three are reported side by side and never blended into one score: an
7
+ // agent can be honest about its claims and still ship weak tests.
8
+ import fs from 'node:fs';
9
+ import os from 'node:os';
10
+ import path from 'node:path';
11
+
12
+ const ledgerFile = () => path.join(process.env.CROSSEXAM_HOME || path.join(os.homedir(), '.crossexam'), 'ledger.jsonl');
13
+
14
+ /** Monday of the week a date falls in, as yyyy-mm-dd. */
15
+ export function weekOf(iso) {
16
+ const d = new Date(iso);
17
+ if (Number.isNaN(d.getTime())) return null;
18
+ const day = (d.getUTCDay() + 6) % 7;
19
+ d.setUTCDate(d.getUTCDate() - day);
20
+ return d.toISOString().slice(0, 10);
21
+ }
22
+
23
+ export function readLedger(file = ledgerFile()) {
24
+ let text = '';
25
+ try {
26
+ text = fs.readFileSync(file, 'utf8');
27
+ } catch {
28
+ return [];
29
+ }
30
+ const out = [];
31
+ for (const l of text.split('\n')) {
32
+ if (!l.trim()) continue;
33
+ try {
34
+ out.push(JSON.parse(l));
35
+ } catch {
36
+ /* a torn line from a crash: skip it */
37
+ }
38
+ }
39
+ return out;
40
+ }
41
+
42
+ const pct = (a, b) => (b ? Math.round((a / b) * 1000) / 1000 : null);
43
+
44
+ /**
45
+ * Per-agent reliability from ledger records.
46
+ * @param {{ since?: number, agent?: string, repo?: string, records?: any[] }} opts
47
+ */
48
+ export function reliability({ since = 0, agent, repo, records } = {}) {
49
+ const recs = (records ?? readLedger()).filter((r) => {
50
+ const at = Date.parse(r.at ?? '');
51
+ if (since && !(at >= since)) return false;
52
+ if (agent && r.agent !== agent) return false;
53
+ if (repo && r.repo !== repo) return false;
54
+ return true;
55
+ });
56
+
57
+ const agents = new Map();
58
+ const get = (name) => {
59
+ const k = name || 'unknown';
60
+ if (!agents.has(k))
61
+ agents.set(k, {
62
+ agent: k,
63
+ claims: { checked: 0, verified: 0, contradicted: 0, stale: 0, unbacked: 0, review: 0 },
64
+ strength: { runs: 0, killed: 0, survived: 0, weakRuns: 0, behaviouralSurvivors: 0 },
65
+ fixes: { sessions: new Map() },
66
+ weeks: new Map(),
67
+ last: null,
68
+ });
69
+ return agents.get(k);
70
+ };
71
+ const week = (a, at) => {
72
+ const w = weekOf(at);
73
+ if (!w) return null;
74
+ if (!a.weeks.has(w)) a.weeks.set(w, { week: w, checked: 0, falseDone: 0, killed: 0, survived: 0 });
75
+ return a.weeks.get(w);
76
+ };
77
+
78
+ for (const r of recs) {
79
+ // a claim: from verify / MCP (type "verify") or the transcript hook (no type)
80
+ if ((r.type === 'verify' || !r.type) && r.verdict) {
81
+ const a = get(r.agent);
82
+ a.claims.checked++;
83
+ a.claims[r.verdict] = (a.claims[r.verdict] ?? 0) + 1;
84
+ const w = week(a, r.at);
85
+ if (w && r.verdict !== 'review') {
86
+ w.checked++;
87
+ if (r.verdict === 'contradicted' || r.verdict === 'stale') w.falseDone++;
88
+ }
89
+ a.last = !a.last || r.at > a.last ? r.at : a.last;
90
+ } else if (r.type === 'mutation' && r.killed + r.survived > 0) {
91
+ const a = get(r.agent);
92
+ a.strength.runs++;
93
+ a.strength.killed += r.killed;
94
+ a.strength.survived += r.survived;
95
+ if (r.rating === 'weak') a.strength.weakRuns++;
96
+ a.strength.behaviouralSurvivors += (r.survivors ?? []).filter((s) => s.behavioural).length;
97
+ const w = week(a, r.at);
98
+ if (w) {
99
+ w.killed += r.killed;
100
+ w.survived += r.survived;
101
+ }
102
+ a.last = !a.last || r.at > a.last ? r.at : a.last;
103
+ } else if (r.type === 'reverify') {
104
+ const a = get(r.agent);
105
+ // keep the latest round per session
106
+ const prev = a.fixes.sessions.get(r.session);
107
+ if (!prev || r.round >= prev.round) a.fixes.sessions.set(r.session, { ...r, firstRound: prev?.firstRound ?? (r.round === 1 ? r : null) });
108
+ else if (r.round === 1) prev.firstRound = r;
109
+ a.last = !a.last || r.at > a.last ? r.at : a.last;
110
+ }
111
+ }
112
+
113
+ const rows = [...agents.values()].map((a) => {
114
+ const judged = a.claims.checked - a.claims.review;
115
+ const sessions = [...a.fixes.sessions.values()];
116
+ const closed = sessions.filter((s) => s.allResolved);
117
+ const first = sessions.filter((s) => s.firstRound);
118
+ return {
119
+ agent: a.agent,
120
+ evidence: a.claims.checked + a.strength.runs + sessions.length,
121
+ last: a.last,
122
+ claims: { ...a.claims, falseDoneRate: pct(a.claims.contradicted + a.claims.stale, judged) },
123
+ strength: {
124
+ runs: a.strength.runs,
125
+ killed: a.strength.killed,
126
+ survived: a.strength.survived,
127
+ weakRuns: a.strength.weakRuns,
128
+ behaviouralSurvivors: a.strength.behaviouralSurvivors,
129
+ score: pct(a.strength.killed, a.strength.killed + a.strength.survived),
130
+ },
131
+ fixes: {
132
+ sessions: sessions.length,
133
+ closed: closed.length,
134
+ firstRecheckRate: pct(first.filter((s) => s.firstRound.allResolved).length, first.length),
135
+ roundsToClose: closed.length ? Math.round((closed.reduce((n, s) => n + s.round, 0) / closed.length) * 10) / 10 : null,
136
+ stillOpen: sessions.length - closed.length,
137
+ },
138
+ weeks: [...a.weeks.values()]
139
+ .sort((x, y) => x.week.localeCompare(y.week))
140
+ .map((w) => ({ week: w.week, falseDoneRate: pct(w.falseDone, w.checked), score: pct(w.killed, w.killed + w.survived), checked: w.checked })),
141
+ };
142
+ });
143
+ rows.sort((x, y) => y.evidence - x.evidence);
144
+ return { since: since ? new Date(since).toISOString() : null, records: recs.length, agents: rows };
145
+ }
146
+
147
+ /** One sentence per agent, in plain words, with the evidence behind it. */
148
+ export function describeAgent(a) {
149
+ const parts = [];
150
+ if (a.claims.falseDoneRate != null) parts.push(`${Math.round((1 - a.claims.falseDoneRate) * 100)}% of its claims held up (${a.claims.checked} checked)`);
151
+ if (a.strength.score != null) parts.push(`its tests caught ${Math.round(a.strength.score * 100)}% of planted defects (${a.strength.runs} run${a.strength.runs === 1 ? '' : 's'})`);
152
+ if (a.fixes.firstRecheckRate != null) parts.push(`${Math.round(a.fixes.firstRecheckRate * 100)}% of its fixes closed every finding on the first re-check`);
153
+ return parts.length ? parts.join('; ') : 'not enough evidence yet';
154
+ }
package/src/report.js CHANGED
@@ -147,7 +147,8 @@ export function printStrength(r, { line = (s = '') => process.stdout.write(s + '
147
147
  line(c.bold(' Defects the tests did not notice'));
148
148
  line();
149
149
  for (const m of surv.slice(0, limit)) {
150
- line(` ${SHORT[m.status]} ${m.file}:${m.line} ${c.dim((m.function || 'top level') + ' · ' + m.operator)}`);
150
+ const kind = m.category && !['logic', 'arithmetic'].includes(m.category) ? `${m.category} · ` : '';
151
+ line(` ${SHORT[m.status]} ${m.file}:${m.line} ${c.dim((m.function || 'top level') + ' · ' + kind + m.operator)}`);
151
152
  if (m.before != null) line(c.dim(` - ${m.before.split('\n')[0].slice(0, 110)}`));
152
153
  if (m.after != null) line(` ${c.red('+ ' + m.after.split('\n')[0].slice(0, 110))}`);
153
154
  line(` ${c.dim('→ ' + m.why)}`);
package/src/sandbox.js CHANGED
@@ -39,6 +39,11 @@ const SECRET_PREFIX = /^(?:AWS_|AZURE_|GCP_|GOOGLE_APPLICATION|GH_|GITHUB_TOKEN|
39
39
  const RUNNER_STATE = /^(?:NODE_TEST_CONTEXT|NODE_TEST_|VITEST|VITEST_|JEST_WORKER_ID|NODE_UNIQUE_ID|NODE_CHANNEL_FD|NODE_CHANNEL_SERIALIZATION_MODE)/;
40
40
  const FIXED = { CI: '1', FORCE_COLOR: '0', NO_COLOR: '1', CROSSEXAM_MUTATION: '1', GIT_OPTIONAL_LOCKS: '0', GIT_TERMINAL_PROMPT: '0' };
41
41
 
42
+ /** The environment minus a parent test runner's state, so a nested suite reports its own result. */
43
+ export function withoutRunnerState(base = process.env) {
44
+ return Object.fromEntries(Object.entries(base).filter(([k]) => !RUNNER_STATE.test(k)));
45
+ }
46
+
42
47
  /** Unsandboxed runs: the user's environment minus anything credential-like. */
43
48
  export function scrubbedEnv(base = process.env) {
44
49
  const env = {};