crossexamdev 0.3.0 → 0.4.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/bin/crossexam.js +168 -4
- package/package.json +1 -1
- package/src/evidence.js +3 -1
- package/src/findings.js +194 -0
- package/src/mcp.js +259 -198
- package/src/mutate.js +142 -3
- package/src/redact.js +59 -0
- package/src/reliability.js +154 -0
- package/src/report.js +2 -1
- package/src/strength.js +637 -628
- package/src/upload.js +212 -0
package/bin/crossexam.js
CHANGED
|
@@ -13,8 +13,11 @@ 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';
|
|
16
19
|
|
|
17
|
-
const VERSION = '0.
|
|
20
|
+
const VERSION = '0.4.0';
|
|
18
21
|
const HELP = `
|
|
19
22
|
${c.bold('crossexam')} — cross-examine what your coding agents claim
|
|
20
23
|
|
|
@@ -28,6 +31,17 @@ const HELP = `
|
|
|
28
31
|
crossexam mutate plant small defects in the changed code and see if the tests notice
|
|
29
32
|
crossexam verify --mutate verify claims, then grade how strong the tests behind them are
|
|
30
33
|
|
|
34
|
+
${c.bold('Findings and re-verification')}
|
|
35
|
+
crossexam findings [id] the open findings of a session, structured for an agent (--json)
|
|
36
|
+
crossexam reverify <id> re-check a session independently; only this closes a finding
|
|
37
|
+
crossexam reliability how reliably each agent produces working software, from your own
|
|
38
|
+
verify / mutate / reverify evidence (--since 90d, --agent, --json)
|
|
39
|
+
|
|
40
|
+
${c.bold('Cloud')} (not open yet: nothing is ever sent today)
|
|
41
|
+
crossexam upload --dry-run --report <file>
|
|
42
|
+
show exactly what a run would send to crossexam cloud: paths made
|
|
43
|
+
relative, secrets redacted. --source none leaves code lines out
|
|
44
|
+
|
|
31
45
|
${c.bold('History')}
|
|
32
46
|
crossexam scan check local transcripts: Claude Code, Codex, Gemini CLI, Cline,
|
|
33
47
|
Roo Code, Kilo Code, Aider and the open format
|
|
@@ -59,6 +73,13 @@ const HELP = `
|
|
|
59
73
|
--agent <name> record which agent made the change, for history
|
|
60
74
|
--fail-under <0-1> exit 1 when the mutation score is below this
|
|
61
75
|
|
|
76
|
+
${c.bold('upload')}
|
|
77
|
+
--dry-run build and check the payload, print it, send nothing
|
|
78
|
+
--report <file> a report saved with verify --json or mutate --json (repeatable)
|
|
79
|
+
--source <changed-lines|none> include the changed code lines, or none of them (default changed-lines)
|
|
80
|
+
--agent <name> which agent made the change (otherwise taken from the pr)
|
|
81
|
+
--out <file> write the payload to a file instead of stdout
|
|
82
|
+
|
|
62
83
|
${c.bold('scan')}
|
|
63
84
|
--since <30d|12h|all> how far back to look (default 30d)
|
|
64
85
|
--agent <name> one of: ${AGENTS.join(', ')}
|
|
@@ -75,7 +96,7 @@ const HELP = `
|
|
|
75
96
|
--dry-run print the change, write nothing
|
|
76
97
|
`;
|
|
77
98
|
|
|
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']);
|
|
99
|
+
const VALUED = new Set(['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
100
|
const args = process.argv.slice(2);
|
|
80
101
|
const cmd = args[0] && !args[0].startsWith('-') ? args.shift() : 'scan';
|
|
81
102
|
const flag = (name) => args.includes(`--${name}`);
|
|
@@ -94,6 +115,10 @@ try {
|
|
|
94
115
|
else if (cmd === 'scan') await scan();
|
|
95
116
|
else if (cmd === 'verify') await verify();
|
|
96
117
|
else if (cmd === 'mutate') await mutate();
|
|
118
|
+
else if (cmd === 'upload') upload();
|
|
119
|
+
else if (cmd === 'reverify') await reverify();
|
|
120
|
+
else if (cmd === 'findings') findings();
|
|
121
|
+
else if (cmd === 'reliability') reliabilityCmd();
|
|
97
122
|
else if (cmd === 'mcp') startMcpServer({ version: VERSION, defaultCwd: path.resolve(String(opt('cwd', process.cwd()))) });
|
|
98
123
|
else if (cmd === 'init') init();
|
|
99
124
|
else if (cmd === 'hook') await hook();
|
|
@@ -192,37 +217,176 @@ async function verify() {
|
|
|
192
217
|
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
218
|
}
|
|
194
219
|
|
|
195
|
-
|
|
220
|
+
// evidence for reliability history, and a findings session the agent can close
|
|
221
|
+
const who = pr?.agent || String(opt('agent', 'unknown'));
|
|
222
|
+
ledger(claimRecords(r, who, github ? 'github' : 'verify', cwd));
|
|
223
|
+
const findings = findingsFrom({ verify: r, strength: r.strength });
|
|
224
|
+
const session = findings.length && !github && !flag('dry-run') ? openSession({ findings, cwd, repo: r.strength?.repo, agent: who, source: 'verify', testCommand: r.strength?.testCommand }) : null;
|
|
225
|
+
|
|
226
|
+
if (json) process.stdout.write(JSON.stringify({ ...r, pr, findings, session: session?.id ?? null }, null, 2) + '\n');
|
|
196
227
|
else if (github) emitActions(pr, r);
|
|
197
228
|
else {
|
|
198
229
|
console.log();
|
|
199
230
|
console.log(formatForAgent(r).replace(/^/gm, ' '));
|
|
200
231
|
if (r.strength) printStrength(r.strength, { limit: 4 });
|
|
201
232
|
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(', ')}`));
|
|
233
|
+
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
234
|
console.log();
|
|
203
235
|
}
|
|
204
236
|
if (opt('fail-on', 'contradicted') !== 'none' && !r.ok) process.exitCode = 1;
|
|
205
237
|
}
|
|
206
238
|
|
|
239
|
+
/**
|
|
240
|
+
* What a run would send to crossexam cloud. Cloud isn't open yet, so this only
|
|
241
|
+
* ever builds, checks and prints the payload; it has no way to send it.
|
|
242
|
+
*/
|
|
243
|
+
function upload() {
|
|
244
|
+
if (!flag('dry-run')) {
|
|
245
|
+
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");
|
|
246
|
+
process.exitCode = 2;
|
|
247
|
+
return;
|
|
248
|
+
}
|
|
249
|
+
const files = opts('report');
|
|
250
|
+
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`.');
|
|
251
|
+
let verify = null;
|
|
252
|
+
let mutation = null;
|
|
253
|
+
for (const f of files) {
|
|
254
|
+
const got = classifyReport(JSON.parse(fs.readFileSync(path.resolve(f), 'utf8')));
|
|
255
|
+
verify = got.verify ?? verify;
|
|
256
|
+
mutation = got.mutation ?? mutation;
|
|
257
|
+
}
|
|
258
|
+
const source = String(opt('source', 'changed-lines'));
|
|
259
|
+
if (!SOURCE_POLICIES.includes(source)) throw new Error(`--source must be one of ${SOURCE_POLICIES.join(', ')}`);
|
|
260
|
+
const agent = opt('agent');
|
|
261
|
+
const payload = buildPayload({
|
|
262
|
+
verify,
|
|
263
|
+
mutation,
|
|
264
|
+
github: githubContext(),
|
|
265
|
+
agent: typeof agent === 'string' ? agent : undefined,
|
|
266
|
+
cliVersion: VERSION,
|
|
267
|
+
root: path.resolve(String(opt('cwd', verify?.cwd || process.cwd()))),
|
|
268
|
+
sourcePolicy: source,
|
|
269
|
+
});
|
|
270
|
+
const errors = validatePayload(payload);
|
|
271
|
+
if (errors.length) throw new Error(`the payload failed its own checks:\n ${errors.join('\n ')}`);
|
|
272
|
+
const text = JSON.stringify(payload, null, 2);
|
|
273
|
+
const out = opt('out');
|
|
274
|
+
if (typeof out === 'string') {
|
|
275
|
+
fs.writeFileSync(out, text + '\n');
|
|
276
|
+
process.stderr.write(`dry run: ${Buffer.byteLength(text)} bytes written to ${out}. nothing was sent.\n`);
|
|
277
|
+
} else {
|
|
278
|
+
process.stdout.write(text + '\n');
|
|
279
|
+
process.stderr.write(`dry run: ${Buffer.byteLength(text)} bytes. nothing was sent.\n`);
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
|
|
207
283
|
async function mutate() {
|
|
208
284
|
const cwd = path.resolve(String(opt('cwd', process.cwd())));
|
|
209
285
|
const json = opt('json');
|
|
210
286
|
const toStdout = json === true;
|
|
211
287
|
const full = await assessStrength({ cwd, ...mutateOpts(), onProgress: toStdout ? undefined : progress });
|
|
212
288
|
const r = flag('no-source') ? withoutSource(full) : full;
|
|
213
|
-
|
|
289
|
+
const who = String(opt('agent', 'unknown'));
|
|
290
|
+
ledger([ledgerRecord(r, { agent: who, source: 'mutate' })]);
|
|
291
|
+
const findings = findingsFrom({ strength: full });
|
|
292
|
+
const session = findings.length ? openSession({ findings, cwd, repo: full.repo, agent: who, source: 'mutate', testCommand: full.testCommand }) : null;
|
|
293
|
+
r.findings = flag('no-source') ? findings.map(({ before, after, ...f }) => f) : findings;
|
|
294
|
+
r.session = session?.id ?? null;
|
|
214
295
|
const csv = opt('csv');
|
|
215
296
|
if (typeof csv === 'string') fs.writeFileSync(csv, toCsv(r));
|
|
216
297
|
if (toStdout) process.stdout.write(JSON.stringify(r, null, 2) + '\n');
|
|
217
298
|
else {
|
|
218
299
|
if (typeof json === 'string') fs.writeFileSync(json, JSON.stringify(r, null, 2));
|
|
219
300
|
printStrength(r, { limit: Number(opt('limit', 8)) });
|
|
301
|
+
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
302
|
if (typeof json === 'string') console.log(` ${c.dim('Report written to')} ${path.resolve(json)}\n`);
|
|
221
303
|
}
|
|
222
304
|
const under = opt('fail-under');
|
|
223
305
|
if (under !== undefined && r.summary.score != null && r.summary.score < Number(under)) process.exitCode = 1;
|
|
224
306
|
}
|
|
225
307
|
|
|
308
|
+
/** One ledger record per checked claim: the evidence reliability history is built from. */
|
|
309
|
+
function claimRecords(r, agent, source, cwd) {
|
|
310
|
+
const at = new Date().toISOString();
|
|
311
|
+
const repo = path.basename(cwd);
|
|
312
|
+
return r.results.map((x) => ({ type: 'verify', at, agent, repo, source, kind: x.kind, verdict: x.verdict }));
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
/** Re-check a findings session independently: only this can close a finding. */
|
|
316
|
+
async function reverify() {
|
|
317
|
+
const id = positional()[0];
|
|
318
|
+
if (!id) {
|
|
319
|
+
const recent = listSessions(8);
|
|
320
|
+
if (!recent.length) throw new Error('reverify needs a session id. Sessions are opened when verify or mutate finds something.');
|
|
321
|
+
console.log(`\n ${c.bold('Recent sessions')}`);
|
|
322
|
+
for (const s of recent) {
|
|
323
|
+
const open = s.findings.filter((f) => f.status === 'open' || f.status === 'still-open').length;
|
|
324
|
+
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'}`)}`);
|
|
325
|
+
}
|
|
326
|
+
console.log(c.dim('\n crossexam reverify <id>\n'));
|
|
327
|
+
return;
|
|
328
|
+
}
|
|
329
|
+
const json = flag('json');
|
|
330
|
+
const unsandboxed = flag('unsandboxed');
|
|
331
|
+
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 });
|
|
332
|
+
ledger([reverifyRecord(session, summary)]);
|
|
333
|
+
if (json) {
|
|
334
|
+
process.stdout.write(JSON.stringify({ session: session.id, ...summary, changes, findings: session.findings }, null, 2) + '\n');
|
|
335
|
+
} else {
|
|
336
|
+
const mark = { resolved: c.green('✓ resolved '), 'still-open': c.red('✗ still open'), superseded: c.gray('○ superseded') };
|
|
337
|
+
console.log(`\n ${c.bold(`Re-check ${summary.round}`)} ${c.dim(`· session ${session.id} · ${session.repo}`)}`);
|
|
338
|
+
if (summary.blocker) console.log(` ${c.yellow(summary.blocker)}`);
|
|
339
|
+
for (const ch of changes) {
|
|
340
|
+
const f = session.findings.find((x) => x.id === ch.id);
|
|
341
|
+
const what = f.type === 'claim' ? `"${f.claim}"` : `${f.file}:${f.line} ${c.dim(`${f.category} · ${f.operator}`)}`;
|
|
342
|
+
console.log(` ${mark[ch.status]} ${what}\n ${c.dim(ch.evidence)}`);
|
|
343
|
+
}
|
|
344
|
+
const open = session.findings.filter((f) => f.status === 'still-open' || f.status === 'open').length;
|
|
345
|
+
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`);
|
|
346
|
+
}
|
|
347
|
+
if (session.findings.some((f) => f.status === 'still-open' || f.status === 'open')) process.exitCode = 1;
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
/** The open findings of a session, structured for an agent. */
|
|
351
|
+
function findings() {
|
|
352
|
+
const id = positional()[0];
|
|
353
|
+
const session = id ? loadSession(id) : listSessions(1)[0];
|
|
354
|
+
if (!session) throw new Error('No findings sessions yet. They are opened when verify or mutate finds something.');
|
|
355
|
+
if (flag('json')) process.stdout.write(JSON.stringify(session, null, 2) + '\n');
|
|
356
|
+
else console.log('\n' + formatFindingsForAgent(session).replace(/^/gm, ' ') + '\n');
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
/** How reliably each agent produces working software, from recorded evidence. */
|
|
360
|
+
function reliabilityCmd() {
|
|
361
|
+
const since = parseSince(opt('since', '90d'));
|
|
362
|
+
const agent = typeof opt('agent') === 'string' ? String(opt('agent')) : undefined;
|
|
363
|
+
const repo = typeof opt('repo') === 'string' ? String(opt('repo')) : undefined;
|
|
364
|
+
const r = reliabilityOf({ since, agent, repo });
|
|
365
|
+
if (flag('json')) {
|
|
366
|
+
process.stdout.write(JSON.stringify(r, null, 2) + '\n');
|
|
367
|
+
return;
|
|
368
|
+
}
|
|
369
|
+
if (!r.agents.length) {
|
|
370
|
+
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`);
|
|
371
|
+
return;
|
|
372
|
+
}
|
|
373
|
+
const p = (v) => (v == null ? c.dim(' — ') : `${String(Math.round(v * 100)).padStart(3)}%`);
|
|
374
|
+
console.log(`\n ${c.bold('Reliability by agent')} ${c.dim(`· ${r.records} records from your own runs`)}\n`);
|
|
375
|
+
console.log(c.dim(' agent claims held tests caught fixed on 1st re-check evidence'));
|
|
376
|
+
for (const a of r.agents) {
|
|
377
|
+
const held = a.claims.falseDoneRate == null ? null : 1 - a.claims.falseDoneRate;
|
|
378
|
+
console.log(` ${a.agent.padEnd(16)} ${p(held)} ${p(a.strength.score)} ${p(a.fixes.firstRecheckRate)} ${String(a.evidence).padStart(4)}`);
|
|
379
|
+
}
|
|
380
|
+
console.log();
|
|
381
|
+
for (const a of r.agents) {
|
|
382
|
+
console.log(` ${c.bold(a.agent)}: ${describeAgent(a)}.`);
|
|
383
|
+
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.`));
|
|
384
|
+
const recent = a.weeks.slice(-6).filter((w) => w.falseDoneRate != null || w.score != null);
|
|
385
|
+
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(' ')}`));
|
|
386
|
+
}
|
|
387
|
+
console.log(c.dim('\n Three separate measures, never blended: an agent can be honest about its claims and still ship weak tests.\n'));
|
|
388
|
+
}
|
|
389
|
+
|
|
226
390
|
function mutateOpts() {
|
|
227
391
|
const files = opts('files').flatMap((f) => f.split(',')).filter(Boolean);
|
|
228
392
|
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
|
+
"version": "0.4.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/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
|
-
|
|
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) {
|
package/src/findings.js
ADDED
|
@@ -0,0 +1,194 @@
|
|
|
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
|
+
|
|
16
|
+
const home = () => process.env.CROSSEXAM_HOME || path.join(os.homedir(), '.crossexam');
|
|
17
|
+
const sessionsDir = () => path.join(home(), 'sessions');
|
|
18
|
+
const SESSION_ID = /^cx-[0-9a-f]{10}$/;
|
|
19
|
+
const hash = (s) => createHash('sha256').update(s).digest('hex').slice(0, 16);
|
|
20
|
+
|
|
21
|
+
/** Findings from a verify result and/or a mutation report. Empty when nothing is wrong. */
|
|
22
|
+
export function findingsFrom({ verify = null, strength = null } = {}) {
|
|
23
|
+
const out = [];
|
|
24
|
+
for (const r of verify?.results ?? []) {
|
|
25
|
+
if (r.verdict !== 'contradicted' && r.verdict !== 'stale') continue;
|
|
26
|
+
const cmd = r.evidence?.command ?? null;
|
|
27
|
+
out.push({
|
|
28
|
+
id: `claim-${hash(`${r.kind}\u0000${r.claim}`)}`,
|
|
29
|
+
type: 'claim',
|
|
30
|
+
severity: ['tests', 'build', 'types', 'migration'].includes(r.kind) ? 'high' : 'medium',
|
|
31
|
+
kind: r.kind,
|
|
32
|
+
claim: r.claim,
|
|
33
|
+
verdict: r.verdict,
|
|
34
|
+
reason: r.reason,
|
|
35
|
+
command: cmd,
|
|
36
|
+
excerpt: r.evidence?.excerpt ?? null,
|
|
37
|
+
ask:
|
|
38
|
+
r.verdict === 'stale'
|
|
39
|
+
? `Re-run ${cmd ? `\`${cmd}\`` : 'the check'} after your last edit, then report what it printed.`
|
|
40
|
+
: `Fix what makes ${cmd ? `\`${cmd}\`` : 'the check'} disagree, or correct the claim to say what is true.`,
|
|
41
|
+
recheck: cmd ? `crossexam re-runs \`${cmd}\`` : 'crossexam re-checks the claim',
|
|
42
|
+
status: 'open',
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
for (const m of strength?.mutants ?? []) {
|
|
46
|
+
if (m.status !== STATUS.SURVIVED || !m.fingerprint) continue;
|
|
47
|
+
out.push({
|
|
48
|
+
id: `mutant-${m.fingerprint}`,
|
|
49
|
+
type: 'mutant',
|
|
50
|
+
severity: severityOf(m.operator),
|
|
51
|
+
fingerprint: m.fingerprint,
|
|
52
|
+
category: m.category,
|
|
53
|
+
operator: m.operator,
|
|
54
|
+
file: m.file,
|
|
55
|
+
line: m.line,
|
|
56
|
+
function: m.function,
|
|
57
|
+
before: m.before ?? null,
|
|
58
|
+
after: m.after ?? null,
|
|
59
|
+
why: m.why,
|
|
60
|
+
ask: 'Add or strengthen a test that fails when this change is made. Do not change the code under test to dodge it.',
|
|
61
|
+
recheck: 'crossexam plants this exact defect again and runs your tests',
|
|
62
|
+
status: 'open',
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
const rank = { high: 0, medium: 1, low: 2 };
|
|
66
|
+
return out.sort((a, b) => rank[a.severity] - rank[b.severity]);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Save a session for these findings and return it. */
|
|
70
|
+
export function openSession({ findings, cwd, repo, agent = 'unknown', source = 'cli', testCommand = null }) {
|
|
71
|
+
const id = `cx-${randomBytes(5).toString('hex')}`;
|
|
72
|
+
const session = {
|
|
73
|
+
id,
|
|
74
|
+
createdAt: new Date().toISOString(),
|
|
75
|
+
cwd: path.resolve(cwd),
|
|
76
|
+
repo: repo ?? path.basename(path.resolve(cwd)),
|
|
77
|
+
agent,
|
|
78
|
+
source,
|
|
79
|
+
testCommand,
|
|
80
|
+
findings,
|
|
81
|
+
rounds: [],
|
|
82
|
+
};
|
|
83
|
+
save(session);
|
|
84
|
+
return session;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export function loadSession(id) {
|
|
88
|
+
if (!SESSION_ID.test(String(id))) throw new Error(`"${id}" is not a crossexam session id (they look like cx-1a2b3c4d5e)`);
|
|
89
|
+
const f = path.join(sessionsDir(), `${id}.json`);
|
|
90
|
+
if (!fs.existsSync(f)) throw new Error(`no session ${id} on this machine`);
|
|
91
|
+
return JSON.parse(fs.readFileSync(f, 'utf8'));
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function save(session) {
|
|
95
|
+
fs.mkdirSync(sessionsDir(), { recursive: true });
|
|
96
|
+
fs.writeFileSync(path.join(sessionsDir(), `${session.id}.json`), JSON.stringify(session, null, 2));
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** Recent sessions, newest first. */
|
|
100
|
+
export function listSessions(limit = 20) {
|
|
101
|
+
try {
|
|
102
|
+
return fs
|
|
103
|
+
.readdirSync(sessionsDir())
|
|
104
|
+
.filter((f) => /^cx-[0-9a-f]{10}\.json$/.test(f))
|
|
105
|
+
.map((f) => JSON.parse(fs.readFileSync(path.join(sessionsDir(), f), 'utf8')))
|
|
106
|
+
.sort((a, b) => b.createdAt.localeCompare(a.createdAt))
|
|
107
|
+
.slice(0, limit);
|
|
108
|
+
} catch {
|
|
109
|
+
return [];
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Re-check every open finding in a session, independently.
|
|
115
|
+
* Claims: the original sentences are verified again from scratch.
|
|
116
|
+
* Mutants: each surviving defect is planted again by fingerprint and the tests
|
|
117
|
+
* re-run. A defect whose code is gone is "superseded": the code changed, so the
|
|
118
|
+
* finding can't be closed or kept, and a fresh `mutate` is the way to judge it.
|
|
119
|
+
*/
|
|
120
|
+
export async function reverify(id, { cwd, isolation, allowUnsandboxed, timeoutSeconds } = {}) {
|
|
121
|
+
const session = loadSession(id);
|
|
122
|
+
const repoDir = path.resolve(cwd || session.cwd);
|
|
123
|
+
const open = session.findings.filter((f) => f.status === 'open' || f.status === 'still-open');
|
|
124
|
+
const round = session.rounds.length + 1;
|
|
125
|
+
const changes = [];
|
|
126
|
+
let blocker = null;
|
|
127
|
+
|
|
128
|
+
const claims = open.filter((f) => f.type === 'claim');
|
|
129
|
+
if (claims.length) {
|
|
130
|
+
const r = await verifyText(claims.map((f) => f.claim).join('\n'), { cwd: repoDir, timeoutMs: timeoutSeconds ? timeoutSeconds * 1000 : undefined });
|
|
131
|
+
for (const f of claims) {
|
|
132
|
+
const now = r.results.find((x) => x.kind === f.kind && x.claim === f.claim) ?? r.results.find((x) => x.kind === f.kind);
|
|
133
|
+
const ok = now && (now.verdict === 'verified' || now.verdict === 'review');
|
|
134
|
+
changes.push({ id: f.id, status: ok ? 'resolved' : 'still-open', evidence: now ? `${now.verdict}: ${now.reason}` : 'the claim was not found again' });
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
const muts = open.filter((f) => f.type === 'mutant');
|
|
139
|
+
if (muts.length) {
|
|
140
|
+
const files = [...new Set(muts.map((f) => f.file))];
|
|
141
|
+
const s = await assessStrength({ cwd: repoDir, files, fingerprints: muts.map((f) => f.fingerprint), max: muts.length, cache: false, isolation, allowUnsandboxed, testCommand: session.testCommand || undefined });
|
|
142
|
+
if (s.blocker) blocker = s.blocker;
|
|
143
|
+
const byFp = new Map(s.mutants.map((m) => [m.fingerprint, m]));
|
|
144
|
+
for (const f of muts) {
|
|
145
|
+
const m = byFp.get(f.fingerprint);
|
|
146
|
+
if (s.blocker) changes.push({ id: f.id, status: 'still-open', evidence: `not re-checked: ${s.blocker}` });
|
|
147
|
+
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' });
|
|
148
|
+
else if (m.status === STATUS.KILLED) changes.push({ id: f.id, status: 'resolved', evidence: `caught now: ${m.why || 'a test failed'}` });
|
|
149
|
+
else if (m.status === STATUS.SURVIVED) changes.push({ id: f.id, status: 'still-open', evidence: 'the tests still pass with this defect planted' });
|
|
150
|
+
else changes.push({ id: f.id, status: 'still-open', evidence: `inconclusive (${m.status.toLowerCase().replace('mutation_', '')}): ${m.why || ''}`.trim() });
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
for (const c of changes) {
|
|
155
|
+
const f = session.findings.find((x) => x.id === c.id);
|
|
156
|
+
f.status = c.status;
|
|
157
|
+
f.evidence = c.evidence;
|
|
158
|
+
if (c.status === 'resolved' && !f.resolvedRound) f.resolvedRound = round;
|
|
159
|
+
}
|
|
160
|
+
const count = (st) => changes.filter((c) => c.status === st).length;
|
|
161
|
+
const summary = { round, at: new Date().toISOString(), checked: changes.length, resolved: count('resolved'), stillOpen: count('still-open'), superseded: count('superseded'), blocker };
|
|
162
|
+
session.rounds.push(summary);
|
|
163
|
+
save(session);
|
|
164
|
+
return { session, summary, changes };
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** A ledger record for one re-verification round, for reliability history. */
|
|
168
|
+
export function reverifyRecord(session, summary) {
|
|
169
|
+
return {
|
|
170
|
+
type: 'reverify',
|
|
171
|
+
at: summary.at,
|
|
172
|
+
session: session.id,
|
|
173
|
+
agent: session.agent,
|
|
174
|
+
repo: session.repo,
|
|
175
|
+
round: summary.round,
|
|
176
|
+
findings: session.findings.length,
|
|
177
|
+
resolved: summary.resolved,
|
|
178
|
+
stillOpen: summary.stillOpen,
|
|
179
|
+
superseded: summary.superseded,
|
|
180
|
+
allResolved: session.findings.every((f) => f.status === 'resolved' || f.status === 'superseded'),
|
|
181
|
+
};
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** Plain text an agent can act on. */
|
|
185
|
+
export function formatFindingsForAgent(session, findings = session.findings) {
|
|
186
|
+
const open = findings.filter((f) => f.status === 'open' || f.status === 'still-open');
|
|
187
|
+
if (!open.length) return `Session ${session.id}: nothing open.`;
|
|
188
|
+
const lines = open.slice(0, 12).map((f, i) =>
|
|
189
|
+
f.type === 'claim'
|
|
190
|
+
? `${i + 1}. [${f.severity}] claim ${f.verdict}: "${f.claim}"${f.command ? `\n evidence: \`${f.command}\`` : ''}\n do: ${f.ask}`
|
|
191
|
+
: `${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}`,
|
|
192
|
+
);
|
|
193
|
+
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.`;
|
|
194
|
+
}
|