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.
@@ -0,0 +1,230 @@
1
+ // Readers for agent transcripts. Each agent writes its own format; all of
2
+ // them are normalised into the same Session shape so the verifier stays
3
+ // neutral about who did the work.
4
+ //
5
+ // Session = { agent, id, file, cwd, repo, model, startedAt, turns: Turn[] }
6
+ // Turn = { index, prompt, at, model, items: Item[] }
7
+ // Item = { kind: 'text', text, at } | { kind: 'tool', id, name, command, output, isError, exitCode, denied, at }
8
+
9
+ import fs from 'node:fs';
10
+ import os from 'node:os';
11
+ import path from 'node:path';
12
+ import readline from 'node:readline';
13
+ import { readAiderSession, readClineSession, readGeminiSession, readOpenSession } from './readers.js';
14
+
15
+ export function defaultSources(home = os.homedir()) {
16
+ return [
17
+ { agent: 'claude-code', root: path.join(process.env.CLAUDE_CONFIG_DIR || path.join(home, '.claude'), 'projects') },
18
+ { agent: 'codex', root: path.join(process.env.CODEX_HOME || path.join(home, '.codex'), 'sessions') },
19
+ ];
20
+ }
21
+
22
+ export function findTranscripts(root, sinceMs = 0) {
23
+ const out = [];
24
+ if (!fs.existsSync(root)) return out;
25
+ const walk = (dir, depth) => {
26
+ for (const ent of fs.readdirSync(dir, { withFileTypes: true })) {
27
+ const p = path.join(dir, ent.name);
28
+ if (ent.isDirectory()) {
29
+ // Claude Code keeps subagent runs under <session>/subagents; their claims
30
+ // are checked by the parent turn that reports them.
31
+ if (depth < 5 && ent.name !== 'subagents' && ent.name !== 'tool-results') walk(p, depth + 1);
32
+ } else if (ent.name.endsWith('.jsonl')) {
33
+ const st = fs.statSync(p);
34
+ if (st.mtimeMs >= sinceMs) out.push(p);
35
+ }
36
+ }
37
+ };
38
+ walk(root, 0);
39
+ return out;
40
+ }
41
+
42
+ async function* lines(file) {
43
+ const rl = readline.createInterface({ input: fs.createReadStream(file, 'utf8'), crlfDelay: Infinity });
44
+ for await (const line of rl) {
45
+ if (!line) continue;
46
+ try {
47
+ yield JSON.parse(line);
48
+ } catch {
49
+ /* torn final line while the agent is still writing */
50
+ }
51
+ }
52
+ }
53
+
54
+ export function repoOf(cwd = '') {
55
+ const norm = cwd.replace(/\\/g, '/').replace(/\/\.claude\/worktrees\/[^/]+.*$/, '').replace(/\/+$/, '');
56
+ return norm.split('/').pop() || 'unknown';
57
+ }
58
+
59
+ const DENIED = /doesn't want to proceed|was rejected|permission to use .* (?:was )?denied|requires approval|tool use was rejected/i;
60
+
61
+ function textOf(content) {
62
+ if (typeof content === 'string') return content;
63
+ if (Array.isArray(content)) return content.map((c) => (typeof c === 'string' ? c : c.text || '')).join('\n');
64
+ return '';
65
+ }
66
+
67
+ function commandOf(name, input = {}) {
68
+ if (typeof input.command === 'string') return input.command;
69
+ if (Array.isArray(input.command)) return input.command.join(' ');
70
+ if (name === 'Grep') return `grep ${input.pattern ?? ''} ${input.path ?? ''}`.trim();
71
+ if (name === 'Glob') return `glob ${input.pattern ?? ''}`;
72
+ return undefined;
73
+ }
74
+
75
+ /** Claude Code: ~/.claude/projects/<project>/<session>.jsonl */
76
+ export async function readClaudeSession(file) {
77
+ const s = { agent: 'claude-code', id: path.basename(file, '.jsonl'), file, cwd: '', repo: '', model: '', startedAt: '', turns: [] };
78
+ const byId = new Map();
79
+ let turn = null;
80
+ const newTurn = (prompt, at) => {
81
+ turn = { index: s.turns.length, prompt: prompt.slice(0, 400), at, model: '', items: [] };
82
+ s.turns.push(turn);
83
+ };
84
+
85
+ for await (const o of lines(file)) {
86
+ if (o.isSidechain) continue;
87
+ if (o.cwd && !s.cwd) s.cwd = o.cwd;
88
+ if (o.timestamp && !s.startedAt) s.startedAt = o.timestamp;
89
+ const msg = o.message;
90
+ if (o.type === 'user' && msg) {
91
+ const blocks = Array.isArray(msg.content) ? msg.content : null;
92
+ const results = blocks?.filter((b) => b.type === 'tool_result') ?? [];
93
+ if (results.length) {
94
+ for (const r of results) {
95
+ const ev = byId.get(r.tool_use_id);
96
+ if (!ev) continue;
97
+ const out = textOf(r.content);
98
+ ev.output = out.length > 20000 ? out.slice(0, 4000) + '\n…\n' + out.slice(-12000) : out;
99
+ ev.isError = !!r.is_error;
100
+ const code = out.match(/^Exit code (-?\d+)/);
101
+ // Claude Code's shell tools only flag an error on a non-zero exit.
102
+ ev.exitCode = code ? Number(code[1]) : ev.isError ? null : ev.command ? 0 : null;
103
+ ev.denied = ev.isError && DENIED.test(out.slice(0, 300));
104
+ }
105
+ } else if (!o.isMeta) {
106
+ const prompt = textOf(msg.content);
107
+ if (prompt.trim()) newTurn(prompt, o.timestamp);
108
+ }
109
+ } else if (o.type === 'assistant' && msg && Array.isArray(msg.content)) {
110
+ if (!turn) newTurn('', o.timestamp);
111
+ if (msg.model && msg.model !== '<synthetic>') {
112
+ turn.model = msg.model;
113
+ s.model = msg.model;
114
+ }
115
+ for (const b of msg.content) {
116
+ if (b.type === 'text' && b.text?.trim()) turn.items.push({ kind: 'text', text: b.text, at: o.timestamp });
117
+ if (b.type === 'tool_use') {
118
+ const ev = { kind: 'tool', id: b.id, name: b.name, command: commandOf(b.name, b.input), file: b.input?.file_path || b.input?.notebook_path, output: '', isError: false, exitCode: null, denied: false, at: o.timestamp };
119
+ byId.set(b.id, ev);
120
+ turn.items.push(ev);
121
+ }
122
+ }
123
+ }
124
+ }
125
+ s.repo = repoOf(s.cwd);
126
+ return s;
127
+ }
128
+
129
+ /** Codex CLI: ~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl (wrapped and legacy rows). */
130
+ export async function readCodexSession(file) {
131
+ const s = { agent: 'codex', id: path.basename(file, '.jsonl'), file, cwd: '', repo: '', model: '', startedAt: '', turns: [] };
132
+ const byId = new Map();
133
+ let turn = null;
134
+ const newTurn = (prompt, at) => {
135
+ turn = { index: s.turns.length, prompt: prompt.slice(0, 400), at, model: s.model, items: [] };
136
+ s.turns.push(turn);
137
+ };
138
+
139
+ for await (const o of lines(file)) {
140
+ const at = o.timestamp;
141
+ if (at && !s.startedAt) s.startedAt = at;
142
+ const p = o.payload ?? o;
143
+ if (o.type === 'turn_context') {
144
+ if (p.model) s.model = p.model;
145
+ if (turn && p.model) turn.model = p.model;
146
+ s.cwd ||= p.cwd || '';
147
+ continue;
148
+ }
149
+ if (o.type === 'session_meta' || (p.cwd && !p.type)) {
150
+ s.cwd ||= p.cwd || '';
151
+ s.id = p.id || s.id;
152
+ continue;
153
+ }
154
+ if (p.type === 'message') {
155
+ const text = textOf(p.content);
156
+ if (p.role === 'user') {
157
+ if (/^\s*<(environment_context|user_instructions|permissions)/.test(text)) continue;
158
+ if (text.trim()) newTurn(text, at);
159
+ } else if (p.role === 'assistant' && text.trim()) {
160
+ if (!turn) newTurn('', at);
161
+ turn.items.push({ kind: 'text', text, at });
162
+ }
163
+ } else if (p.type === 'function_call' || p.type === 'local_shell_call' || p.type === 'custom_tool_call') {
164
+ if (!turn) newTurn('', at);
165
+ let args = {};
166
+ try {
167
+ args = typeof p.arguments === 'string' ? JSON.parse(p.arguments) : p.arguments || p.action || {};
168
+ } catch {
169
+ args = {};
170
+ }
171
+ if (p.action?.command) args = p.action;
172
+ const cmd = Array.isArray(args.command) ? unwrapShell(args.command) : args.command || args.cmd;
173
+ const name = p.name === 'apply_patch' || (typeof p.input === 'string' && p.input.includes('*** Begin Patch')) ? 'apply_patch' : p.name || 'shell';
174
+ const ev = { kind: 'tool', id: p.call_id || p.id, name, command: name === 'apply_patch' ? undefined : cmd, output: '', isError: false, exitCode: null, denied: false, at };
175
+ byId.set(ev.id, ev);
176
+ turn.items.push(ev);
177
+ } else if (p.type === 'function_call_output' || p.type === 'local_shell_call_output' || p.type === 'custom_tool_call_output') {
178
+ const ev = byId.get(p.call_id);
179
+ if (!ev) continue;
180
+ let out = p.output;
181
+ let code = null;
182
+ if (typeof out === 'string') {
183
+ try {
184
+ const j = JSON.parse(out);
185
+ out = j.output ?? out;
186
+ code = j.metadata?.exit_code ?? null;
187
+ } catch {
188
+ const m = out.match(/Exit code:\s*(-?\d+)/i);
189
+ if (m) code = Number(m[1]);
190
+ }
191
+ } else if (out && typeof out === 'object') {
192
+ code = out.metadata?.exit_code ?? null;
193
+ out = out.output ?? out.content ?? '';
194
+ }
195
+ ev.output = String(out ?? '');
196
+ ev.exitCode = code;
197
+ ev.isError = code != null && code !== 0;
198
+ ev.denied = DENIED.test(ev.output.slice(0, 300));
199
+ }
200
+ }
201
+ s.repo = repoOf(s.cwd);
202
+ return s;
203
+ }
204
+
205
+ function unwrapShell(argv) {
206
+ // ["bash","-lc","npm test"] -> "npm test"
207
+ if (argv.length >= 3 && /(?:ba|z)?sh$|pwsh|powershell/i.test(argv[0]) && /^-l?c$|^-Command$/i.test(argv[1])) return argv.slice(2).join(' ');
208
+ return argv.join(' ');
209
+ }
210
+
211
+ export const AGENTS = ['claude-code', 'codex', 'gemini', 'cline', 'roo-code', 'kilo-code', 'aider', 'open'];
212
+
213
+ export async function readSession(agent, file) {
214
+ switch (agent) {
215
+ case 'codex':
216
+ return readCodexSession(file);
217
+ case 'gemini':
218
+ return readGeminiSession(file);
219
+ case 'cline':
220
+ case 'roo-code':
221
+ case 'kilo-code':
222
+ return readClineSession(file, agent);
223
+ case 'aider':
224
+ return readAiderSession(file);
225
+ case 'open':
226
+ return readOpenSession(file);
227
+ default:
228
+ return readClaudeSession(file);
229
+ }
230
+ }