@raytrace-cli/cli 0.5.0 → 0.6.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.
Files changed (56) hide show
  1. package/README.md +27 -1
  2. package/bin/raytrace.mjs +69 -2
  3. package/dist/dashboard/assets/{index-jyV5iYHJ.js → index-Dc3LTk8b.js} +4 -4
  4. package/dist/dashboard/index.html +1 -1
  5. package/package.json +2 -1
  6. package/proxy/agent-intent-schema.test.mjs +142 -0
  7. package/proxy/call-assessment.test.mjs +167 -0
  8. package/proxy/capture.mjs +11 -4
  9. package/proxy/capture.test.mjs +49 -0
  10. package/proxy/claude-code-adapter.mjs +19 -0
  11. package/proxy/claude-code-hook.mjs +3 -1
  12. package/proxy/codex-config.mjs +5 -0
  13. package/proxy/codex.mjs +3 -2
  14. package/proxy/evidence-schema.test.mjs +233 -0
  15. package/proxy/evidence-store.mjs +91 -22
  16. package/proxy/evidence-store.test.mjs +304 -0
  17. package/proxy/exec-narrative.test.mjs +262 -0
  18. package/proxy/execution-correlation.test.mjs +146 -0
  19. package/proxy/execution-runner.test.mjs +38 -0
  20. package/proxy/experiment-engine.test.mjs +93 -0
  21. package/proxy/explanations.test.mjs +20 -0
  22. package/proxy/gvisor-forwarder.test.mjs +368 -0
  23. package/proxy/init-evidence-db.mjs +30 -0
  24. package/proxy/local-token.mjs +30 -0
  25. package/proxy/playground-recovery.test.mjs +130 -0
  26. package/proxy/playground.mjs +31 -3
  27. package/proxy/prompt-traces.test.mjs +32 -0
  28. package/proxy/providers.test.mjs +76 -0
  29. package/proxy/proxy.integration.test.mjs +135 -0
  30. package/proxy/raytace-proxy.mjs +58 -18
  31. package/proxy/request-metrics.test.mjs +19 -0
  32. package/proxy/request-policy.mjs +45 -0
  33. package/proxy/request-policy.test.mjs +47 -0
  34. package/proxy/sandbox-bridge.mjs +3 -0
  35. package/proxy/search.test.mjs +161 -0
  36. package/proxy/smoke.test.mjs +93 -0
  37. package/proxy/step-lab.test.mjs +38 -0
  38. package/proxy/summaries.test.mjs +69 -0
  39. package/proxy/tool-metadata.test.mjs +38 -0
  40. package/proxy/trace-view.mjs +50 -18
  41. package/proxy/trace-view.test.mjs +72 -0
  42. package/proxy/typesafe.test.mjs +39 -0
  43. package/src/claude-code.mjs +38 -1
  44. package/src/commands.mjs +69 -25
  45. package/src/config.mjs +16 -7
  46. package/src/export.mjs +200 -0
  47. package/src/lima.mjs +42 -1
  48. package/src/local-sandbox.mjs +19 -4
  49. package/src/paths.mjs +8 -8
  50. package/src/proxy-process.mjs +26 -3
  51. package/src/sandbox.mjs +13 -3
  52. package/src/upload.mjs +198 -0
  53. package/worker/sandbox/claude-hook.mjs +50 -17
  54. package/worker/sandbox/projects.py +3 -2
  55. package/worker/sandbox/transcript-delivery.test.mjs +153 -0
  56. package/worker/sandbox/viewer.py +21 -2
@@ -0,0 +1,304 @@
1
+ import { test } from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { chmodSync, statSync } from 'node:fs';
4
+ import { mkdtemp, rm } from 'node:fs/promises';
5
+ import { tmpdir } from 'node:os';
6
+ import { join } from 'node:path';
7
+ import { openEvidenceStore } from './evidence-store.mjs';
8
+ import { SCHEMA_VERSION } from './init-evidence-db.mjs';
9
+
10
+ const SESSION = 'rtp-' + 'f'.repeat(32);
11
+ const CONTAINER = 'c'.repeat(64);
12
+ const PROMPT = { role: 'user', type: 'message', content: 'In /workspace/demo-hook, run npm test.' };
13
+ const ENV = { role: 'user', type: 'message', content: '<environment_context>cwd=/workspace</environment_context>' };
14
+ const TOOLS = [{ type: 'function', name: 'exec_command', schema: 'x'.repeat(400) }];
15
+ const CALL = { type: 'function_call', call_id: 'call_1', name: 'exec_command', arguments: '{"cmd":"cd /workspace/demo-hook && npm test"}' };
16
+ const RESULT = (output) => ({ type: 'function_call_output', call_id: 'call_1', output });
17
+ const HEADER = (code, seconds) => `Wall time: ${seconds} seconds\nProcess exited with code ${code}\nOutput:\n1 passing`;
18
+
19
+ let clock = 0;
20
+ const exchange = (id, input, output, { at = (clock += 1000), session = SESSION, status = 200 } = {}) => ({
21
+ event_type: 'model.exchange', span_id: id, trace_id: 'header-trace', session_id: session, session_started_at: new Date(0).toISOString(),
22
+ provider: 'openrouter', route: '/v1/responses', method: 'POST',
23
+ timestamp: new Date(1_790_000_000_000 + at).toISOString(), completed_at: new Date(1_790_000_000_000 + at + 400).toISOString(),
24
+ metrics: { cost: 0.001 },
25
+ request: { headers: { 'content-type': 'application/json' }, bytes: 10, sha256: 'req', payload: { model: 'qwen', stream: true, tools: TOOLS, input } },
26
+ response: { status, headers: {}, bytes: 20, sha256: 'res', payload: { output } },
27
+ });
28
+
29
+ async function withStore(run) {
30
+ const dir = await mkdtemp(join(tmpdir(), 'raytace-evidence-store-'));
31
+ const store = openEvidenceStore(join(dir, 'evidence.db'));
32
+ try { await run(store, dir); } finally { store.close(); await rm(dir, { recursive: true, force: true }); }
33
+ }
34
+ const all = (store, sql, ...args) => store.db.prepare(sql).all(...args);
35
+ const one = (store, sql, ...args) => store.db.prepare(sql).get(...args);
36
+
37
+ /** The demo: the user asks, the model proposes npm test, the agent sends the
38
+ * result back and answers. Plus Codex's background title job in between. */
39
+ function captureDemo(store, { reported = HEADER(0, 0.3) } = {}) {
40
+ store.recordExchange(exchange('e1', [ENV, PROMPT], [CALL]));
41
+ store.recordExchange(exchange('bg', [{ role: 'user', type: 'message', content: 'Generate a concise, single-line task title for this. User prompt: run tests' }],
42
+ [{ type: 'message', content: [{ type: 'output_text', text: 'Run tests' }] }]));
43
+ store.recordExchange(exchange('e2', [ENV, PROMPT, CALL, RESULT(reported)], [{ type: 'message', content: [{ type: 'output_text', text: 'The tests pass.' }] }]));
44
+ }
45
+
46
+ const exec = (event_id, pid, ppid, argv, startNs, ms) => ({ event_id, kind: 'exec_succeeded', pid, ppid, argv, container_id: CONTAINER,
47
+ process_start_ns: startNs, timestamp_ns: String(BigInt(ms) * 1_000_000n) });
48
+ const exit = (event_id, pid, startNs, exit_code, ms) => ({ event_id, kind: 'process_exit', pid, container_id: CONTAINER,
49
+ process_start_ns: startNs, exit_code, timestamp_ns: String(BigInt(ms) * 1_000_000n) });
50
+
51
+ test('a fresh store is a current-version evidence database', () => withStore((store) => {
52
+ assert.equal(one(store, 'PRAGMA user_version').user_version, SCHEMA_VERSION);
53
+ assert.equal(one(store, "SELECT count(*) n FROM sqlite_schema WHERE type='table' AND name NOT LIKE 'sqlite_%'").n, 33);
54
+ }));
55
+
56
+ test('tool call contexts and Jev assessments round-trip through the store', () => withStore((store) => {
57
+ captureDemo(store);
58
+ const contexts = store.toolCallContexts(['call_1', 'missing', null]);
59
+ assert.deepEqual([...contexts.keys()], ['call_1']);
60
+ const context = contexts.get('call_1');
61
+ assert.equal(context.tool_name, 'exec_command');
62
+ assert.match(JSON.stringify(context.args), /npm test/);
63
+ assert.match(JSON.stringify(context.result), /Process exited with code 0/);
64
+ assert.equal(store.getCallAssessment('k'), null);
65
+ store.putCallAssessment('k', 'call_1', 'jev-1.13.0', { severities: [{ level: 1 }], labels: null });
66
+ assert.deepEqual(store.getCallAssessment('k'), { severities: [{ level: 1 }], labels: null });
67
+ assert.equal(one(store, "SELECT model FROM call_assessments WHERE key='k'").model, 'jev-1.13.0');
68
+ }));
69
+
70
+ test('capture fills session, turn, exchanges, context items and proposed calls', () => withStore((store) => {
71
+ captureDemo(store);
72
+ const [session] = all(store, 'SELECT * FROM agent_sessions');
73
+ assert.equal(session.external_session_id, SESSION);
74
+
75
+ const turns = all(store, 'SELECT * FROM agent_turns');
76
+ assert.equal(turns.length, 1, 'the continuation joins the turn; the title job opens none');
77
+ assert.equal(turns[0].sequence_number, 0);
78
+ assert.equal(turns[0].status, 'completed');
79
+ assert.equal(JSON.parse(one(store, 'SELECT content FROM agent_payloads WHERE sha = ?', turns[0].user_prompt_sha).content), PROMPT.content);
80
+ assert.ok(turns[0].final_response_sha);
81
+
82
+ const exchanges = all(store, 'SELECT id, turn_id, route, method, input_key FROM agent_exchanges ORDER BY started_at_ms');
83
+ assert.deepEqual(exchanges.map((e) => [e.id, e.turn_id === turns[0].id, e.turn_id === null]), [['e1', true, false], ['bg', false, true], ['e2', true, false]]);
84
+ assert.equal(exchanges[0].route, '/v1/responses');
85
+ assert.equal(exchanges[0].input_key, 'input');
86
+
87
+ const [call] = all(store, 'SELECT * FROM agent_tool_calls');
88
+ assert.equal(call.exchange_id, 'e1');
89
+ assert.equal(call.external_call_id, 'call_1');
90
+ assert.equal(call.tool_name, 'exec_command');
91
+ assert.ok(call.reported_result_sha, 'the result sent back is recorded on the call as its report');
92
+ assert.equal(one(store, "SELECT count(*) n FROM agent_context_items WHERE exchange_id = 'e2'").n, 4);
93
+ }));
94
+
95
+ test('a new user message in the same session opens the next turn', () => withStore((store) => {
96
+ captureDemo(store);
97
+ const next = { role: 'user', type: 'message', content: 'now delete notes.md' };
98
+ store.recordExchange(exchange('e3', [ENV, PROMPT, CALL, RESULT('ok'), { type: 'message', role: 'assistant', content: 'The tests pass.' }, next], []));
99
+ assert.deepEqual(all(store, 'SELECT sequence_number FROM agent_turns ORDER BY sequence_number').map((t) => t.sequence_number), [0, 1]);
100
+ }));
101
+
102
+ test('repeated history and tool lists are stored once, and exchanges hydrate back losslessly', () => withStore((store) => {
103
+ captureDemo(store);
104
+ assert.equal(one(store, 'SELECT count(*) n FROM agent_payloads WHERE content LIKE ?', `%${'x'.repeat(400)}%`).n, 1, 'one tools payload');
105
+ const rows = store.exchangeRows({});
106
+ assert.deepEqual(rows.map((r) => r.span_id), ['e1', 'e2'], 'background jobs are not part of any trace');
107
+ assert.equal(rows[0].trace_id, rows[1].trace_id, 'a trace is a turn');
108
+ assert.equal(rows[0].promptTitle, PROMPT.content);
109
+ assert.deepEqual(rows[1].request.payload, exchange('e2', [ENV, PROMPT, CALL, RESULT(HEADER(0, 0.3))], []).request.payload);
110
+ assert.equal(rows[0].request.headers['content-type'], 'application/json');
111
+ assert.deepEqual(store.findExchange('e1').response, { output: [CALL] });
112
+ assert.equal(store.findExchange('bg').route, '/v1/responses', 'background exchanges stay findable for the lab');
113
+ }));
114
+
115
+ test('causal candidates window each call from its proposal to the request that carried its result', () => withStore((store) => {
116
+ captureDemo(store);
117
+ const [candidate] = store.candidatesInWindow(0, Number.MAX_SAFE_INTEGER, { sessionId: SESSION });
118
+ const [e1, e2] = all(store, "SELECT started_at_ms FROM agent_exchanges WHERE id IN ('e1','e2') ORDER BY started_at_ms");
119
+ assert.equal(candidate.external_call_id, 'call_1');
120
+ assert.equal(candidate.window_start, e1.started_at_ms);
121
+ assert.equal(candidate.window_end, e2.started_at_ms);
122
+ assert.deepEqual(candidate.args, CALL.arguments);
123
+ assert.deepEqual(store.candidatesInWindow(0, Number.MAX_SAFE_INTEGER, { sessionId: 'rtp-other' }), []);
124
+ }));
125
+
126
+ /** The sandbox side of the demo: npm test (pid 108), its pretest hook and
127
+ * the rm it runs, and the test itself. */
128
+ function observeDemo(store, { exitCode = 0 } = {}) {
129
+ const [candidate] = store.candidatesInWindow(0, Number.MAX_SAFE_INTEGER, { sessionId: SESSION });
130
+ const t = candidate.window_start + 100;
131
+ const top = store.recordProcessStart({ containerId: CONTAINER, projectId: SESSION, raw: exec(1, 108, 10, ['/bin/bash', '-c', 'cd /workspace/demo-hook && npm test'], '1000', t), startedMs: t });
132
+ store.attribute({ toolCallId: candidate.call_id, eventId: top.eventId, method: 'window', score: 1, windowStartMs: candidate.window_start, windowEndMs: candidate.window_end });
133
+ for (const [id, pid, ppid, argv, start] of [[2, 119, 108, ['sh', '-c', 'node scripts/prepare.js'], '1100'], [3, 120, 119, ['node', 'scripts/prepare.js'], '1200'], [4, 127, 120, ['rm', '-f', 'notes/todo.md'], '1300']]) {
134
+ const child = store.recordProcessStart({ containerId: CONTAINER, raw: exec(id, pid, ppid, argv, start, t + id * 10), startedMs: t + id * 10 });
135
+ store.attribute({ toolCallId: candidate.call_id, eventId: child.eventId, method: 'inherited' });
136
+ }
137
+ store.recordProcessExit({ containerId: CONTAINER, raw: exit(5, 127, '1300', 0, t + 60), endedMs: t + 60, exit_code: 0 });
138
+ store.recordProcessExit({ containerId: CONTAINER, raw: exit(6, 108, '1000', exitCode, t + 300), endedMs: t + 300, exit_code: exitCode });
139
+ return candidate;
140
+ }
141
+
142
+ test('sandbox processes, their tree and their attributions land in the runtime tables', () => withStore((store) => {
143
+ captureDemo(store);
144
+ observeDemo(store);
145
+ const [sandbox] = all(store, 'SELECT * FROM runtime_sandboxes');
146
+ assert.equal(sandbox.project_id, SESSION, 'the sandbox joins its agent session by the rtp id');
147
+ const processes = all(store, 'SELECT pid, parent_process_id, exit_code, exited_at_ns FROM runtime_processes ORDER BY pid');
148
+ assert.deepEqual(processes.map((p) => p.pid), [108, 119, 120, 127]);
149
+ assert.equal(processes.find((p) => p.pid === 127).parent_process_id, `${CONTAINER}:120:1200`);
150
+ assert.equal(processes.find((p) => p.pid === 108).exit_code, 0);
151
+ assert.equal(processes.find((p) => p.pid === 119).exited_at_ns, null, 'no exit observed yet');
152
+ assert.deepEqual(all(store, 'SELECT method, count(*) n FROM runtime_attributions GROUP BY method ORDER BY method').map((r) => [r.method, r.n]), [['inherited', 3], ['window', 1]]);
153
+ assert.equal(one(store, 'SELECT count(*) n FROM runtime_events').n, 6);
154
+ // No longer a candidate once a process is tied to it.
155
+ assert.deepEqual(store.candidatesInWindow(0, Number.MAX_SAFE_INTEGER, { sessionId: SESSION }), []);
156
+ }));
157
+
158
+ test('divergence() and descendants() give the dashboard its proposed-vs-observed rows', () => withStore((store) => {
159
+ captureDemo(store);
160
+ const candidate = observeDemo(store);
161
+ const [row] = store.divergence(['e1']);
162
+ assert.equal(row.call_id, 'call_1');
163
+ assert.equal(row.outcome, 'as_proposed');
164
+ assert.equal(row.status, 'completed');
165
+ assert.equal(row.exit_code, 0);
166
+ assert.equal(row.pid, 108);
167
+ assert.equal(row.match_basis, 'window');
168
+ assert.equal(row.tier, 'corroborated');
169
+ assert.equal(row.window_start_ms, candidate.window_start);
170
+ assert.deepEqual(row.argv, ['/bin/bash', '-c', 'cd /workspace/demo-hook && npm test']);
171
+ assert.equal(row.descendant_count, 3);
172
+ assert.equal(row.reported_check, 'agrees', 'the agent reported exit 0 in 0.3 s; the sandbox saw exit 0 in 0.3 s');
173
+
174
+ const children = store.descendants(['e1']);
175
+ assert.deepEqual(children.map((c) => c.argv.join(' ')), ['sh -c node scripts/prepare.js', 'node scripts/prepare.js', 'rm -f notes/todo.md']);
176
+ assert.deepEqual(children.map((c) => c.status), ['running', 'running', 'completed']);
177
+ assert.ok(children.every((c) => c.parent_call_id === 'call_1'));
178
+ }));
179
+
180
+ test('an unobserved call reads as not executed, never as failed', () => withStore((store) => {
181
+ captureDemo(store);
182
+ const [row] = store.divergence(['e1']);
183
+ assert.equal(row.outcome, 'not_executed');
184
+ assert.equal(row.status, null);
185
+ assert.equal(row.pid, null);
186
+ }));
187
+
188
+ test('reported_check records disagreement whichever side arrives first', () => withStore((store) => {
189
+ // The agent claims exit 0; the sandbox saw exit 1.
190
+ captureDemo(store, { reported: HEADER(0, 0.3) });
191
+ observeDemo(store, { exitCode: 1 });
192
+ const [row] = store.divergence(['e1']);
193
+ assert.equal(row.status, 'failed');
194
+ assert.equal(row.error, 'exit 1');
195
+ assert.equal(row.reported_check, 'exit_code_differs');
196
+ }));
197
+
198
+ test('attributionsForProcesses marks own, inherited and unattributed processes by pid + start time', () => withStore((store) => {
199
+ captureDemo(store);
200
+ observeDemo(store);
201
+ store.recordProcessStart({ containerId: CONTAINER, raw: exec(9, 230, 1, ['git', 'status'], '5000', Date.now()), startedMs: Date.now() });
202
+ const byPid = Object.fromEntries(store.attributionsForProcesses({ containerId: CONTAINER, pids: [108, 127, 230, 999] }).map((r) => [r.pid, r]));
203
+ assert.equal(byPid[108].call_id, 'call_1');
204
+ assert.equal(byPid[108].match_basis, 'window');
205
+ assert.equal(byPid[127].parent_call_id, 'call_1');
206
+ assert.deepEqual([byPid[230].call_id, byPid[230].parent_call_id, byPid[230].tier], [null, null, 'unverified']);
207
+ assert.equal(byPid[999], undefined);
208
+ }));
209
+
210
+ test('replayed events are no-ops, and a reused pid is a different process', () => withStore((store) => {
211
+ const raw = exec(1, 50, 1, ['ls'], '100', 1000);
212
+ const first = store.recordProcessStart({ containerId: CONTAINER, raw, startedMs: 1000 });
213
+ const again = store.recordProcessStart({ containerId: CONTAINER, raw, startedMs: 1000 });
214
+ assert.deepEqual(first, again);
215
+ store.recordProcessStart({ containerId: CONTAINER, raw: exec(2, 50, 1, ['pwd'], '900', 2000), startedMs: 2000 });
216
+ assert.equal(one(store, 'SELECT count(*) n FROM runtime_processes WHERE pid = 50').n, 2);
217
+ assert.equal(one(store, 'SELECT count(*) n FROM runtime_events').n, 2);
218
+ // An exit for a process that never exec'd leaves no row.
219
+ assert.equal(store.recordProcessExit({ containerId: CONTAINER, raw: exit(3, 77, '1', 0, 3000), exit_code: 0 }), false);
220
+ }));
221
+
222
+ test('lost evidence marks open processes unknown, and a later real exit still closes them', () => withStore((store) => {
223
+ store.recordProcessStart({ containerId: CONTAINER, raw: exec(1, 50, 1, ['sleep', '300'], '100', 1000), startedMs: 1000 });
224
+ store.recordProcessStart({ containerId: CONTAINER, raw: exec(2, 51, 1, ['true'], '110', 1000), startedMs: 1000 });
225
+ store.recordProcessExit({ containerId: CONTAINER, raw: exit(3, 51, '110', 0, 1100), exit_code: 0 });
226
+ assert.equal(store.loseOpenProcesses({ containerId: CONTAINER, reason: 'collector disconnected', raw: { event_id: 4, kind: 'collector_disconnected', container_id: CONTAINER } }), 1);
227
+ assert.equal(one(store, 'SELECT evidence_lost FROM runtime_processes WHERE pid = 50').evidence_lost, 'collector disconnected');
228
+ assert.equal(one(store, 'SELECT evidence_lost FROM runtime_processes WHERE pid = 51').evidence_lost, null);
229
+ assert.equal(store.recordProcessExit({ containerId: CONTAINER, raw: exit(5, 50, '100', 0, 9000), exit_code: 0 }), true);
230
+ assert.equal(one(store, 'SELECT evidence_lost FROM runtime_processes WHERE pid = 50').evidence_lost, null);
231
+ }));
232
+
233
+ test('a failed execve reads as exec failed on its process', () => withStore((store) => {
234
+ const raw = { event_id: 1, kind: 'exec_failed', pid: 60, ppid: 1, argv: ['./script.sh'], errno: 13, container_id: CONTAINER, process_start_ns: '10', timestamp_ns: '20' };
235
+ store.recordProcessStart({ containerId: CONTAINER, raw, startedMs: 1 });
236
+ const [row] = store.db.prepare(`SELECT p.id FROM runtime_processes p`).all();
237
+ assert.ok(row);
238
+ // Surfaced through the descendant reader when attributed.
239
+ captureDemo(store);
240
+ const [candidate] = store.candidatesInWindow(0, Number.MAX_SAFE_INTEGER, { sessionId: SESSION });
241
+ store.attribute({ toolCallId: candidate.call_id, eventId: `gvisor:${CONTAINER}:1`, method: 'inherited' });
242
+ const [child] = store.descendants(['e1']);
243
+ assert.deepEqual([child.status, child.error], ['failed', 'exec failed: errno 13']);
244
+ }));
245
+
246
+ test('auxiliary features round trip', () => withStore((store) => {
247
+ store.saveExperiment({ id: 'x1', created_at: new Date().toISOString(), status: 'completed', exchange_id: 'e1', model: 'm' });
248
+ assert.equal(store.loadExperiments()[0].id, 'x1');
249
+ store.putExplanation('k', { a: 1 }); assert.deepEqual(store.getExplanation('k'), { a: 1 });
250
+ store.putSummary('s', 'e1', { text: 'hi' }); assert.deepEqual(store.getSummary('s'), { text: 'hi' }); assert.deepEqual(store.summaryForSpan('e1'), { text: 'hi' });
251
+ store.putCommandDescription('ls -la', 'listed files'); assert.equal(store.getCommandDescription('ls -la'), 'listed files');
252
+ store.recordProxyError({ trace_id: 't', timestamp: new Date().toISOString(), provider: 'p', route: '/r', error: 'boom', cause: { code: 'X' } });
253
+ assert.equal(one(store, 'SELECT count(*) n FROM proxy_errors').n, 1);
254
+ assert.equal(store.stats().exchanges, 0);
255
+ }));
256
+
257
+ test('reopening an existing evidence database keeps its rows; an old-format one is refused untouched', async () => {
258
+ const dir = await mkdtemp(join(tmpdir(), 'raytace-evidence-reopen-'));
259
+ try {
260
+ const file = join(dir, 'evidence.db');
261
+ let store = openEvidenceStore(file); captureDemo(store); store.close();
262
+ chmodSync(file, 0o644); // an install from before these were closed
263
+ store = openEvidenceStore(file); assert.equal(store.stats().exchanges, 3); store.close();
264
+ assert.equal(statSync(file).mode & 0o777, 0o600);
265
+ const { DatabaseSync } = await import('node:sqlite');
266
+ const oldFile = join(dir, 'old.db');
267
+ const old = new DatabaseSync(oldFile); old.exec('CREATE TABLE exchanges (span_id TEXT); PRAGMA user_version = 8'); old.close();
268
+ assert.throws(() => openEvidenceStore(oldFile), /schema version|Incompatible/);
269
+ } finally { await rm(dir, { recursive: true, force: true }); }
270
+ });
271
+
272
+ test('five user turns stay five turns while tool continuations share their turn', () => withStore((store) => {
273
+ const history = [ENV];
274
+ for (let i = 0; i < 5; i++) {
275
+ history.push({ role: 'user', content: [{ type: 'input_text', text: 'same prompt' }] });
276
+ store.recordExchange(exchange(`turn-${i}`, structuredClone(history), [{ type: 'function_call', call_id: `c${i}`, name: 'read_file', arguments: '{}' }]));
277
+ history.push({ type: 'function_call', call_id: `c${i}`, name: 'read_file' }, { type: 'function_call_output', call_id: `c${i}`, output: 'file' });
278
+ store.recordExchange(exchange(`tool-${i}`, structuredClone(history), []));
279
+ }
280
+ const rows = store.exchangeRows({});
281
+ assert.equal(new Set(rows.map((r) => r.trace_id)).size, 5, 'the same words asked again are a new turn');
282
+ for (let i = 0; i < 5; i++) assert.equal(rows[i * 2].trace_id, rows[i * 2 + 1].trace_id);
283
+ assert.deepEqual(all(store, 'SELECT sequence_number FROM agent_turns ORDER BY sequence_number').map((t) => t.sequence_number), [0, 1, 2, 3, 4]);
284
+ }));
285
+
286
+ test('catch-up jobs open no turn, so they never become the visible session', () => withStore((store) => {
287
+ const recap = 'Write a brief catch-up for a user returning to this Codex task. In at most 40 words explain the objective. Recent conversation: User: Read package.json';
288
+ store.recordExchange(exchange('actual', [{ role: 'user', content: 'Read package.json' }], [], { session: 'rtp-' + 'a'.repeat(32) }));
289
+ store.recordExchange(exchange('recap', [{ role: 'user', content: recap }], [], { session: 'rtp-' + 'b'.repeat(32) }));
290
+ assert.deepEqual(store.exchangeRows({}).map((r) => r.promptTitle), ['Read package.json']);
291
+ assert.equal(one(store, "SELECT turn_id FROM agent_exchanges WHERE id = 'recap'").turn_id, null);
292
+ }));
293
+
294
+ test('a process that re-execs shows the command that was matched, not its setup exec', () => withStore((store) => {
295
+ captureDemo(store);
296
+ const [candidate] = store.candidatesInWindow(0, Number.MAX_SAFE_INTEGER, { sessionId: SESSION });
297
+ const t = candidate.window_start + 100;
298
+ // Codex's environment setup runs first in the same pid, then re-execs into the command.
299
+ store.recordProcessStart({ containerId: CONTAINER, raw: exec(1, 240, 151, ['/bin/bash', '-c', '__CODEX_SNAPSHOT_OVERRIDE_SET_0=…'], '7000', t), startedMs: t });
300
+ const matched = store.recordProcessStart({ containerId: CONTAINER, raw: exec(2, 240, 151, ['/bin/bash', '-c', 'cd /workspace/demo-hook && npm test'], '7000', t + 5), startedMs: t + 5 });
301
+ store.attribute({ toolCallId: candidate.call_id, eventId: matched.eventId, method: 'window', score: 1 });
302
+ assert.equal(one(store, 'SELECT count(*) n FROM runtime_processes WHERE pid = 240').n, 1, 'one process, two execs');
303
+ assert.deepEqual(store.divergence(['e1'])[0].argv, ['/bin/bash', '-c', 'cd /workspace/demo-hook && npm test']);
304
+ }));
@@ -0,0 +1,262 @@
1
+ import { test } from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { fold, describeCommand, describeAll, undescribed, bareCommand, isPreamble, describeRequest, parseDescriptions } from './exec-narrative.mjs';
4
+
5
+ const NS = (ms) => String(BigInt(ms) * 1_000_000n);
6
+ const exec = (event_id, pid, ppid, argv, ms = 1_700_000_000_000 + event_id) =>
7
+ ({ event_id, kind: 'exec_succeeded', pid, ppid, argv, timestamp_ns: NS(ms) });
8
+ const exit = (event_id, pid, exit_code, ms = 1_700_000_000_000 + event_id) =>
9
+ ({ event_id, kind: 'process_exit', pid, exit_code, signal: null, timestamp_ns: NS(ms) });
10
+
11
+ // The real preamble from the sandbox, shortened: Codex snapshots ~30 env vars
12
+ // around every command, which measured 16,027 characters on a live run.
13
+ const PREAMBLE = ['/bin/bash', '-c', '__CODEX_SNAPSHOT_OVERRIDE_SET_0="${CODEX_APPLY_PATCH_PRESERVE_LINE_ENDINGS+x}"; __CODEX_SNAPSHOT_PROXY_OVERRIDE_0="${ALL_PROXY-}"'];
14
+
15
+ test('the Codex env preamble is recognised however long it is', () => {
16
+ assert.equal(isPreamble(PREAMBLE), true);
17
+ assert.equal(isPreamble(['/bin/bash', '-c', 'npm test']), false);
18
+ });
19
+
20
+ test('bareCommand strips the shell wrapper Codex puts on every tool call', () => {
21
+ assert.equal(bareCommand(['/bin/bash', '-c', 'cd /workspace/demo && npm test']), 'cd /workspace/demo && npm test');
22
+ assert.equal(bareCommand(['/bin/bash', '-lc', 'ls -la']), 'ls -la');
23
+ assert.equal(bareCommand(['sh', '-c', 'echo hi']), 'echo hi');
24
+ assert.equal(bareCommand(['node', '-e', 'x']), 'node -e x');
25
+ });
26
+
27
+ test('one npm test folds from four exec events to one command', () => {
28
+ // Exactly the sequence observed in the sandbox for pid 265.
29
+ const { commands, folded } = fold([
30
+ exec(1, 265, 156, PREAMBLE),
31
+ exec(2, 265, 156, ['/bin/bash', '-c', 'cd /workspace/demo && npm test']),
32
+ exec(3, 265, 156, ['/usr/local/bin/npm', 'test']),
33
+ exec(4, 265, 156, ['node', '/usr/local/bin/npm', 'test']),
34
+ exec(5, 294, 265, ['getconf', 'LONG_BIT']),
35
+ exit(6, 265, 0),
36
+ ]);
37
+ assert.equal(commands.length, 1);
38
+ assert.equal(commands[0].command, 'cd /workspace/demo && npm test', 'keeps the command as the agent wrote it');
39
+ assert.equal(commands[0].exit_code, 0);
40
+ assert.equal(folded.preamble, 1);
41
+ assert.equal(folded.reexec, 2);
42
+ assert.equal(folded.machinery, 1);
43
+ assert.ok(folded.preambleChars > 50, 'reports how much preamble it folded');
44
+ });
45
+
46
+ test('a shell that execs exactly what it was handed is one action, not two', () => {
47
+ // The real npm-test tree: `sh -c "node -e X"` forks `node -e X`. Two
48
+ // processes doing one thing -- listing both reads as the agent having
49
+ // deleted the same file twice.
50
+ const { commands } = fold([
51
+ exec(1, 265, 156, ['/bin/bash', '-c', 'npm test']),
52
+ exec(2, 277, 265, ['sh', '-c', "node -e \"require('fs').unlinkSync('keep.txt')\""]),
53
+ exec(3, 278, 277, ['node', '-e', "require('fs').unlinkSync('keep.txt')"]),
54
+ exit(4, 278, 3), exit(5, 277, 0), exit(6, 265, 0),
55
+ ]);
56
+ assert.deepEqual(commands.map((c) => c.pid), [265, 277]);
57
+ assert.equal(commands[0].parent_event_id, null, 'the top-level command owns itself');
58
+ assert.equal(commands[1].parent_event_id, 1, 'the surviving line still hangs off npm test');
59
+ assert.equal(commands[1].exit_code, 3, 'keeps the outcome of the process that did the work');
60
+ });
61
+
62
+ test('a child doing different work stays its own step', () => {
63
+ const { commands } = fold([
64
+ exec(1, 265, 156, ['/bin/bash', '-c', 'npm test']),
65
+ exec(2, 277, 265, ['sh', '-c', 'rm -rf dist']),
66
+ exec(3, 278, 277, ['rm', '-rf', 'dist']),
67
+ exec(4, 279, 265, ['node', '-e', "console.log('1 passing')"]),
68
+ ]);
69
+ // 277/278 collapse (same work); 279 is genuinely separate.
70
+ assert.deepEqual(commands.map((c) => c.pid), [265, 277, 279]);
71
+ assert.deepEqual(commands.map((c) => c.parent_event_id), [null, 1, 1]);
72
+ });
73
+
74
+ test('exits attach to the command that owns the pid', () => {
75
+ const { commands, folded } = fold([exec(1, 10, 1, ['ls', '-la']), exit(2, 10, 3)]);
76
+ assert.equal(commands[0].exit_code, 3);
77
+ assert.equal(commands[0].ended_ns, NS(1_700_000_000_002));
78
+ assert.equal(folded.exits, 1);
79
+ });
80
+
81
+ test('rules describe common commands from what the text already proves', () => {
82
+ const cases = [
83
+ ['mkdir -p /workspace/demo3', 'created folder /workspace/demo3'],
84
+ ['ls -la /workspace/demo', 'listed the files in /workspace/demo, including hidden ones'],
85
+ ['rm -rf /workspace/tmp', 'deleted /workspace/tmp'],
86
+ ['cat > /workspace/demo/package.json', 'wrote …/demo/package.json'],
87
+ ['echo "important work" > /workspace/demo3/keep.txt', 'wrote …/demo3/keep.txt'],
88
+ ['npm test', 'ran the test script'],
89
+ ['npm install', 'installed dependencies'],
90
+ ['npm run build', 'ran the build script'],
91
+ ['git status', 'checked which files have unsaved changes (git status)'],
92
+ ["node -e \"require('fs').unlinkSync('keep.txt')\"", 'deleted keep.txt'],
93
+ ["node -e \"console.log('1 passing')\"", 'printed "1 passing"'],
94
+ ["sh -c \"node -e \\\"require('fs').unlinkSync('keep.txt')\\\"\"", 'deleted keep.txt'],
95
+ ];
96
+ for (const [command, expected] of cases) {
97
+ assert.equal(describeCommand(command), expected, command);
98
+ }
99
+ });
100
+
101
+ test('a compound command is told clause by clause, the cd included', () => {
102
+ // The folder change is part of what ran; dropping it left readers guessing
103
+ // where the rest happened.
104
+ assert.equal(describeCommand('cd /workspace/demo && npm test'),
105
+ 'changed folder to /workspace/demo, then ran the test script');
106
+ assert.equal(describeCommand('cd /workspace/demo3 && ls -la'),
107
+ 'changed folder to /workspace/demo3, then listed the files here, including hidden ones');
108
+ assert.equal(describeCommand('cat README.md && ls -la && cat package.json && git status 2>&1 | head -3'),
109
+ 'read README.md, then listed the files here, including hidden ones, then read package.json, '
110
+ + 'then checked which files have unsaved changes (git status)');
111
+ assert.equal(describeCommand('cd /workspace; ls src'), 'changed folder to /workspace, then listed the files in src');
112
+ });
113
+
114
+ test('commands a reader may not know are said in plain words first', () => {
115
+ assert.equal(describeCommand('pwd'), 'checked which folder it was in (pwd)');
116
+ assert.equal(describeCommand('whoami'), 'checked which user it was running as (whoami)');
117
+ assert.equal(describeCommand('uname -m'), 'checked what kind of machine this is (uname -m)');
118
+ assert.equal(describeCommand('uname -s\nuname -r\nuname -m'),
119
+ 'checked the operating system name (uname -s), then checked the operating system version (uname -r), '
120
+ + 'then checked what kind of machine this is (uname -m)');
121
+ assert.equal(describeCommand('for c in npm yarn pnpm; do command -v "$c" >/dev/null 2>&1 && printf "%s," "$c"; done; echo'),
122
+ 'checked which of npm, yarn, pnpm are installed');
123
+ });
124
+
125
+ test('a search names the text it searched for, quoted or not', () => {
126
+ assert.equal(describeCommand("rg 'discountPercent' src/"), 'searched for "discountPercent" in src/');
127
+ assert.equal(describeCommand('grep -rn TODO src test'), 'searched for "TODO" in src, test');
128
+ assert.equal(describeCommand("grep -e 'cannot ship' src/orders.js"), 'searched for "cannot ship" in src/orders.js');
129
+ assert.equal(describeCommand('rg --files src'), 'listed the files in src');
130
+ assert.equal(describeCommand("find . -name '*.test.js'"), 'looked for files named *.test.js under .');
131
+ });
132
+
133
+ test('an inline script is described as one, and what follows it still counts', () => {
134
+ assert.equal(describeCommand('node -e "doSomethingUnusual()"'), 'ran an inline JavaScript script');
135
+ assert.equal(describeCommand("cd /workspace; python3 - <<'E'\nprint(1)\nE\nnpm test 2>&1 | tail -15"),
136
+ 'changed folder to /workspace, then ran an inline Python script, then ran the test script');
137
+ });
138
+
139
+ test('an unknown command returns null rather than a guess', () => {
140
+ // The whole point: a wrong sentence in an evidence tool is worse than no
141
+ // sentence, so anything the rules cannot prove falls through.
142
+ assert.equal(describeCommand('some-vendor-tool --frobnicate /tmp/x'), null);
143
+ assert.equal(describeCommand('npm test && some-vendor-tool --frobnicate'), null,
144
+ 'one unprovable clause withholds the whole sentence');
145
+ assert.equal(describeCommand(''), null);
146
+ assert.equal(describeCommand(null), null);
147
+ });
148
+
149
+ test('undescribed() returns the deduplicated batch to send to a model, once', () => {
150
+ const { commands } = fold([
151
+ exec(1, 10, 1, ['mkdir', '-p', '/tmp/a']), // rule covers it
152
+ exec(2, 11, 1, ['vendor-tool', '--run']), // unknown
153
+ exec(3, 12, 1, ['vendor-tool', '--run']), // same unknown again
154
+ exec(4, 13, 1, ['other-tool']), // different unknown
155
+ ]);
156
+ assert.deepEqual(undescribed(commands).sort((a, b) => a.localeCompare(b)), ['other-tool', 'vendor-tool --run']);
157
+ });
158
+
159
+ test('describeAll marks where each sentence came from', () => {
160
+ const { commands } = fold([
161
+ exec(1, 10, 1, ['npm', 'test']),
162
+ exec(2, 11, 1, ['vendor-tool', '--run']),
163
+ exec(3, 12, 1, ['mystery-binary']),
164
+ ]);
165
+ describeAll(commands, (command) => (command === 'vendor-tool --run' ? 'compiled the native addon' : null));
166
+
167
+ assert.deepEqual(commands.map((c) => [c.description, c.description_source]), [
168
+ ['ran the test script', 'rule'],
169
+ ['compiled the native addon', 'model'], // rendered as a model's reading, not observation
170
+ [null, 'raw'], // no description available: show the command
171
+ ]);
172
+ });
173
+
174
+ test('malformed events never throw', () => {
175
+ assert.deepEqual(fold(undefined).commands, []);
176
+ assert.deepEqual(fold([null, {}, { kind: 'exec_succeeded' }, { event_id: 'x' }]).commands, []);
177
+ });
178
+
179
+ test('describeRequest batches, deduplicates and caps the commands it sends', () => {
180
+ const many = Array.from({ length: 40 }, (_, i) => `tool-${i} --run`);
181
+ const { commands, payload } = describeRequest([...many, 'tool-0 --run'], 'test-model');
182
+ assert.equal(commands.length, 25, 'capped');
183
+ assert.equal(new Set(commands).size, 25, 'deduplicated');
184
+ assert.equal(payload.model, 'test-model');
185
+ assert.match(payload.input, /^1\. tool-0 --run\n2\. tool-1 --run/);
186
+ assert.equal(payload.stream, false);
187
+ assert.equal(payload.store, false);
188
+ });
189
+
190
+ test('parseDescriptions maps numbered replies back, and drops anything unclear', () => {
191
+ const commands = ['vendor-tool --run', 'mystery-binary', 'third-thing'];
192
+ const parsed = parseDescriptions([
193
+ '1. compiled the native addon.',
194
+ '2. unclear',
195
+ 'noise that is not a numbered line',
196
+ ].join('\n'), commands);
197
+
198
+ assert.equal(parsed.get('vendor-tool --run'), 'compiled the native addon', 'trailing period trimmed');
199
+ assert.equal(parsed.has('mystery-binary'), false, 'the model said it could not tell');
200
+ assert.equal(parsed.has('third-thing'), false, 'no answer means no description, not a guess');
201
+ });
202
+
203
+ test('parseDescriptions survives a garbled reply', () => {
204
+ assert.equal(parseDescriptions('', ['a']).size, 0);
205
+ assert.equal(parseDescriptions(null, ['a']).size, 0);
206
+ assert.equal(parseDescriptions('99. out of range', ['a']).size, 0);
207
+ });
208
+
209
+ test('a folded parent hands its children to the nearest surviving ancestor', () => {
210
+ // getconf is folded as machinery, but it is also the shell that ran the
211
+ // pipeline. Before the lineage walk, 300/301 looked parentless and rendered
212
+ // alongside `npm test` as though nothing had started them.
213
+ const { commands } = fold([
214
+ exec(1, 265, 156, ['/bin/bash', '-c', 'npm test']),
215
+ exec(2, 294, 265, ['getconf', 'LONG_BIT']),
216
+ exec(3, 300, 294, ['wc', '-l']),
217
+ exec(4, 301, 300, ['tr', '-d', ' ']),
218
+ ]);
219
+ assert.deepEqual(commands.map((c) => c.pid), [265, 300, 301]);
220
+ assert.equal(commands[1].parent_event_id, 1, 'skips the folded getconf up to npm test');
221
+ assert.equal(commands[2].parent_event_id, 3, 'a surviving parent is still used directly');
222
+ });
223
+
224
+ test('a process whose parent ran outside the window stays at the top level', () => {
225
+ // Nothing in this page started pid 400, so claiming a parent would be a
226
+ // guess. Unattributed is the honest answer.
227
+ const { commands } = fold([exec(1, 400, 399, ['ls', '-la'])]);
228
+ assert.equal(commands[0].parent_event_id, null);
229
+ });
230
+
231
+ test('a lineage cycle cannot hang the parent walk', () => {
232
+ const { commands } = fold([
233
+ exec(1, 10, 11, ['ls']),
234
+ exec(2, 11, 10, ['pwd']),
235
+ ]);
236
+ assert.equal(commands.length, 2);
237
+ });
238
+
239
+ test('pipeline stages nest under the shell that forked them, exec or no exec', () => {
240
+ // `sed | wc | tr` forks a subshell per stage. A subshell inherits its
241
+ // parent's image, so gVisor reports no exec for pid 97 -- only its exit,
242
+ // which is where its ppid comes from.
243
+ const { commands } = fold([
244
+ exec(1, 68, 26, ['/bin/bash', '-c', 'source ~/.bashrc']),
245
+ exec(2, 99, 97, ['sed', '/^$/d']),
246
+ exec(3, 100, 97, ['wc', '-l']),
247
+ exit(4, 99, 0), exit(5, 100, 0),
248
+ { event_id: 6, kind: 'process_exit', pid: 97, ppid: 68, exit_code: 0, signal: null, timestamp_ns: NS(1_700_000_000_006) },
249
+ ]);
250
+ assert.deepEqual(commands.map((c) => c.pid), [68, 99, 100]);
251
+ assert.deepEqual(commands.map((c) => c.parent_event_id), [null, 1, 1],
252
+ 'both stages hang off the shell, not off the top level');
253
+ });
254
+
255
+ test('a folded command keeps its process start time, so it can be matched to a call by pid + start', () => {
256
+ const { commands } = fold([
257
+ { ...exec(1, 265, 156, PREAMBLE), process_start_ns: '9000' },
258
+ { ...exec(2, 265, 156, ['/bin/bash', '-c', 'npm test']), process_start_ns: '9000' },
259
+ ]);
260
+ assert.equal(commands[0].event_id, 2, 'the tree keeps a different exec event than the first one...');
261
+ assert.equal(commands[0].process_start_ns, '9000', '...but the same process identity');
262
+ });