@raytrace-cli/cli 0.5.0 → 0.7.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 (59) hide show
  1. package/README.md +54 -2
  2. package/bin/raytrace.mjs +81 -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/api.mjs +57 -0
  44. package/src/auth.mjs +35 -1
  45. package/src/beta.mjs +96 -0
  46. package/src/claude-code.mjs +38 -1
  47. package/src/commands.mjs +69 -25
  48. package/src/config.mjs +16 -7
  49. package/src/export.mjs +200 -0
  50. package/src/lima.mjs +42 -1
  51. package/src/local-sandbox.mjs +19 -4
  52. package/src/paths.mjs +8 -8
  53. package/src/proxy-process.mjs +26 -3
  54. package/src/sandbox.mjs +73 -40
  55. package/src/upload.mjs +198 -0
  56. package/worker/sandbox/claude-hook.mjs +50 -17
  57. package/worker/sandbox/projects.py +3 -2
  58. package/worker/sandbox/transcript-delivery.test.mjs +153 -0
  59. package/worker/sandbox/viewer.py +21 -2
@@ -0,0 +1,233 @@
1
+ import { test } from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { DatabaseSync } from 'node:sqlite';
4
+ import { mkdtempSync, rmSync } from 'node:fs';
5
+ import { tmpdir } from 'node:os';
6
+ import { join } from 'node:path';
7
+ import { initializeEvidenceDatabase, CATALOG_VERSION_ID, SCHEMA_VERSION } from './init-evidence-db.mjs';
8
+
9
+ function isolated(run) {
10
+ const dir = mkdtempSync(join(tmpdir(), 'raytace-evidence-test-'));
11
+ const path = join(dir, 'evidence.db');
12
+ let db;
13
+ try {
14
+ initializeEvidenceDatabase(path);
15
+ db = new DatabaseSync(path);
16
+ db.exec('PRAGMA foreign_keys=ON');
17
+ return run(db, path, dir);
18
+ } finally { db?.close(); rmSync(dir, { recursive: true, force: true }); }
19
+ }
20
+
21
+ function insert(db, table, values, prefix = 'INSERT') {
22
+ db.prepare(`${prefix} INTO ${table} (${Object.keys(values).join(',')}) VALUES (${Object.keys(values).map(() => '?').join(',')})`).run(...Object.values(values));
23
+ }
24
+
25
+ function fixtures(db) {
26
+ for (const id of ['a', 'b']) {
27
+ insert(db, 'runtime_sandboxes', { id, external_container_id: id, runtime_name: 'gvisor', runtime_version: 'test', architecture: 'aarch64', capture_config_json: '{}' });
28
+ insert(db, 'runtime_processes', { id: `p-${id}`, sandbox_id: id, pid: 101, first_seen_ns: '9007199254740993000', identity_basis: 'test' });
29
+ }
30
+ insert(db, 'agent_sessions', { id: 's', started_at_ms: 100 });
31
+ insert(db, 'agent_turns', { id: 't', session_id: 's', sequence_number: 0, started_at_ms: 100 });
32
+ insert(db, 'agent_exchanges', { id: 'x', turn_id: 't', session_id: 's', provider: 'test', started_at_ms: 100 });
33
+ insert(db, 'agent_tool_calls', { id: 'tool', exchange_id: 'x', output_index: 0, tool_name: 'exec_command' });
34
+ }
35
+
36
+ let sequence = 0;
37
+ function event(db, id, overrides = {}) {
38
+ insert(db, 'runtime_events', { id, sandbox_id: 'a', process_id: 'p-a', stream_id: 'stream', stream_sequence: sequence++,
39
+ event_kind: 'syscall_enter', observed_at_ns: '9007199254740993001', received_at_ms: 100,
40
+ tid: 101, payload_json: '{"syscall_name":"unlinkat","syscall_number":35}', decoder_version: 'test', ...overrides });
41
+ }
42
+
43
+ function call(db, id, options = {}) {
44
+ const { outcome = 'succeeded', ...overrides } = options;
45
+ event(db, `${id}-entry`);
46
+ event(db, `${id}-exit`, { event_kind: 'syscall_exit', payload_json: JSON.stringify({ syscall_name: 'unlinkat', syscall_number: 35,
47
+ return_value: outcome === 'failed' ? '-1' : '0', errno: outcome === 'failed' ? 13 : 0 }) });
48
+ const row = { id, sandbox_id: 'a', process_id: 'p-a', tid: 101, syscall_name: 'unlinkat', syscall_number: 35,
49
+ entry_event_id: `${id}-entry`, exit_event_id: `${id}-exit`, arguments_json: '{"pathname":"notes.md"}',
50
+ return_value: outcome === 'failed' ? '-1' : '0', errno: outcome === 'failed' ? 13 : 0,
51
+ outcome, correlation_status: 'paired', normalizer_version: 'test', ...overrides };
52
+ insert(db, 'runtime_syscall_calls', row);
53
+ return row;
54
+ }
55
+
56
+ function result(db, id, callId, extra = {}) {
57
+ insert(db, 'classification_results', { id, syscall_call_id: callId, version_id: CATALOG_VERSION_ID,
58
+ input_sha256: 'a'.repeat(64), category_id: 'delete', operation_level: 3, confirmed_effect_level: 3,
59
+ effect_status: 'confirmed', reason: 'Test fixture, not automatic classification', classified_at_ms: 101, ...extra });
60
+ }
61
+
62
+ test('33 tables, catalog seeds and repeat initialization preserve evidence', () => isolated((db, path) => {
63
+ fixtures(db); call(db, 'delete');
64
+ assert.equal(db.prepare("SELECT count(*) n FROM sqlite_schema WHERE type='table' AND name NOT LIKE 'sqlite_%'").get().n, 33); // 20 evidence + 7 auxiliary + search_events + FTS5 (virtual + 4 shadows)
65
+ for (const [table, count] of [['classification_impact_levels', 4], ['classification_categories', 34], ['classification_syscall_rules', 353], ['file_labels', 6], ['classification_results', 0]]) {
66
+ assert.equal(db.prepare(`SELECT count(*) n FROM ${table}`).get().n, count);
67
+ }
68
+ const before = db.prepare('SELECT * FROM runtime_syscall_calls').all();
69
+ assert.equal(initializeEvidenceDatabase(path).created, false);
70
+ assert.deepEqual(db.prepare('SELECT * FROM runtime_syscall_calls').all(), before);
71
+ assert.deepEqual(db.prepare('PRAGMA foreign_key_check').all(), []);
72
+ assert.equal(db.prepare('SELECT classifier_version FROM classification_versions').get().classifier_version, 'not-implemented');
73
+ }));
74
+
75
+ test('cross-sandbox references are rejected, including nullable process context', () => isolated(db => {
76
+ fixtures(db);
77
+ assert.throws(() => db.exec("UPDATE runtime_processes SET parent_process_id='p-b' WHERE id='p-a'"), /FOREIGN KEY/);
78
+ assert.throws(() => event(db, 'wrong', { process_id: 'p-b' }), /FOREIGN KEY/);
79
+ assert.throws(() => event(db, 'no-sandbox', { sandbox_id: null }), /CHECK/);
80
+ event(db, 'other', { sandbox_id: 'b', process_id: 'p-b' });
81
+ assert.throws(() => insert(db, 'runtime_syscall_calls', { id: 'wrong', sandbox_id: 'a', syscall_number: 35,
82
+ entry_event_id: 'other', arguments_json: '{}', outcome: 'unknown', correlation_status: 'entry_only', normalizer_version: 'test' }), /FOREIGN KEY/);
83
+ call(db, 'ok');
84
+ insert(db, 'file_objects', { id: 'object-b', sandbox_id: 'b', object_type: 'regular', identity_basis: 'test', first_seen_ns: '1', last_seen_ns: '1' });
85
+ for (const values of [{ sandbox_id: 'b' }, { sandbox_id: 'a', file_object_id: 'object-b' }]) {
86
+ assert.throws(() => insert(db, 'file_operation_targets', { id: 'wrong-target', syscall_call_id: 'ok', target_role: 'target', resolution_status: 'unresolved', ...values }), /FOREIGN KEY/);
87
+ }
88
+ }));
89
+
90
+ test('PID reuse, repeated exec and collector-wide events are representable', () => isolated(db => {
91
+ fixtures(db);
92
+ insert(db, 'runtime_processes', { id: 'p-reused', sandbox_id: 'a', pid: 101, start_time_ns: '9007199254740994000', first_seen_ns: '9007199254740994001', identity_basis: 'start_time' });
93
+ event(db, 'exec1', { event_kind: 'exec_succeeded', payload_json: '{"executable":"sh"}' });
94
+ event(db, 'exec2', { event_kind: 'exec_succeeded', payload_json: '{"executable":"node"}' });
95
+ event(db, 'gap', { sandbox_id: null, process_id: null, tid: null, observed_at_ns: null, event_kind: 'collection_gap', payload_json: '{"dropped_delta":3}' });
96
+ assert.equal(db.prepare('SELECT started_at_ms FROM runtime_sandboxes LIMIT 1').get().started_at_ms, null);
97
+ const original = db.prepare("SELECT * FROM runtime_events WHERE id='exec1'").get();
98
+ assert.throws(() => insert(db, 'runtime_events', { ...original, id: 'duplicate' }), /cannot be replaced/);
99
+ assert.throws(() => insert(db, 'runtime_events', { ...original, id: 'replacement' }, 'INSERT OR REPLACE'), /cannot be replaced/);
100
+ assert.equal(db.prepare('SELECT count(*) n FROM runtime_attributions').get().n, 0);
101
+ }));
102
+
103
+ test('known outcomes require reliable phases, matching identities and decoded results', () => isolated(db => {
104
+ fixtures(db);
105
+ const success = call(db, 'success');
106
+ call(db, 'failure', { outcome: 'failed' });
107
+ insert(db, 'runtime_syscall_calls', { ...success, id: 'entry', exit_event_id: null, outcome: 'unknown', return_value: null, errno: null, correlation_status: 'entry_only' });
108
+ insert(db, 'runtime_syscall_calls', { ...success, id: 'exit', entry_event_id: null, correlation_status: 'exit_only' });
109
+ insert(db, 'runtime_syscall_calls', { ...success, id: 'uncertain', correlation_status: 'uncertain', outcome: 'unknown' });
110
+ for (const override of [
111
+ { outcome: 'failed' }, { outcome: 'unknown', errno: 13 }, { return_value: '1' }, { correlation_status: 'uncertain' },
112
+ { exit_event_id: null }, { syscall_number: 99 }, { syscall_name: 'write' }, { tid: 102 },
113
+ { entry_event_id: success.exit_event_id, exit_event_id: success.entry_event_id },
114
+ { return_value: '-0' }, { return_value: '00' }, { return_value: '1.5' },
115
+ ]) assert.throws(() => insert(db, 'runtime_syscall_calls', { ...success, id: 'bad', ...override }));
116
+ event(db, 'mismatched-thread', { tid: 102 });
117
+ assert.throws(() => insert(db, 'runtime_syscall_calls', { ...success, id: 'hidden-tid', tid: null, entry_event_id: 'mismatched-thread' }), /disagree/);
118
+ event(db, 'earlier-exit', { event_kind: 'syscall_exit', observed_at_ns: '9007199254740993000', payload_json: '{"return_value":"0","errno":0}' });
119
+ assert.throws(() => insert(db, 'runtime_syscall_calls', { ...success, id: 'backwards', exit_event_id: 'earlier-exit' }), /disagree/);
120
+ }));
121
+
122
+ test('classification preserves impact versus effect and is append-only even through REPLACE', () => isolated(db => {
123
+ fixtures(db);
124
+ call(db, 'success'); call(db, 'failure', { outcome: 'failed' });
125
+ call(db, 'unknown', { outcome: 'unknown', correlation_status: 'uncertain' });
126
+ result(db, 'r', 'success');
127
+ assert.throws(() => result(db, 'bad-fail', 'failure'), /successful syscall/);
128
+ assert.throws(() => result(db, 'bad-unknown', 'unknown'), /successful syscall/);
129
+ result(db, 'failed-class', 'failure', { confirmed_effect_level: null, effect_status: 'no_effect' });
130
+ assert.throws(() => result(db, 'bad-level', 'success', { input_sha256: 'b'.repeat(64), effect_status: 'unknown' }), /CHECK/);
131
+ for (const table of ['classification_versions', 'classification_syscall_rules', 'classification_results', 'classification_categories', 'classification_impact_levels']) {
132
+ assert.throws(() => db.exec(`DELETE FROM ${table}`), /append-only/);
133
+ const row = db.prepare(`SELECT * FROM ${table} LIMIT 1`).get();
134
+ const key = Object.keys(row)[0];
135
+ assert.throws(() => db.exec(`UPDATE ${table} SET ${key}=${key}`), /append-only/);
136
+ assert.throws(() => insert(db, table, row, 'INSERT OR REPLACE'), /cannot be replaced/);
137
+ }
138
+ const saved = db.prepare("SELECT * FROM classification_results WHERE id='r'").get();
139
+ assert.throws(() => insert(db, 'classification_results', { ...saved, id: 'replacement' }, 'INSERT OR REPLACE'), /cannot be replaced/);
140
+ }));
141
+
142
+ test('deletion joins to accepted tool attribution, classification and multiple file labels', () => isolated(db => {
143
+ fixtures(db); call(db, 'delete'); result(db, 'r', 'delete');
144
+ insert(db, 'runtime_attributions', { id: 'link', tool_call_id: 'tool', event_id: 'delete-exit', method: 'marker', confidence: 'exact', status: 'accepted', basis_json: '{}', attributor_version: 'test', created_at_ms: 100 });
145
+ for (const id of ['old-file', 'new-file']) insert(db, 'file_objects', { id, sandbox_id: 'a', object_type: 'regular', identity_basis: 'fixture', first_seen_ns: '1', last_seen_ns: '2' });
146
+ for (const [id, object] of [['target', 'old-file'], ['reused-path', 'new-file']]) {
147
+ insert(db, 'file_operation_targets', { id, syscall_call_id: 'delete', sandbox_id: 'a', file_object_id: object, target_role: 'target', observed_path: '/workspace/notes.md', resolution_status: 'runtime_resolved' });
148
+ }
149
+ for (const label of ['documentation', 'potentially_sensitive']) insert(db, 'file_label_assignments', { id: label, target_id: 'target', label_id: label, basis: 'fixture', confidence: 'inferred', rule_version: 'test', reason: 'test only', assigned_at_ms: 100 });
150
+ const rows = db.prepare(`SELECT tc.tool_name,c.label AS category,r.operation_level,r.effect_status,t.observed_path,l.label AS file_label
151
+ FROM runtime_attributions a JOIN agent_tool_calls tc ON tc.id=a.tool_call_id
152
+ JOIN runtime_syscall_calls s ON s.exit_event_id=a.event_id
153
+ JOIN classification_results r ON r.syscall_call_id=s.id
154
+ JOIN classification_categories c ON c.id=r.category_id
155
+ JOIN file_operation_targets t ON t.syscall_call_id=s.id
156
+ JOIN file_label_assignments fl ON fl.target_id=t.id JOIN file_labels l ON l.id=fl.label_id
157
+ WHERE a.status='accepted'`).all();
158
+ assert.equal(rows.length, 2);
159
+ assert.ok(rows.every(r => r.tool_name === 'exec_command' && r.operation_level === 3 && r.effect_status === 'confirmed' && r.observed_path === '/workspace/notes.md'));
160
+ assert.ok(rows.every(r => r.category === 'Delete'));
161
+ event(db, 'rename-entry', { payload_json: '{"syscall_name":"renameat2","syscall_number":276}' });
162
+ insert(db, 'runtime_syscall_calls', { id: 'rename', sandbox_id: 'a', syscall_name: 'renameat2', syscall_number: 276,
163
+ entry_event_id: 'rename-entry', arguments_json: '{}', outcome: 'unknown', correlation_status: 'entry_only', normalizer_version: 'test' });
164
+ for (const role of ['source', 'destination', 'replaced_destination']) insert(db, 'file_operation_targets', { id: role, syscall_call_id: 'rename', sandbox_id: 'a', target_role: role, resolution_status: 'unresolved' });
165
+ }));
166
+
167
+ test('JSON, enums, exact timestamps, context and foreign-key deletion constraints', () => isolated(db => {
168
+ fixtures(db); call(db, 'delete');
169
+ for (const sql of [
170
+ "UPDATE runtime_sandboxes SET architecture='unknown' WHERE id='a'",
171
+ "UPDATE runtime_sandboxes SET ended_at_ms='tomorrow' WHERE id='a'",
172
+ "UPDATE runtime_sandboxes SET started_at_ms=10,ended_at_ms=9 WHERE id='a'",
173
+ "UPDATE runtime_sandboxes SET capture_config_json='[]' WHERE id='a'",
174
+ "UPDATE runtime_processes SET first_seen_ns='01' WHERE id='p-a'",
175
+ "UPDATE runtime_processes SET exited_at_ns='9007199254740992999' WHERE id='p-a'",
176
+ "DELETE FROM runtime_sandboxes WHERE id='a'",
177
+ "DELETE FROM agent_exchanges WHERE id='x'",
178
+ ]) assert.throws(() => db.exec(sql));
179
+ assert.throws(() => event(db, 'invalid-json', { payload_json: 'invalid' }));
180
+ assert.throws(() => event(db, 'invalid-seq', { stream_sequence: -1 }));
181
+ insert(db, 'agent_payloads', { sha: 'fixture', content: '"prompt"' });
182
+ insert(db, 'agent_context_items', { exchange_id: 'x', position: 0, payload_sha: 'fixture' });
183
+ assert.throws(() => insert(db, 'agent_context_items', { exchange_id: 'x', position: -1, payload_sha: 'fixture' }));
184
+ assert.throws(() => db.exec("DELETE FROM agent_payloads WHERE sha='fixture'"), /FOREIGN KEY/);
185
+ }));
186
+
187
+ test('initializer rejects unrelated/changed databases and rolls back on verification errors', () => isolated((db, path, dir) => {
188
+ const unrelatedPath = join(dir, 'unrelated.db');
189
+ const unrelated = new DatabaseSync(unrelatedPath);
190
+ try {
191
+ unrelated.exec('CREATE TABLE keep(value); INSERT INTO keep VALUES (42)');
192
+ assert.throws(() => initializeEvidenceDatabase(unrelatedPath), /Incompatible/);
193
+ assert.equal(unrelated.prepare('SELECT value FROM keep').get().value, 42);
194
+ assert.equal(unrelated.prepare("SELECT count(*) n FROM sqlite_schema WHERE type='table'").get().n, 1);
195
+ } finally { unrelated.close(); }
196
+ db.exec('PRAGMA user_version=99');
197
+ assert.throws(() => initializeEvidenceDatabase(path), /schema version/);
198
+ db.exec(`PRAGMA user_version=${SCHEMA_VERSION}`);
199
+ db.exec("UPDATE file_labels SET description='tampered' WHERE id='temporary'");
200
+ assert.throws(() => initializeEvidenceDatabase(path), /seed/);
201
+ assert.equal(db.prepare("SELECT description FROM file_labels WHERE id='temporary'").get().description, 'tampered');
202
+ db.exec('CREATE TABLE unrelated(value)');
203
+ assert.throws(() => initializeEvidenceDatabase(path), /schema structure/);
204
+ assert.throws(() => initializeEvidenceDatabase(), /explicit/);
205
+ }));
206
+
207
+ test('a version-2 database is upgraded in place to add call_assessments, keeping its data', () => isolated((db, path) => {
208
+ // Recreate exactly what a v2 database looked like: no call_assessments, and
209
+ // none of the later tables either.
210
+ db.exec('DROP INDEX call_assessments_call; DROP TABLE call_assessments; DROP TABLE workspace_snapshots; DROP TRIGGER search_events_ai; DROP TRIGGER search_events_ad; DROP TRIGGER search_events_au; DROP TABLE search_fts; DROP TABLE search_events; PRAGMA user_version=2');
211
+ insert(db, 'command_descriptions', { key: 'k', command: 'ls', description: 'listed files', created_at_ms: 1 });
212
+ const result = initializeEvidenceDatabase(path);
213
+ assert.equal(result.schemaVersion, SCHEMA_VERSION);
214
+ assert.equal(result.created, false);
215
+ assert.equal(db.prepare('PRAGMA user_version').get().user_version, SCHEMA_VERSION);
216
+ assert.equal(db.prepare("SELECT count(*) n FROM sqlite_schema WHERE name='call_assessments'").get().n, 1);
217
+ assert.equal(db.prepare("SELECT count(*) n FROM sqlite_schema WHERE name='workspace_snapshots'").get().n, 1);
218
+ assert.equal(db.prepare("SELECT description FROM command_descriptions WHERE key='k'").get().description, 'listed files');
219
+ }));
220
+
221
+ test('same catalog version with changed content is rejected without rewriting history', () => isolated((db, path) => {
222
+ // Simulate out-of-band administrative corruption, then restore the schema
223
+ // exactly so reinitialization must validate seed contents, not only DDL.
224
+ const trigger = db.prepare("SELECT sql FROM sqlite_schema WHERE name='classification_versions_no_update'").get().sql;
225
+ db.exec('DROP TRIGGER classification_versions_no_update');
226
+ db.prepare('UPDATE classification_versions SET content_sha256=? WHERE id=?').run('f'.repeat(64), CATALOG_VERSION_ID);
227
+ db.exec(trigger);
228
+ assert.throws(() => initializeEvidenceDatabase(path), /catalog version/);
229
+ assert.equal(db.prepare('SELECT content_sha256 FROM classification_versions').get().content_sha256, 'f'.repeat(64));
230
+ assert.equal(db.prepare('SELECT count(*) n FROM classification_syscall_rules').get().n, 353);
231
+ // A rollback releases the write transaction even while this reader stays open.
232
+ db.exec('BEGIN IMMEDIATE; ROLLBACK');
233
+ }));
@@ -17,9 +17,9 @@
17
17
  */
18
18
  import { DatabaseSync } from 'node:sqlite';
19
19
  import { createHash, randomUUID } from 'node:crypto';
20
- import { mkdirSync } from 'node:fs';
20
+ import { chmodSync, existsSync, mkdirSync } from 'node:fs';
21
21
  import { dirname } from 'node:path';
22
- import { initializeEvidenceDatabase } from './init-evidence-db.mjs';
22
+ import { initializeEvidenceDatabase, verifyEvidenceDatabase } from './init-evidence-db.mjs';
23
23
  import { promptInfo } from './prompt-traces.mjs';
24
24
  import { TOOL_RESULT_KINDS, toolResultFacts } from './tool-metadata.mjs';
25
25
  import { reportedOutcome, observedOutcome, combineOutcomes, payloadToText, extractFilePaths, pathsFromText, commandTextOf, clipText, runSearch, topFailureSignatures } from './search.mjs';
@@ -75,19 +75,32 @@ const PROCESS_FACTS = `
75
75
  WHERE ev.process_id = p.id AND ev.event_kind = 'exec_failed' ORDER BY ev.stream_sequence DESC LIMIT 1) AS failed_errno,
76
76
  EXISTS (SELECT 1 FROM runtime_events ev WHERE ev.process_id = p.id AND ev.event_kind = 'exec_succeeded') AS exec_ok`;
77
77
 
78
- export function openEvidenceStore(file) {
79
- mkdirSync(dirname(file), { recursive: true });
80
- // Creates a fresh v2 database, or verifies an existing one; refuses
81
- // anything else (an old-format database, a changed schema) untouched.
82
- initializeEvidenceDatabase(file);
83
- const db = new DatabaseSync(file);
84
- // WAL lets the dashboard read while the proxy writes, but needs shared
85
- // memory network mounts cannot provide. Fall back rather than refuse.
78
+ export function openEvidenceStore(file, { readOnly = false } = {}) {
86
79
  let journal = 'wal';
87
- try { db.exec('PRAGMA journal_mode = WAL'); db.exec('PRAGMA synchronous = NORMAL'); }
88
- catch { db.exec('PRAGMA journal_mode = DELETE'); db.exec('PRAGMA synchronous = FULL'); journal = 'delete'; }
89
- db.exec('PRAGMA foreign_keys = ON');
90
- db.exec('PRAGMA busy_timeout = 5000');
80
+ let db;
81
+ if (readOnly) {
82
+ if (!existsSync(file)) throw Error(`Database file does not exist: ${file}`);
83
+ verifyEvidenceDatabase(file);
84
+ db = new DatabaseSync(file, { readOnly: true });
85
+ journal = 'read-only';
86
+ } else {
87
+ mkdirSync(dirname(file), { recursive: true });
88
+ // Creates a fresh v2 database, or verifies an existing one; refuses
89
+ // anything else (an old-format database, a changed schema) untouched.
90
+ initializeEvidenceDatabase(file);
91
+ db = new DatabaseSync(file);
92
+ // WAL lets the dashboard read while the proxy writes, but needs shared
93
+ // memory network mounts cannot provide. Fall back rather than refuse.
94
+ try { db.exec('PRAGMA journal_mode = WAL'); db.exec('PRAGMA synchronous = NORMAL'); }
95
+ catch { db.exec('PRAGMA journal_mode = DELETE'); db.exec('PRAGMA synchronous = FULL'); journal = 'delete'; }
96
+ db.exec('PRAGMA foreign_keys = ON');
97
+ db.exec('PRAGMA busy_timeout = 5000');
98
+ // Prompts and tool output, for this user only. SQLite gives new -wal and
99
+ // -shm files the database's mode; ones made before this keep their own.
100
+ for (const path of [file, `${file}-wal`, `${file}-shm`]) {
101
+ try { chmodSync(path, 0o600); } catch { /* not there yet, or a filesystem without modes */ }
102
+ }
103
+ }
91
104
 
92
105
  const q = (sql) => db.prepare(sql);
93
106
  const insertPayload = q('INSERT OR IGNORE INTO agent_payloads (sha, content) VALUES (?, ?)');
@@ -361,7 +374,7 @@ export function openEvidenceStore(file) {
361
374
 
362
375
  // Rebuild the capture-time row shape the dashboard and lab consume.
363
376
  const selectContextPayloads = q('SELECT payload_sha FROM agent_context_items WHERE exchange_id = ? ORDER BY position');
364
- const EXCHANGE_COLUMNS = `e.*, s.external_session_id, s.started_at_ms AS session_started_ms, t.user_prompt_sha`;
377
+ const EXCHANGE_COLUMNS = `e.*, s.external_session_id, s.started_at_ms AS session_started_ms, t.user_prompt_sha, t.status AS turn_status`;
365
378
  function hydrate(record) {
366
379
  const payload = { ...getPayload(record.request_sha) };
367
380
  const tools = getPayload(record.tools_sha);
@@ -373,6 +386,7 @@ export function openEvidenceStore(file) {
373
386
  session_id: record.external_session_id, session_started_at: toIso(record.session_started_ms),
374
387
  // A trace is a turn: one prompt and everything the agent did for it.
375
388
  trace_id: record.turn_id, promptTitle: record.user_prompt_sha ? getPayload(record.user_prompt_sha) : null,
389
+ turn_status: record.turn_status ?? null,
376
390
  span_id: record.id, parent_span_id: transport.parent_span_id ?? null,
377
391
  timestamp: toIso(record.started_at_ms), completed_at: toIso(record.completed_at_ms),
378
392
  provider: record.provider, route: record.route, method: record.method,
@@ -384,11 +398,14 @@ export function openEvidenceStore(file) {
384
398
  }
385
399
  const latestSession = q(`SELECT e.session_id FROM agent_exchanges e JOIN agent_sessions s ON s.id = e.session_id
386
400
  WHERE e.turn_id IS NOT NULL AND ${ROUTES} ORDER BY s.started_at_ms DESC, e.started_at_ms DESC LIMIT 1`);
387
- const turnExchanges = (scoped) => q(`SELECT ${EXCHANGE_COLUMNS} FROM agent_exchanges e
401
+ const turnExchangesQuery = (scoped) => q(`SELECT ${EXCHANGE_COLUMNS} FROM agent_exchanges e
388
402
  JOIN agent_sessions s ON s.id = e.session_id JOIN agent_turns t ON t.id = e.turn_id
389
403
  WHERE ${ROUTES} ${scoped ? 'AND e.session_id = ?' : ''} ORDER BY e.started_at_ms DESC LIMIT ?`);
390
- const recentAll = turnExchanges(false);
391
- const recentBySession = turnExchanges(true);
404
+ const recentAll = turnExchangesQuery(false);
405
+ const recentBySession = turnExchangesQuery(true);
406
+ const exchangesForTurn = q(`SELECT ${EXCHANGE_COLUMNS} FROM agent_exchanges e
407
+ JOIN agent_sessions s ON s.id = e.session_id JOIN agent_turns t ON t.id = e.turn_id
408
+ WHERE ${ROUTES} AND (e.turn_id = ? OR t.id = ? OR e.id = ?) ORDER BY e.started_at_ms ASC, e.id ASC`);
392
409
  const selectExchange = q(`SELECT ${EXCHANGE_COLUMNS} FROM agent_exchanges e
393
410
  JOIN agent_sessions s ON s.id = e.session_id LEFT JOIN agent_turns t ON t.id = e.turn_id WHERE e.id = ?`);
394
411
 
@@ -442,7 +459,7 @@ export function openEvidenceStore(file) {
442
459
  function findProcess(sandboxId, pid, startNs) { return selectProcess.get(sandboxId, pid, startNs); }
443
460
 
444
461
  // Fill the index for captures that predate it (or a missed hook update).
445
- indexGuarded(() => backfillSearchIndex());
462
+ if (!readOnly) indexGuarded(() => backfillSearchIndex());
446
463
 
447
464
  return {
448
465
  db, journal, recordExchange,
@@ -455,6 +472,12 @@ export function openEvidenceStore(file) {
455
472
  return rows.map(hydrate).reverse();
456
473
  },
457
474
 
475
+ /** All captured exchanges belonging to one turn (trace), ordered oldest-first. */
476
+ turnExchanges(turnId) {
477
+ if (!turnId) return [];
478
+ return exchangesForTurn.all(turnId, turnId, turnId).map(hydrate);
479
+ },
480
+
458
481
  findExchange(exchangeId) {
459
482
  const record = selectExchange.get(exchangeId);
460
483
  if (!record) return undefined;
@@ -614,11 +637,18 @@ export function openEvidenceStore(file) {
614
637
  },
615
638
 
616
639
  /** The snapshot taken after each of these calls (external call ids), by call id. */
617
- snapshotsForCalls(callIds) {
640
+ snapshotsForCalls(callIds, { sessionId } = {}) {
618
641
  const list = [...new Set((callIds ?? []).filter(Boolean))];
619
642
  if (!list.length) return new Map();
620
- const rows = q(`SELECT call_id, commit_sha, parent_sha, changed, taken_at_ms, changes_json FROM workspace_snapshots
621
- WHERE call_id IN (${marks(list)}) ORDER BY taken_at_ms`).all(...list);
643
+ let sql = `SELECT call_id, commit_sha, parent_sha, changed, taken_at_ms, changes_json FROM workspace_snapshots
644
+ WHERE call_id IN (${marks(list)})`;
645
+ const params = [...list];
646
+ if (sessionId) {
647
+ sql += ' AND (session_id = ? OR agent_session_id = ?)';
648
+ params.push(sessionId, sessionId);
649
+ }
650
+ sql += ' ORDER BY taken_at_ms';
651
+ const rows = q(sql).all(...params);
622
652
  return new Map(rows.map((row) => {
623
653
  const body = fromJson(row.changes_json) ?? {};
624
654
  return [row.call_id, { commit: row.commit_sha, parent: row.parent_sha, changed: row.changed === 1, taken_at: toIso(row.taken_at_ms),
@@ -753,6 +783,45 @@ export function openEvidenceStore(file) {
753
783
  return new Map(rows.map((row) => [row.external_call_id, {
754
784
  tool_name: row.tool_name, args: getPayload(row.arguments_sha), result: getPayload(row.reported_result_sha) }]));
755
785
  },
786
+ toolCallResult(externalCallId, { exchangeId, sessionId } = {}) {
787
+ if (!externalCallId) return null;
788
+ let sql = `SELECT c.reported_result_sha
789
+ FROM agent_tool_calls c JOIN agent_exchanges e ON e.id = c.exchange_id
790
+ WHERE c.external_call_id = ? AND c.reported_result_sha IS NOT NULL`;
791
+ const params = [externalCallId];
792
+ if (exchangeId) {
793
+ sql += ' AND c.exchange_id = ?';
794
+ params.push(exchangeId);
795
+ } else if (sessionId) {
796
+ sql += ' AND (e.session_id = ? OR e.session_id IN (SELECT id FROM agent_sessions WHERE external_session_id = ?))';
797
+ params.push(sessionId, sessionId);
798
+ }
799
+ sql += ' ORDER BY e.started_at_ms DESC LIMIT 1';
800
+ const row = q(sql).get(...params);
801
+ return row ? getPayload(row.reported_result_sha) : null;
802
+ },
803
+ recordToolResult(externalCallId, resultItem, { exchangeId, sessionId } = {}) {
804
+ if (!externalCallId || !resultItem) return null;
805
+ let sql = `SELECT c.id FROM agent_tool_calls c
806
+ JOIN agent_exchanges e ON e.id = c.exchange_id
807
+ WHERE c.external_call_id = ?`;
808
+ const params = [externalCallId];
809
+ if (exchangeId) {
810
+ sql += ' AND c.exchange_id = ?';
811
+ params.push(exchangeId);
812
+ } else if (sessionId) {
813
+ sql += ' AND (e.session_id = ? OR e.session_id IN (SELECT id FROM agent_sessions WHERE external_session_id = ?))';
814
+ params.push(sessionId, sessionId);
815
+ }
816
+ sql += ' ORDER BY e.started_at_ms DESC LIMIT 1';
817
+ const call = q(sql).get(...params);
818
+ if (!call) return null;
819
+ const payloadSha = putPayload(resultItem);
820
+ setReportedResult.run(payloadSha, call.id);
821
+ checkReported({ toolCallId: call.id });
822
+ indexGuarded(() => indexCall(call.id));
823
+ return call.id;
824
+ },
756
825
  getCallAssessment(key) { return fromJson(q('SELECT body_json FROM call_assessments WHERE key = ?').get(key)?.body_json ?? null); },
757
826
  putCallAssessment(key, callId, model, value) {
758
827
  q('INSERT OR REPLACE INTO call_assessments (key, call_id, model, created_at_ms, body_json) VALUES (?,?,?,?,?)')