@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,161 @@
1
+ import { test } from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { mkdtemp, rm } from 'node:fs/promises';
4
+ import { tmpdir } from 'node:os';
5
+ import { join } from 'node:path';
6
+ import { openEvidenceStore } from './evidence-store.mjs';
7
+ import { parseSearchQuery, reportedOutcome, combineOutcomes, pathsFromText } from './search.mjs';
8
+ import { failureSignature } from './failure-signature.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, run npm test and fix notes.md.' };
13
+ const CALL = { type: 'function_call', call_id: 'call_1', name: 'exec_command', arguments: '{"cmd":"cd /workspace/demo && npm test"}' };
14
+ const EDIT = { type: 'tool_use', call_id: 'call_2', name: 'Edit', input: { file_path: '/workspace/demo/notes.md', old_string: 'a', new_string: 'b' } };
15
+ const RESULT = (call_id, output) => ({ type: 'function_call_output', call_id, output });
16
+ const HEADER = (code, body) => `Wall time: 0.4 seconds\nProcess exited with code ${code}\nOutput:\n${body}`;
17
+
18
+ let clock = 0;
19
+ const exchange = (id, input, output, { status = 200 } = {}) => ({
20
+ event_type: 'model.exchange', span_id: id, trace_id: 't', session_id: SESSION, session_started_at: new Date(0).toISOString(),
21
+ provider: 'openrouter', route: '/v1/responses', method: 'POST',
22
+ timestamp: new Date(1_790_000_000_000 + (clock += 1000)).toISOString(),
23
+ completed_at: new Date(1_790_000_000_000 + clock + 400).toISOString(), metrics: { cost: 0.001 },
24
+ request: { headers: {}, bytes: 10, sha256: 'req', payload: { model: 'qwen', tools: [], input } },
25
+ response: { status, headers: {}, bytes: 20, sha256: 'res', payload: { output } },
26
+ });
27
+
28
+ async function withStore(run) {
29
+ const dir = await mkdtemp(join(tmpdir(), 'raytace-search-'));
30
+ const file = join(dir, 'evidence.db');
31
+ const store = openEvidenceStore(file);
32
+ try { await run(store, file); } finally { store.close(); await rm(dir, { recursive: true, force: true }); }
33
+ }
34
+
35
+ const FAILING = HEADER(1, "Error: Cannot find module './missing.js'");
36
+
37
+ function captureFailing(store, reported = FAILING) {
38
+ store.recordExchange(exchange('e1', [PROMPT], [CALL, EDIT]));
39
+ store.recordExchange(exchange('e2', [PROMPT, CALL, RESULT('call_1', reported), EDIT, { type: 'tool_result', call_id: 'call_2', content: 'edited' }],
40
+ [{ type: 'message', content: [{ type: 'output_text', text: 'Done.' }] }]));
41
+ }
42
+
43
+ test('parser: fields, phrases, negation, pipes, unknown fields', () => {
44
+ const parsed = parseSearchQuery('outcome:failed tool:Bash "permission denied" -flaky exit:>=1 bogus:x');
45
+ assert.deepEqual(parsed.filters, [
46
+ { field: 'outcome', value: 'failed', negated: false },
47
+ { field: 'tool', value: 'Bash', negated: false },
48
+ { field: 'exit_code', value: '>=1', negated: false },
49
+ ]);
50
+ assert.equal(parsed.text.length, 3); // phrase, -flaky, bogus:x as text
51
+ assert.deepEqual(parsed.errors, ['Unknown field: bogus']);
52
+ assert.deepEqual(parseSearchQuery('failed | stats count by tool').pipe, { type: 'stats', agg: 'count', by: 'tool' });
53
+ assert.deepEqual(parseSearchQuery('x | timechart count by model span=1d').pipe, { type: 'timechart', by: 'model', spanMs: 86_400_000 });
54
+ assert.equal(parseSearchQuery('perm*').text[0].prefix, true);
55
+ });
56
+
57
+ test('outcome truth table: missing evidence stays unknown', () => {
58
+ assert.equal(combineOutcomes('ok', 'failed'), 'failed');
59
+ assert.equal(combineOutcomes('failed', 'ok'), 'failed');
60
+ assert.equal(combineOutcomes('ok', 'unknown'), 'ok');
61
+ assert.equal(combineOutcomes('unknown', 'ok'), 'ok');
62
+ assert.equal(combineOutcomes('unknown', 'unknown'), 'unknown');
63
+ assert.equal(reportedOutcome(null), 'unknown');
64
+ assert.equal(reportedOutcome({ type: 'function_call_output', output: HEADER(2, 'boom') }), 'failed');
65
+ assert.equal(reportedOutcome({ type: 'function_call_output', output: HEADER(0, 'fine') }), 'ok');
66
+ assert.equal(reportedOutcome({ type: 'tool_result', is_error: true, content: 'no' }), 'failed');
67
+ });
68
+
69
+ test('failure signatures cluster volatile parts, split distinct errors', () => {
70
+ const a = failureSignature({ errorText: 'Error: ENOENT open /Users/a/proj/src/index.js', exitCode: 1, toolName: 'Bash' });
71
+ const b = failureSignature({ errorText: 'Error: ENOENT open /home/b/other/src/index.js', exitCode: 1, toolName: 'Bash' });
72
+ const c = failureSignature({ errorText: 'TypeError: x is not a function', exitCode: 1, toolName: 'Bash' });
73
+ assert.equal(a.signature, b.signature);
74
+ assert.notEqual(a.signature, c.signature);
75
+ const headed = failureSignature({ errorText: FAILING, exitCode: 1, toolName: 'exec_command' });
76
+ assert.match(headed.label, /cannot find module/);
77
+ assert.equal(failureSignature({ errorText: '' }), null);
78
+ });
79
+
80
+ test('captured failure is indexed and searchable by outcome, text and file', () => withStore((store) => {
81
+ captureFailing(store);
82
+ const failed = store.search({ q: 'outcome:failed kind:call' });
83
+ assert.equal(failed.mode, 'events');
84
+ assert.equal(failed.total, 1);
85
+ const [hit] = failed.hits;
86
+ assert.equal(hit.tool_name, 'exec_command');
87
+ assert.equal(hit.outcome_reported, 'failed');
88
+ assert.equal(hit.outcome_observed, 'unknown');
89
+ assert.equal(hit.exit_code, 1);
90
+ assert.ok(hit.failure_signature);
91
+ assert.equal(hit.turn_id.length > 0, true);
92
+ assert.equal(hit.external_call_id, 'call_1');
93
+
94
+ assert.equal(store.search({ q: '"cannot find module"' }).total, 1);
95
+ assert.equal(store.search({ q: 'missing' }).total >= 1, true);
96
+ assert.equal(store.search({ q: 'missing -module' }).total, 0);
97
+ assert.equal(store.search({ q: 'tool:Edit' }).total, 1);
98
+ assert.equal(store.search({ q: 'file:notes.md' }).total, 1);
99
+ assert.deepEqual([...pathsFromText('node src/parser.js && cat ./a/b.test.ts; echo v1.2 done')], ['src/parser.js', './a/b.test.ts']);
100
+ assert.equal(store.search({ q: 'exit:1' }).total, 1);
101
+ assert.equal(store.search({ q: 'exit:>=2' }).total, 0);
102
+ assert.equal(store.search({ q: 'kind:turn outcome:failed' }).total, 1, 'turn inherits its failed call');
103
+ assert.equal(failed.summary.failed, 1);
104
+ assert.ok(failed.facets.tool.some((f) => f.value === 'exec_command'));
105
+ assert.ok(failed.histogram.length >= 1);
106
+ }));
107
+
108
+ test('agent reported ok but sandbox saw failure is findable as a mismatch', () => withStore((store) => {
109
+ captureFailing(store, HEADER(0, '1 passing'));
110
+ const [candidate] = store.candidatesInWindow(0, Number.MAX_SAFE_INTEGER, { sessionId: SESSION });
111
+ const t = candidate.window_start + 100;
112
+ const proc = store.recordProcessStart({ containerId: CONTAINER, projectId: SESSION,
113
+ raw: { event_id: 1, kind: 'exec_succeeded', pid: 108, ppid: 10, argv: ['/bin/bash', '-c', 'npm test'], container_id: CONTAINER, process_start_ns: '1000', timestamp_ns: String(BigInt(t) * 1_000_000n) }, startedMs: t });
114
+ store.attribute({ toolCallId: candidate.call_id, eventId: proc.eventId, method: 'window', score: 1, windowStartMs: candidate.window_start, windowEndMs: candidate.window_end });
115
+ store.recordProcessExit({ containerId: CONTAINER,
116
+ raw: { event_id: 2, kind: 'process_exit', pid: 108, container_id: CONTAINER, process_start_ns: '1000', exit_code: 1, timestamp_ns: String(BigInt(t + 300) * 1_000_000n) }, endedMs: t + 300, exit_code: 1 });
117
+
118
+ const mismatch = store.search({ q: 'reported:ok observed:failed' });
119
+ assert.equal(mismatch.total, 1);
120
+ assert.equal(mismatch.hits[0].outcome, 'failed');
121
+ assert.equal(mismatch.hits[0].exit_code, 1);
122
+ assert.equal(mismatch.summary.mismatched, 1);
123
+ }));
124
+
125
+ test('unanswered call with no process stays unknown, pipes aggregate', () => withStore((store) => {
126
+ store.recordExchange(exchange('e1', [PROMPT], [CALL]));
127
+ const unknown = store.search({ q: 'outcome:unknown kind:call' });
128
+ assert.equal(unknown.total, 1);
129
+ assert.equal(unknown.hits[0].failure_signature, null);
130
+
131
+ captureFailing(store);
132
+ const stats = store.search({ q: '| stats count by outcome' });
133
+ assert.equal(stats.mode, 'stats');
134
+ assert.ok(stats.rows.some((row) => row.key === 'failed' && row.count >= 1));
135
+ const chart = store.search({ q: 'failed | timechart count by tool span=1d' });
136
+ assert.equal(chart.mode, 'timechart');
137
+ assert.ok(chart.rows.length >= 1);
138
+
139
+ const clusters = store.failureSignatures({});
140
+ assert.equal(clusters.length, 1);
141
+ assert.match(clusters[0].label, /cannot find module/);
142
+ }));
143
+
144
+ test('backfill fills the index for captures that predate it; reindex rebuilds', async () => {
145
+ const dir = await mkdtemp(join(tmpdir(), 'raytace-search-backfill-'));
146
+ const file = join(dir, 'evidence.db');
147
+ try {
148
+ const first = openEvidenceStore(file);
149
+ captureFailing(first);
150
+ first.db.exec('DELETE FROM search_events');
151
+ assert.equal(first.search({ q: 'outcome:failed' }).total, 0);
152
+ first.close();
153
+ const reopened = openEvidenceStore(file);
154
+ try {
155
+ assert.equal(reopened.search({ q: 'outcome:failed kind:call' }).total, 1, 'reopen backfills');
156
+ reopened.db.exec('DELETE FROM search_events');
157
+ assert.ok(reopened.reindexSearch() >= 3);
158
+ assert.equal(reopened.search({ q: 'outcome:failed kind:call' }).total, 1);
159
+ } finally { reopened.close(); }
160
+ } finally { await rm(dir, { recursive: true, force: true }); }
161
+ });
@@ -0,0 +1,93 @@
1
+ import assert from 'node:assert/strict';
2
+ import test from 'node:test';
3
+ import { createServer } from 'node:http';
4
+ import { spawn } from 'node:child_process';
5
+ import { once } from 'node:events';
6
+ import { mkdtemp, rm } from 'node:fs/promises';
7
+ import { readToken } from './local-token.mjs';
8
+ import { tmpdir } from 'node:os';
9
+ import { join } from 'node:path';
10
+
11
+ // A deliberately small user-facing check: this is the shortest path proving
12
+ // the three things a local install must provide — capture, inspection, and a
13
+ // persisted counterfactual run — without Codex CLI or a paid provider.
14
+ test('smoke: capture → inspect → experiment', { timeout: 20000 }, async (t) => {
15
+ const directory = await mkdtemp(join(tmpdir(), 'raytace-smoke-'));
16
+ t.after(() => rm(directory, { recursive: true, force: true }));
17
+ const upstream = createServer(async (request, response) => {
18
+ for await (const _chunk of request) { /* consume the request body */ }
19
+ const body = JSON.stringify({
20
+ id: 'smoke-response', status: 'completed',
21
+ output: [{ type: 'function_call', name: 'read_file', arguments: '{"path":"README.md"}' }],
22
+ });
23
+ response.writeHead(200, { 'content-type': 'text/event-stream' });
24
+ response.end(`event: response.completed\ndata: ${JSON.stringify({ type: 'response.completed', response: JSON.parse(body) })}\n\n`);
25
+ });
26
+ upstream.listen(0, '127.0.0.1');
27
+ await once(upstream, 'listening');
28
+ t.after(() => { upstream.closeAllConnections(); upstream.close(); });
29
+
30
+ const child = spawn(process.execPath, ['--disable-warning=ExperimentalWarning', 'proxy/raytace-proxy.mjs'], {
31
+ cwd: join(import.meta.dirname, '..'),
32
+ env: {
33
+ ...process.env,
34
+ RAYTACE_PORT: '0',
35
+ RAYTACE_DATA_DIR: directory,
36
+ RAYTACE_DB: join(directory, 'evidence.db'),
37
+ RAYTACE_PROVIDER: 'openrouter',
38
+ OPENROUTER_API_KEY: 'smoke-secret',
39
+ RAYTACE_OPENROUTER_MODEL: 'coder',
40
+ RAYTACE_OPENROUTER_UPSTREAM: `http://127.0.0.1:${upstream.address().port}`,
41
+ },
42
+ stdio: ['ignore', 'pipe', 'pipe'],
43
+ });
44
+ const exited = once(child, 'exit');
45
+ t.after(async () => { if (child.exitCode === null) child.kill('SIGTERM'); await exited; });
46
+ const url = await new Promise((resolve, reject) => {
47
+ child.stdout.on('data', (chunk) => {
48
+ const match = String(chunk).match(/http:\/\/127\.0\.0\.1:\d+/);
49
+ if (match) resolve(match[0]);
50
+ });
51
+ child.stderr.on('data', (chunk) => reject(new Error(String(chunk))));
52
+ child.on('exit', (code) => reject(new Error(`Proxy exited before startup (${code})`)));
53
+ });
54
+
55
+ const signedIn = { authorization: `Bearer ${readToken(directory)}` };
56
+ const fetch = (address, init = {}) => globalThis.fetch(address, { ...init, headers: { ...signedIn, ...init.headers } });
57
+ const headers = { 'content-type': 'application/json', ...signedIn };
58
+ const captured = await fetch(`${url}/v1/responses`, {
59
+ method: 'POST', headers,
60
+ body: JSON.stringify({ model: 'smoke-model', stream: false, input: [{ role: 'user', content: 'Inspect the README.' }] }),
61
+ });
62
+ assert.equal(captured.status, 200);
63
+ const traces = await fetch(`${url}/raytace/traces`).then((response) => response.json());
64
+ assert.equal(traces.traces.length, 1);
65
+ const trace = traces.traces[0];
66
+ const exchangeId = JSON.parse(trace.events[0].raw).exchange_id;
67
+ const outputIndex = trace.events.find((event) => event.output_index === 0)?.output_index ?? 0;
68
+
69
+ const inspected = await fetch(`${url}/raytace/steps/${exchangeId}/${outputIndex}`);
70
+ assert.equal(inspected.status, 200);
71
+ const step = await inspected.json();
72
+ assert.equal(step.decision.calls[0].name, 'read_file');
73
+ assert.ok(step.evidence.length > 0);
74
+
75
+ const experiment = await fetch(`${url}/raytace/step-runs`, {
76
+ method: 'POST',
77
+ headers: { ...headers, origin: 'http://localhost:3000', 'x-raytace-experiment': '1' },
78
+ body: JSON.stringify({
79
+ exchange_id: exchangeId, output_index: outputIndex, evidence_id: step.evidence[0].id,
80
+ context: 'README.md exists', model: 'coder', mode: 'decision', repetitions: 2, max_requests: 2,
81
+ }),
82
+ });
83
+ assert.equal(experiment.status, 202);
84
+ let job = await experiment.json();
85
+ for (let attempt = 0; attempt < 100 && ['queued', 'running'].includes(job.status); attempt += 1) {
86
+ await new Promise((resolve) => setTimeout(resolve, 20));
87
+ job = await fetch(`${url}/raytace/experiments/${job.id}`).then((response) => response.json());
88
+ }
89
+ assert.equal(job.status, 'completed');
90
+ assert.equal(job.trials.length, 4);
91
+ const history = await fetch(`${url}/raytace/experiments`).then((response) => response.json());
92
+ assert.equal(history.experiments[0].status, 'completed');
93
+ });
@@ -0,0 +1,38 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { inspectStep, createStepRun, runDecision, selectedActionMatches } from './step-lab.mjs';
4
+ const call = (file) => ({ type: 'function_call', name: 'read_file', arguments: JSON.stringify({ file }) });
5
+ const entry = { provider: 'openrouter', route: '/v1/responses', payload: { model: 'a/model', input: [{ role: 'user', content: 'Find returnPayment in transaction.js' }, { type: 'function_call', call_id: '1', name: 'search', arguments: '{}' }, { type: 'function_call_output', call_id: '1', output: 'transaction.js contains returnPayment()' }], tools: [] }, response: { status: 'completed', output: [call('other.js'), call('transaction.js')] } };
6
+ const config = { exchange_id: 'e', output_index: 1, evidence_id: 'e:2', context: 'No matches', mode: 'decision', repetitions: 3, max_requests: 2 };
7
+
8
+ test('selected second call has its own target and prior evidence', () => {
9
+ const step = inspectStep(entry, 'e', 1);
10
+ assert.match(step.decision.label, /transaction.js/);
11
+ assert.equal(step.hypotheses[0].evidence_id, 'e:2');
12
+ assert.match(step.hypotheses[0].title, /transaction.js/);
13
+ assert.equal(selectedActionMatches(entry.response, step.decision), true);
14
+ assert.equal(selectedActionMatches({ status: 'completed', output: [call('other.js')] }, step.decision), false);
15
+ assert.throws(() => inspectStep(entry, 'e', 10), /Select/);
16
+ });
17
+ test('context editing preserves the original and call IDs; chosen model applies to both arms', async () => {
18
+ const original = structuredClone(entry);
19
+ const { job, baseline, variant } = createStepRun(entry, config, 'b/model');
20
+ assert.equal(variant.input[2].output, 'No matches'); assert.equal(variant.input[2].call_id, '1');
21
+ assert.equal(baseline.model, 'b/model'); assert.equal(variant.model, 'b/model');
22
+ const invoked = [];
23
+ await runDecision(job, baseline, variant, async (payload) => {
24
+ invoked.push(payload);
25
+ return { status: 'completed', output: payload.input[2].output === 'No matches' ? [call('other.js')] : [call('other.js'), call('transaction.js')], usage: { cost: 0.01 } };
26
+ }, new AbortController().signal);
27
+ assert.equal(invoked.length, 6); assert.equal(job.summary.baseline.rate, 1); assert.equal(job.summary.intervention.rate, 0);
28
+ assert.equal(job.status, 'completed'); assert.deepEqual(entry, original);
29
+ });
30
+ test('reject invalid edits/counts and model-specific cross-model state; cancellation makes no calls', async () => {
31
+ for (const repetitions of [0, 1, 2.5, 21]) assert.throws(() => createStepRun(entry, { ...config, repetitions }, 'a/model'));
32
+ assert.throws(() => createStepRun(entry, { ...config, evidence_id: 'elsewhere' }, 'a/model'));
33
+ const stateful = structuredClone(entry); stateful.payload.input.push({ type: 'reasoning', encrypted_content: 'opaque' });
34
+ assert.throws(() => createStepRun(stateful, config, 'b/model'), /model-specific/);
35
+ const { job, baseline, variant } = createStepRun(entry, config, 'a/model');
36
+ await runDecision(job, baseline, variant, () => { throw new Error('Must not call'); }, AbortSignal.abort());
37
+ assert.equal(job.status, 'cancelled'); assert.equal(job.trials.length, 0);
38
+ });
@@ -0,0 +1,69 @@
1
+ import { test } from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { stripBoilerplate, excerpt, compactExchange, summaryRequest, parseSummary } from './summaries.mjs';
4
+
5
+ test('stripBoilerplate removes timestamps, pid/hostname lines and ANSI codes', () => {
6
+ const raw = 'pid: 4821\nhostname: worker-3\n2026-09-10T12:00:00.123Z started\n\x1b[32mok\x1b[0m\nreal output line';
7
+ const stripped = stripBoilerplate(raw);
8
+ assert.ok(!stripped.includes('pid:'));
9
+ assert.ok(!stripped.includes('hostname:'));
10
+ assert.ok(!stripped.includes('2026-09-10T12:00:00'));
11
+ assert.ok(!stripped.includes('\x1b['));
12
+ assert.ok(stripped.includes('real output line'));
13
+ });
14
+
15
+ test('excerpt keeps content under budget and prioritizes error lines', () => {
16
+ const long = Array.from({ length: 200 }, (_, i) => `line ${i} did something fine`).join('\n');
17
+ const withError = `${long}\nTraceback: something broke here\n${long}`;
18
+ const bounded = excerpt(withError, 200);
19
+ assert.ok(bounded.length <= 220); // a little slack for the error-only path
20
+ assert.ok(bounded.includes('Traceback'));
21
+ });
22
+
23
+ test('excerpt falls back to head+tail when there is no error', () => {
24
+ const long = Array.from({ length: 200 }, (_, i) => `line ${i}`).join('\n');
25
+ const bounded = excerpt(long, 100);
26
+ assert.ok(bounded.length <= 110);
27
+ assert.ok(bounded.startsWith('line 0'));
28
+ assert.ok(bounded.includes('line 199') || bounded.includes('…'));
29
+ });
30
+
31
+ test('compactExchange pulls the decision label and the latest tool result only', () => {
32
+ const entry = {
33
+ payload: { model: 'gpt', input: [
34
+ { role: 'user', type: 'message', content: 'do the thing' },
35
+ { type: 'function_call_output', call_id: 'c1', output: 'pid: 100\nold result' },
36
+ { type: 'function_call_output', call_id: 'c2', output: 'pid: 200\nfresh result: build succeeded' },
37
+ ] },
38
+ response: { status: 'completed', output: [{ type: 'message', content: 'Done.' }] },
39
+ };
40
+ const compacted = compactExchange(entry, 'ex1');
41
+ assert.equal(compacted.decision.label, 'Text answer');
42
+ assert.ok(compacted.seen_before.excerpt.includes('fresh result'));
43
+ assert.ok(!compacted.seen_before.excerpt.includes('pid:'));
44
+ assert.ok(!compacted.seen_before.excerpt.includes('old result'));
45
+ });
46
+
47
+ test('summaryRequest stays within the combined token budget and produces a stable cache key', () => {
48
+ const hugeOutput = 'x'.repeat(20000);
49
+ const entry = {
50
+ payload: { model: 'gpt', input: [
51
+ { type: 'function_call_output', call_id: 'c1', output: hugeOutput },
52
+ ] },
53
+ response: { status: 'completed', output: [{ type: 'message', content: 'ok' }] },
54
+ };
55
+ const { key, payload } = summaryRequest(entry, 'ex1', 'openai/gpt-oss-120b');
56
+ assert.ok(payload.input.length <= 1400 + 50); // MAX_INPUT_CHARS with small slack
57
+ assert.equal(payload.max_output_tokens, 300);
58
+ assert.deepEqual(payload.reasoning, { effort: 'low' });
59
+ const again = summaryRequest(entry, 'ex1', 'openai/gpt-oss-120b');
60
+ assert.equal(key, again.key); // deterministic for identical compacted input+model
61
+ });
62
+
63
+ test('parseSummary requires a completed response with text', () => {
64
+ assert.throws(() => parseSummary({ status: 'incomplete' }), /incomplete/);
65
+ assert.throws(() => parseSummary({ status: 'completed', output: [] }), /no text/);
66
+ const result = parseSummary({ status: 'completed', output: [{ type: 'message', content: 'It ran the build and it passed.' }], usage: { input_tokens: 10, output_tokens: 5 } });
67
+ assert.equal(result.text, 'It ran the build and it passed.');
68
+ assert.equal(result.generated, true);
69
+ });
@@ -0,0 +1,38 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { omitToolChunkIds, toolResultStatus } from './tool-metadata.mjs';
4
+ const output = 'Chunk ID: 259a39\nWall time: 0.001 seconds\nProcess exited with code 0\nOutput:\nChunk ID: actual-file-content';
5
+ test('summarize execution status without exposing output or misreading file contents', () => {
6
+ assert.equal(toolResultStatus({ output }), 'Successful');
7
+ assert.equal(toolResultStatus({ output: output.replace('code 0', 'code 1') }), 'Failed');
8
+ assert.equal(toolResultStatus({ output: 'Wall time: 0.1 seconds\nProcess running with session ID 123\nOutput:\n' }), 'Still running');
9
+ assert.equal(toolResultStatus({ output: 'a file containing\nProcess exited with code 1' }), 'Result received');
10
+ assert.equal(toolResultStatus({ omitted: true }), 'Output omitted');
11
+ assert.equal(toolResultStatus({ output: '' }), 'No output');
12
+ assert.equal(toolResultStatus({ is_error: true, output: 'details' }), 'Failed');
13
+ });
14
+ test('remove runner chunk headers while preserving correlation IDs, content, and original payload', () => {
15
+ const original = { input: [{ type: 'function_call_output', call_id: 'call_123', chunk_id: '259a39', output }, { role: 'user', content: output }] };
16
+ const cleaned = omitToolChunkIds(original);
17
+ assert.equal(cleaned.input[0].call_id, 'call_123'); assert.equal(cleaned.input[0].chunk_id, undefined);
18
+ assert.ok(cleaned.input[0].output.startsWith('Wall time:')); assert.ok(cleaned.input[0].output.endsWith('Chunk ID: actual-file-content'));
19
+ assert.equal(cleaned.input[1].content, output); assert.equal(original.input[0].output, output);
20
+ });
21
+ test('strip evidence previews and structured text tool results', () => {
22
+ const evidence = omitToolChunkIds({ kind: 'tool result', content: output, preview: output });
23
+ assert.ok(evidence.content.startsWith('Wall time:')); assert.ok(evidence.preview.startsWith('Wall time:'));
24
+ const item = omitToolChunkIds({ type: 'tool_result', content: [{ type: 'text', text: output }] });
25
+ assert.ok(item.content[0].text.startsWith('Wall time:'));
26
+ });
27
+ test('toolResultFacts reads exit code and wall time from the runner header only', async () => {
28
+ const { toolResultFacts } = await import('./tool-metadata.mjs');
29
+ assert.deepEqual(toolResultFacts({ output }), { exitCode: 0, wallMs: 1 });
30
+ assert.deepEqual(toolResultFacts({ output: output.replace('code 0', 'code 3').replace('0.001', '1.5') }), { exitCode: 3, wallMs: 1500 });
31
+ // Still running: the wall time is how long Codex waited, not a run time.
32
+ assert.deepEqual(toolResultFacts({ output: 'Wall time: 10.0 seconds\nProcess running with session ID 7\nOutput:\n' }), { exitCode: null, wallMs: null });
33
+ // File contents that look like a header are not a header.
34
+ assert.deepEqual(toolResultFacts({ output: 'a file containing\nProcess exited with code 1' }), { exitCode: null, wallMs: null });
35
+ // The older shell tool's JSON metadata.
36
+ assert.deepEqual(toolResultFacts({ output: JSON.stringify({ output: 'ok', metadata: { exit_code: 2, duration_seconds: 0.25 } }) }), { exitCode: 2, wallMs: 250 });
37
+ assert.deepEqual(toolResultFacts(undefined), { exitCode: null, wallMs: null });
38
+ });
@@ -9,7 +9,7 @@ import { evidenceFor, outcome, proposedCommand } from './experiment-engine.mjs';
9
9
  import { callKind } from './tool-metadata.mjs';
10
10
  import { callCategory } from './call-category.mjs';
11
11
  import { latestSessionRows, promptAsWritten } from './prompt-traces.mjs';
12
- import { omitToolChunkIds, toolResultStatus } from './tool-metadata.mjs';
12
+ import { omitToolChunkIds, toolResultStatus, TOOL_RESULT_KINDS } from './tool-metadata.mjs';
13
13
  import { requestMetrics } from './request-metrics.mjs';
14
14
  import { describeCommand } from './exec-narrative.mjs';
15
15
 
@@ -54,7 +54,7 @@ export function splitExchange(row, replayReason = () => undefined) {
54
54
  let decision = null; try { decision = outcome(response); } catch { /* incomplete capture */ }
55
55
  const steps = [event('model', 'Context assembled', `${request.model || 'unknown model'} · ${input.length} input items · ${toolCount} available tools`, started, { exchange_id: row.span_id, model: request.model, stream: request.stream, input_items: input.length, tool_count: toolCount, reasoning: request.reasoning ?? null, replay_reason: reason, decision })];
56
56
  for (const item of input) {
57
- if (!/function_call_output|tool_result/i.test(item?.type || '')) continue;
57
+ if (!TOOL_RESULT_KINDS.includes(item?.type)) continue;
58
58
  const name = item.name || item.tool_name || item.call_id || 'tool';
59
59
  steps.push(event(toolKind(name), `Tool result: ${name}`, toolResultStatus(item), started, item));
60
60
  }
@@ -75,14 +75,14 @@ export function splitExchange(row, replayReason = () => undefined) {
75
75
  steps.push(event('model', `Exchange complete · ${row.response?.status || 'unknown'}`, `${row.request?.bytes || 0} B sent · ${row.response?.bytes || 0} B received`, completed, { response_status: response.status ?? null, http_status: row.response?.status ?? null, request_bytes: row.request?.bytes || 0, response_bytes: row.response?.bytes || 0, response_reasoning: response.reasoning ?? null }));
76
76
  return steps;
77
77
  }
78
- export async function readTraces(db, { includeHistory = false, evidence = true, replayReason = () => undefined } = {}) {
79
- const rows = (await db.exchangeRows({ history: includeHistory })).map(omitToolChunkIds);
78
+ export async function readTraces(db, { includeHistory = false, evidence = true, replayReason = () => undefined, turnId = null } = {}) {
79
+ const rows = (turnId && db?.turnExchanges ? await db.turnExchanges(turnId) : await db.exchangeRows({ history: includeHistory })).map(omitToolChunkIds);
80
80
  // Rows arrive already grouped: each carries its turn as trace_id and the
81
81
  // turn's prompt as promptTitle, decided once at capture (evidence-store.mjs).
82
82
  const groupedRows = rows;
83
83
  // The store already scopes the live view to the newest session; keep the
84
84
  // filter so captures made before session tracking behave as they always did.
85
- const exchangeRows = includeHistory ? groupedRows : (latestSessionRows(groupedRows).length ? latestSessionRows(groupedRows) : groupedRows);
85
+ const exchangeRows = (turnId || includeHistory) ? groupedRows : (latestSessionRows(groupedRows).length ? latestSessionRows(groupedRows) : groupedRows);
86
86
  // A tool call proposed in one captured exchange comes back as evidence (its
87
87
  // result) in a later one. Index call_id -> the exchange that first proposed it
88
88
  // so the UI can jump from "this evidence" to "the decision that produced it".
@@ -91,21 +91,34 @@ export async function readTraces(db, { includeHistory = false, evidence = true,
91
91
  const output = row.response?.payload?.output;
92
92
  if (!Array.isArray(output)) continue;
93
93
  for (const [outputIndex, item] of output.entries()) {
94
- if (item?.call_id && /function_call|tool_use|tool_call/i.test(item?.type || '') && !origins.has(item.call_id)) {
95
- const args = item.arguments ?? item.input ?? item.function?.arguments ?? '';
96
- origins.set(item.call_id, { call_id: item.call_id, trace_id: row.trace_id, exchange_id: row.span_id, output_index: outputIndex, name: item.name,
97
- kind: callKind(item.name),
98
- // What the call did, for the Tool column; null with its command
99
- // when only Jev can say (call-category.mjs resolveCategories).
100
- category: callCategory(item.name, args),
101
- proposed: proposedCommand(args, item.name) });
94
+ if (item?.call_id && /function_call|tool_use|tool_call/i.test(item?.type || '')) {
95
+ const scopedKey = `${row.session_id || ''}:${item.call_id}`;
96
+ if (!origins.has(scopedKey) || !origins.has(item.call_id)) {
97
+ const args = item.arguments ?? item.input ?? item.function?.arguments ?? '';
98
+ const info = {
99
+ call_id: item.call_id,
100
+ trace_id: row.trace_id,
101
+ session_id: row.session_id,
102
+ exchange_id: row.span_id,
103
+ output_index: outputIndex,
104
+ name: item.name,
105
+ kind: callKind(item.name),
106
+ // What the call did, for the Tool column; null with its command
107
+ // when only Jev can say (call-category.mjs resolveCategories).
108
+ category: callCategory(item.name, args),
109
+ proposed: proposedCommand(args, item.name)
110
+ };
111
+ if (!origins.has(scopedKey)) origins.set(scopedKey, info);
112
+ if (!origins.has(item.call_id)) origins.set(item.call_id, info);
113
+ }
102
114
  }
103
115
  }
104
116
  }
105
117
  const grouped = new Map();
106
118
  const shownResultsByTrace = new Map(); // trace_id -> Set(call_id) already rendered once
107
119
  for (const row of exchangeRows) {
108
- const trace = grouped.get(row.trace_id) || { id: row.trace_id, provider: row.provider, model: row.request?.payload?.model || 'unknown model', title: promptAsWritten(row.promptTitle), promptRaw: row.promptTitle, startedAt: row.timestamp, status: 'complete', events: [], evidence: [], requests: [] };
120
+ const trace = grouped.get(row.trace_id) || { id: row.trace_id, provider: row.provider, model: row.request?.payload?.model || 'unknown model', title: promptAsWritten(row.promptTitle), promptRaw: row.promptTitle, startedAt: row.timestamp, status: row.turn_status || 'complete', events: [], evidence: [], requests: [] };
121
+ if (row.turn_status) trace.status = row.turn_status;
109
122
  const shownResults = shownResultsByTrace.get(row.trace_id) || new Set();
110
123
  // rtp- a project's sandbox; rtf- a Playground fork of one (playground.mjs).
111
124
  if (/^rt[pf]-[a-f0-9]{32}$/.test(row.session_id || '')) trace.sandboxId = row.session_id;
@@ -118,7 +131,7 @@ export async function readTraces(db, { includeHistory = false, evidence = true,
118
131
  try { const text = outcome(row.response?.payload || {}).text; if (text) trace.answer = text; } catch { /* incomplete capture */ }
119
132
  trace.events.push(...splitExchange(row, replayReason).map((step) => {
120
133
  if (!step.title.startsWith('Tool result:')) return step;
121
- const raw = JSON.parse(step.raw); const origin = origins.get(raw.call_id);
134
+ const raw = JSON.parse(step.raw); const origin = origins.get(`${row.session_id || ''}:${raw.call_id}`) || origins.get(raw.call_id);
122
135
  // The tool result carries only a call_id and output, never the tool's
123
136
  // name — fall back to the exchange that originally proposed the call,
124
137
  // where the real name is known, instead of showing the raw id.
@@ -151,6 +164,25 @@ export async function readTraces(db, { includeHistory = false, evidence = true,
151
164
  // heuristic (succeeded, based on scanning the result text) wherever no
152
165
  // process was tied to the call, e.g. a session run outside the sandbox.
153
166
  for (const trace of grouped.values()) {
167
+ const shownResults = shownResultsByTrace.get(trace.id) || new Set();
168
+ const traceOrigins = [...origins.values()].filter((origin) => origin.trace_id === trace.id);
169
+ for (const origin of traceOrigins) {
170
+ if (!shownResults.has(origin.call_id)) {
171
+ const reported = db?.toolCallResult ? await db.toolCallResult(origin.call_id, { exchangeId: origin.exchange_id, sessionId: origin.session_id || trace.sandboxId }) : null;
172
+ if (reported) {
173
+ const rawItem = (reported && typeof reported === 'object')
174
+ ? { ...reported, call_id: origin.call_id }
175
+ : { call_id: origin.call_id, output: reported };
176
+ trace.events.push({
177
+ ...event(toolKind(origin.name), `Tool result: ${origin.name}`,
178
+ toolResultStatus(rawItem), trace.endedAt, rawItem),
179
+ exchange_id: origin.exchange_id,
180
+ output_index: origin.output_index
181
+ });
182
+ shownResults.add(origin.call_id);
183
+ }
184
+ }
185
+ }
154
186
  const spanIds = trace.requests.map((request) => request.id);
155
187
  const divergenceRows = (await db.divergence(spanIds)).filter((row) => row.call_id);
156
188
  const byCallId = new Map(divergenceRows.map((row) => [row.call_id, row]));
@@ -218,9 +250,8 @@ export async function readTraces(db, { includeHistory = false, evidence = true,
218
250
  // `origins` already has one entry per call_id with the exchange that
219
251
  // proposed it, so this is just that, decorated with whatever real
220
252
  // execution data (if any) `divergence()` found for the same call_id.
221
- const traceOrigins = [...origins.values()].filter((origin) => origin.trace_id === trace.id);
222
253
  // Where a sandboxed Claude Code's project folder stood after each call.
223
- const snapshots = await db.snapshotsForCalls(traceOrigins.map((origin) => origin.call_id));
254
+ const snapshots = await db.snapshotsForCalls(traceOrigins.map((origin) => origin.call_id), { sessionId: trace.sandboxId || trace.id });
224
255
  trace.callVerifications = traceOrigins.map((origin) => {
225
256
  const real = byCallId.get(origin.call_id);
226
257
  return {
@@ -258,7 +289,8 @@ export async function readTraces(db, { includeHistory = false, evidence = true,
258
289
 
259
290
  // Codex requests include a large tool schema. Return recent traces only so the
260
291
  // live dashboard stays responsive instead of repeatedly transferring history.
261
- const result = [...grouped.values()].sort((a, b) => b.startedAt.localeCompare(a.startedAt)).slice(0, includeHistory ? 100 : 10);
292
+ const sorted = [...grouped.values()].sort((a, b) => b.startedAt.localeCompare(a.startedAt));
293
+ const result = turnId ? sorted : sorted.slice(0, includeHistory ? 100 : 10);
262
294
  // Every request resends the whole conversation, so each earlier item comes
263
295
  // back once per later request: a long Claude Code session made one prompt
264
296
  // tens of MB, fetched every few seconds. An item is sent in full once; a
@@ -0,0 +1,72 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { readTraces } from './trace-view.mjs';
4
+
5
+ test('synthesizes terminal tool results for proposed calls with no subsequent exchange', async () => {
6
+ const fakeRow = {
7
+ span_id: 'span-1',
8
+ trace_id: 'trace-1',
9
+ session_id: 'rtp-12345678123456781234567812345678',
10
+ provider: 'claude-code',
11
+ timestamp: '2026-10-28T12:00:00.000Z',
12
+ promptTitle: 'test prompt',
13
+ request: {
14
+ payload: {
15
+ model: 'claude-3-5-sonnet',
16
+ input: [{ type: 'message', role: 'user', content: [{ type: 'input_text', text: 'run exit 7' }] }]
17
+ }
18
+ },
19
+ response: {
20
+ payload: {
21
+ output: [
22
+ {
23
+ type: 'function_call',
24
+ call_id: 'toolu_term_1',
25
+ name: 'Bash',
26
+ arguments: JSON.stringify({ command: 'exit 7' })
27
+ }
28
+ ]
29
+ }
30
+ }
31
+ };
32
+
33
+ const fakeDb = {
34
+ exchangeRows: async () => [fakeRow],
35
+ divergence: async () => [],
36
+ descendants: async () => [],
37
+ snapshotsForCalls: async () => new Map(),
38
+ toolCallResult: async (callId) => {
39
+ if (callId === 'toolu_term_1') {
40
+ return { call_id: 'toolu_term_1', is_error: true, exit_code: 7, output: 'Process exited with code 7' };
41
+ }
42
+ return null;
43
+ }
44
+ };
45
+
46
+ const traces = await readTraces(fakeDb, { includeHistory: true });
47
+ assert.equal(traces.length, 1);
48
+ const trace = traces[0];
49
+
50
+ const resultEvent = trace.events.find((e) => e.title.startsWith('Tool result:') && e.raw.includes('toolu_term_1'));
51
+ assert.ok(resultEvent, 'terminal tool result event was synthesized into trace.events');
52
+ const parsed = JSON.parse(resultEvent.raw);
53
+ assert.equal(parsed.call_id, 'toolu_term_1');
54
+ assert.equal(parsed.exit_code, 7);
55
+ assert.equal(parsed.is_error, true);
56
+ });
57
+
58
+ test('toolResultsFromTranscript extracts tool results from user messages', async () => {
59
+ const { toolResultsFromTranscript } = await import('./claude-code-adapter.mjs');
60
+ const lines = [
61
+ { type: 'user', message: { content: [{ type: 'text', text: 'hello' }] } },
62
+ { type: 'assistant', message: { id: 'msg_1', content: [{ type: 'tool_use', id: 'call_99', name: 'Bash', input: { command: 'ls' } }] } },
63
+ { type: 'user', message: { content: [{ type: 'tool_result', tool_use_id: 'call_99', content: 'file.txt', is_error: false }] } }
64
+ ];
65
+ const results = toolResultsFromTranscript(lines);
66
+ assert.equal(results.size, 1);
67
+ assert.deepEqual(results.get('call_99'), {
68
+ type: 'function_call_output',
69
+ call_id: 'call_99',
70
+ output: 'file.txt'
71
+ });
72
+ });