@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,368 @@
1
+ import { test } from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { toExecutionEvent, toFailedExec, exitOutcome, msFromNs, processEvents, SandboxTracker, startGvisorForwarder, clockFromSamples, UNMEASURED_CLOCK } from './gvisor-forwarder.mjs';
4
+
5
+ // Event shapes below mirror what worker/gvisor/collector.py writes and
6
+ // viewer.py serves (see `decode()` there): timestamp_ns / process_start_ns
7
+ // are strings because they don't fit a JS number losslessly.
8
+ const CONTAINER = 'c'.repeat(64);
9
+ const SESSION = 'rtp-' + 'a'.repeat(32);
10
+ const NS = (ms) => String(BigInt(ms) * 1_000_000n);
11
+ const exec = (event_id, pid, ppid, argv, ms = 1_700_000_000_000 + event_id) => ({ event_id, kind: 'exec_succeeded', pid, ppid, argv, container_id: CONTAINER, timestamp_ns: NS(ms), cwd: '/workspace' });
12
+ const exit = (event_id, pid, exit_code, signal = null, ms = 1_700_000_000_000 + event_id) => ({ event_id, kind: 'process_exit', pid, exit_code, signal, container_id: CONTAINER, timestamp_ns: NS(ms) });
13
+
14
+ test('msFromNs converts the collector\'s ns strings and rejects garbage', () => {
15
+ assert.equal(msFromNs('1700000000000000000'), 1_700_000_000_000);
16
+ assert.equal(msFromNs(''), null);
17
+ assert.equal(msFromNs(null), null);
18
+ assert.equal(msFromNs('not-a-number'), null);
19
+ assert.equal(msFromNs('0'), null);
20
+ });
21
+
22
+ test('toExecutionEvent maps exec_succeeded into the matcher shape with a collision-proof id', () => {
23
+ const raw = exec(42, 10, 1, ['/bin/bash', '-lc', 'git status']);
24
+ assert.deepEqual(toExecutionEvent(raw), {
25
+ id: `gvisor-${'c'.repeat(12)}-42`, pid: 10, ppid: 1, command: '/bin/bash -lc git status',
26
+ argv: ['/bin/bash', '-lc', 'git status'], cwd: '/workspace', timestamp: 1_700_000_000_042,
27
+ start_time_ns: null, call_marker: null, margin: 2000,
28
+ // The observation itself travels with it, for the evidence store.
29
+ container_id: CONTAINER, raw,
30
+ });
31
+ });
32
+
33
+ test('toExecutionEvent carries RAYTRACE_CALL_ID through, and ignores other markers', () => {
34
+ const marked = { ...exec(7, 10, 1, ['ls']), markers: { RAYTRACE_CALL_ID: 'call_abc', RAYTRACE_SESSION: 'rtp-x' } };
35
+ assert.equal(toExecutionEvent(marked).call_marker, 'call_abc');
36
+ // A session marker alone is not a per-call join; it must not become one.
37
+ assert.equal(toExecutionEvent({ ...exec(8, 10, 1, ['ls']), markers: { RAYTRACE_SESSION: 'rtp-x' } }).call_marker, null);
38
+ assert.equal(toExecutionEvent({ ...exec(9, 10, 1, ['ls']), markers: { RAYTRACE_CALL_ID: '' } }).call_marker, null);
39
+ });
40
+
41
+ test('toExecutionEvent rejects anything that is not a usable exec', () => {
42
+ assert.equal(toExecutionEvent(exit(1, 10, 0)), null);
43
+ assert.equal(toExecutionEvent(exec(2, 10, 1, [])), null);
44
+ assert.equal(toExecutionEvent({ ...exec(3, 10, 1, ['ls']), timestamp_ns: 'nope' }), null);
45
+ assert.equal(toExecutionEvent({ ...exec(4, 10, 1, ['ls']), pid: 'x' }), null);
46
+ assert.equal(toExecutionEvent(null), null);
47
+ });
48
+
49
+ test('exitOutcome never upgrades an unreadable exit to success', () => {
50
+ assert.deepEqual(exitOutcome({ exit_code: 0, signal: null }), { status: 'completed', error: null, exit_code: 0 });
51
+ assert.deepEqual(exitOutcome({ exit_code: 2, signal: null }), { status: 'failed', error: 'exit 2', exit_code: 2 });
52
+ assert.deepEqual(exitOutcome({ exit_code: null, signal: 9 }), { status: 'failed', error: 'killed by signal 9', exit_code: null });
53
+ assert.deepEqual(exitOutcome({ exit_code: null, signal: null }), { status: 'unknown', error: null, exit_code: null });
54
+ assert.deepEqual(exitOutcome(undefined), { status: 'unknown', error: null, exit_code: null });
55
+ });
56
+
57
+ /** ingest() fake: matches when the command text contains one of the given
58
+ * substrings; records every call so tests can assert on what was sent. */
59
+ function fakeIngest(matchIf) {
60
+ const calls = [];
61
+ const ingest = async (events, opts) => {
62
+ calls.push({ events, opts });
63
+ const out = new Map();
64
+ for (const e of events) if (matchIf.some((needle) => e.command.includes(needle))) out.set(e.id, { call_id: `call-for-${e.id}`, score: 1, basis: 'text' });
65
+ return out;
66
+ };
67
+ return { ingest, calls };
68
+ }
69
+
70
+ test('a top-level bash -lc exec is forwarded and scoped to the sandbox session; its children are recorded, not matched', async () => {
71
+ const { ingest, calls } = fakeIngest(['git status']);
72
+ const finished = [];
73
+ const descended = [];
74
+ const tracker = new SandboxTracker();
75
+ const counts = await processEvents([
76
+ exec(1, 100, 1, ['/bin/bash', '-lc', 'git status']),
77
+ exec(2, 101, 100, ['git', 'status']), // child of the matched bash: never offered to the matcher
78
+ exit(3, 101, 0), // child exit: closes the CHILD's own row
79
+ exit(4, 100, 0), // the command itself finishing
80
+ ], { sessionId: SESSION, tracker, ingest, finish: async (row) => { finished.push(row); return true; },
81
+ descend: async (row) => { descended.push(row); } });
82
+
83
+ assert.deepEqual(counts, { forwarded: 1, matched: 1, finished: 2, descendants: 1, unattributed: 0, failedExecs: 0, lost: 0 });
84
+ assert.equal(calls.length, 1, 'only the top-level exec reached the matcher');
85
+ assert.equal(calls[0].opts.sessionId, SESSION);
86
+ assert.equal(calls[0].events[0].command, '/bin/bash -lc git status');
87
+
88
+ // The child is stored against the call its parent resolved to.
89
+ assert.equal(descended.length, 1);
90
+ assert.equal(descended[0].parent_call_id, `call-for-gvisor-${'c'.repeat(12)}-1`);
91
+ assert.equal(descended[0].tier, 'corroborated');
92
+ assert.equal(descended[0].exec.pid, 101);
93
+
94
+ // Each pid closes its OWN row -- a child's exit must never finish its parent.
95
+ assert.deepEqual(finished.map((r) => r.id), [`gvisor-${'c'.repeat(12)}-2`, `gvisor-${'c'.repeat(12)}-1`]);
96
+ assert.equal(tracker.cursor, 4);
97
+ assert.equal(tracker.live.size, 0, 'exits released both pids');
98
+ });
99
+
100
+ test('a grandchild inherits attribution: the one-level check never reached it', async () => {
101
+ // npm test -> sh -c node -e "...unlinkSync" -> node. The deletion is two
102
+ // levels down; before this it fell past the parent check into the matcher,
103
+ // scored too low against every candidate, and was discarded.
104
+ const { ingest } = fakeIngest(['npm test']);
105
+ const descended = [];
106
+ const tracker = new SandboxTracker();
107
+ const counts = await processEvents([
108
+ exec(1, 265, 156, ['/bin/bash', '-lc', 'npm test']),
109
+ exec(2, 277, 265, ['sh', '-c', 'node -e "require(\'fs\').unlinkSync(\'keep.txt\')"']),
110
+ exec(3, 278, 277, ['node', '-e', "require('fs').unlinkSync('keep.txt')"]),
111
+ ], { sessionId: SESSION, tracker, ingest, finish: async () => true, descend: async (row) => { descended.push(row); } });
112
+
113
+ assert.equal(counts.descendants, 2);
114
+ const call = `call-for-gvisor-${'c'.repeat(12)}-1`;
115
+ assert.deepEqual(descended.map((r) => [r.exec.pid, r.parent_call_id]), [[277, call], [278, call]]);
116
+ });
117
+
118
+ test('an exec that matches nothing is recorded as unattributed rather than discarded', async () => {
119
+ const { ingest } = fakeIngest([]); // nothing matches
120
+ const descended = [];
121
+ const tracker = new SandboxTracker();
122
+ const counts = await processEvents([
123
+ exec(1, 900, 1, ['curl', 'https://example.com']),
124
+ ], { sessionId: SESSION, tracker, ingest, finish: async () => true, descend: async (row) => { descended.push(row); } });
125
+
126
+ assert.deepEqual(counts, { forwarded: 1, matched: 0, finished: 0, descendants: 0, unattributed: 1, failedExecs: 0, lost: 0 });
127
+ assert.equal(descended.length, 1);
128
+ assert.equal(descended[0].parent_call_id, null, 'belongs to no proposed call');
129
+ assert.equal(descended[0].tier, 'unverified');
130
+ });
131
+
132
+ test('a same-pid re-exec (bash exec()ing its last command) is not offered as a separate candidate', async () => {
133
+ const { ingest, calls } = fakeIngest(['ls']);
134
+ const tracker = new SandboxTracker();
135
+ await processEvents([
136
+ exec(1, 100, 1, ['/bin/bash', '-lc', 'ls -la']),
137
+ exec(2, 100, 1, ['ls', '-la']), // same pid 100, ppid still 1
138
+ ], { sessionId: SESSION, tracker, ingest, finish: async () => true });
139
+ assert.equal(calls.length, 1, 'only the wrapper exec was ingested');
140
+ });
141
+
142
+ test('unmatched execs never occupy a pid, so their children remain eligible', async () => {
143
+ // e.g. the container entrypoint (`codex` itself) is a top-level exec that
144
+ // matches nothing -- its children (the real tool calls) must still flow.
145
+ const { ingest, calls } = fakeIngest(['npm test']);
146
+ const tracker = new SandboxTracker();
147
+ const counts = await processEvents([
148
+ exec(1, 1, 0, ['codex']),
149
+ exec(2, 50, 1, ['/bin/bash', '-lc', 'npm test']),
150
+ ], { sessionId: SESSION, tracker, ingest, finish: async () => true });
151
+ assert.deepEqual(counts, { forwarded: 2, matched: 1, finished: 0, descendants: 0, unattributed: 1, failedExecs: 0, lost: 0 });
152
+ assert.equal(calls.length, 2);
153
+ assert.equal(tracker.live.get(50).execId, `gvisor-${'c'.repeat(12)}-2`);
154
+ assert.equal(tracker.live.has(1), false);
155
+ });
156
+
157
+ test('a failing command closes out as failed with the exit code, a signal as killed', async () => {
158
+ const { ingest } = fakeIngest(['make', 'sleep']);
159
+ const finished = [];
160
+ const tracker = new SandboxTracker();
161
+ await processEvents([
162
+ exec(1, 7, 1, ['/bin/bash', '-lc', 'make']), exit(2, 7, 2),
163
+ exec(3, 8, 1, ['/bin/bash', '-lc', 'sleep 100']), exit(4, 8, null, 9),
164
+ ], { sessionId: SESSION, tracker, ingest, finish: async (row) => { finished.push(row); return true; } });
165
+ assert.deepEqual(finished.map((r) => [r.status, r.error]), [['failed', 'exit 2'], ['failed', 'killed by signal 9']]);
166
+ });
167
+
168
+ test('events are processed in id order regardless of page order, and only past the cursor', async () => {
169
+ const { ingest, calls } = fakeIngest(['one', 'two']);
170
+ const tracker = new SandboxTracker();
171
+ tracker.cursor = 10;
172
+ // Old viewers ignore `after` and return newest-first; the page also
173
+ // contains events at/below the cursor which must be ignored.
174
+ await processEvents([
175
+ exec(12, 20, 1, ['/bin/bash', '-lc', 'two']),
176
+ exec(11, 19, 1, ['/bin/bash', '-lc', 'one']),
177
+ exec(10, 18, 1, ['/bin/bash', '-lc', 'already seen']),
178
+ exec(9, 17, 1, ['/bin/bash', '-lc', 'older']),
179
+ ], { sessionId: SESSION, tracker, ingest, finish: async () => true });
180
+ assert.deepEqual(calls.map((c) => c.events[0].command), ['/bin/bash -lc one', '/bin/bash -lc two']);
181
+ assert.equal(tracker.cursor, 12);
182
+ });
183
+
184
+ test('malformed pages and events never throw', async () => {
185
+ const tracker = new SandboxTracker();
186
+ const deps = { sessionId: SESSION, tracker, ingest: async () => new Map(), finish: async () => true };
187
+ const none = { forwarded: 0, matched: 0, finished: 0, descendants: 0, unattributed: 0, failedExecs: 0, lost: 0 };
188
+ assert.deepEqual(await processEvents(undefined, deps), none);
189
+ assert.deepEqual(await processEvents([null, {}, { kind: 'exec_succeeded' }, { event_id: 'x', kind: 'process_exit' }], deps), none);
190
+ });
191
+
192
+ test('startGvisorForwarder discovers sandboxes from the manager and tails each container from the viewer', async () => {
193
+ const requested = [];
194
+ const fetchImpl = async (url) => {
195
+ requested.push(url);
196
+ if (url.endsWith('/api/projects')) {
197
+ return { ok: true, json: async () => [
198
+ { id: SESSION, container_id: CONTAINER, status: 'running' },
199
+ { id: 'rtp-short', container_id: CONTAINER }, // invalid ids are ignored
200
+ { id: 'rtp-' + 'b'.repeat(32), container_id: null }, // no container yet: ignored
201
+ ] };
202
+ }
203
+ // limit=1 is the cursor seed probe; this container has no history yet.
204
+ if (url.includes('limit=1')) return { ok: true, json: async () => ({ events: [], next_before: null }) };
205
+ if (url.includes('/events?')) return { ok: true, json: async () => ({ events: [exec(1, 5, 1, ['/bin/bash', '-lc', 'pwd']), exit(2, 5, 0)], next_before: null }) };
206
+ throw new Error('unexpected ' + url);
207
+ };
208
+ const { ingest } = fakeIngest(['pwd']);
209
+ const finished = [];
210
+ const logs = [];
211
+ const forwarder = startGvisorForwarder({ ingest, finish: async (row) => { finished.push(row); return true; }, fetchImpl, log: (m) => logs.push(m), pollMs: 60_000, discoverMs: 60_000 });
212
+ try {
213
+ await forwarder.discover();
214
+ assert.equal(forwarder.sandboxes.size, 1);
215
+ assert.equal(forwarder.sandboxes.get(CONTAINER).sessionId, SESSION);
216
+ await forwarder.poll();
217
+ const viewerUrl = requested.find((u) => u.includes('limit=500'));
218
+ assert.match(viewerUrl, new RegExp(`container=${CONTAINER}&after=0&limit=500&processes=1`));
219
+ assert.equal(finished.length, 1);
220
+ assert.equal(forwarder.sandboxes.get(CONTAINER).tracker.cursor, 2);
221
+ assert.ok(logs.some((m) => m.includes('forwarding evidence for sandbox')));
222
+ assert.ok(logs.some((m) => m.includes('1 exec(s) matched')));
223
+ // A second poll asks from the advanced cursor.
224
+ await forwarder.poll();
225
+ assert.ok(requested.some((u) => u.includes('&after=2&')));
226
+ } finally { forwarder.stop(); }
227
+ });
228
+
229
+ test('a newly discovered sandbox starts at the newest event, not at zero', async () => {
230
+ // The collector's evidence store lives in the VM and is append-only, so it
231
+ // outlives the proxy. Beginning at 0 re-reads every past session: none of it
232
+ // can match (no proposed calls were captured then), so it all lands as
233
+ // unattributed rows and pushes the live session behind days of backlog.
234
+ const requested = [];
235
+ const fetchImpl = async (url) => {
236
+ requested.push(url);
237
+ if (url.endsWith('/api/projects')) return { ok: true, json: async () => [{ id: SESSION, container_id: CONTAINER }] };
238
+ if (url.includes('limit=1')) return { ok: true, json: async () => ({ events: [exec(4096, 9, 1, ['old', 'history'])] }) };
239
+ return { ok: true, json: async () => ({ events: [] }) };
240
+ };
241
+ const logs = [];
242
+ const forwarder = startGvisorForwarder({ ingest: async () => new Map(), finish: async () => true, fetchImpl, log: (m) => logs.push(m), pollMs: 60_000, discoverMs: 60_000 });
243
+ try {
244
+ await forwarder.discover();
245
+ assert.equal(forwarder.sandboxes.get(CONTAINER).tracker.cursor, 4096, 'seeded past the backlog');
246
+ await forwarder.poll();
247
+ assert.ok(requested.some((u) => u.includes('&after=4096&')), 'tails forward from there');
248
+ assert.ok(logs.some((m) => m.includes('from event 4096')));
249
+ } finally { forwarder.stop(); }
250
+ });
251
+
252
+ test('an unreachable viewer during discovery falls back to replaying rather than skipping evidence', async () => {
253
+ const fetchImpl = async (url) => {
254
+ if (url.endsWith('/api/projects')) return { ok: true, json: async () => [{ id: SESSION, container_id: CONTAINER }] };
255
+ throw new Error('ECONNREFUSED');
256
+ };
257
+ const forwarder = startGvisorForwarder({ ingest: async () => new Map(), finish: async () => true, fetchImpl, log: () => {}, pollMs: 60_000, discoverMs: 60_000 });
258
+ try {
259
+ await forwarder.discover();
260
+ // Over-inclusive is recoverable; starting blind loses evidence silently.
261
+ assert.equal(forwarder.sandboxes.get(CONTAINER).tracker.cursor, 0);
262
+ } finally { forwarder.stop(); }
263
+ });
264
+
265
+ test('startGvisorForwarder logs an unreachable manager once and stays idle rather than failing', async () => {
266
+ const logs = [];
267
+ const forwarder = startGvisorForwarder({ ingest: async () => new Map(), finish: async () => true, fetchImpl: async () => { throw new Error('ECONNREFUSED'); }, log: (m) => logs.push(m), pollMs: 60_000, discoverMs: 60_000 });
268
+ try {
269
+ await forwarder.discover();
270
+ await forwarder.discover();
271
+ assert.equal(logs.filter((m) => m.includes('sandbox manager not reachable')).length, 1);
272
+ await forwarder.poll(); // nothing to poll; must not throw
273
+ assert.equal(forwarder.sandboxes.size, 0);
274
+ } finally { forwarder.stop(); }
275
+ });
276
+
277
+ const BASE = 1_700_000_000_000;
278
+ const PREFIX = `gvisor-${'c'.repeat(12)}-`;
279
+
280
+ test('clockFromSamples trusts the shortest round trip, and is unmeasured with no samples', () => {
281
+ assert.deepEqual(clockFromSamples([{ offsetMs: 3100, rttMs: 40 }, { offsetMs: 2990, rttMs: 4 }, { offsetMs: 3500, rttMs: 900 }]),
282
+ { offsetMs: 2990, marginMs: 252, measured: true });
283
+ assert.equal(clockFromSamples([]), UNMEASURED_CLOCK);
284
+ assert.equal(clockFromSamples([{ offsetMs: NaN, rttMs: 1 }]), UNMEASURED_CLOCK);
285
+ });
286
+
287
+ test('exec times are shifted onto the proxy clock, carrying the measured margin', () => {
288
+ // The VM clock runs 3 s ahead: an exec it stamps at +3 s happened at +0 s for us.
289
+ const event = toExecutionEvent(exec(1, 10, 1, ['ls'], BASE + 3000), { offsetMs: 3000, marginMs: 260 });
290
+ assert.equal(event.timestamp, BASE);
291
+ assert.equal(event.margin, 260);
292
+ });
293
+
294
+ test('a failed execve under a matched command gets its own failed row instead of vanishing', async () => {
295
+ const tracker = new SandboxTracker();
296
+ tracker.live.set(100, { execId: `${PREFIX}1`, callId: 'call_x' });
297
+ const descended = [];
298
+ const failed = { event_id: 5, kind: 'exec_failed', pid: 101, ppid: 100, argv: ['./script.sh'], errno: 13, container_id: CONTAINER, timestamp_ns: NS(BASE + 5) };
299
+ const counts = await processEvents([failed], { sessionId: SESSION, tracker, ingest: async () => new Map(), finish: async () => true,
300
+ descend: async (row) => { descended.push(row); } });
301
+ assert.equal(counts.failedExecs, 1);
302
+ assert.equal(descended[0].parent_call_id, 'call_x');
303
+ assert.equal(descended[0].tier, 'corroborated');
304
+ assert.equal(descended[0].exec.status, 'failed');
305
+ assert.equal(descended[0].exec.error, 'exec failed: errno 13');
306
+ assert.equal(descended[0].exec.ended_at, new Date(BASE + 5).toISOString());
307
+ assert.equal(tracker.live.has(101), false, 'nothing ran, so nothing is tracked');
308
+ assert.equal(toFailedExec({ ...failed, argv: [], executable: '' }), null);
309
+ });
310
+
311
+ test('an exit with no in-memory link (proxy restarted) is closed by pid + start time', async () => {
312
+ const closed = [];
313
+ const counts = await processEvents([{ ...exit(9, 42, 3), process_start_ns: '555' }], {
314
+ sessionId: SESSION, tracker: new SandboxTracker(), ingest: async () => new Map(), finish: async () => { throw new Error('no live entry to finish'); },
315
+ finishByProcess: async (row) => { closed.push(row); return true; } });
316
+ assert.equal(counts.finished, 1);
317
+ const { raw, ...row } = closed[0];
318
+ assert.deepEqual(row, { container_id: CONTAINER, session_id: SESSION, pid: 42, start_time_ns: '555', ended_at: new Date(BASE + 9).toISOString(),
319
+ ended_ms: BASE + 9, status: 'failed', error: 'exit 3', exit_code: 3, signal: null });
320
+ assert.equal(raw.event_id, 9);
321
+ });
322
+
323
+ test('a sandbox\'s collector disconnecting marks its open rows unknown and forgets its live pids', async () => {
324
+ const tracker = new SandboxTracker();
325
+ tracker.live.set(100, { execId: `${PREFIX}1`, callId: 'call_x' });
326
+ const lost = [];
327
+ const counts = await processEvents([{ event_id: 7, kind: 'collector_disconnected', container_id: CONTAINER }], {
328
+ sessionId: SESSION, tracker, ingest: async () => new Map(), finish: async () => true,
329
+ lose: async (row) => { lost.push(row); return 2; } });
330
+ assert.deepEqual(lost, [{ container_id: CONTAINER, session_id: SESSION, reason: 'collector disconnected', raw: { event_id: 7, kind: 'collector_disconnected', container_id: CONTAINER } }]);
331
+ assert.equal(counts.lost, 2);
332
+ assert.equal(tracker.live.size, 0);
333
+ });
334
+
335
+ test('startGvisorForwarder measures the VM clock, falls back when it cannot, and closes out removed sandboxes', async () => {
336
+ let listed = true;
337
+ let timeUp = true;
338
+ const fetchImpl = async (url) => {
339
+ if (url.endsWith('/api/projects')) return { ok: true, json: async () => (listed ? [{ id: SESSION, container_id: CONTAINER }] : []) };
340
+ if (url.endsWith('/time')) {
341
+ if (!timeUp) throw new Error('connection refused');
342
+ return { ok: true, json: async () => ({ realtime_ns: NS(Date.now() + 3000) }) };
343
+ }
344
+ if (url.includes('/events?')) return { ok: true, json: async () => ({ events: [] }) };
345
+ throw new Error('unexpected ' + url);
346
+ };
347
+ const lost = [];
348
+ const logs = [];
349
+ const forwarder = startGvisorForwarder({ ingest: async () => new Map(), finish: async () => true, lose: async (row) => { lost.push(row); return 1; },
350
+ fetchImpl, log: (m) => logs.push(m), pollMs: 60_000, discoverMs: 60_000 });
351
+ try {
352
+ await forwarder.discover();
353
+ assert.equal(forwarder.clock().measured, true);
354
+ assert.ok(Math.abs(forwarder.clock().offsetMs - 3000) < 100, `offset ${forwarder.clock().offsetMs}`);
355
+
356
+ timeUp = false;
357
+ await forwarder.discover();
358
+ await forwarder.discover();
359
+ assert.equal(forwarder.clock().measured, true, 'a failed sample keeps the last good mapping');
360
+ assert.equal(logs.filter((m) => m.includes('could not read the sandbox clock')).length, 1, 'logged once per outage');
361
+
362
+ listed = false;
363
+ await forwarder.discover();
364
+ assert.equal(forwarder.sandboxes.size, 0);
365
+ assert.deepEqual(lost, [{ container_id: CONTAINER, session_id: SESSION, reason: 'sandbox removed', ended: true }]);
366
+ assert.ok(logs.some((m) => m.includes('is gone') && m.includes('1 open execution(s) marked unknown')));
367
+ } finally { forwarder.stop(); }
368
+ });
@@ -131,6 +131,36 @@ function seed(db, data, fresh, adding = false) {
131
131
  for (const [id, label, description] of fileLabels) insertOrVerify(db, 'file_labels', 'id', { id, label, description }, fresh);
132
132
  }
133
133
 
134
+ /** Verifies an existing database is compatible without mutating it. */
135
+ export function verifyEvidenceDatabase(outputPath) {
136
+ if (typeof outputPath !== 'string' || !outputPath.trim() || outputPath === ':memory:') {
137
+ throw Error('An explicit standalone database file path is required');
138
+ }
139
+ if (!existsSync(outputPath)) {
140
+ throw Error(`Database file does not exist: ${outputPath}`);
141
+ }
142
+ const path = realpathSync(outputPath);
143
+ const sql = schemaSql();
144
+ const reference = new DatabaseSync(':memory:');
145
+ let db;
146
+ try {
147
+ reference.exec('PRAGMA foreign_keys=ON');
148
+ reference.exec(sql);
149
+ const expected = structure(reference);
150
+ db = new DatabaseSync(path, { readOnly: true });
151
+ const existing = structure(db);
152
+ const version = db.prepare('PRAGMA user_version').get()?.user_version;
153
+ if (version !== SCHEMA_VERSION) {
154
+ throw Error(`Incompatible schema version ${version}; expected ${SCHEMA_VERSION}`);
155
+ }
156
+ same(existing, expected, 'schema structure');
157
+ return { path, schemaVersion: version };
158
+ } finally {
159
+ db?.close();
160
+ reference.close();
161
+ }
162
+ }
163
+
134
164
  /** Creates a new standalone database, or verifies an existing compatible one. */
135
165
  export function initializeEvidenceDatabase(outputPath) {
136
166
  if (typeof outputPath !== 'string' || !outputPath.trim() || outputPath === ':memory:') {
@@ -0,0 +1,30 @@
1
+ /**
2
+ * The local API's credential: a random token in the data folder, readable only
3
+ * by the user who runs RayTrace. Binding to 127.0.0.1 keeps the network out and
4
+ * the Origin and Host checks keep web pages out, but neither says anything
5
+ * about another account on the same machine; this file's mode does.
6
+ */
7
+ import { randomBytes } from 'node:crypto';
8
+ import { chmodSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
9
+ import { homedir } from 'node:os';
10
+ import { join } from 'node:path';
11
+
12
+ const FILE = 'api-token';
13
+
14
+ /** The data folder of a caller the CLI did not start, such as the Claude Code hook. */
15
+ export const dataFolder = () => process.env.RAYTACE_DATA_DIR || process.env.RAYTRACE_HOME || join(homedir(), '.raytrace');
16
+
17
+ export function readToken(folder = dataFolder()) {
18
+ try { return readFileSync(join(folder, FILE), 'utf8').trim() || null; } catch { return null; }
19
+ }
20
+
21
+ /** The token, made on first use. Also closes the folder: what is recorded in it
22
+ * (prompts, tool output) is as private as the token. */
23
+ export function ensureToken(folder = dataFolder()) {
24
+ mkdirSync(folder, { recursive: true, mode: 0o700 });
25
+ try { chmodSync(folder, 0o700); } catch { /* not ours to change, or a filesystem without modes */ }
26
+ try { writeFileSync(join(folder, FILE), `${randomBytes(32).toString('hex')}\n`, { mode: 0o600, flag: 'wx' }); }
27
+ catch (error) { if (error.code !== 'EEXIST') throw error; }
28
+ chmodSync(join(folder, FILE), 0o600);
29
+ return readToken(folder);
30
+ }
@@ -0,0 +1,130 @@
1
+ import assert from 'node:assert/strict';
2
+ import test from 'node:test';
3
+ import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
4
+ import { tmpdir } from 'node:os';
5
+ import { join } from 'node:path';
6
+ import { startPlayground } from './playground.mjs';
7
+
8
+ const id = (letter) => `rtf-${letter.repeat(32)}`;
9
+ const job = (letter, status, extra = {}) => ({ id: id(letter), kind: 'fork', status,
10
+ created_at: new Date().toISOString(), check: { status: 'pending' }, ...extra });
11
+
12
+ async function fixture(t, records, initial = {}) {
13
+ const directory = await mkdtemp(join(tmpdir(), 'raytrace-recovery-test-'));
14
+ const statePath = join(directory, 'state.json');
15
+ const before = { path: process.env.PATH, ssh: process.env.RAYTACE_WORKER_SSH, lima: process.env.RAYTRACE_LIMACTL };
16
+ const saveHost = (state) => writeFile(statePath, JSON.stringify(state));
17
+ const host = async () => JSON.parse(await readFile(statePath, 'utf8'));
18
+ await saveHost({ calls: [], boxes: records.filter((r) => r.status !== 'queued').map((r) => ({ id: r.id, running: true })),
19
+ failStop: [], failList: false, ...initial });
20
+ // A fake host only changes an in-memory-fixture JSON file. No VM/provider is used.
21
+ await writeFile(join(directory, 'limactl'), `#!${process.execPath}
22
+ const fs = require('node:fs');
23
+ const file = ${JSON.stringify(statePath)};
24
+ const state = JSON.parse(fs.readFileSync(file, 'utf8'));
25
+ const [action, id] = process.argv.slice(process.argv.indexOf('/opt/raytace/projects.py') + 1);
26
+ state.calls.push([action, id]);
27
+ fs.writeFileSync(file, JSON.stringify(state));
28
+ if (action === 'fork-stop' && state.stopDelayMs) Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, state.stopDelayMs);
29
+ let code = 0;
30
+ if (action === 'fork-stop') {
31
+ const box = state.boxes.find((box) => box.id === id);
32
+ if (!box || state.failStop.includes(id)) code = 1;
33
+ else box.running = false;
34
+ } else if (action === 'list' && state.failList) code = 1;
35
+ else if (action === 'fork-delete') throw new Error('Recovery must retain recent fork data');
36
+ fs.writeFileSync(file, JSON.stringify(state));
37
+ if (code) console.error('Simulated unavailable worker or absent container');
38
+ else console.log(JSON.stringify(action === 'list' ? state.boxes : {}));
39
+ process.exitCode = code;
40
+ `, { mode: 0o700 });
41
+ process.env.PATH = directory + ':' + before.path;
42
+ process.env.RAYTRACE_LIMACTL = join(directory, 'limactl');
43
+ delete process.env.RAYTACE_WORKER_SSH;
44
+ t.after(async () => {
45
+ process.env.PATH = before.path;
46
+ if (before.ssh === undefined) delete process.env.RAYTACE_WORKER_SSH;
47
+ else process.env.RAYTACE_WORKER_SSH = before.ssh;
48
+ if (before.lima === undefined) delete process.env.RAYTRACE_LIMACTL;
49
+ else process.env.RAYTRACE_LIMACTL = before.lima;
50
+ await rm(directory, { recursive: true, force: true });
51
+ });
52
+ const saves = [];
53
+ const playground = startPlayground({ db: { loadExperiments: () => records,
54
+ saveExperiment(record) { saves.push(structuredClone(record)); } }, transcriptsDir: directory,
55
+ hookSource: () => '', orphans: false, log() {} });
56
+ return { playground, host, saveHost, saves };
57
+ }
58
+
59
+ test('recovery stops each known active fork before saving it interrupted, retaining kept data', async (t) => {
60
+ const records = ['creating', 'running', 'collecting', 'checking'].map((status, index) => job('abcd'[index], status, { keep: true }));
61
+ const { playground, host, saves } = await fixture(t, records);
62
+ await playground.recover();
63
+ const state = await host();
64
+ assert.equal(state.boxes.every((box) => !box.running), true);
65
+ assert.deepEqual(state.calls, records.map((record) => ['fork-stop', record.id]));
66
+ assert.equal(saves.length, 4);
67
+ for (const record of records) {
68
+ assert.equal(playground.get(record.id).status, 'interrupted');
69
+ assert.equal(playground.get(record.id).deleted_at, undefined);
70
+ assert.equal(playground.get(record.id).keep, true);
71
+ }
72
+ });
73
+
74
+ test('queued, completed and deleted jobs do not stop unrelated workers', async (t) => {
75
+ const records = [job('a', 'queued'), job('b', 'completed'), job('c', 'running', { deleted_at: 'already deleted' })];
76
+ const { playground, host } = await fixture(t, records, { boxes: [{ id: id('d'), running: true }] });
77
+ await playground.recover();
78
+ assert.equal(playground.get(id('a')).status, 'interrupted');
79
+ assert.ok(playground.get(id('a')).deleted_at);
80
+ assert.equal(playground.get(id('b')).status, 'completed');
81
+ assert.deepEqual((await host()).calls, []);
82
+ assert.equal((await host()).boxes[0].running, true);
83
+ });
84
+
85
+ test('failed stop remains active and blocks new runs until a successful recovery retry', async (t) => {
86
+ const record = job('a', 'checking');
87
+ const { playground, host, saveHost } = await fixture(t, [record], { failStop: [record.id] });
88
+ await playground.recover();
89
+ assert.equal(playground.get(record.id).status, 'checking');
90
+ assert.equal(playground.get(record.id).recovery_stop_pending, true);
91
+ assert.match(playground.get(record.id).error, /Could not confirm.*Restart RayTrace/);
92
+ assert.equal((await host()).boxes[0].running, true);
93
+ await assert.rejects(playground.create({}), /previous fork could not be stopped/);
94
+ await saveHost({ ...await host(), failStop: [] });
95
+ await playground.recover();
96
+ assert.equal(playground.get(record.id).status, 'interrupted');
97
+ assert.equal(playground.get(record.id).recovery_stop_pending, undefined);
98
+ assert.equal((await host()).boxes[0].running, false);
99
+ });
100
+
101
+ test('a creating job confirmed absent does not permanently block new runs', async (t) => {
102
+ const record = job('a', 'creating');
103
+ const { playground, host } = await fixture(t, [record], { boxes: [{ id: id('b'), running: true }] });
104
+ await playground.recover();
105
+ assert.equal(playground.get(record.id).status, 'interrupted');
106
+ assert.equal(playground.get(record.id).recovery_stop_pending, undefined);
107
+ assert.deepEqual((await host()).calls, [['fork-stop', record.id], ['list', null]]);
108
+ assert.equal((await host()).boxes[0].running, true);
109
+ });
110
+
111
+ test('failed host inventory cannot establish a missing fork is stopped', async (t) => {
112
+ const record = job('a', 'creating');
113
+ const { playground } = await fixture(t, [record], { boxes: [], failList: true });
114
+ await playground.recover();
115
+ assert.equal(playground.get(record.id).status, 'creating');
116
+ assert.equal(playground.get(record.id).recovery_stop_pending, true);
117
+ });
118
+
119
+ test('new fork creation is blocked while restart recovery is still stopping old work', async (t) => {
120
+ const record = job('a', 'running');
121
+ const { playground, host } = await fixture(t, [record], { stopDelayMs: 300 });
122
+ const recovery = playground.recover();
123
+ try {
124
+ await assert.rejects(playground.create({}), /previous fork could not be stopped/);
125
+ } finally {
126
+ await recovery;
127
+ }
128
+ assert.equal(playground.get(record.id).status, 'interrupted');
129
+ assert.equal((await host()).boxes[0].running, false);
130
+ });
@@ -200,6 +200,9 @@ export function startPlayground({ db, transcriptsDir, hookSource, log = console.
200
200
  const command = typeof config.check === 'string' ? config.check.trim() : '';
201
201
  if (command.length > 2000) throw new Error('The check command must be under 2000 characters.');
202
202
  if (controllers.size || queue.length) throw new Error('A fork is already running. Wait for it or delete it first.');
203
+ if ([...forks.values()].some((job) => job.recovery_stop_pending && !job.deleted_at)) {
204
+ throw new Error('A previous fork could not be stopped after a restart. Retry recovery or delete that fork before starting another.');
205
+ }
203
206
  const repeat = Math.min(maxRepeat, Math.max(1, Math.trunc(Number(config.repeat)) || 1));
204
207
  const found = await locate(config.exchange_id, results);
205
208
  if (!found) throw new Error('That step is not from a sandboxed Claude Code session, so it cannot be forked.');
@@ -366,7 +369,7 @@ export function startPlayground({ db, transcriptsDir, hookSource, log = console.
366
369
  async function retire(newest = null) {
367
370
  const now = Date.now();
368
371
  for (const job of forks.values()) {
369
- if (job.deleted_at || job.keep || job.status === 'queued' || controllers.has(job.id)) continue;
372
+ if (job.deleted_at || job.keep || job.recovery_stop_pending || job.status === 'queued' || controllers.has(job.id)) continue;
370
373
  const stale = job.id !== newest && (newest || now - Date.parse(job.created_at) > KEEP_LATEST_MS);
371
374
  if (stale) await remove(job.id).catch((error) => log(`[raytace][playground] could not delete ${job.id.slice(0, 12)}: ${error.message}`));
372
375
  }
@@ -375,9 +378,34 @@ export function startPlayground({ db, transcriptsDir, hookSource, log = console.
375
378
  /** After a restart: a fork that was mid-run cannot be followed any more. */
376
379
  async function recover() {
377
380
  for (const job of forks.values()) {
378
- if (['queued', 'creating', 'running', 'collecting', 'checking'].includes(job.status) && !controllers.has(job.id)) {
381
+ if (!job.deleted_at && ['queued', 'creating', 'running', 'collecting', 'checking'].includes(job.status) && !controllers.has(job.id)) {
382
+ if (job.status !== 'queued') {
383
+ // The worker may have survived the service and its timeout controller.
384
+ // Retaining a recent or kept fork must retain its files, not its execution.
385
+ job.recovery_stop_pending = true; // block new work while the stop is in flight too
386
+ try {
387
+ await vmJson('fork-stop', job.id, null);
388
+ } catch (error) {
389
+ // A creating job may not have made its container. Confirm absence
390
+ // with a successful host inventory; an unreachable host proves nothing.
391
+ let absent = false;
392
+ try {
393
+ const inventory = await vmAction('list', null, null);
394
+ const boxes = inventory.code === 0 ? JSON.parse(inventory.stdout) : null;
395
+ absent = Array.isArray(boxes) && !boxes.some((box) => box.id === job.id);
396
+ } catch { /* keep the unknown state visible and retryable */ }
397
+ if (!absent) {
398
+ job.recovery_stop_pending = true;
399
+ job.error = `RayTrace restarted. Could not confirm this fork stopped: ${String(error.message ?? error).slice(0, 300)}. Restart RayTrace to retry recovery, or delete the fork.`;
400
+ save(job);
401
+ log(`[raytace][playground] ${job.id.slice(0, 12)} recovery stop failed: ${job.error}`);
402
+ continue;
403
+ }
404
+ }
405
+ }
406
+ delete job.recovery_stop_pending;
379
407
  if (job.status === 'queued') job.deleted_at = new Date().toISOString(); // never had a sandbox
380
- job.error = job.status === 'queued' ? 'RayTrace restarted before this run started.' : 'RayTrace restarted while this fork was running.';
408
+ job.error = job.status === 'queued' ? 'RayTrace restarted before this run started.' : 'RayTrace restarted while this fork was running; its sandbox is stopped or no longer exists.';
381
409
  job.status = 'interrupted';
382
410
  if (job.check && ['pending', 'running'].includes(job.check.status)) job.check.status = 'error';
383
411
  save(job);
@@ -0,0 +1,32 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { promptInfo, latestSessionRows } from './prompt-traces.mjs';
4
+
5
+ test('only the latest launched session is shown, even when an older session finishes later', () => {
6
+ const rows = [
7
+ { span_id: 'legacy' },
8
+ { session_id: 'old', session_started_at: '2026-09-09T10:00:00Z' },
9
+ { session_id: 'new', session_started_at: '2026-09-09T11:00:00Z' },
10
+ { session_id: 'old', session_started_at: '2026-09-09T10:00:00Z' },
11
+ { session_id: 'new', session_started_at: '2026-09-09T11:00:00Z' },
12
+ ];
13
+ assert.deepEqual(latestSessionRows(rows), [rows[2], rows[4]]);
14
+ assert.equal(rows.length, 5);
15
+ assert.deepEqual(latestSessionRows([rows[0]]), []);
16
+ });
17
+
18
+ const user = (text) => ({ role: 'user', content: [{ type: 'input_text', text }] });
19
+ const context = user('<environment_context>local</environment_context>');
20
+ test('labels use actual user text and omit background title jobs and context-only requests', () => {
21
+ assert.equal(promptInfo({ input: [context, user('Whatever I actually typed')] }).title, 'Whatever I actually typed');
22
+ assert.equal(promptInfo({ input: [context] }), null);
23
+ assert.equal(promptInfo({ input: [user('Generate a concise, single-line task title of at most 36 characters\n\nUser prompt:\nhello')] }), null);
24
+ assert.equal(promptInfo({ input: [user('<in-app-browser-context source="ambient">metadata</in-app-browser-context>\n## My request:\nFix this')] }).title, 'Fix this');
25
+ });
26
+
27
+ test('catch-up requests are excluded before selecting the latest visible session', () => {
28
+ 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';
29
+ assert.equal(promptInfo({ input: [context, user(recap)] }), null);
30
+ assert.equal(promptInfo({ input: recap }), null);
31
+ assert.equal(promptInfo({ input: [user('Explain how catch-up summaries work')] }).title, 'Explain how catch-up summaries work');
32
+ });