crossexamdev 0.2.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.
@@ -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
+ }
package/src/github.js CHANGED
@@ -1,69 +1,93 @@
1
- // Pull-request mode: every cloud agent that opens a PR (Copilot coding agent,
2
- // Codex, Devin, Jules, Cursor background agents, Claude) writes its claims in
3
- // the PR description. In CI the branch is checked out, so verify them there.
4
-
5
- import crypto from 'node:crypto';
6
- import fs from 'node:fs';
7
-
8
- const BOTS = [
9
- [/^copilot(-swe-agent)?(\[bot\])?$/i, 'copilot'],
10
- [/^devin-ai-integration\[bot\]$/i, 'devin'],
11
- [/^chatgpt-codex-connector\[bot\]$|codex/i, 'codex'],
12
- [/^google-labs-jules\[bot\]$|jules/i, 'jules'],
13
- [/^cursor(-agent)?\[bot\]$|^cursor$/i, 'cursor'],
14
- [/^claude(\[bot\])?$|anthropic/i, 'claude-code'],
15
- [/^sweep-ai\[bot\]$/i, 'sweep'],
16
- ];
17
-
18
- /** Read the PR from the Actions event payload. */
19
- export function readPullRequest(eventPath = process.env.GITHUB_EVENT_PATH) {
20
- if (!eventPath || !fs.existsSync(eventPath)) return null;
21
- const ev = JSON.parse(fs.readFileSync(eventPath, 'utf8'));
22
- const pr = ev.pull_request;
23
- if (!pr) return null;
24
- return { number: pr.number, title: pr.title || '', body: pr.body || '', author: pr.user?.login || '', agent: agentOf(pr.user?.login || '', pr.body || '') };
25
- }
26
-
27
- export function agentOf(login, body = '') {
28
- for (const [re, name] of BOTS) if (re.test(login)) return name;
29
- if (/Generated with \[?Claude Code/i.test(body)) return 'claude-code';
30
- if (/codex/i.test(body) && /openai/i.test(body)) return 'codex';
31
- return 'unknown';
32
- }
33
-
34
- const ICON = { verified: '✅', contradicted: '❌', review: '🔎', stale: '⏱️', unbacked: '⚪' };
35
-
36
- export function markdownSummary(pr, r) {
37
- const head = `### crossexam · ${r.ok ? 'claims hold up' : 'false claims in this PR'}`;
38
- const who = pr ? `PR #${pr.number}${pr.agent !== 'unknown' ? ` by **${pr.agent}**` : pr.author ? ` by @​${pr.author}` : ''}` : '';
39
- if (!r.results.length) return `${head}\n\n${who}\n\nNo checkable completion claims in the description.\n`;
40
- const rows = r.results.map((x) => `| ${ICON[x.verdict]} ${x.verdict} | ${cell(x.claim)} | ${cell(x.reason)} |`);
41
- const details = r.results
42
- .filter((x) => x.verdict === 'contradicted' && x.evidence?.excerpt)
43
- .map((x) => `<details><summary><code>${escapeHtml(x.evidence.command)}</code></summary>\n\n\`\`\`\n${x.evidence.excerpt}\n\`\`\`\n</details>`);
44
- return `${head}\n\n${who}\n\n| Verdict | Claim | Why |\n|---|---|---|\n${rows.join('\n')}\n\n${details.join('\n\n')}\n`;
45
- }
46
-
47
- /** Workflow commands: annotations on the run, plus the job summary. */
48
- export function emitActions(pr, r) {
49
- for (const x of r.results) {
50
- const msg = `${x.claim} → ${x.reason}`.replace(/\r?\n/g, ' ').replace(/%/g, '%25');
51
- if (x.verdict === 'contradicted') console.log(`::error title=crossexam: false claim::${msg}`);
52
- else if (x.verdict === 'review') console.log(`::warning title=crossexam: needs review::${msg}`);
53
- else console.log(`::notice title=crossexam: verified::${msg}`);
54
- }
55
- const md = markdownSummary(pr, r);
56
- if (process.env.GITHUB_STEP_SUMMARY) fs.appendFileSync(process.env.GITHUB_STEP_SUMMARY, md);
57
- if (process.env.GITHUB_OUTPUT) {
58
- const n = (v) => r.results.filter((x) => x.verdict === v).length;
59
- fs.appendFileSync(process.env.GITHUB_OUTPUT, `ok=${r.ok}\ncontradicted=${n('contradicted')}\nverified=${n('verified')}\nagent=${pr?.agent ?? 'unknown'}\n`);
60
- // A fresh delimiter each run, so test output or grepped repo text can't end
61
- // the block early and set outputs of its own.
62
- const eof = `CROSSEXAM_EOF_${crypto.randomUUID().replace(/-/g, '')}`;
63
- fs.appendFileSync(process.env.GITHUB_OUTPUT, `summary<<${eof}\n${md}\n${eof}\n`);
64
- }
65
- return md;
66
- }
67
-
68
- const cell = (s) => String(s).replace(/\|/g, '\\|').replace(/\r?\n/g, ' ').replace(/`([^`]+)`/g, '<code>$1</code>');
69
- const escapeHtml = (s) => String(s).replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c]);
1
+ // Pull-request mode: every cloud agent that opens a PR (Copilot coding agent,
2
+ // Codex, Devin, Jules, Cursor background agents, Claude) writes its claims in
3
+ // the PR description. In CI the branch is checked out, so verify them there.
4
+
5
+ import crypto from 'node:crypto';
6
+ import fs from 'node:fs';
7
+
8
+ const BOTS = [
9
+ [/^copilot(-swe-agent)?(\[bot\])?$/i, 'copilot'],
10
+ [/^devin-ai-integration\[bot\]$/i, 'devin'],
11
+ [/^chatgpt-codex-connector\[bot\]$|codex/i, 'codex'],
12
+ [/^google-labs-jules\[bot\]$|jules/i, 'jules'],
13
+ [/^cursor(-agent)?\[bot\]$|^cursor$/i, 'cursor'],
14
+ [/^claude(\[bot\])?$|anthropic/i, 'claude-code'],
15
+ [/^sweep-ai\[bot\]$/i, 'sweep'],
16
+ ];
17
+
18
+ /** Read the PR from the Actions event payload. */
19
+ export function readPullRequest(eventPath = process.env.GITHUB_EVENT_PATH) {
20
+ if (!eventPath || !fs.existsSync(eventPath)) return null;
21
+ const ev = JSON.parse(fs.readFileSync(eventPath, 'utf8'));
22
+ const pr = ev.pull_request;
23
+ if (!pr) return null;
24
+ return { number: pr.number, title: pr.title || '', body: pr.body || '', author: pr.user?.login || '', agent: agentOf(pr.user?.login || '', pr.body || '') };
25
+ }
26
+
27
+ export function agentOf(login, body = '') {
28
+ for (const [re, name] of BOTS) if (re.test(login)) return name;
29
+ if (/Generated with \[?Claude Code/i.test(body)) return 'claude-code';
30
+ if (/codex/i.test(body) && /openai/i.test(body)) return 'codex';
31
+ return 'unknown';
32
+ }
33
+
34
+ const ICON = { verified: '✅', contradicted: '❌', review: '🔎', stale: '⏱️', unbacked: '⚪' };
35
+
36
+ export function markdownSummary(pr, r) {
37
+ const head = `### crossexam · ${r.ok ? 'claims hold up' : 'false claims in this PR'}`;
38
+ const who = pr ? `PR #${pr.number}${pr.agent !== 'unknown' ? ` by **${pr.agent}**` : pr.author ? ` by @​${pr.author}` : ''}` : '';
39
+ if (!r.results.length) return `${head}\n\n${who}\n\nNo checkable completion claims in the description.\n${r.strength ? strengthMarkdown(r.strength) : ''}`;
40
+ const rows = r.results.map((x) => `| ${ICON[x.verdict]} ${x.verdict} | ${cell(x.claim)} | ${cell(x.reason)} |`);
41
+ const details = r.results
42
+ .filter((x) => x.verdict === 'contradicted' && x.evidence?.excerpt)
43
+ .map((x) => `<details><summary><code>${escapeHtml(x.evidence.command)}</code></summary>\n\n\`\`\`\n${x.evidence.excerpt}\n\`\`\`\n</details>`);
44
+ return `${head}\n\n${who}\n\n| Verdict | Claim | Why |\n|---|---|---|\n${rows.join('\n')}\n\n${details.join('\n\n')}\n${r.strength ? strengthMarkdown(r.strength) : ''}`;
45
+ }
46
+
47
+ const RATING_ICON = { strong: '🟢', moderate: '🟡', weak: '🔴', inconclusive: '⚪' };
48
+
49
+ /** Test strength is its own section: it never changes a verdict above. */
50
+ export function strengthMarkdown(s) {
51
+ const t = s.summary;
52
+ const score = t.score != null ? ` · ${Math.round(t.score * 100)}% of planted defects caught` : '';
53
+ const surv = s.mutants.filter((m) => m.status === 'MUTATION_SURVIVED').slice(0, 8);
54
+ const code = (x) => `<code>${escapeHtml(x.split('\n')[0].trim().slice(0, 80)).replace(/\|/g, '&#124;')}</code>`;
55
+ const rows = surv.map((m) => `| \`${m.file}:${m.line}\` | ${cell(m.function || 'top level')} | ${code(m.before)} → ${code(m.after)} |`);
56
+ return [
57
+ `\n#### Test strength: ${RATING_ICON[s.rating]} ${s.rating}${score}`,
58
+ s.headline ? `\n${cell(s.headline.text)}` : '',
59
+ t.attempted ? `\n${t.attempted} mutants · ${t.killed} killed · ${t.survived} survived · ${t.invalid} invalid · ${t.unresolved} unresolved · ${(t.ms / 1000).toFixed(0)}s` : '',
60
+ rows.length ? `\n<details><summary>Defects the tests did not notice</summary>\n\n| Where | Function | Change that still passed |\n|---|---|---|\n${rows.join('\n')}\n</details>` : '',
61
+ '\n<sub>Separate from the verdicts above: a mutation score measures how well the tests pin down the changed code, not whether the code is correct.</sub>\n',
62
+ ].join('\n');
63
+ }
64
+
65
+ /** Workflow commands: annotations on the run, plus the job summary. */
66
+ export function emitActions(pr, r) {
67
+ for (const x of r.results) {
68
+ const msg = `${x.claim} → ${x.reason}`.replace(/\r?\n/g, ' ').replace(/%/g, '%25');
69
+ if (x.verdict === 'contradicted') console.log(`::error title=crossexam: false claim::${msg}`);
70
+ else if (x.verdict === 'review') console.log(`::warning title=crossexam: needs review::${msg}`);
71
+ else console.log(`::notice title=crossexam: verified::${msg}`);
72
+ }
73
+ if (r.strength?.headline && (r.strength.rating === 'weak' || r.strength.rating === 'moderate')) {
74
+ const top = r.strength.mutants.find((m) => m.id === r.strength.headline.mutant);
75
+ const loc = top ? ` file=${top.file},line=${top.line},` : ' ';
76
+ console.log(`::warning${loc}title=crossexam: ${r.strength.rating} tests::${r.strength.headline.text.replace(/\r?\n/g, ' ').replace(/%/g, '%25')}`);
77
+ }
78
+ const md = markdownSummary(pr, r);
79
+ if (process.env.GITHUB_STEP_SUMMARY) fs.appendFileSync(process.env.GITHUB_STEP_SUMMARY, md);
80
+ if (process.env.GITHUB_OUTPUT) {
81
+ const n = (v) => r.results.filter((x) => x.verdict === v).length;
82
+ fs.appendFileSync(process.env.GITHUB_OUTPUT, `ok=${r.ok}\ncontradicted=${n('contradicted')}\nverified=${n('verified')}\nagent=${pr?.agent ?? 'unknown'}\n`);
83
+ if (r.strength) fs.appendFileSync(process.env.GITHUB_OUTPUT, `mutation-score=${r.strength.summary.score ?? ''}\nmutation-rating=${r.strength.rating}\nmutants-survived=${r.strength.summary.survived}\n`);
84
+ // A fresh delimiter each run, so test output or grepped repo text can't end
85
+ // the block early and set outputs of its own.
86
+ const eof = `CROSSEXAM_EOF_${crypto.randomUUID().replace(/-/g, '')}`;
87
+ fs.appendFileSync(process.env.GITHUB_OUTPUT, `summary<<${eof}\n${md}\n${eof}\n`);
88
+ }
89
+ return md;
90
+ }
91
+
92
+ const cell = (s) => String(s).replace(/\|/g, '\\|').replace(/\r?\n/g, ' ').replace(/`([^`]+)`/g, '<code>$1</code>');
93
+ const escapeHtml = (s) => String(s).replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c]);
package/src/mcp.js CHANGED
@@ -6,11 +6,17 @@
6
6
 
7
7
  import path from 'node:path';
8
8
  import readline from 'node:readline';
9
+ import fs from 'node:fs';
10
+ import os from 'node:os';
11
+ import { detectWorkClaims } from './claims.js';
9
12
  import { detectCommands, verifyText } from './live.js';
13
+ import { findingsFrom, formatFindingsForAgent, openSession, reverify, reverifyRecord } from './findings.js';
14
+ import { describeAgent, reliability } from './reliability.js';
15
+ import { STATUS, assessStrength, ledgerRecord, qualityOf } from './strength.js';
10
16
 
11
17
  const SUPPORTED = ['2025-06-18', '2025-03-26', '2024-11-05'];
12
18
 
13
- const INSTRUCTIONS = `crossexam checks claims against the repository. Before you tell the user a task is done, call verify_claims with the exact summary you are about to give and the absolute path of the workspace. If any claim comes back "contradicted", fix the problem or correct the summary before finishing. Never say tests, build, types or lint pass unless verify_claims verified it.`;
19
+ const INSTRUCTIONS = `crossexam checks claims against the repository. Before you tell the user a task is done, call verify_claims with the exact summary you are about to give and the absolute path of the workspace. If any claim comes back "contradicted", fix the problem or correct the summary before finishing. Never say tests, build, types or lint pass unless verify_claims verified it. When a result includes a findings session, fix each finding, then call reverify_findings with that session: only its independent re-check can close a finding, so never report findings as fixed before it does.`;
14
20
 
15
21
  const TOOLS = [
16
22
  {
@@ -23,11 +29,50 @@ const TOOLS = [
23
29
  properties: {
24
30
  summary: { type: 'string', description: 'The completion message you are about to send, verbatim.' },
25
31
  cwd: { type: 'string', description: 'Absolute path of the workspace/repository root. Defaults to the server\'s working directory.' },
32
+ mutate: { type: 'boolean', description: 'Also grade how strong the tests behind a "tests pass" or "implemented/fixed" claim are, by planting small defects in the changed code (slower: runs the test suite once per mutant).' },
26
33
  },
27
34
  required: ['summary'],
28
35
  },
29
36
  annotations: { readOnlyHint: false, openWorldHint: false },
30
37
  },
38
+ {
39
+ name: 'assess_test_strength',
40
+ title: 'Assess test strength (mutation testing)',
41
+ description:
42
+ "Plant small deterministic defects (flipped comparisons, inverted conditions, swapped operators) in the code you changed, run the repo's tests against each one in an isolated copy, and report which defects the tests failed to notice. Your working tree is never modified. Use the surviving defects to write tests that would catch them.",
43
+ inputSchema: {
44
+ type: 'object',
45
+ properties: {
46
+ cwd: { type: 'string', description: 'Absolute path of the repository root.' },
47
+ base: { type: 'string', description: 'Git ref to compare against. Default: uncommitted changes, else the last commit.' },
48
+ files: { type: 'array', items: { type: 'string' }, description: 'Mutate these files (every line) instead of the diff.' },
49
+ max: { type: 'number', description: 'Most mutants to run in this call (default 15). Finished results are cached, so calling again continues.' },
50
+ },
51
+ },
52
+ annotations: { readOnlyHint: true, openWorldHint: false },
53
+ },
54
+ {
55
+ name: 'reverify_findings',
56
+ title: 'Submit fixes for independent re-verification',
57
+ description:
58
+ 'After fixing the findings from verify_claims or assess_test_strength, call this with the session id they returned. crossexam re-checks every open finding itself: contradicted claims are verified again from scratch, and each surviving defect is planted again and your tests re-run. Returns what is now resolved, what is still open, and what no longer applies because the code changed. You cannot mark a finding resolved any other way.',
59
+ inputSchema: {
60
+ type: 'object',
61
+ properties: {
62
+ session: { type: 'string', description: 'The findings session id, like cx-1a2b3c4d5e.' },
63
+ cwd: { type: 'string', description: 'Absolute path of the repository root, if it moved since the session opened.' },
64
+ },
65
+ required: ['session'],
66
+ },
67
+ annotations: { readOnlyHint: false, openWorldHint: false },
68
+ },
69
+ {
70
+ name: 'agent_reliability',
71
+ title: 'Reliability by agent',
72
+ description: 'How reliably each coding agent has produced working software on this machine, from recorded verification evidence: how often its claims held up, how many planted defects its tests caught, and how often its fixes closed findings on the first independent re-check. Three separate measures, never blended.',
73
+ inputSchema: { type: 'object', properties: { days: { type: 'number', description: 'How far back to look (default 90).' }, agent: { type: 'string', description: 'Only this agent.' } } },
74
+ annotations: { readOnlyHint: true, openWorldHint: false },
75
+ },
31
76
  {
32
77
  name: 'list_checks',
33
78
  title: 'List the checks crossexam would run',
@@ -38,6 +83,7 @@ const TOOLS = [
38
83
  ];
39
84
 
40
85
  export function startMcpServer({ version, defaultCwd = process.cwd() }) {
86
+ let client = 'unknown';
41
87
  const send = (msg) => process.stdout.write(JSON.stringify(msg) + '\n');
42
88
  const reply = (id, result) => send({ jsonrpc: '2.0', id, result });
43
89
  const fail = (id, code, message) => send({ jsonrpc: '2.0', id, error: { code, message } });
@@ -56,6 +102,7 @@ export function startMcpServer({ version, defaultCwd = process.cwd() }) {
56
102
  try {
57
103
  switch (method) {
58
104
  case 'initialize':
105
+ client = agentFromClient(params.clientInfo?.name);
59
106
  return reply(id, {
60
107
  protocolVersion: SUPPORTED.includes(params.protocolVersion) ? params.protocolVersion : SUPPORTED[0],
61
108
  capabilities: { tools: { listChanged: false } },
@@ -67,7 +114,7 @@ export function startMcpServer({ version, defaultCwd = process.cwd() }) {
67
114
  case 'tools/list':
68
115
  return reply(id, { tools: TOOLS });
69
116
  case 'tools/call':
70
- return reply(id, await callTool(params.name, params.arguments || {}, defaultCwd));
117
+ return reply(id, await callTool(params.name, params.arguments || {}, defaultCwd, client));
71
118
  default:
72
119
  if (isRequest) return fail(id, -32601, `Method not found: ${method}`);
73
120
  }
@@ -79,7 +126,10 @@ export function startMcpServer({ version, defaultCwd = process.cwd() }) {
79
126
  process.stderr.write(`crossexam MCP server ${version} ready (cwd ${defaultCwd})\n`);
80
127
  }
81
128
 
82
- async function callTool(name, args, defaultCwd) {
129
+ // Keep MCP calls well inside client timeouts; results are cached, so the agent can call again.
130
+ const MCP_LIMITS = { max: 15, budgetSeconds: 120 };
131
+
132
+ async function callTool(name, args, defaultCwd, client = 'unknown') {
83
133
  const cwd = path.resolve(typeof args.cwd === 'string' && args.cwd ? args.cwd : defaultCwd);
84
134
  if (name === 'list_checks') {
85
135
  const cmds = detectCommands(cwd);
@@ -91,7 +141,61 @@ async function callTool(name, args, defaultCwd) {
91
141
  return { isError: true, content: [{ type: 'text', text: 'summary is required: pass the completion message you are about to send.' }] };
92
142
  }
93
143
  const r = await verifyText(args.summary, { cwd });
94
- return { content: [{ type: 'text', text: formatForAgent(r) }], structuredContent: { ok: r.ok, results: r.results } };
144
+ if (args.mutate === true && (r.results.some((x) => x.kind === 'tests') || detectWorkClaims(args.summary).length)) {
145
+ const strength = await assessStrength({ cwd, ...MCP_LIMITS });
146
+ r.strength = strength;
147
+ for (const x of r.results) if (x.kind === 'tests') x.quality = qualityOf(strength);
148
+ ledger(ledgerRecord(strength, { agent: client, claim: args.summary.slice(0, 280), source: 'mcp' }));
149
+ }
150
+ const at = new Date().toISOString();
151
+ ledger(...r.results.map((x) => ({ type: 'verify', at, agent: client, repo: path.basename(cwd), source: 'mcp', kind: x.kind, verdict: x.verdict })));
152
+ const findings = findingsFrom({ verify: r, strength: r.strength });
153
+ const session = findings.length ? openSession({ findings, cwd, repo: r.strength?.repo, agent: client, source: 'mcp', testCommand: r.strength?.testCommand }) : null;
154
+ const text = formatForAgent(r) + (r.strength ? '\n\n' + formatStrengthForAgent(r.strength) : '') + (session ? '\n\n' + formatFindingsForAgent(session) : '');
155
+ return { content: [{ type: 'text', text }], structuredContent: { ok: r.ok, results: r.results, strength: r.strength ? qualityOf(r.strength) : undefined, session: session?.id ?? null, findings } };
156
+ }
157
+ if (name === 'assess_test_strength') {
158
+ const files = Array.isArray(args.files) ? args.files.filter((x) => typeof x === 'string') : undefined;
159
+ const max = Number.isFinite(args.max) ? Math.min(Math.max(1, args.max), 50) : MCP_LIMITS.max;
160
+ const strength = await assessStrength({ cwd, base: typeof args.base === 'string' ? args.base : undefined, files, max, budgetSeconds: MCP_LIMITS.budgetSeconds });
161
+ ledger(ledgerRecord(strength, { agent: client, source: 'mcp' }));
162
+ const findings = findingsFrom({ strength });
163
+ const session = findings.length ? openSession({ findings, cwd, repo: strength.repo, agent: client, source: 'mcp', testCommand: strength.testCommand }) : null;
164
+ const tail = session ? `\n\nFindings session ${session.id}: after adding tests, call reverify_findings with this session. Only that independent re-check closes a finding.` : '';
165
+ return {
166
+ content: [{ type: 'text', text: formatStrengthForAgent(strength) + tail }],
167
+ structuredContent: { quality: qualityOf(strength), summary: strength.summary, survivors: strength.mutants.filter((m) => m.status === STATUS.SURVIVED), session: session?.id ?? null, findings },
168
+ };
169
+ }
170
+ if (name === 'reverify_findings') {
171
+ if (typeof args.session !== 'string' || !args.session.trim()) return { isError: true, content: [{ type: 'text', text: 'session is required: pass the findings session id you were given.' }] };
172
+ let result;
173
+ try {
174
+ result = await reverify(args.session.trim(), { cwd: typeof args.cwd === 'string' && args.cwd ? args.cwd : undefined });
175
+ } catch (e) {
176
+ return { isError: true, content: [{ type: 'text', text: String(e?.message || e) }] };
177
+ }
178
+ const { session, summary, changes } = result;
179
+ ledger(reverifyRecord(session, summary));
180
+ const mark = { resolved: '✓ resolved', 'still-open': '✗ STILL OPEN', superseded: '○ superseded' };
181
+ const lines = changes.map((ch) => {
182
+ const f = session.findings.find((x) => x.id === ch.id);
183
+ const what = f.type === 'claim' ? `"${f.claim}"` : `${f.file}:${f.line} (${f.category} · ${f.operator})`;
184
+ return `${mark[ch.status]}: ${what}\n ${ch.evidence}`;
185
+ });
186
+ const open = session.findings.filter((f) => f.status === 'still-open' || f.status === 'open');
187
+ const head = summary.blocker
188
+ ? `The re-check could not run: ${summary.blocker}`
189
+ : open.length
190
+ ? `${open.length} finding${open.length === 1 ? ' is' : 's are'} still open. Keep working on them and call reverify_findings again; do not report them as fixed.`
191
+ : 'Every finding in this session is closed by an independent re-check. You may report them as fixed.';
192
+ return { content: [{ type: 'text', text: `Re-check ${summary.round} of session ${session.id}\n\n${head}\n\n${lines.join('\n\n')}` }], structuredContent: { session: session.id, ...summary, changes, open: open.map((f) => f.id) } };
193
+ }
194
+ if (name === 'agent_reliability') {
195
+ const days = Number.isFinite(args.days) ? Math.min(Math.max(1, args.days), 3650) : 90;
196
+ const r = reliability({ since: Date.now() - days * 86400000, agent: typeof args.agent === 'string' ? args.agent : undefined });
197
+ const text = r.agents.length ? r.agents.map((a) => `${a.agent}: ${describeAgent(a)}.`).join('\n') : 'No verification evidence recorded on this machine yet.';
198
+ return { content: [{ type: 'text', text: `Reliability over the last ${days} days, from recorded evidence (three separate measures, never blended):\n\n${text}` }], structuredContent: r };
95
199
  }
96
200
  return { isError: true, content: [{ type: 'text', text: `Unknown tool: ${name}` }] };
97
201
  }
@@ -101,9 +205,55 @@ export function formatForAgent(r) {
101
205
  return 'No checkable claims found in that summary. If you are saying tests, build, types or lint pass, say so explicitly; if you renamed something, name it in `backticks`.';
102
206
  }
103
207
  const mark = { verified: '✓ verified', contradicted: '✗ CONTRADICTED', review: '◇ needs review', stale: '◷ stale', unbacked: '○ unbacked' };
104
- const lines = r.results.map((x) => `${mark[x.verdict]}: "${x.claim}"\n ${x.reason.replace(/`/g, '')}${x.verdict === 'contradicted' && x.evidence?.excerpt ? `\n Output:\n${x.evidence.excerpt.split('\n').map((l) => ' ' + l).join('\n')}` : ''}`);
208
+ const lines = r.results.map((x) => `${mark[x.verdict]}: "${x.claim}"\n ${x.reason.replace(/`/g, '')}${x.quality ? `\n test strength: ${x.quality.rating}${x.quality.score != null ? ` (${Math.round(x.quality.score * 100)}% of planted defects caught)` : ''}. This is separate from the verdict above.` : ''}${x.verdict === 'contradicted' && x.evidence?.excerpt ? `\n Output:\n${x.evidence.excerpt.split('\n').map((l) => ' ' + l).join('\n')}` : ''}`);
105
209
  const head = r.ok
106
210
  ? 'No claim was contradicted. You may report these as checked.'
107
211
  : 'At least one claim is FALSE. Do not report the task as done: fix the problem and verify again, or correct your summary to say what is actually true.';
108
212
  return `${head}\n\n${lines.join('\n\n')}`;
109
213
  }
214
+
215
+ /** What an agent needs to act on: the gap, the exact surviving defects, and what to do next. */
216
+ export function formatStrengthForAgent(r) {
217
+ const s = r.summary;
218
+ const head = `Test strength: ${r.rating}${s.score != null ? ` (${s.killed} of ${s.killed + s.survived} planted defects caught)` : ''}. ${r.headline?.text ?? ''}`.trim();
219
+ const surv = r.mutants.filter((m) => m.status === STATUS.SURVIVED).slice(0, 10);
220
+ const lines = surv.map((m) => `- ${m.file}:${m.line} (${m.function || 'top level'}): changing\n ${m.before.split('\n')[0].trim()}\n to\n ${m.after.split('\n')[0].trim()}\n did not fail any test.`);
221
+ const next = surv.length
222
+ ? 'Add or strengthen tests so each of these changes would fail them, then call assess_test_strength again. Do not describe the tests as thorough until it reports strong.'
223
+ : r.blocker
224
+ ? ''
225
+ : 'The tests caught every planted defect in the changed code.';
226
+ const tail = [
227
+ r.remaining ? `${r.remaining} more mutants were not run in this call; call again to continue (finished ones are cached).` : '',
228
+ 'A mutation score measures how well tests pin down the changed code, not whether the code is correct. The working tree was not modified.',
229
+ ].filter(Boolean);
230
+ return [head, lines.join('\n'), next, ...tail].filter(Boolean).join('\n\n');
231
+ }
232
+
233
+ const CLIENTS = [
234
+ [/claude/i, 'claude-code'],
235
+ [/codex/i, 'codex'],
236
+ [/cursor/i, 'cursor'],
237
+ [/copilot|visual studio code|vscode/i, 'copilot'],
238
+ [/gemini/i, 'gemini'],
239
+ [/windsurf|codeium/i, 'windsurf'],
240
+ [/roo/i, 'roo-code'],
241
+ [/kilo/i, 'kilo-code'],
242
+ [/cline/i, 'cline'],
243
+ [/zed/i, 'zed'],
244
+ [/goose/i, 'goose'],
245
+ ];
246
+ function agentFromClient(name = '') {
247
+ for (const [re, id] of CLIENTS) if (re.test(name)) return id;
248
+ return name ? String(name).toLowerCase().slice(0, 40) : 'unknown';
249
+ }
250
+
251
+ function ledger(...recs) {
252
+ try {
253
+ const dir = (process.env.CROSSEXAM_HOME || path.join(os.homedir(), '.crossexam'));
254
+ fs.mkdirSync(dir, { recursive: true });
255
+ if (recs.length) fs.appendFileSync(path.join(dir, 'ledger.jsonl'), recs.map((r) => JSON.stringify(r)).join('\n') + '\n');
256
+ } catch {
257
+ /* history is best effort */
258
+ }
259
+ }