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/README.md CHANGED
@@ -10,10 +10,14 @@ npx crossexamdev verify "All tests pass." # re-check any agent's summary ri
10
10
  npx crossexamdev init --mcp # make every agent in this repo check itself
11
11
  npx crossexamdev mcp # MCP server with verify_claims and assess_test_strength
12
12
  npx crossexamdev mutate # would the tests notice a bug in what the agent changed?
13
+ npx crossexamdev prove-fix # does the fix count? the tests must fail without it
14
+ npx crossexamdev selfcheck # check the checker: canaries and rewrites it must not be fooled by
13
15
  ```
14
16
 
15
17
  Node 18.17+, zero dependencies, runs entirely on your machine. Once installed, the command is also available as `crossexam`.
16
18
 
19
+ `prove-fix` runs your tests with the change, then again with every non-test file put back the way it was (new tests kept). A fix is proven only if they pass with it and fail without it. `selfcheck` runs canary repos with known answers and rewrites summaries nine ways (formatting, invisible characters, instructions aimed at the verifier) that must not change what crossexam sees.
20
+
17
21
  `mutate` plants small defects in the changed lines and runs your tests against each one, in a disposable copy of the repo. Tests run inside a sandbox (bubblewrap on Linux, `sandbox-exec` on macOS, or Docker). Where none is available, crossexam refuses unless you pass `--unsandboxed`. Details and the threat model: https://github.com/zackt223/crossexam/blob/master/docs/mutation-security.md
18
22
 
19
23
  Site: https://zackt223.github.io/crossexam/
package/bin/crossexam.js CHANGED
@@ -13,8 +13,13 @@ import { discoverAider, discoverMore } from '../src/readers.js';
13
13
  import { buildReport, c, printReport, printStrength } from '../src/report.js';
14
14
  import { assessStrength, ledgerRecord, qualityOf, strengthHistory, toCsv, withoutSource } from '../src/strength.js';
15
15
  import { AGENTS, defaultSources, findTranscripts, readSession } from '../src/transcripts.js';
16
+ import { SOURCE_POLICIES, buildPayload, classifyReport, githubContext, validatePayload } from '../src/upload.js';
17
+ import { findingsFrom, formatFindingsForAgent, listSessions, loadSession, openSession, reverify as reverifySession, reverifyRecord } from '../src/findings.js';
18
+ import { describeAgent, reliability as reliabilityOf } from '../src/reliability.js';
19
+ import { fixFinding, proveFix } from '../src/provefix.js';
20
+ import { selfcheck } from '../src/selfcheck.js';
16
21
 
17
- const VERSION = '0.3.0';
22
+ const VERSION = '0.5.0';
18
23
  const HELP = `
19
24
  ${c.bold('crossexam')} — cross-examine what your coding agents claim
20
25
 
@@ -27,6 +32,25 @@ const HELP = `
27
32
  ${c.bold('Test strength')}
28
33
  crossexam mutate plant small defects in the changed code and see if the tests notice
29
34
  crossexam verify --mutate verify claims, then grade how strong the tests behind them are
35
+ crossexam prove-fix ["<claim>"]
36
+ prove a fix: the tests must fail with it taken out and pass with it in
37
+ (isolated copy; --base, --test-command, --isolation, --json as for mutate)
38
+
39
+ ${c.bold('Checking the checker')}
40
+ crossexam selfcheck run canaries with known answers, and check that reformatting, invisible
41
+ characters or instructions to the verifier never change what is claimed
42
+ (--text "<summary>" adds your own; --quick skips the slower canaries)
43
+
44
+ ${c.bold('Findings and re-verification')}
45
+ crossexam findings [id] the open findings of a session, structured for an agent (--json)
46
+ crossexam reverify <id> re-check a session independently; only this closes a finding
47
+ crossexam reliability how reliably each agent produces working software, from your own
48
+ verify / mutate / reverify evidence (--since 90d, --agent, --json)
49
+
50
+ ${c.bold('Cloud')} (not open yet: nothing is ever sent today)
51
+ crossexam upload --dry-run --report <file>
52
+ show exactly what a run would send to crossexam cloud: paths made
53
+ relative, secrets redacted. --source none leaves code lines out
30
54
 
31
55
  ${c.bold('History')}
32
56
  crossexam scan check local transcripts: Claude Code, Codex, Gemini CLI, Cline,
@@ -59,6 +83,13 @@ const HELP = `
59
83
  --agent <name> record which agent made the change, for history
60
84
  --fail-under <0-1> exit 1 when the mutation score is below this
61
85
 
86
+ ${c.bold('upload')}
87
+ --dry-run build and check the payload, print it, send nothing
88
+ --report <file> a report saved with verify --json or mutate --json (repeatable)
89
+ --source <changed-lines|none> include the changed code lines, or none of them (default changed-lines)
90
+ --agent <name> which agent made the change (otherwise taken from the pr)
91
+ --out <file> write the payload to a file instead of stdout
92
+
62
93
  ${c.bold('scan')}
63
94
  --since <30d|12h|all> how far back to look (default 30d)
64
95
  --agent <name> one of: ${AGENTS.join(', ')}
@@ -75,7 +106,7 @@ const HELP = `
75
106
  --dry-run print the change, write nothing
76
107
  `;
77
108
 
78
- const VALUED = new Set(['since', 'agent', 'repo', 'file', 'json', 'limit', 'path', 'cwd', 'fail-on', 'timeout', 'base', 'files', 'max', 'budget', 'isolation', 'test-command', 'csv', 'fail-under']);
109
+ const VALUED = new Set(['text', 'report','source', 'out', 'since', 'agent', 'repo', 'file', 'json', 'limit', 'path', 'cwd', 'fail-on', 'timeout', 'base', 'files', 'max', 'budget', 'isolation', 'test-command', 'csv', 'fail-under']);
79
110
  const args = process.argv.slice(2);
80
111
  const cmd = args[0] && !args[0].startsWith('-') ? args.shift() : 'scan';
81
112
  const flag = (name) => args.includes(`--${name}`);
@@ -94,6 +125,12 @@ try {
94
125
  else if (cmd === 'scan') await scan();
95
126
  else if (cmd === 'verify') await verify();
96
127
  else if (cmd === 'mutate') await mutate();
128
+ else if (cmd === 'prove-fix') await proveFixCmd();
129
+ else if (cmd === 'selfcheck') await selfcheckCmd();
130
+ else if (cmd === 'upload') upload();
131
+ else if (cmd === 'reverify') await reverify();
132
+ else if (cmd === 'findings') findings();
133
+ else if (cmd === 'reliability') reliabilityCmd();
97
134
  else if (cmd === 'mcp') startMcpServer({ version: VERSION, defaultCwd: path.resolve(String(opt('cwd', process.cwd()))) });
98
135
  else if (cmd === 'init') init();
99
136
  else if (cmd === 'hook') await hook();
@@ -192,37 +229,243 @@ async function verify() {
192
229
  ledger([ledgerRecord(strength, { agent: pr?.agent || String(opt('agent', 'unknown')), claim: r.results.find((x) => x.kind === 'tests')?.claim ?? null, source: github ? 'github' : 'verify' })]);
193
230
  }
194
231
 
195
- if (json) process.stdout.write(JSON.stringify({ ...r, pr }, null, 2) + '\n');
232
+ // evidence for reliability history, and a findings session the agent can close
233
+ const who = pr?.agent || String(opt('agent', 'unknown'));
234
+ ledger(claimRecords(r, who, github ? 'github' : 'verify', cwd));
235
+ const findings = findingsFrom({ verify: r, strength: r.strength });
236
+ const session = findings.length && !github && !flag('dry-run') ? openSession({ findings, cwd, repo: r.strength?.repo, agent: who, source: 'verify', testCommand: r.strength?.testCommand }) : null;
237
+
238
+ if (json) process.stdout.write(JSON.stringify({ ...r, pr, findings, session: session?.id ?? null }, null, 2) + '\n');
196
239
  else if (github) emitActions(pr, r);
197
240
  else {
198
241
  console.log();
199
242
  console.log(formatForAgent(r).replace(/^/gm, ' '));
200
243
  if (r.strength) printStrength(r.strength, { limit: 4 });
201
244
  if (!r.results.length && Object.keys(r.commands).length) console.log(c.dim(`\n Checks available here: ${Object.entries(r.commands).map(([k, v]) => `${k} (${v.command})`).join(', ')}`));
245
+ if (session) console.log(`\n ${c.bold(`${findings.length} finding${findings.length === 1 ? '' : 's'}`)} ${c.dim(`· session ${session.id} · after fixing, re-check with`)} crossexam reverify ${session.id}`);
202
246
  console.log();
203
247
  }
204
248
  if (opt('fail-on', 'contradicted') !== 'none' && !r.ok) process.exitCode = 1;
205
249
  }
206
250
 
251
+ /**
252
+ * What a run would send to crossexam cloud. Cloud isn't open yet, so this only
253
+ * ever builds, checks and prints the payload; it has no way to send it.
254
+ */
255
+ function upload() {
256
+ if (!flag('dry-run')) {
257
+ process.stderr.write("crossexam cloud isn't open yet, so there is nowhere to send this and nothing was sent.\nRun with --dry-run to see exactly what a run would send.\n");
258
+ process.exitCode = 2;
259
+ return;
260
+ }
261
+ const files = opts('report');
262
+ if (!files.length) throw new Error('upload --dry-run needs --report <file>: save one with `crossexam verify "…" --json > verify.json` or `crossexam mutate --json mutate.json`.');
263
+ let verify = null;
264
+ let mutation = null;
265
+ for (const f of files) {
266
+ const got = classifyReport(JSON.parse(fs.readFileSync(path.resolve(f), 'utf8')));
267
+ verify = got.verify ?? verify;
268
+ mutation = got.mutation ?? mutation;
269
+ }
270
+ const source = String(opt('source', 'changed-lines'));
271
+ if (!SOURCE_POLICIES.includes(source)) throw new Error(`--source must be one of ${SOURCE_POLICIES.join(', ')}`);
272
+ const agent = opt('agent');
273
+ const payload = buildPayload({
274
+ verify,
275
+ mutation,
276
+ github: githubContext(),
277
+ agent: typeof agent === 'string' ? agent : undefined,
278
+ cliVersion: VERSION,
279
+ root: path.resolve(String(opt('cwd', verify?.cwd || process.cwd()))),
280
+ sourcePolicy: source,
281
+ });
282
+ const errors = validatePayload(payload);
283
+ if (errors.length) throw new Error(`the payload failed its own checks:\n ${errors.join('\n ')}`);
284
+ const text = JSON.stringify(payload, null, 2);
285
+ const out = opt('out');
286
+ if (typeof out === 'string') {
287
+ fs.writeFileSync(out, text + '\n');
288
+ process.stderr.write(`dry run: ${Buffer.byteLength(text)} bytes written to ${out}. nothing was sent.\n`);
289
+ } else {
290
+ process.stdout.write(text + '\n');
291
+ process.stderr.write(`dry run: ${Buffer.byteLength(text)} bytes. nothing was sent.\n`);
292
+ }
293
+ }
294
+
207
295
  async function mutate() {
208
296
  const cwd = path.resolve(String(opt('cwd', process.cwd())));
209
297
  const json = opt('json');
210
298
  const toStdout = json === true;
211
299
  const full = await assessStrength({ cwd, ...mutateOpts(), onProgress: toStdout ? undefined : progress });
212
300
  const r = flag('no-source') ? withoutSource(full) : full;
213
- ledger([ledgerRecord(r, { agent: String(opt('agent', 'unknown')), source: 'mutate' })]);
301
+ const who = String(opt('agent', 'unknown'));
302
+ ledger([ledgerRecord(r, { agent: who, source: 'mutate' })]);
303
+ const findings = findingsFrom({ strength: full });
304
+ const session = findings.length ? openSession({ findings, cwd, repo: full.repo, agent: who, source: 'mutate', testCommand: full.testCommand }) : null;
305
+ r.findings = flag('no-source') ? findings.map(({ before, after, ...f }) => f) : findings;
306
+ r.session = session?.id ?? null;
214
307
  const csv = opt('csv');
215
308
  if (typeof csv === 'string') fs.writeFileSync(csv, toCsv(r));
216
309
  if (toStdout) process.stdout.write(JSON.stringify(r, null, 2) + '\n');
217
310
  else {
218
311
  if (typeof json === 'string') fs.writeFileSync(json, JSON.stringify(r, null, 2));
219
312
  printStrength(r, { limit: Number(opt('limit', 8)) });
313
+ if (session) console.log(` ${c.bold(`${findings.length} finding${findings.length === 1 ? '' : 's'}`)} ${c.dim(`· session ${session.id} · after adding tests, re-check with`)} crossexam reverify ${session.id}\n`);
220
314
  if (typeof json === 'string') console.log(` ${c.dim('Report written to')} ${path.resolve(json)}\n`);
221
315
  }
222
316
  const under = opt('fail-under');
223
317
  if (under !== undefined && r.summary.score != null && r.summary.score < Number(under)) process.exitCode = 1;
224
318
  }
225
319
 
320
+ /** Prove a fix: the tests must fail without it and pass with it. */
321
+ async function proveFixCmd() {
322
+ const cwd = path.resolve(String(opt('cwd', process.cwd())));
323
+ const json = opt('json');
324
+ const toStdout = json === true;
325
+ const { base, isolation, allowUnsandboxed, testCommand } = mutateOpts();
326
+ const claim = positional().join(' ').trim() || undefined;
327
+ const timeout = typeof opt('timeout') === 'string' ? Number(opt('timeout')) : undefined;
328
+ const say = (s) => !toStdout && process.stderr.isTTY && process.stderr.write(c.dim(s));
329
+ const r = await proveFix({
330
+ cwd, base, isolation, allowUnsandboxed, testCommand, claim, timeoutSeconds: timeout,
331
+ onProgress: (e) => say(e.phase === 'with-fix' ? ' running the tests with the fix…\n' : ' taking the fix out and running them again…\n'),
332
+ });
333
+ const who = String(opt('agent', 'unknown'));
334
+ ledger([{ type: 'prove-fix', at: r.generatedAt, agent: who, repo: r.repo, verdict: r.verdict }]);
335
+ const finding = fixFinding(r);
336
+ const session = finding ? openSession({ findings: [finding], cwd, repo: r.repo, agent: who, source: 'prove-fix', testCommand: r.testCommand }) : null;
337
+ r.session = session?.id ?? null;
338
+ if (toStdout) process.stdout.write(JSON.stringify(r, null, 2) + '\n');
339
+ else {
340
+ if (typeof json === 'string') fs.writeFileSync(json, JSON.stringify(r, null, 2));
341
+ const mark = { proven: c.green('✓ proven'), 'load-only': c.yellow('◐ load-only'), unproven: c.red('✗ unproven'), broken: c.red('✗ broken'), inconclusive: c.gray('○ inconclusive') }[r.verdict];
342
+ console.log(`\n ${c.bold('crossexam prove-fix')} ${c.dim(`· ${r.repo} · ${r.scope}${r.isolation.method ? ` · ${r.isolation.sandboxed ? `sandboxed (${r.isolation.method})` : 'NOT SANDBOXED'}` : ''}`)}`);
343
+ if (r.claim) console.log(` ${c.dim('claim')} "${r.claim}"`);
344
+ if (r.change.source.length) console.log(` ${c.dim('the fix')} ${r.change.source.slice(0, 6).join(', ')}${r.change.source.length > 6 ? c.dim(` +${r.change.source.length - 6}`) : ''}`);
345
+ if (r.change.tests.length) console.log(` ${c.dim('its tests')} ${r.change.tests.slice(0, 6).join(', ')}`);
346
+ if (r.withFix) console.log(` ${c.dim('with it')} ${r.withFix.passed ? c.green('pass') : c.red(`fail (exit ${r.withFix.exitCode})`)}`);
347
+ if (r.withoutFix) console.log(` ${c.dim('without')} ${r.withoutFix.passed ? c.red('pass') : c.green(`fail (exit ${r.withoutFix.exitCode})`)}`);
348
+ console.log(`\n ${mark} ${r.headline}`);
349
+ const ex = r.verdict === 'proven' || r.verdict === 'load-only' ? r.withoutFix?.excerpt : r.verdict === 'broken' ? r.withFix?.excerpt : '';
350
+ if (ex) console.log(c.dim(ex.split('\n').slice(0, 8).map((l) => ` ${l}`).join('\n')));
351
+ for (const n of r.notes) console.log(` ${c.dim(n)}`);
352
+ if (session) console.log(`\n ${c.bold('1 finding')} ${c.dim(`· session ${session.id} · after adding a test, re-check with`)} crossexam reverify ${session.id}`);
353
+ if (typeof json === 'string') console.log(` ${c.dim('Report written to')} ${path.resolve(json)}`);
354
+ console.log();
355
+ }
356
+ if (r.verdict !== 'proven' && !flag('no-fail')) process.exitCode = 1;
357
+ }
358
+
359
+ /** Check the checker: canaries with known answers, and robustness to reformatting and injected text. */
360
+ async function selfcheckCmd() {
361
+ const json = flag('json');
362
+ const texts = [...opts('text'), ...(typeof opt('file') === 'string' ? [fs.readFileSync(String(opt('file')), 'utf8')] : [])];
363
+ const r = await selfcheck({
364
+ texts,
365
+ quick: flag('quick'),
366
+ onProgress: (e) => !json && process.stderr.isTTY && process.stderr.write(c.dim(` ${e.ok ? '✓' : '✗'} ${e.label}\n`)),
367
+ });
368
+ if (json) process.stdout.write(JSON.stringify(r, null, 2) + '\n');
369
+ else {
370
+ const s = r.summary;
371
+ console.log(`\n ${c.bold('crossexam selfcheck')} ${c.dim('· checking the checker')}\n`);
372
+ console.log(` ${c.bold('Canaries')} ${c.dim('· tiny repos with a known answer')}`);
373
+ for (const k of r.canaries) {
374
+ if (k.skipped) console.log(` ${c.gray('○')} ${k.label} ${c.dim(`(skipped: ${k.skipped})`)}`);
375
+ else console.log(` ${k.ok ? c.green('✓') : c.red('✗')} ${k.label}${k.ok ? '' : c.red(` expected ${k.expected}, got ${k.got}`)}`);
376
+ }
377
+ const unstable = r.robustness.filter((x) => !x.ok);
378
+ console.log(`\n ${c.bold('Robustness')} ${c.dim(`· ${r.robustness.length} rewrites of ${new Set(r.robustness.map((x) => x.text)).size} summaries: formatting, invisible characters, injected instructions`)}`);
379
+ if (!unstable.length) console.log(` ${c.green('✓')} every rewrite produced the same claims as the original`);
380
+ for (const u of unstable.slice(0, 12)) console.log(` ${c.red('✗')} ${u.variant}: "${u.text.slice(0, 60)}"\n ${c.dim(`expected [${u.expected.join(', ')}], got [${u.got.join(', ')}]`)}`);
381
+ for (const n of r.notes) console.log(` ${c.dim(n)}`);
382
+ console.log(`\n ${r.ok ? c.green('All checks held.') : c.red('Some checks did not hold.')} ${c.dim(`${s.canariesPassed}/${s.canaries} canaries · ${s.variantsStable}/${s.variants} rewrites stable · ${Math.round(r.durationMs / 100) / 10}s`)}\n`);
383
+ }
384
+ if (!r.ok) process.exitCode = 1;
385
+ }
386
+
387
+ /** One ledger record per checked claim: the evidence reliability history is built from. */
388
+ function claimRecords(r, agent, source, cwd) {
389
+ const at = new Date().toISOString();
390
+ const repo = path.basename(cwd);
391
+ return r.results.map((x) => ({ type: 'verify', at, agent, repo, source, kind: x.kind, verdict: x.verdict }));
392
+ }
393
+
394
+ /** Re-check a findings session independently: only this can close a finding. */
395
+ async function reverify() {
396
+ const id = positional()[0];
397
+ if (!id) {
398
+ const recent = listSessions(8);
399
+ if (!recent.length) throw new Error('reverify needs a session id. Sessions are opened when verify or mutate finds something.');
400
+ console.log(`\n ${c.bold('Recent sessions')}`);
401
+ for (const s of recent) {
402
+ const open = s.findings.filter((f) => f.status === 'open' || f.status === 'still-open').length;
403
+ console.log(` ${s.id} ${c.dim(s.createdAt.slice(0, 16).replace('T', ' '))} ${s.repo} ${open ? c.red(`${open} open`) : c.green('all closed')} ${c.dim(`${s.rounds.length} re-check${s.rounds.length === 1 ? '' : 's'}`)}`);
404
+ }
405
+ console.log(c.dim('\n crossexam reverify <id>\n'));
406
+ return;
407
+ }
408
+ const json = flag('json');
409
+ const unsandboxed = flag('unsandboxed');
410
+ const { session, summary, changes } = await reverifySession(id, { cwd: typeof opt('cwd') === 'string' ? String(opt('cwd')) : undefined, isolation: typeof opt('isolation') === 'string' ? String(opt('isolation')) : unsandboxed ? 'none' : undefined, allowUnsandboxed: unsandboxed });
411
+ ledger([reverifyRecord(session, summary)]);
412
+ if (json) {
413
+ process.stdout.write(JSON.stringify({ session: session.id, ...summary, changes, findings: session.findings }, null, 2) + '\n');
414
+ } else {
415
+ const mark = { resolved: c.green('✓ resolved '), 'still-open': c.red('✗ still open'), superseded: c.gray('○ superseded') };
416
+ console.log(`\n ${c.bold(`Re-check ${summary.round}`)} ${c.dim(`· session ${session.id} · ${session.repo}`)}`);
417
+ if (summary.blocker) console.log(` ${c.yellow(summary.blocker)}`);
418
+ for (const ch of changes) {
419
+ const f = session.findings.find((x) => x.id === ch.id);
420
+ const what = f.type === 'claim' ? `"${f.claim}"` : f.type === 'fix' ? `fix${f.claim ? ` "${f.claim}"` : ''} in ${f.files.slice(0, 3).join(', ')}` : `${f.file}:${f.line} ${c.dim(`${f.category} · ${f.operator}`)}`;
421
+ console.log(` ${mark[ch.status]} ${what}\n ${c.dim(ch.evidence)}`);
422
+ }
423
+ const open = session.findings.filter((f) => f.status === 'still-open' || f.status === 'open').length;
424
+ console.log(open ? `\n ${c.red(`${open} still open.`)} ${c.dim('Fix them and run this again.')}\n` : `\n ${c.green('Every finding is closed.')}\n`);
425
+ }
426
+ if (session.findings.some((f) => f.status === 'still-open' || f.status === 'open')) process.exitCode = 1;
427
+ }
428
+
429
+ /** The open findings of a session, structured for an agent. */
430
+ function findings() {
431
+ const id = positional()[0];
432
+ const session = id ? loadSession(id) : listSessions(1)[0];
433
+ if (!session) throw new Error('No findings sessions yet. They are opened when verify or mutate finds something.');
434
+ if (flag('json')) process.stdout.write(JSON.stringify(session, null, 2) + '\n');
435
+ else console.log('\n' + formatFindingsForAgent(session).replace(/^/gm, ' ') + '\n');
436
+ }
437
+
438
+ /** How reliably each agent produces working software, from recorded evidence. */
439
+ function reliabilityCmd() {
440
+ const since = parseSince(opt('since', '90d'));
441
+ const agent = typeof opt('agent') === 'string' ? String(opt('agent')) : undefined;
442
+ const repo = typeof opt('repo') === 'string' ? String(opt('repo')) : undefined;
443
+ const r = reliabilityOf({ since, agent, repo });
444
+ if (flag('json')) {
445
+ process.stdout.write(JSON.stringify(r, null, 2) + '\n');
446
+ return;
447
+ }
448
+ if (!r.agents.length) {
449
+ console.log(`\n ${c.dim('No verification evidence yet. It builds up as you run verify, mutate and reverify (or the MCP tools and the hook).')}\n`);
450
+ return;
451
+ }
452
+ const p = (v) => (v == null ? c.dim(' — ') : `${String(Math.round(v * 100)).padStart(3)}%`);
453
+ console.log(`\n ${c.bold('Reliability by agent')} ${c.dim(`· ${r.records} records from your own runs`)}\n`);
454
+ console.log(c.dim(' agent claims held tests caught fixed on 1st re-check evidence'));
455
+ for (const a of r.agents) {
456
+ const held = a.claims.falseDoneRate == null ? null : 1 - a.claims.falseDoneRate;
457
+ console.log(` ${a.agent.padEnd(16)} ${p(held)} ${p(a.strength.score)} ${p(a.fixes.firstRecheckRate)} ${String(a.evidence).padStart(4)}`);
458
+ }
459
+ console.log();
460
+ for (const a of r.agents) {
461
+ console.log(` ${c.bold(a.agent)}: ${describeAgent(a)}.`);
462
+ if (a.strength.behaviouralSurvivors) console.log(c.dim(` ${a.strength.behaviouralSurvivors} behavioural gap${a.strength.behaviouralSurvivors === 1 ? '' : 's'} (access checks, transactions, retries, concurrency) went untested.`));
463
+ const recent = a.weeks.slice(-6).filter((w) => w.falseDoneRate != null || w.score != null);
464
+ if (recent.length > 1) console.log(c.dim(` weekly: ${recent.map((w) => `${w.week.slice(5)} ${w.score != null ? Math.round(w.score * 100) + '%' : '—'}`).join(' ')}`));
465
+ }
466
+ console.log(c.dim('\n Three separate measures, never blended: an agent can be honest about its claims and still ship weak tests.\n'));
467
+ }
468
+
226
469
  function mutateOpts() {
227
470
  const files = opts('files').flatMap((f) => f.split(',')).filter(Boolean);
228
471
  const str = (k) => (typeof opt(k) === 'string' ? String(opt(k)) : undefined);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "crossexamdev",
3
- "version": "0.3.0",
3
+ "version": "0.5.0",
4
4
  "description": "Cross-examine what any coding agent claims: verify CLI, MCP server, GitHub Action and transcript history for Claude Code, Codex, Gemini CLI, Cline, Aider and more.",
5
5
  "type": "module",
6
6
  "bin": {
package/src/claims.js CHANGED
@@ -45,9 +45,21 @@ const HEDGE =
45
45
  const NEGATION =
46
46
  /\b(?:not|n't|never|no\s+longer|fail(?:s|ed|ing)?|broken|still\s+(?:fail|broken|red)|couldn'?t|unable|can'?t|without\s+running|didn'?t\s+run|haven'?t\s+run)\b/i;
47
47
 
48
+ /**
49
+ * Undo formatting that changes how text looks to a pattern but not to a
50
+ * reader: full-width and compatibility letters (NFKC), and invisible
51
+ * characters (zero-width spaces and joiners, soft hyphens, bidi overrides)
52
+ * that would otherwise split "all tests pass" so no claim is seen.
53
+ */
54
+ export function normalizeText(text) {
55
+ return String(text)
56
+ .normalize('NFKC')
57
+ .replace(/[​-‍⁠­‪-‮⁦-⁩]/g, '');
58
+ }
59
+
48
60
  /** Split assistant prose into sentence-ish units without breaking `code`. */
49
61
  export function sentences(text) {
50
- const clean = text
62
+ const clean = normalizeText(text)
51
63
  .replace(/```[\s\S]*?```/g, ' ')
52
64
  .replace(/\r/g, '');
53
65
  const out = [];
package/src/evidence.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { redact } from './redact.js';
1
2
  // Evidence: which commands count as a check for which claim, and whether
2
3
  // a given run passed, failed, or hid its own exit status.
3
4
 
@@ -121,7 +122,8 @@ export function excerpt(out = '', max = 420) {
121
122
  const idx = lines.findIndex((l) => FAIL_SIGNALS.some((re) => re.test(l)));
122
123
  const from = idx > 2 ? idx - 2 : 0;
123
124
  const s = lines.slice(from, from + 10).join('\n');
124
- return s.length > max ? s.slice(0, max) + '…' : s;
125
+ // excerpts end up in reports, pr summaries and uploads: no secrets in them
126
+ return redact(s.length > max ? s.slice(0, max) + '…' : s);
125
127
  }
126
128
 
127
129
  function clip(s) {
@@ -0,0 +1,208 @@
1
+ // Agent-driven verification: structured findings an agent can act on, and an
2
+ // independent re-check that is the only way a finding gets closed.
3
+ //
4
+ // A run with something wrong opens a session (~/.crossexam/sessions/<id>.json):
5
+ // each contradicted claim and each surviving mutant becomes a finding with a
6
+ // stable id, what to do, and how it will be re-checked. The agent fixes things
7
+ // and calls `reverify`; crossexam re-runs exactly those checks itself. Nothing
8
+ // the agent says can mark a finding resolved.
9
+ import { createHash, randomBytes } from 'node:crypto';
10
+ import fs from 'node:fs';
11
+ import os from 'node:os';
12
+ import path from 'node:path';
13
+ import { verifyText } from './live.js';
14
+ import { STATUS, assessStrength, severityOf } from './strength.js';
15
+ import { FIX, proveFix } from './provefix.js';
16
+
17
+ const home = () => process.env.CROSSEXAM_HOME || path.join(os.homedir(), '.crossexam');
18
+ const sessionsDir = () => path.join(home(), 'sessions');
19
+ const SESSION_ID = /^cx-[0-9a-f]{10}$/;
20
+ const hash = (s) => createHash('sha256').update(s).digest('hex').slice(0, 16);
21
+
22
+ /** Findings from a verify result and/or a mutation report. Empty when nothing is wrong. */
23
+ export function findingsFrom({ verify = null, strength = null } = {}) {
24
+ const out = [];
25
+ for (const r of verify?.results ?? []) {
26
+ if (r.verdict !== 'contradicted' && r.verdict !== 'stale') continue;
27
+ const cmd = r.evidence?.command ?? null;
28
+ out.push({
29
+ id: `claim-${hash(`${r.kind}\u0000${r.claim}`)}`,
30
+ type: 'claim',
31
+ severity: ['tests', 'build', 'types', 'migration'].includes(r.kind) ? 'high' : 'medium',
32
+ kind: r.kind,
33
+ claim: r.claim,
34
+ verdict: r.verdict,
35
+ reason: r.reason,
36
+ command: cmd,
37
+ excerpt: r.evidence?.excerpt ?? null,
38
+ ask:
39
+ r.verdict === 'stale'
40
+ ? `Re-run ${cmd ? `\`${cmd}\`` : 'the check'} after your last edit, then report what it printed.`
41
+ : `Fix what makes ${cmd ? `\`${cmd}\`` : 'the check'} disagree, or correct the claim to say what is true.`,
42
+ recheck: cmd ? `crossexam re-runs \`${cmd}\`` : 'crossexam re-checks the claim',
43
+ status: 'open',
44
+ });
45
+ }
46
+ for (const m of strength?.mutants ?? []) {
47
+ if (m.status !== STATUS.SURVIVED || !m.fingerprint) continue;
48
+ out.push({
49
+ id: `mutant-${m.fingerprint}`,
50
+ type: 'mutant',
51
+ severity: severityOf(m.operator),
52
+ fingerprint: m.fingerprint,
53
+ category: m.category,
54
+ operator: m.operator,
55
+ file: m.file,
56
+ line: m.line,
57
+ function: m.function,
58
+ before: m.before ?? null,
59
+ after: m.after ?? null,
60
+ why: m.why,
61
+ ask: 'Add or strengthen a test that fails when this change is made. Do not change the code under test to dodge it.',
62
+ recheck: 'crossexam plants this exact defect again and runs your tests',
63
+ status: 'open',
64
+ });
65
+ }
66
+ const rank = { high: 0, medium: 1, low: 2 };
67
+ return out.sort((a, b) => rank[a.severity] - rank[b.severity]);
68
+ }
69
+
70
+ /** Save a session for these findings and return it. */
71
+ export function openSession({ findings, cwd, repo, agent = 'unknown', source = 'cli', testCommand = null }) {
72
+ const id = `cx-${randomBytes(5).toString('hex')}`;
73
+ const session = {
74
+ id,
75
+ createdAt: new Date().toISOString(),
76
+ cwd: path.resolve(cwd),
77
+ repo: repo ?? path.basename(path.resolve(cwd)),
78
+ agent,
79
+ source,
80
+ testCommand,
81
+ findings,
82
+ rounds: [],
83
+ };
84
+ save(session);
85
+ return session;
86
+ }
87
+
88
+ export function loadSession(id) {
89
+ if (!SESSION_ID.test(String(id))) throw new Error(`"${id}" is not a crossexam session id (they look like cx-1a2b3c4d5e)`);
90
+ const f = path.join(sessionsDir(), `${id}.json`);
91
+ if (!fs.existsSync(f)) throw new Error(`no session ${id} on this machine`);
92
+ return JSON.parse(fs.readFileSync(f, 'utf8'));
93
+ }
94
+
95
+ function save(session) {
96
+ fs.mkdirSync(sessionsDir(), { recursive: true });
97
+ fs.writeFileSync(path.join(sessionsDir(), `${session.id}.json`), JSON.stringify(session, null, 2));
98
+ }
99
+
100
+ /** Recent sessions, newest first. */
101
+ export function listSessions(limit = 20) {
102
+ try {
103
+ return fs
104
+ .readdirSync(sessionsDir())
105
+ .filter((f) => /^cx-[0-9a-f]{10}\.json$/.test(f))
106
+ .map((f) => JSON.parse(fs.readFileSync(path.join(sessionsDir(), f), 'utf8')))
107
+ .sort((a, b) => b.createdAt.localeCompare(a.createdAt))
108
+ .slice(0, limit);
109
+ } catch {
110
+ return [];
111
+ }
112
+ }
113
+
114
+ /**
115
+ * Re-check every open finding in a session, independently.
116
+ * Claims: the original sentences are verified again from scratch.
117
+ * Mutants: each surviving defect is planted again by fingerprint and the tests
118
+ * re-run. A defect whose code is gone is "superseded": the code changed, so the
119
+ * finding can't be closed or kept, and a fresh `mutate` is the way to judge it.
120
+ */
121
+ export async function reverify(id, { cwd, isolation, allowUnsandboxed, timeoutSeconds } = {}) {
122
+ const session = loadSession(id);
123
+ const repoDir = path.resolve(cwd || session.cwd);
124
+ const open = session.findings.filter((f) => f.status === 'open' || f.status === 'still-open');
125
+ const round = session.rounds.length + 1;
126
+ const changes = [];
127
+ let blocker = null;
128
+
129
+ const claims = open.filter((f) => f.type === 'claim');
130
+ if (claims.length) {
131
+ const r = await verifyText(claims.map((f) => f.claim).join('\n'), { cwd: repoDir, timeoutMs: timeoutSeconds ? timeoutSeconds * 1000 : undefined });
132
+ for (const f of claims) {
133
+ const now = r.results.find((x) => x.kind === f.kind && x.claim === f.claim) ?? r.results.find((x) => x.kind === f.kind);
134
+ const ok = now && (now.verdict === 'verified' || now.verdict === 'review');
135
+ changes.push({ id: f.id, status: ok ? 'resolved' : 'still-open', evidence: now ? `${now.verdict}: ${now.reason}` : 'the claim was not found again' });
136
+ }
137
+ }
138
+
139
+ const muts = open.filter((f) => f.type === 'mutant');
140
+ if (muts.length) {
141
+ const files = [...new Set(muts.map((f) => f.file))];
142
+ const s = await assessStrength({ cwd: repoDir, files, fingerprints: muts.map((f) => f.fingerprint), max: muts.length, cache: false, isolation, allowUnsandboxed, testCommand: session.testCommand || undefined });
143
+ if (s.blocker) blocker = s.blocker;
144
+ const byFp = new Map(s.mutants.map((m) => [m.fingerprint, m]));
145
+ for (const f of muts) {
146
+ const m = byFp.get(f.fingerprint);
147
+ if (s.blocker) changes.push({ id: f.id, status: 'still-open', evidence: `not re-checked: ${s.blocker}` });
148
+ else if (!m) changes.push({ id: f.id, status: 'superseded', evidence: 'that code is no longer there; run crossexam mutate to judge the new code' });
149
+ else if (m.status === STATUS.KILLED) changes.push({ id: f.id, status: 'resolved', evidence: `caught now: ${m.why || 'a test failed'}` });
150
+ else if (m.status === STATUS.SURVIVED) changes.push({ id: f.id, status: 'still-open', evidence: 'the tests still pass with this defect planted' });
151
+ else changes.push({ id: f.id, status: 'still-open', evidence: `inconclusive (${m.status.toLowerCase().replace('mutation_', '')}): ${m.why || ''}`.trim() });
152
+ }
153
+ }
154
+
155
+ // Unproven fixes: take the fix out again, against the same pinned base.
156
+ for (const f of open.filter((x) => x.type === 'fix')) {
157
+ const r = await proveFix({ cwd: repoDir, base: f.base, testCommand: session.testCommand || undefined, isolation, allowUnsandboxed, timeoutSeconds, claim: f.claim });
158
+ if (r.verdict === FIX.PROVEN) changes.push({ id: f.id, status: 'resolved', evidence: 'the tests now fail without the fix and pass with it' });
159
+ else if (r.verdict === FIX.INCONCLUSIVE && /^Nothing changed|^Only tests changed/.test(r.headline)) changes.push({ id: f.id, status: 'superseded', evidence: `${r.headline} Run crossexam prove-fix on the new change.` });
160
+ else {
161
+ if (r.verdict === FIX.INCONCLUSIVE) blocker = blocker || r.headline;
162
+ changes.push({ id: f.id, status: 'still-open', evidence: `${r.verdict}: ${r.headline}` });
163
+ }
164
+ }
165
+
166
+ for (const c of changes) {
167
+ const f = session.findings.find((x) => x.id === c.id);
168
+ f.status = c.status;
169
+ f.evidence = c.evidence;
170
+ if (c.status === 'resolved' && !f.resolvedRound) f.resolvedRound = round;
171
+ }
172
+ const count = (st) => changes.filter((c) => c.status === st).length;
173
+ const summary = { round, at: new Date().toISOString(), checked: changes.length, resolved: count('resolved'), stillOpen: count('still-open'), superseded: count('superseded'), blocker };
174
+ session.rounds.push(summary);
175
+ save(session);
176
+ return { session, summary, changes };
177
+ }
178
+
179
+ /** A ledger record for one re-verification round, for reliability history. */
180
+ export function reverifyRecord(session, summary) {
181
+ return {
182
+ type: 'reverify',
183
+ at: summary.at,
184
+ session: session.id,
185
+ agent: session.agent,
186
+ repo: session.repo,
187
+ round: summary.round,
188
+ findings: session.findings.length,
189
+ resolved: summary.resolved,
190
+ stillOpen: summary.stillOpen,
191
+ superseded: summary.superseded,
192
+ allResolved: session.findings.every((f) => f.status === 'resolved' || f.status === 'superseded'),
193
+ };
194
+ }
195
+
196
+ /** Plain text an agent can act on. */
197
+ export function formatFindingsForAgent(session, findings = session.findings) {
198
+ const open = findings.filter((f) => f.status === 'open' || f.status === 'still-open');
199
+ if (!open.length) return `Session ${session.id}: nothing open.`;
200
+ const lines = open.slice(0, 12).map((f, i) =>
201
+ f.type === 'fix'
202
+ ? `${i + 1}. [${f.severity}] fix ${f.verdict}${f.claim ? `: "${f.claim}"` : ''}\n files: ${f.files.slice(0, 6).join(', ')}\n ${f.reason}\n do: ${f.ask}`
203
+ : f.type === 'claim'
204
+ ?`${i + 1}. [${f.severity}] claim ${f.verdict}: "${f.claim}"${f.command ? `\n evidence: \`${f.command}\`` : ''}\n do: ${f.ask}`
205
+ : `${i + 1}. [${f.severity}] ${f.category} gap in ${f.file}:${f.line}${f.function ? ` (${f.function})` : ''}\n changing ${String(f.before ?? '').split('\n')[0].trim()}\n to ${String(f.after ?? '').split('\n')[0].trim()}\n still passed every test. ${f.why ?? ''}\n do: ${f.ask}`,
206
+ );
207
+ return `crossexam findings, session ${session.id} (${open.length} open):\n\n${lines.join('\n\n')}\n\nWhen you have fixed them, call reverify_findings with session "${session.id}" (or run: crossexam reverify ${session.id}). Only that re-check can close a finding; do not report them as fixed before it does.`;
208
+ }
package/src/live.js CHANGED
@@ -9,6 +9,7 @@ import fs from 'node:fs';
9
9
  import path from 'node:path';
10
10
  import { detectClaims } from './claims.js';
11
11
  import { excerpt, judgeRun } from './evidence.js';
12
+ import { withoutRunnerState } from './sandbox.js';
12
13
 
13
14
  const CONFIG_FILES = ['crossexam.json', '.crossexam.json'];
14
15
 
@@ -93,7 +94,7 @@ export function detectCommands(cwd, config = loadConfig(cwd)) {
93
94
  /** Run a shell command without blocking the event loop (the MCP server keeps answering pings). */
94
95
  export function runCommand(command, { cwd, timeoutMs = 300000 } = {}) {
95
96
  return new Promise((resolve) => {
96
- const child = spawn(command, { cwd, shell: true, env: { ...process.env, CI: '1', FORCE_COLOR: '0', NO_COLOR: '1' }, windowsHide: true });
97
+ const child = spawn(command, { cwd, shell: true, env: { ...withoutRunnerState(), CI: '1', FORCE_COLOR: '0', NO_COLOR: '1' }, windowsHide: true });
97
98
  let output = '';
98
99
  const keep = (d) => {
99
100
  output += d;
@@ -117,7 +118,7 @@ export function runCommand(command, { cwd, timeoutMs = 300000 } = {}) {
117
118
  }
118
119
 
119
120
  export function runCommandSync(command, { cwd, timeoutMs = 300000 } = {}) {
120
- const r = spawnSync(command, { cwd, shell: true, encoding: 'utf8', timeout: timeoutMs, env: { ...process.env, CI: '1', FORCE_COLOR: '0', NO_COLOR: '1' }, windowsHide: true });
121
+ const r = spawnSync(command, { cwd, shell: true, encoding: 'utf8', timeout: timeoutMs, env: { ...withoutRunnerState(), CI: '1', FORCE_COLOR: '0', NO_COLOR: '1' }, windowsHide: true });
121
122
  return { command, exitCode: r.status ?? 1, output: (r.stdout || '') + (r.stderr || ''), isError: r.status !== 0 };
122
123
  }
123
124