crossexamdev 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/mcp.js ADDED
@@ -0,0 +1,109 @@
1
+ // A Model Context Protocol server over stdio, so any MCP-capable agent
2
+ // (Claude Code, Cursor, Copilot, Codex, Gemini CLI, Windsurf, Cline, Zed,
3
+ // Goose…) can ask crossexam to check its summary before it says "done".
4
+ // Newline-delimited JSON-RPC 2.0, no dependencies. stdout is the protocol;
5
+ // anything human goes to stderr.
6
+
7
+ import path from 'node:path';
8
+ import readline from 'node:readline';
9
+ import { detectCommands, verifyText } from './live.js';
10
+
11
+ const SUPPORTED = ['2025-06-18', '2025-03-26', '2024-11-05'];
12
+
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.`;
14
+
15
+ const TOOLS = [
16
+ {
17
+ name: 'verify_claims',
18
+ title: 'Verify completion claims',
19
+ description:
20
+ 'Check what you are about to tell the user ("all tests pass", "build is clean", "renamed `foo` to `bar` everywhere", "bumped zod to 3.23.8") against the repository right now. Runs the project\'s own test/build/typecheck/lint commands and searches the code. Call this before reporting a task as done.',
21
+ inputSchema: {
22
+ type: 'object',
23
+ properties: {
24
+ summary: { type: 'string', description: 'The completion message you are about to send, verbatim.' },
25
+ cwd: { type: 'string', description: 'Absolute path of the workspace/repository root. Defaults to the server\'s working directory.' },
26
+ },
27
+ required: ['summary'],
28
+ },
29
+ annotations: { readOnlyHint: false, openWorldHint: false },
30
+ },
31
+ {
32
+ name: 'list_checks',
33
+ title: 'List the checks crossexam would run',
34
+ description: 'Show which test, build, typecheck, lint and migration-status commands crossexam found for a repository.',
35
+ inputSchema: { type: 'object', properties: { cwd: { type: 'string', description: 'Absolute path of the repository root.' } } },
36
+ annotations: { readOnlyHint: true, openWorldHint: false },
37
+ },
38
+ ];
39
+
40
+ export function startMcpServer({ version, defaultCwd = process.cwd() }) {
41
+ const send = (msg) => process.stdout.write(JSON.stringify(msg) + '\n');
42
+ const reply = (id, result) => send({ jsonrpc: '2.0', id, result });
43
+ const fail = (id, code, message) => send({ jsonrpc: '2.0', id, error: { code, message } });
44
+
45
+ const rl = readline.createInterface({ input: process.stdin, crlfDelay: Infinity });
46
+ rl.on('line', async (line) => {
47
+ if (!line.trim()) return;
48
+ let msg;
49
+ try {
50
+ msg = JSON.parse(line);
51
+ } catch {
52
+ return fail(null, -32700, 'Parse error');
53
+ }
54
+ const { id, method, params = {} } = msg;
55
+ const isRequest = id !== undefined && id !== null;
56
+ try {
57
+ switch (method) {
58
+ case 'initialize':
59
+ return reply(id, {
60
+ protocolVersion: SUPPORTED.includes(params.protocolVersion) ? params.protocolVersion : SUPPORTED[0],
61
+ capabilities: { tools: { listChanged: false } },
62
+ serverInfo: { name: 'crossexam', title: 'crossexam', version },
63
+ instructions: INSTRUCTIONS,
64
+ });
65
+ case 'ping':
66
+ return reply(id, {});
67
+ case 'tools/list':
68
+ return reply(id, { tools: TOOLS });
69
+ case 'tools/call':
70
+ return reply(id, await callTool(params.name, params.arguments || {}, defaultCwd));
71
+ default:
72
+ if (isRequest) return fail(id, -32601, `Method not found: ${method}`);
73
+ }
74
+ } catch (e) {
75
+ if (isRequest) fail(id, -32603, String(e?.message || e));
76
+ }
77
+ });
78
+ rl.on('close', () => process.exit(0));
79
+ process.stderr.write(`crossexam MCP server ${version} ready (cwd ${defaultCwd})\n`);
80
+ }
81
+
82
+ async function callTool(name, args, defaultCwd) {
83
+ const cwd = path.resolve(typeof args.cwd === 'string' && args.cwd ? args.cwd : defaultCwd);
84
+ if (name === 'list_checks') {
85
+ const cmds = detectCommands(cwd);
86
+ const lines = ['tests', 'build', 'types', 'lint', 'migration'].map((k) => `${k.padEnd(9)} ${cmds[k] ? `${cmds[k].command} (from ${cmds[k].source})` : '—'}`);
87
+ return { content: [{ type: 'text', text: `Checks for ${cwd}\n\n${lines.join('\n')}` }], structuredContent: { cwd, commands: cmds } };
88
+ }
89
+ if (name === 'verify_claims') {
90
+ if (typeof args.summary !== 'string' || !args.summary.trim()) {
91
+ return { isError: true, content: [{ type: 'text', text: 'summary is required: pass the completion message you are about to send.' }] };
92
+ }
93
+ const r = await verifyText(args.summary, { cwd });
94
+ return { content: [{ type: 'text', text: formatForAgent(r) }], structuredContent: { ok: r.ok, results: r.results } };
95
+ }
96
+ return { isError: true, content: [{ type: 'text', text: `Unknown tool: ${name}` }] };
97
+ }
98
+
99
+ export function formatForAgent(r) {
100
+ if (!r.results.length) {
101
+ 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
+ }
103
+ 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')}` : ''}`);
105
+ const head = r.ok
106
+ ? 'No claim was contradicted. You may report these as checked.'
107
+ : '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
+ return `${head}\n\n${lines.join('\n\n')}`;
109
+ }
package/src/readers.js ADDED
@@ -0,0 +1,297 @@
1
+ // More transcript readers, each normalised into the same Session shape as
2
+ // transcripts.js. Formats are the agents' own on-disk logs:
3
+ //
4
+ // gemini ~/.gemini/tmp/<project>/chats/session-*.json
5
+ // cline <editor>/User/globalStorage/<extension>/tasks/<id>/ui_messages.json
6
+ // (Cline, Roo Code and Kilo Code share the format; any VS Code-family editor)
7
+ // aider <repo>/.aider.chat.history.md
8
+ // open the crossexam open format (docs/transcript-format.md): one JSON
9
+ // event per line, for any agent or framework that wants in
10
+
11
+ import fs from 'node:fs';
12
+ import os from 'node:os';
13
+ import path from 'node:path';
14
+ import { repoOf } from './transcripts.js';
15
+
16
+ const newSession = (agent, file, id) => ({ agent, id, file, cwd: '', repo: '', model: '', startedAt: '', turns: [] });
17
+ const pushTurn = (s, prompt, at) => {
18
+ const t = { index: s.turns.length, prompt: String(prompt || '').slice(0, 400), at, model: s.model, items: [] };
19
+ s.turns.push(t);
20
+ return t;
21
+ };
22
+ const lastTurn = (s, at) => s.turns.at(-1) ?? pushTurn(s, '', at);
23
+
24
+ // ---------------------------------------------------------------- discovery
25
+
26
+ /** VS Code-family editors' per-user storage roots on this OS. */
27
+ function editorRoots(home = os.homedir()) {
28
+ const editors = ['Code', 'Code - Insiders', 'Cursor', 'Windsurf', 'VSCodium', 'Trae', 'Kiro'];
29
+ const base =
30
+ process.platform === 'win32' ? process.env.APPDATA || path.join(home, 'AppData', 'Roaming') : process.platform === 'darwin' ? path.join(home, 'Library', 'Application Support') : process.env.XDG_CONFIG_HOME || path.join(home, '.config');
31
+ return editors.map((e) => ({ editor: e, dir: path.join(base, e, 'User', 'globalStorage') }));
32
+ }
33
+
34
+ const CLINE_FAMILY = [
35
+ ['saoudrizwan.claude-dev', 'cline'],
36
+ ['rooveterinaryinc.roo-cline', 'roo-code'],
37
+ ['kilocode.kilo-code', 'kilo-code'],
38
+ ];
39
+
40
+ export function discoverMore(sinceMs = 0, home = os.homedir()) {
41
+ const out = [];
42
+ const fresh = (p) => {
43
+ try {
44
+ return fs.statSync(p).mtimeMs >= sinceMs;
45
+ } catch {
46
+ return false;
47
+ }
48
+ };
49
+ // Gemini CLI
50
+ const gem = path.join(home, '.gemini', 'tmp');
51
+ if (fs.existsSync(gem)) {
52
+ for (const proj of safeDir(gem)) {
53
+ const chats = path.join(gem, proj, 'chats');
54
+ for (const f of safeDir(chats)) if (f.endsWith('.json') && fresh(path.join(chats, f))) out.push({ agent: 'gemini', file: path.join(chats, f) });
55
+ }
56
+ }
57
+ // Cline / Roo / Kilo in any VS Code-family editor
58
+ for (const { dir } of editorRoots(home)) {
59
+ for (const [ext, agent] of CLINE_FAMILY) {
60
+ const tasks = path.join(dir, ext, 'tasks');
61
+ for (const id of safeDir(tasks)) {
62
+ const f = path.join(tasks, id, 'ui_messages.json');
63
+ if (fs.existsSync(f) && fresh(f)) out.push({ agent, file: f });
64
+ }
65
+ }
66
+ }
67
+ // Open-format transcripts dropped into ~/.crossexam/transcripts by any tool
68
+ const open = path.join(home, '.crossexam', 'transcripts');
69
+ for (const f of safeDir(open)) if (f.endsWith('.jsonl') && fresh(path.join(open, f))) out.push({ agent: 'open', file: path.join(open, f) });
70
+ return out;
71
+ }
72
+
73
+ /** Aider keeps history in the repo, not in a home directory. */
74
+ export function discoverAider(dirs, sinceMs = 0) {
75
+ return dirs.map((d) => path.join(d, '.aider.chat.history.md')).filter((f) => fs.existsSync(f) && fs.statSync(f).mtimeMs >= sinceMs).map((file) => ({ agent: 'aider', file }));
76
+ }
77
+
78
+ function safeDir(d) {
79
+ try {
80
+ return fs.readdirSync(d);
81
+ } catch {
82
+ return [];
83
+ }
84
+ }
85
+
86
+ // ---------------------------------------------------------------- Gemini CLI
87
+
88
+ const GEMINI_EDITS = new Set(['replace', 'write_file', 'edit', 'smart_edit', 'write_new_file']);
89
+ const GEMINI_SEARCH = new Set(['search_file_content', 'grep', 'glob']);
90
+
91
+ export function readGeminiSession(file) {
92
+ const j = JSON.parse(fs.readFileSync(file, 'utf8'));
93
+ const s = newSession('gemini', file, j.sessionId || path.basename(file, '.json'));
94
+ s.startedAt = j.startTime || '';
95
+ for (const m of j.messages || []) {
96
+ const text = typeof m.content === 'string' ? m.content : Array.isArray(m.content) ? m.content.map((p) => p.text || '').join('') : '';
97
+ if (m.type === 'user') {
98
+ if (text.trim() && !text.startsWith('/')) pushTurn(s, text, m.timestamp);
99
+ continue;
100
+ }
101
+ if (m.type !== 'gemini') continue;
102
+ const t = lastTurn(s, m.timestamp);
103
+ if (m.model) t.model = s.model = m.model;
104
+ if (text.trim()) t.items.push({ kind: 'text', text, at: m.timestamp });
105
+ for (const tc of m.toolCalls || []) {
106
+ const args = tc.args || {};
107
+ const output = geminiOutput(tc);
108
+ const ev = { kind: 'tool', id: tc.id, name: tc.name, command: undefined, file: args.file_path || args.absolute_path, output, isError: tc.status === 'error', exitCode: null, denied: tc.status === 'cancelled', at: tc.timestamp || m.timestamp };
109
+ if (tc.name === 'run_shell_command') {
110
+ ev.command = args.command;
111
+ const dir = output.match(/^Directory:\s*(.+)$/m)?.[1];
112
+ if (dir && !s.cwd && !/\(root\)/.test(dir)) s.cwd = dir.trim();
113
+ const code = output.match(/^Exit Code:\s*(-?\d+)/m);
114
+ ev.exitCode = code ? Number(code[1]) : /^Error:\s*(?!\(none\))\S/m.test(output) ? 1 : tc.status === 'success' ? 0 : null;
115
+ } else if (GEMINI_EDITS.has(tc.name)) {
116
+ ev.name = 'Edit';
117
+ } else if (GEMINI_SEARCH.has(tc.name)) {
118
+ ev.name = 'Grep';
119
+ ev.command = `grep ${args.pattern ?? ''}`;
120
+ }
121
+ t.items.push(ev);
122
+ }
123
+ }
124
+ if (!s.cwd && j.projectHash) s.repo = `gemini:${String(j.projectHash).slice(0, 8)}`;
125
+ else s.repo = repoOf(s.cwd);
126
+ return s;
127
+ }
128
+
129
+ function geminiOutput(tc) {
130
+ const r = tc.result;
131
+ if (Array.isArray(r)) {
132
+ return r
133
+ .map((x) => {
134
+ const resp = x?.functionResponse?.response;
135
+ return typeof resp?.output === 'string' ? resp.output : resp?.error || (resp ? JSON.stringify(resp) : '');
136
+ })
137
+ .join('\n');
138
+ }
139
+ if (typeof tc.resultDisplay === 'string') return tc.resultDisplay;
140
+ return typeof r === 'string' ? r : '';
141
+ }
142
+
143
+ // ---------------------------------------------------------------- Cline / Roo / Kilo
144
+
145
+ const CLINE_EDIT_TOOLS = new Set(['editedExistingFile', 'newFileCreated', 'appliedDiff', 'insertContent', 'searchAndReplace', 'fileDeleted']);
146
+
147
+ export function readClineSession(file, agent = 'cline') {
148
+ const msgs = JSON.parse(fs.readFileSync(file, 'utf8'));
149
+ const s = newSession(agent, file, path.basename(path.dirname(file)));
150
+ // The API history carries the workspace path in its environment details.
151
+ try {
152
+ const api = fs.readFileSync(path.join(path.dirname(file), 'api_conversation_history.json'), 'utf8');
153
+ const cwd = api.match(/Current Working Directory \(([^)]+)\)/)?.[1];
154
+ if (cwd) s.cwd = cwd.replace(/\\\\/g, '\\');
155
+ } catch {}
156
+ let lastCmd = null;
157
+ for (const m of Array.isArray(msgs) ? msgs : []) {
158
+ const at = m.ts ? new Date(m.ts).toISOString() : '';
159
+ if (!s.startedAt && at) s.startedAt = at;
160
+ const kind = m.type === 'say' ? m.say : m.ask;
161
+ const text = m.text || '';
162
+ if (kind === 'task' || kind === 'user_feedback') {
163
+ pushTurn(s, text, at);
164
+ lastCmd = null;
165
+ } else if (kind === 'command') {
166
+ // Commands needing approval arrive as ask, auto-approved ones as say; don't double count.
167
+ if (lastCmd && lastCmd.command === text && !lastCmd.output) continue;
168
+ lastCmd = { kind: 'tool', id: String(m.ts), name: 'execute_command', command: text.replace(/\s*COMMAND_OUTPUT_STRING[\s\S]*$/, ''), output: '', isError: false, exitCode: null, denied: false, at };
169
+ lastTurn(s, at).items.push(lastCmd);
170
+ } else if (kind === 'command_output') {
171
+ if (lastCmd) {
172
+ lastCmd.output += text;
173
+ const code = text.match(/exit(?:ed)? (?:with )?code:?\s*(-?\d+)/i);
174
+ if (code) lastCmd.exitCode = Number(code[1]);
175
+ }
176
+ } else if (kind === 'tool') {
177
+ let tool = {};
178
+ try {
179
+ tool = JSON.parse(text);
180
+ } catch {}
181
+ if (CLINE_EDIT_TOOLS.has(tool.tool)) lastTurn(s, at).items.push({ kind: 'tool', id: String(m.ts), name: 'Edit', file: tool.path, output: '', isError: false, exitCode: null, denied: false, at });
182
+ if (tool.tool === 'searchFiles') lastTurn(s, at).items.push({ kind: 'tool', id: String(m.ts), name: 'Grep', command: `grep ${tool.regex ?? ''}`, output: tool.content || '', isError: false, exitCode: null, denied: false, at });
183
+ } else if ((kind === 'text' || kind === 'completion_result') && text.trim() && m.type === 'say') {
184
+ lastTurn(s, at).items.push({ kind: 'text', text, at });
185
+ } else if (kind === 'api_req_started') {
186
+ try {
187
+ const info = JSON.parse(text);
188
+ if (info.model) s.model = lastTurn(s, at).model = info.model;
189
+ } catch {}
190
+ }
191
+ }
192
+ s.repo = repoOf(s.cwd);
193
+ return s;
194
+ }
195
+
196
+ // ---------------------------------------------------------------- Aider
197
+
198
+ export function readAiderSession(file) {
199
+ const s = newSession('aider', file, 'aider-' + path.basename(path.dirname(file)));
200
+ s.cwd = path.dirname(file);
201
+ s.repo = repoOf(s.cwd);
202
+ let at = '';
203
+ let text = [];
204
+ let cmd = null;
205
+ const flushText = () => {
206
+ const t = text.join('\n').trim();
207
+ if (t) lastTurn(s, at).items.push({ kind: 'text', text: t, at });
208
+ text = [];
209
+ };
210
+ const startCmd = (command) => {
211
+ flushText();
212
+ cmd = { kind: 'tool', id: `${s.turns.length}:${command}`, name: 'run', command, output: '', isError: false, exitCode: null, denied: false, at };
213
+ lastTurn(s, at).items.push(cmd);
214
+ };
215
+ for (const line of fs.readFileSync(file, 'utf8').split(/\r?\n/)) {
216
+ const started = line.match(/^# aider chat started at (.+)$/);
217
+ if (started) {
218
+ flushText();
219
+ const d = new Date(started[1].replace(' ', 'T'));
220
+ at = Number.isNaN(d.getTime()) ? '' : d.toISOString();
221
+ if (!s.startedAt) s.startedAt = at;
222
+ cmd = null;
223
+ continue;
224
+ }
225
+ const user = line.match(/^#### (.*)$/);
226
+ if (user) {
227
+ flushText();
228
+ const u = user[1];
229
+ const run = u.match(/^\/(?:run|test|lint)\s+(.+)$/) || u.match(/^!\s*(.+)$/);
230
+ if (run) {
231
+ startCmd(run[1]);
232
+ continue;
233
+ }
234
+ pushTurn(s, u, at);
235
+ cmd = null;
236
+ continue;
237
+ }
238
+ if (line.startsWith('> ') || line === '>') {
239
+ const q = line.slice(2);
240
+ const running = q.match(/^Running (.+)$/);
241
+ const edited = q.match(/^Applied edit to (.+)$/);
242
+ if (running) startCmd(running[1]);
243
+ else if (edited) {
244
+ flushText();
245
+ lastTurn(s, at).items.push({ kind: 'tool', id: `${s.turns.length}:edit:${edited[1]}`, name: 'Edit', file: edited[1], output: '', isError: false, exitCode: null, denied: false, at });
246
+ cmd = null;
247
+ } else if (cmd && !/^(Add command output to the chat|Tokens:|Commit [0-9a-f]{7}|Added \d+ lines? of output)/.test(q)) cmd.output += q + '\n';
248
+ continue;
249
+ }
250
+ // Aider puts a blank line between a command and its quoted output.
251
+ if (line.trim()) cmd = null;
252
+ text.push(line);
253
+ }
254
+ flushText();
255
+ return s;
256
+ }
257
+
258
+ // ---------------------------------------------------------------- open format
259
+
260
+ /**
261
+ * {"type":"session","agent":"my-agent","model":"x","cwd":"/repo"}
262
+ * {"type":"prompt","text":"fix the bug"}
263
+ * {"type":"command","command":"npm test","exit_code":1,"output":"..."}
264
+ * {"type":"edit","path":"src/a.ts"}
265
+ * {"type":"search","pattern":"getUserById","output":""}
266
+ * {"type":"message","text":"All tests pass."}
267
+ */
268
+ export function readOpenSession(file) {
269
+ const s = newSession('open', file, path.basename(file, '.jsonl'));
270
+ let n = 0;
271
+ for (const line of fs.readFileSync(file, 'utf8').split(/\r?\n/)) {
272
+ if (!line.trim()) continue;
273
+ let e;
274
+ try {
275
+ e = JSON.parse(line);
276
+ } catch {
277
+ continue;
278
+ }
279
+ const at = e.at || e.timestamp || '';
280
+ if (!s.startedAt && at) s.startedAt = at;
281
+ if (e.type === 'session') {
282
+ if (e.agent) s.agent = String(e.agent);
283
+ if (e.model) s.model = String(e.model);
284
+ if (e.cwd) s.cwd = String(e.cwd);
285
+ if (e.id) s.id = String(e.id);
286
+ } else if (e.type === 'prompt') pushTurn(s, e.text, at);
287
+ else if (e.type === 'message') lastTurn(s, at).items.push({ kind: 'text', text: String(e.text || ''), at });
288
+ else if (e.type === 'command') {
289
+ const code = e.exit_code ?? e.exitCode;
290
+ lastTurn(s, at).items.push({ kind: 'tool', id: String(++n), name: 'command', command: String(e.command || ''), output: String(e.output || ''), isError: code != null && code !== 0, exitCode: code ?? null, denied: !!e.denied, at });
291
+ } else if (e.type === 'edit') lastTurn(s, at).items.push({ kind: 'tool', id: String(++n), name: 'Edit', file: e.path, output: '', isError: false, exitCode: null, denied: false, at });
292
+ else if (e.type === 'search') lastTurn(s, at).items.push({ kind: 'tool', id: String(++n), name: 'Grep', command: `grep ${e.pattern ?? ''}`, output: String(e.output || ''), isError: false, exitCode: e.exit_code ?? null, denied: false, at });
293
+ if (e.model && s.turns.length) s.turns.at(-1).model = String(e.model);
294
+ }
295
+ s.repo = repoOf(s.cwd);
296
+ return s;
297
+ }
package/src/report.js ADDED
@@ -0,0 +1,99 @@
1
+ // Aggregate claims into a reliability report and print it for humans.
2
+
3
+ export const VERDICTS = ['verified', 'contradicted', 'stale', 'unbacked', 'review'];
4
+
5
+ export function buildReport(claims, meta = {}) {
6
+ const tally = (key) => {
7
+ const m = {};
8
+ for (const c of claims) {
9
+ const k = typeof key === 'function' ? key(c) : c[key];
10
+ m[k] ??= { claims: 0, verified: 0, contradicted: 0, stale: 0, unbacked: 0, review: 0 };
11
+ m[k].claims++;
12
+ m[k][c.verdict]++;
13
+ }
14
+ for (const v of Object.values(m)) Object.assign(v, rates(v));
15
+ return m;
16
+ };
17
+ const totals = tally(() => 'all').all ?? { claims: 0, ...rates({}) };
18
+ return {
19
+ version: 1,
20
+ generatedAt: new Date().toISOString(),
21
+ ...meta,
22
+ totals,
23
+ byAgent: tally('agent'),
24
+ byModel: tally('model'),
25
+ byRepo: tally('repo'),
26
+ byKind: tally('kind'),
27
+ byTaskType: tally('taskType'),
28
+ matrix: tally((c) => `${c.agent}|${c.kind}`),
29
+ claims: claims.sort((a, b) => String(b.at).localeCompare(String(a.at))),
30
+ };
31
+ }
32
+
33
+ function rates(v) {
34
+ const checked = (v.verified || 0) + (v.contradicted || 0) + (v.stale || 0);
35
+ const settled = checked + (v.unbacked || 0);
36
+ return {
37
+ // Of claims that had a check behind them, how many were false or out of date.
38
+ falseDoneRate: checked ? round(((v.contradicted || 0) + (v.stale || 0)) / checked) : 0,
39
+ // Of all settled claims, how many were backed by a passing check.
40
+ trustRate: settled ? round((v.verified || 0) / settled) : 0,
41
+ };
42
+ }
43
+
44
+ const round = (n) => Math.round(n * 1000) / 1000;
45
+
46
+ // ---------- terminal output ----------
47
+
48
+ const tty = process.stdout.isTTY && !process.env.NO_COLOR;
49
+ const paint = (code) => (s) => (tty ? `\x1b[${code}m${s}\x1b[0m` : String(s));
50
+ export const c = { dim: paint('2'), bold: paint('1'), red: paint('31'), green: paint('32'), yellow: paint('33'), blue: paint('34'), gray: paint('90') };
51
+
52
+ const MARK = { verified: c.green('✓ verified'), contradicted: c.red('✗ contradicted'), stale: c.yellow('◷ stale'), unbacked: c.gray('○ unbacked'), review: c.blue('◇ review') };
53
+
54
+ export function printReport(r, { limit = 8 } = {}) {
55
+ const t = r.totals;
56
+ const line = (s = '') => process.stdout.write(s + '\n');
57
+ line();
58
+ line(` ${c.bold('crossexam')} ${c.dim('· cross-examined ' + r.sessions + ' sessions, ' + r.turns + ' turns')}`);
59
+ line();
60
+ if (!t.claims) {
61
+ line(c.dim(' No completion claims found. Agents that never say "done" are hard to catch lying.'));
62
+ line();
63
+ return;
64
+ }
65
+ line(` ${pad(t.claims, 5)} claims ${c.green(pad(t.verified, 4))} verified ${c.red(pad(t.contradicted, 4))} contradicted ${c.yellow(pad(t.stale, 4))} stale ${c.gray(pad(t.unbacked, 4))} unbacked ${c.blue(pad(t.review, 4))} review`);
66
+ line();
67
+ line(` ${c.bold(pct(t.falseDoneRate))} of checked claims were false or stale ${c.dim('(contradicted + stale) / (verified + contradicted + stale)')}`);
68
+ if (r.ranCheckTurns) line(` ${c.bold(r.contradictedTurns + ' of ' + r.ranCheckTurns)} turns that ran a check ended with a contradicted claim ${c.dim('(' + pct(r.contradictedTurns / r.ranCheckTurns) + ')')}`);
69
+ line();
70
+
71
+ const table = (title, m) => {
72
+ const rows = Object.entries(m).sort((a, b) => b[1].claims - a[1].claims).slice(0, 6);
73
+ if (!rows.length) return;
74
+ line(c.dim(` ${title.padEnd(26)} claims trust false-done`));
75
+ for (const [k, v] of rows) line(` ${k.slice(0, 26).padEnd(26)} ${pad(v.claims, 6)} ${pad(pct(v.trustRate), 5)} ${v.falseDoneRate > 0.1 ? c.red(pad(pct(v.falseDoneRate), 5)) : pad(pct(v.falseDoneRate), 5)}`);
76
+ line();
77
+ };
78
+ table('by agent', r.byAgent);
79
+ table('by model', r.byModel);
80
+ table('by claim', r.byKind);
81
+ table('by repo', r.byRepo);
82
+
83
+ const bad = r.claims.filter((x) => x.verdict === 'contradicted' || x.verdict === 'stale').slice(0, limit);
84
+ if (bad.length) {
85
+ line(c.bold(' Most recent false "done"s'));
86
+ line();
87
+ for (const x of bad) printClaim(x, line);
88
+ }
89
+ }
90
+
91
+ export function printClaim(x, line = (s = '') => process.stdout.write(s + '\n')) {
92
+ line(` ${MARK[x.verdict]} ${c.dim(x.repo + ' · ' + x.agent + ' · ' + (x.at || '').slice(0, 10))}`);
93
+ line(` “${x.claim.length > 140 ? x.claim.slice(0, 137) + '…' : x.claim}”`);
94
+ line(` ${c.dim('→ ' + x.reason)}`);
95
+ line();
96
+ }
97
+
98
+ const pad = (v, n) => String(v).padStart(n);
99
+ const pct = (n) => `${(n * 100).toFixed(n && n < 0.1 ? 1 : 0)}%`;