@raytrace-cli/cli 0.4.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 (137) hide show
  1. package/README.md +155 -123
  2. package/bin/raytrace.mjs +110 -22
  3. package/dist/dashboard/assets/dm-sans-latin-400-normal-BwCSEQnW.woff +0 -0
  4. package/dist/dashboard/assets/dm-sans-latin-400-normal-CW0RaeGs.woff2 +0 -0
  5. package/dist/dashboard/assets/dm-sans-latin-500-normal-B9HHJjqV.woff2 +0 -0
  6. package/dist/dashboard/assets/dm-sans-latin-500-normal-Dr3UlScf.woff +0 -0
  7. package/dist/dashboard/assets/dm-sans-latin-600-normal-Aqo67rzb.woff2 +0 -0
  8. package/dist/dashboard/assets/dm-sans-latin-600-normal-BmdmIIQ2.woff +0 -0
  9. package/dist/dashboard/assets/dm-sans-latin-700-normal-CUSSCpQX.woff +0 -0
  10. package/dist/dashboard/assets/dm-sans-latin-700-normal-DvUfVpUG.woff2 +0 -0
  11. package/dist/dashboard/assets/dm-sans-latin-ext-400-normal-BjWJ59Pq.woff +0 -0
  12. package/dist/dashboard/assets/dm-sans-latin-ext-400-normal-BtiwyxMk.woff2 +0 -0
  13. package/dist/dashboard/assets/dm-sans-latin-ext-500-normal-BJfUCQsA.woff2 +0 -0
  14. package/dist/dashboard/assets/dm-sans-latin-ext-500-normal-DR84L5F-.woff +0 -0
  15. package/dist/dashboard/assets/dm-sans-latin-ext-600-normal-4vooXBpG.woff2 +0 -0
  16. package/dist/dashboard/assets/dm-sans-latin-ext-600-normal-DRtaDpgU.woff +0 -0
  17. package/dist/dashboard/assets/dm-sans-latin-ext-700-normal-BLI3TTWz.woff +0 -0
  18. package/dist/dashboard/assets/dm-sans-latin-ext-700-normal-CJIcxD6K.woff2 +0 -0
  19. package/dist/dashboard/assets/ibm-plex-mono-cyrillic-400-normal-BSMlKf0J.woff2 +0 -0
  20. package/dist/dashboard/assets/ibm-plex-mono-cyrillic-400-normal-CEL4l2ZJ.woff +0 -0
  21. package/dist/dashboard/assets/ibm-plex-mono-cyrillic-500-normal-Ael50iVv.woff +0 -0
  22. package/dist/dashboard/assets/ibm-plex-mono-cyrillic-500-normal-Bq9vWWag.woff2 +0 -0
  23. package/dist/dashboard/assets/ibm-plex-mono-cyrillic-600-normal-CTOM6hUh.woff2 +0 -0
  24. package/dist/dashboard/assets/ibm-plex-mono-cyrillic-600-normal-fLZuRloM.woff +0 -0
  25. package/dist/dashboard/assets/ibm-plex-mono-cyrillic-ext-400-normal-DMdlQ8Kv.woff +0 -0
  26. package/dist/dashboard/assets/ibm-plex-mono-cyrillic-ext-400-normal-xuaO2J-f.woff2 +0 -0
  27. package/dist/dashboard/assets/ibm-plex-mono-cyrillic-ext-500-normal-BIfNGwUT.woff +0 -0
  28. package/dist/dashboard/assets/ibm-plex-mono-cyrillic-ext-500-normal-BqneJy0T.woff2 +0 -0
  29. package/dist/dashboard/assets/ibm-plex-mono-cyrillic-ext-600-normal-9HEixskS.woff +0 -0
  30. package/dist/dashboard/assets/ibm-plex-mono-cyrillic-ext-600-normal-V-xxqcpd.woff2 +0 -0
  31. package/dist/dashboard/assets/ibm-plex-mono-latin-400-normal-CvHOgSBP.woff +0 -0
  32. package/dist/dashboard/assets/ibm-plex-mono-latin-400-normal-DMJ8VG8y.woff2 +0 -0
  33. package/dist/dashboard/assets/ibm-plex-mono-latin-500-normal-CB9ihrfo.woff +0 -0
  34. package/dist/dashboard/assets/ibm-plex-mono-latin-500-normal-DSY6xOcd.woff2 +0 -0
  35. package/dist/dashboard/assets/ibm-plex-mono-latin-600-normal-BgSNZQsw.woff2 +0 -0
  36. package/dist/dashboard/assets/ibm-plex-mono-latin-600-normal-DWFSQ4vo.woff +0 -0
  37. package/dist/dashboard/assets/ibm-plex-mono-latin-ext-400-normal-BmRBH3aV.woff2 +0 -0
  38. package/dist/dashboard/assets/ibm-plex-mono-latin-ext-400-normal-D3D2R8hC.woff +0 -0
  39. package/dist/dashboard/assets/ibm-plex-mono-latin-ext-500-normal-CAhNIIs5.woff2 +0 -0
  40. package/dist/dashboard/assets/ibm-plex-mono-latin-ext-500-normal-CZ70TYgx.woff +0 -0
  41. package/dist/dashboard/assets/ibm-plex-mono-latin-ext-600-normal-D38SheWl.woff2 +0 -0
  42. package/dist/dashboard/assets/ibm-plex-mono-latin-ext-600-normal-DmB0ttJJ.woff +0 -0
  43. package/dist/dashboard/assets/ibm-plex-mono-vietnamese-400-normal-BulugwFq.woff2 +0 -0
  44. package/dist/dashboard/assets/ibm-plex-mono-vietnamese-400-normal-DDuiU_S-.woff +0 -0
  45. package/dist/dashboard/assets/ibm-plex-mono-vietnamese-500-normal-C8zxqsMH.woff +0 -0
  46. package/dist/dashboard/assets/ibm-plex-mono-vietnamese-500-normal-DZ4AoWbu.woff2 +0 -0
  47. package/dist/dashboard/assets/ibm-plex-mono-vietnamese-600-normal-D2EvbN8M.woff2 +0 -0
  48. package/dist/dashboard/assets/ibm-plex-mono-vietnamese-600-normal-iLQfcSjf.woff +0 -0
  49. package/dist/dashboard/assets/index-Dc3LTk8b.js +38 -0
  50. package/dist/dashboard/assets/index-DtV3UdEB.css +1 -0
  51. package/dist/dashboard/index.html +2 -2
  52. package/package.json +4 -1
  53. package/proxy/agent-intent-schema.test.mjs +142 -0
  54. package/proxy/call-assessment.mjs +385 -0
  55. package/proxy/call-assessment.test.mjs +167 -0
  56. package/proxy/call-category.mjs +461 -0
  57. package/proxy/capture.mjs +38 -0
  58. package/proxy/capture.test.mjs +49 -0
  59. package/proxy/claude-code-adapter.mjs +65 -3
  60. package/proxy/claude-code-hook.mjs +3 -1
  61. package/proxy/codex-config.mjs +5 -0
  62. package/proxy/codex.mjs +3 -2
  63. package/proxy/evidence-schema.test.mjs +233 -0
  64. package/proxy/evidence-store.mjs +704 -33
  65. package/proxy/evidence-store.test.mjs +304 -0
  66. package/proxy/exec-narrative.mjs +625 -0
  67. package/proxy/exec-narrative.test.mjs +262 -0
  68. package/proxy/execution-correlation.mjs +185 -0
  69. package/proxy/execution-correlation.test.mjs +146 -0
  70. package/proxy/execution-runner.test.mjs +38 -0
  71. package/proxy/experiment-engine.mjs +7 -4
  72. package/proxy/experiment-engine.test.mjs +93 -0
  73. package/proxy/explanations.test.mjs +20 -0
  74. package/proxy/failure-signature.mjs +56 -0
  75. package/proxy/gvisor-forwarder.mjs +454 -0
  76. package/proxy/gvisor-forwarder.test.mjs +368 -0
  77. package/proxy/init-evidence-db.mjs +166 -12
  78. package/proxy/local-sandboxes.mjs +94 -0
  79. package/proxy/local-token.mjs +30 -0
  80. package/proxy/playground-recovery.test.mjs +130 -0
  81. package/proxy/playground.mjs +439 -0
  82. package/proxy/prompt-context.mjs +12 -7
  83. package/proxy/prompt-traces.mjs +6 -0
  84. package/proxy/prompt-traces.test.mjs +32 -0
  85. package/proxy/providers.test.mjs +76 -0
  86. package/proxy/proxy.integration.test.mjs +135 -0
  87. package/proxy/raytace-proxy.mjs +512 -188
  88. package/proxy/request-metrics.test.mjs +19 -0
  89. package/proxy/request-policy.mjs +45 -0
  90. package/proxy/request-policy.test.mjs +47 -0
  91. package/proxy/run-recap.mjs +139 -0
  92. package/proxy/runtime-attribution.mjs +110 -0
  93. package/proxy/sandbox-bridge.mjs +49 -0
  94. package/proxy/schema/EVIDENCE_DATABASE.md +276 -0
  95. package/proxy/schema/auxiliary.sql +48 -1
  96. package/proxy/schema/classification.sql +89 -0
  97. package/proxy/schema/file_context.sql +53 -0
  98. package/proxy/schema/runtime_evidence.sql +201 -0
  99. package/proxy/schema/search.sql +66 -0
  100. package/proxy/search.mjs +418 -0
  101. package/proxy/search.test.mjs +161 -0
  102. package/proxy/smoke.test.mjs +93 -0
  103. package/proxy/step-attribution.mjs +380 -0
  104. package/proxy/step-lab.test.mjs +38 -0
  105. package/proxy/summaries.test.mjs +69 -0
  106. package/proxy/tool-metadata.mjs +36 -0
  107. package/proxy/tool-metadata.test.mjs +38 -0
  108. package/proxy/trace-view.mjs +308 -0
  109. package/proxy/trace-view.test.mjs +72 -0
  110. package/proxy/typesafe.mjs +63 -0
  111. package/proxy/typesafe.test.mjs +39 -0
  112. package/src/claude-code.mjs +38 -1
  113. package/src/commands.mjs +133 -20
  114. package/src/config.mjs +16 -7
  115. package/src/export.mjs +200 -0
  116. package/src/lima.mjs +176 -0
  117. package/src/local-sandbox.mjs +339 -0
  118. package/src/paths.mjs +8 -8
  119. package/src/proxy-process.mjs +45 -3
  120. package/src/sandbox.mjs +37 -9
  121. package/src/upload.mjs +198 -0
  122. package/worker/sandbox/Dockerfile +8 -0
  123. package/worker/sandbox/SYSCALL_CATALOG.md +197 -0
  124. package/worker/sandbox/claude-hook.mjs +364 -0
  125. package/worker/sandbox/collector.py +357 -0
  126. package/worker/sandbox/dns_forwarder.py +255 -0
  127. package/worker/sandbox/engine.py +940 -0
  128. package/worker/sandbox/file_scan.py +491 -0
  129. package/worker/sandbox/lima.yaml +29 -0
  130. package/worker/sandbox/network.py +90 -0
  131. package/worker/sandbox/projects.py +679 -0
  132. package/worker/sandbox/setup.py +159 -0
  133. package/worker/sandbox/syscall_catalog.sql +985 -0
  134. package/worker/sandbox/transcript-delivery.test.mjs +153 -0
  135. package/worker/sandbox/viewer.py +151 -0
  136. package/dist/dashboard/assets/index-BQ9_JxGq.js +0 -27
  137. package/dist/dashboard/assets/index-L5cUAvhE.css +0 -1
@@ -3,31 +3,45 @@
3
3
  * created and verified by init-evidence-db.mjs). This module is the only
4
4
  * place that knows about tables.
5
5
  *
6
- * The proxy writes it once per captured model request: session -> turn ->
7
- * exchange -> proposed tool calls, with payloads stored once by digest.
6
+ * Two writers feed it:
7
+ * - the proxy, once per captured model request: session -> turn ->
8
+ * exchange -> proposed tool calls, with payloads stored once by digest;
9
+ * - the gVisor forwarder, once per sandbox process event: sandbox ->
10
+ * process -> event, plus an attribution when a process is tied to a call.
8
11
  *
9
12
  * Readers (the dashboard) get the row shapes they always had -- hydrated
10
- * exchanges -- so the evidence model can stay
13
+ * exchanges, per-call execution summaries -- so the evidence model can stay
11
14
  * normalized without every consumer learning it. Tool calls are identified
12
15
  * internally by their own ids; reads that the dashboard joins on use the
13
16
  * provider's call id, always scoped to specific exchanges.
14
17
  */
15
18
  import { DatabaseSync } from 'node:sqlite';
16
19
  import { createHash, randomUUID } from 'node:crypto';
17
- import { mkdirSync } from 'node:fs';
20
+ import { chmodSync, existsSync, mkdirSync } from 'node:fs';
18
21
  import { dirname } from 'node:path';
19
- import { initializeEvidenceDatabase } from './init-evidence-db.mjs';
22
+ import { initializeEvidenceDatabase, verifyEvidenceDatabase } from './init-evidence-db.mjs';
20
23
  import { promptInfo } from './prompt-traces.mjs';
21
- import { TOOL_RESULT_KINDS } from './tool-metadata.mjs';
24
+ import { TOOL_RESULT_KINDS, toolResultFacts } from './tool-metadata.mjs';
25
+ import { reportedOutcome, observedOutcome, combineOutcomes, payloadToText, extractFilePaths, pathsFromText, commandTextOf, clipText, runSearch, topFailureSignatures } from './search.mjs';
26
+ import { failureSignature } from './failure-signature.mjs';
27
+ import { callCategory } from './call-category.mjs';
22
28
 
23
29
  const sha256 = (text) => createHash('sha256').update(text).digest('hex');
24
30
  const toMs = (value) => { const parsed = Date.parse(value ?? ''); return Number.isFinite(parsed) ? parsed : null; };
25
31
  const toIso = (ms) => (Number.isFinite(ms) ? new Date(ms).toISOString() : null);
26
32
  const asJson = (value) => (value === undefined || value === null ? null : JSON.stringify(value));
27
33
  const fromJson = (value) => { if (value === null || value === undefined) return null; try { return JSON.parse(value); } catch { return null; } };
34
+ const nsText = (value) => (typeof value === 'string' && /^(0|[1-9]\d*)$/.test(value) ? value : null);
35
+ const intOrNull = (value) => (Number.isInteger(Number(value)) && value !== null && value !== '' ? Number(value) : null);
28
36
  const marks = (list) => list.map(() => '?').join(',');
29
37
  const CALL_TYPES = /function_call|tool_use|tool_call/i;
30
38
  const ROUTES = `(e.route LIKE '%/responses' OR e.route LIKE '%/messages' OR e.route LIKE '%/chat/completions')`;
39
+ const DECODER_VERSION = 'gvisor-collector-1';
40
+ const ATTRIBUTOR_VERSION = 'causal-window-1';
41
+
42
+ // Attribution confidence in the schema's terms, and the dashboard's older
43
+ // name for the same idea (see app/types.ts Tier).
44
+ const TIER = { exact: 'mediated', corroborated: 'corroborated', inferred: 'inferred' };
31
45
 
32
46
  function previewOf(item) {
33
47
  const content = item?.content ?? item?.text ?? item?.output ?? item;
@@ -37,20 +51,56 @@ function previewOf(item) {
37
51
  return (text || '').slice(0, 240);
38
52
  }
39
53
 
54
+ /** What a process's row says about how it ended, in the dashboard's terms.
55
+ * Never upgrades missing evidence into an outcome. */
56
+ function processOutcome(row) {
57
+ if (!row?.process_id) return { status: null, error: null };
58
+ if (!row.exec_ok && row.failed_errno != null) return { status: 'failed', error: `exec failed: errno ${row.failed_errno}` };
59
+ if (row.exited_at_ns != null) {
60
+ if (row.exit_signal) return { status: 'failed', error: `killed by signal ${row.exit_signal}` };
61
+ if (row.exit_code === 0) return { status: 'completed', error: null };
62
+ if (row.exit_code != null) return { status: 'failed', error: `exit ${row.exit_code}` };
63
+ return { status: 'unknown', error: null };
64
+ }
65
+ if (row.evidence_lost) return { status: 'unknown', error: `evidence lost: ${row.evidence_lost}` };
66
+ return { status: 'running', error: null };
67
+ }
68
+
69
+ // Per-process facts derived from its events: the command it first ran, and
70
+ // whether its only exec attempts failed.
71
+ const PROCESS_FACTS = `
72
+ (SELECT json_extract(ev.payload_json, '$.argv') FROM runtime_events ev
73
+ WHERE ev.process_id = p.id AND ev.event_kind IN ('exec_succeeded','exec_failed') ORDER BY ev.stream_sequence LIMIT 1) AS argv_json,
74
+ (SELECT json_extract(ev.payload_json, '$.errno') FROM runtime_events ev
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
+ EXISTS (SELECT 1 FROM runtime_events ev WHERE ev.process_id = p.id AND ev.event_kind = 'exec_succeeded') AS exec_ok`;
40
77
 
41
- export function openEvidenceStore(file) {
42
- mkdirSync(dirname(file), { recursive: true });
43
- // Creates a fresh v2 database, or verifies an existing one; refuses
44
- // anything else (an old-format database, a changed schema) untouched.
45
- initializeEvidenceDatabase(file);
46
- const db = new DatabaseSync(file);
47
- // WAL lets the dashboard read while the proxy writes, but needs shared
48
- // memory network mounts cannot provide. Fall back rather than refuse.
78
+ export function openEvidenceStore(file, { readOnly = false } = {}) {
49
79
  let journal = 'wal';
50
- try { db.exec('PRAGMA journal_mode = WAL'); db.exec('PRAGMA synchronous = NORMAL'); }
51
- catch { db.exec('PRAGMA journal_mode = DELETE'); db.exec('PRAGMA synchronous = FULL'); journal = 'delete'; }
52
- db.exec('PRAGMA foreign_keys = ON');
53
- 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
+ }
54
104
 
55
105
  const q = (sql) => db.prepare(sql);
56
106
  const insertPayload = q('INSERT OR IGNORE INTO agent_payloads (sha, content) VALUES (?, ?)');
@@ -96,6 +146,148 @@ export function openEvidenceStore(file) {
96
146
  ORDER BY e.started_at_ms DESC LIMIT 1`);
97
147
  const setReportedResult = q('UPDATE agent_tool_calls SET reported_result_sha = ? WHERE id = ?');
98
148
 
149
+ // ------------------------------------------------------------ search index
150
+ // Derived rows (search.sql), rebuilt from the evidence tables whenever
151
+ // either side of a call lands: its proposal/result (recordExchange) or
152
+ // its observed process (attribute/recordProcessExit). Indexing must
153
+ // never cost us evidence, so hook sites guard these calls; a missed
154
+ // update self-heals on the next open (backfill) or a full reindex.
155
+
156
+ const SEARCH_COLUMNS = ['id', 'kind', 'ts_ms', 'session_id', 'session_external', 'turn_id', 'exchange_id', 'call_id',
157
+ 'external_call_id', 'output_index', 'agent', 'model', 'provider', 'tool_name', 'category', 'outcome',
158
+ 'outcome_reported', 'outcome_observed', 'reported_check', 'exit_code', 'http_status', 'error_text',
159
+ 'failure_signature', 'signature_label', 'command_text', 'file_paths', 'prompt_text', 'args_text',
160
+ 'result_text', 'duration_ms', 'indexed_at_ms'];
161
+ const upsertSearchEvent = q(`INSERT INTO search_events (${SEARCH_COLUMNS.join(',')})
162
+ VALUES (${SEARCH_COLUMNS.map(() => '?').join(',')})
163
+ ON CONFLICT(id) DO UPDATE SET ${SEARCH_COLUMNS.filter((c) => c !== 'id').map((c) => `${c}=excluded.${c}`).join(',')}`);
164
+ const putSearchEvent = (event) => upsertSearchEvent.run(...SEARCH_COLUMNS.map((c) => event[c] ?? null));
165
+
166
+ const selectCallForIndex = q(`SELECT c.id AS call_pk, c.external_call_id, c.output_index, c.tool_name,
167
+ c.arguments_sha, c.reported_result_sha, c.proposed_at_ms,
168
+ e.id AS exchange_id, e.turn_id, e.session_id, e.provider, e.model, e.started_at_ms, e.completed_at_ms, e.http_status,
169
+ s.external_session_id, s.agent_name, t.user_prompt_sha
170
+ FROM agent_tool_calls c
171
+ JOIN agent_exchanges e ON e.id = c.exchange_id
172
+ JOIN agent_sessions s ON s.id = e.session_id
173
+ LEFT JOIN agent_turns t ON t.id = e.turn_id
174
+ WHERE c.id = ?`);
175
+ const selectCallProcess = q(`SELECT a.reported_check,
176
+ p.id AS process_id, p.first_seen_ms, p.exited_at_ms, p.exited_at_ns, p.exit_code, p.exit_signal, p.evidence_lost,
177
+ ${PROCESS_FACTS}
178
+ FROM runtime_attributions a
179
+ JOIN runtime_events ev ON ev.id = a.event_id
180
+ LEFT JOIN runtime_processes p ON p.id = ev.process_id
181
+ WHERE a.tool_call_id = ? AND a.status = 'accepted' AND a.method != 'inherited'
182
+ ORDER BY a.created_at_ms LIMIT 1`);
183
+ const selectSnapshotPaths = q('SELECT changes_json FROM workspace_snapshots WHERE call_id = ? ORDER BY taken_at_ms DESC LIMIT 1');
184
+
185
+ function indexCall(callPk) {
186
+ const row = selectCallForIndex.get(callPk);
187
+ if (!row) return;
188
+ const args = getPayload(row.arguments_sha);
189
+ const resultItem = getPayload(row.reported_result_sha);
190
+ const reported = reportedOutcome(resultItem);
191
+ const proc = selectCallProcess.get(callPk);
192
+ const observedStatus = proc ? processOutcome(proc) : { status: null, error: null };
193
+ const observed = observedOutcome(observedStatus.status);
194
+ const outcome = combineOutcomes(reported, observed);
195
+ const facts = resultItem != null ? toolResultFacts(resultItem) : { exitCode: null, wallMs: null };
196
+ const exitCode = proc?.exit_code ?? facts.exitCode ?? null;
197
+ const resultText = clipText(payloadToText(resultItem));
198
+ const failed = outcome === 'failed';
199
+ const errorText = failed ? clipText([observedStatus.error, resultText].filter(Boolean).join('\n'), 8000) : (observedStatus.error ?? null);
200
+ const sig = failed ? failureSignature({ errorText: resultText || errorText, exitCode, toolName: row.tool_name }) : null;
201
+ const files = pathsFromText(commandTextOf(args), extractFilePaths(args));
202
+ if (row.external_call_id) {
203
+ const snap = fromJson(selectSnapshotPaths.get(row.external_call_id)?.changes_json ?? null);
204
+ for (const change of snap?.changes ?? []) if (change?.path) files.add(change.path);
205
+ }
206
+ const observedMs = Number.isFinite(proc?.first_seen_ms) && Number.isFinite(proc?.exited_at_ms) ? proc.exited_at_ms - proc.first_seen_ms : null;
207
+ putSearchEvent({
208
+ id: `call:${callPk}`, kind: 'call', ts_ms: row.proposed_at_ms ?? row.completed_at_ms ?? row.started_at_ms,
209
+ session_id: row.session_id, session_external: row.external_session_id, turn_id: row.turn_id,
210
+ exchange_id: row.exchange_id, call_id: callPk, external_call_id: row.external_call_id,
211
+ output_index: row.output_index, agent: row.agent_name, model: row.model, provider: row.provider,
212
+ tool_name: row.tool_name, category: callCategory(row.tool_name, args)?.category ?? null,
213
+ outcome, outcome_reported: reported, outcome_observed: observed,
214
+ reported_check: proc?.reported_check ?? null, exit_code: exitCode, http_status: row.http_status,
215
+ error_text: errorText, failure_signature: sig?.signature ?? null, signature_label: sig?.label ?? null,
216
+ command_text: commandTextOf(args) || null, file_paths: [...files].join('\n') || null,
217
+ prompt_text: clipText(payloadToText(getPayload(row.user_prompt_sha)), 8000) || null,
218
+ args_text: clipText(payloadToText(args)) || null, result_text: resultText || null,
219
+ duration_ms: observedMs ?? facts.wallMs ?? null, indexed_at_ms: Date.now(),
220
+ });
221
+ if (row.turn_id) indexTurn(row.turn_id);
222
+ }
223
+
224
+ const selectTurnForIndex = q(`SELECT t.id, t.session_id, t.status, t.started_at_ms, t.ended_at_ms,
225
+ t.user_prompt_sha, t.final_response_sha, s.external_session_id, s.agent_name,
226
+ (SELECT e.model FROM agent_exchanges e WHERE e.turn_id = t.id ORDER BY e.started_at_ms DESC LIMIT 1) AS model,
227
+ (SELECT e.provider FROM agent_exchanges e WHERE e.turn_id = t.id ORDER BY e.started_at_ms DESC LIMIT 1) AS provider,
228
+ (SELECT MAX(e.http_status) FROM agent_exchanges e WHERE e.turn_id = t.id) AS http_status,
229
+ (SELECT e.id FROM agent_exchanges e WHERE e.turn_id = t.id ORDER BY e.started_at_ms DESC LIMIT 1) AS exchange_id
230
+ FROM agent_turns t JOIN agent_sessions s ON s.id = t.session_id WHERE t.id = ?`);
231
+
232
+ function indexTurn(turnId) {
233
+ const row = selectTurnForIndex.get(turnId);
234
+ if (!row) return;
235
+ const failedCalls = q(`SELECT COUNT(*) AS n FROM search_events WHERE turn_id = ? AND kind = 'call' AND outcome = 'failed'`).get(turnId).n;
236
+ const outcome = row.status === 'failed' || failedCalls > 0 ? 'failed' : row.status === 'completed' ? 'ok' : 'unknown';
237
+ putSearchEvent({
238
+ id: `turn:${turnId}`, kind: 'turn', ts_ms: row.started_at_ms,
239
+ session_id: row.session_id, session_external: row.external_session_id, turn_id: turnId,
240
+ exchange_id: row.exchange_id, agent: row.agent_name, model: row.model, provider: row.provider,
241
+ outcome, outcome_reported: 'unknown', outcome_observed: 'unknown', http_status: row.http_status,
242
+ prompt_text: clipText(payloadToText(getPayload(row.user_prompt_sha)), 16_000) || null,
243
+ result_text: clipText(payloadToText(getPayload(row.final_response_sha)), 16_000) || null,
244
+ duration_ms: row.ended_at_ms != null ? row.ended_at_ms - row.started_at_ms : null,
245
+ indexed_at_ms: Date.now(),
246
+ });
247
+ }
248
+
249
+ function indexExchange(exchangeId) {
250
+ for (const call of q('SELECT id FROM agent_tool_calls WHERE exchange_id = ?').all(exchangeId)) indexCall(call.id);
251
+ const turn = q('SELECT turn_id FROM agent_exchanges WHERE id = ?').get(exchangeId);
252
+ if (turn?.turn_id) indexTurn(turn.turn_id);
253
+ }
254
+
255
+ function indexProcessCalls(processId) {
256
+ const rows = q(`SELECT DISTINCT a.tool_call_id FROM runtime_attributions a
257
+ JOIN runtime_events ev ON ev.id = a.event_id WHERE ev.process_id = ?`).all(processId);
258
+ for (const row of rows) indexCall(row.tool_call_id);
259
+ }
260
+
261
+ function indexProxyErrorRow(row) {
262
+ const sig = failureSignature({ errorText: row.error, toolName: 'proxy' });
263
+ putSearchEvent({
264
+ id: `proxy_error:${row.rowid}`, kind: 'proxy_error', ts_ms: row.occurred_at_ms ?? Date.now(),
265
+ provider: row.provider, outcome: 'failed', outcome_reported: 'unknown', outcome_observed: 'unknown',
266
+ error_text: clipText([row.route, row.error].filter(Boolean).join(' '), 8000) || null,
267
+ failure_signature: sig?.signature ?? null, signature_label: sig?.label ?? null,
268
+ result_text: clipText(payloadToText(fromJson(row.cause_json)), 8000) || null,
269
+ indexed_at_ms: Date.now(),
270
+ });
271
+ }
272
+
273
+ function indexGuarded(work) {
274
+ try { work(); } catch (error) { console.error('[raytace] search indexing failed:', error.message); }
275
+ }
276
+
277
+ function backfillSearchIndex() {
278
+ const missing = (sql) => q(sql).all();
279
+ const calls = missing(`SELECT c.id FROM agent_tool_calls c WHERE NOT EXISTS (SELECT 1 FROM search_events se WHERE se.id = 'call:' || c.id)`);
280
+ const turns = missing(`SELECT t.id FROM agent_turns t WHERE NOT EXISTS (SELECT 1 FROM search_events se WHERE se.id = 'turn:' || t.id)`);
281
+ const errors = missing(`SELECT rowid, * FROM proxy_errors pe WHERE NOT EXISTS (SELECT 1 FROM search_events se WHERE se.id = 'proxy_error:' || pe.rowid)`);
282
+ if (!calls.length && !turns.length && !errors.length) return 0;
283
+ return transaction(() => {
284
+ for (const call of calls) indexCall(call.id);
285
+ for (const turn of turns) indexTurn(turn.id);
286
+ for (const row of errors) indexProxyErrorRow(row);
287
+ return calls.length + turns.length + errors.length;
288
+ });
289
+ }
290
+
99
291
  function ensureSession(row, startedMs) {
100
292
  const external = typeof row.session_id === 'string' && row.session_id ? row.session_id : null;
101
293
  const found = external ? selectSession.get(external) : null;
@@ -113,8 +305,9 @@ export function openEvidenceStore(file) {
113
305
  function resolveTurn(sessionId, row, request, startedMs) {
114
306
  const prompt = promptInfo(request);
115
307
  if (!prompt) return null;
116
- // Two sessions given the same prompt start identically, so the agent's
117
- // own session id is part of the key when a row has one: a session never
308
+ // A sandbox files every Claude Code session under one rtp- id, and two
309
+ // sessions given the same prompt start identically, so the agent's own
310
+ // session id is part of the key when a row has one: a session never
118
311
  // continues another's turn. Rows without one keep their original key.
119
312
  const key = sha256(JSON.stringify([row.provider ?? null, request?.model ?? null, prompt.prefix,
120
313
  ...(row.agent_session_id ? [row.agent_session_id] : [])]));
@@ -139,8 +332,8 @@ export function openEvidenceStore(file) {
139
332
  const output = Array.isArray(response?.output) ? response.output : [];
140
333
  const proposals = output.map((item, index) => [item, index]).filter(([item]) => item?.call_id && CALL_TYPES.test(item?.type || ''));
141
334
 
142
- transaction(() => {
143
- if (selectExchangeId.get(row.span_id)) return;
335
+ const answered = transaction(() => {
336
+ if (selectExchangeId.get(row.span_id)) return [];
144
337
  const sessionId = ensureSession(row, startedMs);
145
338
  const turnId = resolveTurn(sessionId, row, request, startedMs);
146
339
  const responseSha = putPayload(response);
@@ -151,6 +344,7 @@ export function openEvidenceStore(file) {
151
344
  request: { headers: row.request?.headers ?? null, bytes: row.request?.bytes ?? null, sha256: row.request?.sha256 ?? null },
152
345
  response: { headers: row.response?.headers ?? null, bytes: row.response?.bytes ?? null, sha256: row.response?.sha256 ?? null } }));
153
346
 
347
+ const answeredCalls = [];
154
348
  for (const [position, item] of items.entries()) {
155
349
  const payloadSha = putPayload(item);
156
350
  insertContext.run(row.span_id, position, item?.role ?? null, item?.type ?? null, item?.call_id ?? null, payloadSha, previewOf(item));
@@ -158,7 +352,7 @@ export function openEvidenceStore(file) {
158
352
  // did -- recorded on the call as a report, never as evidence.
159
353
  if (item?.call_id && TOOL_RESULT_KINDS.includes(item?.type)) {
160
354
  const call = selectAnsweredCall.get(item.call_id, sessionId, startedMs);
161
- if (call) setReportedResult.run(payloadSha, call.id);
355
+ if (call) { setReportedResult.run(payloadSha, call.id); answeredCalls.push(call.id); }
162
356
  }
163
357
  }
164
358
  for (const [item, outputIndex] of proposals) {
@@ -166,17 +360,21 @@ export function openEvidenceStore(file) {
166
360
  putPayload(item.arguments ?? item.input ?? item.function?.arguments ?? null), completedMs);
167
361
  }
168
362
  if (turnId) {
169
- // A response that proposes nothing more is the agent's answer.
363
+ // A response that proposes nothing more is the agent's answer. This
364
+ // closes the turn for the agent; processes it started may still run.
170
365
  const failed = Number(row.response?.status) >= 400;
171
366
  const status = failed ? 'failed' : proposals.length ? 'active' : 'completed';
172
367
  updateTurn.run(status, completedMs, status === 'completed' ? responseSha : null, turnId);
173
368
  }
369
+ return answeredCalls;
174
370
  });
371
+ for (const callId of answered) checkReported({ toolCallId: callId });
372
+ indexGuarded(() => { indexExchange(row.span_id); for (const callId of answered) indexCall(callId); });
175
373
  }
176
374
 
177
375
  // Rebuild the capture-time row shape the dashboard and lab consume.
178
376
  const selectContextPayloads = q('SELECT payload_sha FROM agent_context_items WHERE exchange_id = ? ORDER BY position');
179
- 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`;
180
378
  function hydrate(record) {
181
379
  const payload = { ...getPayload(record.request_sha) };
182
380
  const tools = getPayload(record.tools_sha);
@@ -188,6 +386,7 @@ export function openEvidenceStore(file) {
188
386
  session_id: record.external_session_id, session_started_at: toIso(record.session_started_ms),
189
387
  // A trace is a turn: one prompt and everything the agent did for it.
190
388
  trace_id: record.turn_id, promptTitle: record.user_prompt_sha ? getPayload(record.user_prompt_sha) : null,
389
+ turn_status: record.turn_status ?? null,
191
390
  span_id: record.id, parent_span_id: transport.parent_span_id ?? null,
192
391
  timestamp: toIso(record.started_at_ms), completed_at: toIso(record.completed_at_ms),
193
392
  provider: record.provider, route: record.route, method: record.method,
@@ -199,14 +398,69 @@ export function openEvidenceStore(file) {
199
398
  }
200
399
  const latestSession = q(`SELECT e.session_id FROM agent_exchanges e JOIN agent_sessions s ON s.id = e.session_id
201
400
  WHERE e.turn_id IS NOT NULL AND ${ROUTES} ORDER BY s.started_at_ms DESC, e.started_at_ms DESC LIMIT 1`);
202
- const turnExchanges = (scoped) => q(`SELECT ${EXCHANGE_COLUMNS} FROM agent_exchanges e
401
+ const turnExchangesQuery = (scoped) => q(`SELECT ${EXCHANGE_COLUMNS} FROM agent_exchanges e
203
402
  JOIN agent_sessions s ON s.id = e.session_id JOIN agent_turns t ON t.id = e.turn_id
204
403
  WHERE ${ROUTES} ${scoped ? 'AND e.session_id = ?' : ''} ORDER BY e.started_at_ms DESC LIMIT ?`);
205
- const recentAll = turnExchanges(false);
206
- 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`);
207
409
  const selectExchange = q(`SELECT ${EXCHANGE_COLUMNS} FROM agent_exchanges e
208
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 = ?`);
209
411
 
412
+ // --------------------------------------------------------- runtime evidence
413
+
414
+ const selectSandbox = q('SELECT id, project_id FROM runtime_sandboxes WHERE id = ?');
415
+ const insertSandbox = q(`INSERT INTO runtime_sandboxes (id, external_container_id, project_id, runtime_name, started_at_ms)
416
+ VALUES (?, ?, ?, 'gvisor', ?)`);
417
+ const setSandboxProject = q('UPDATE runtime_sandboxes SET project_id = ? WHERE id = ? AND project_id IS NULL');
418
+ const selectEventId = q('SELECT id FROM runtime_events WHERE stream_id = ? AND stream_sequence = ?');
419
+ const insertEvent = q(`INSERT INTO runtime_events (id, sandbox_id, process_id, stream_id, stream_sequence, event_kind,
420
+ observed_at_ns, received_at_ms, tid, payload_json, decoder_version) VALUES (?,?,?,?,?,?,?,?,?,?,?)`);
421
+ const selectProcess = q('SELECT * FROM runtime_processes WHERE sandbox_id = ? AND pid = ? AND start_time_ns IS ? ORDER BY first_seen_ms DESC LIMIT 1');
422
+ const selectLiveParent = q(`SELECT id FROM runtime_processes WHERE sandbox_id = ? AND pid = ? AND exited_at_ns IS NULL
423
+ ORDER BY first_seen_ms DESC LIMIT 1`);
424
+ const insertProcess = q(`INSERT INTO runtime_processes (id, sandbox_id, pid, start_time_ns, parent_process_id, observed_ppid,
425
+ first_seen_ns, identity_basis, first_seen_ms) VALUES (?,?,?,?,?,?,?,?,?)`);
426
+ const closeProcess = q(`UPDATE runtime_processes SET exited_at_ns = ?, exited_at_ms = ?, exit_code = ?, exit_signal = ?, evidence_lost = NULL
427
+ WHERE id = ? AND exited_at_ns IS NULL`);
428
+ const loseProcesses = q(`UPDATE runtime_processes SET evidence_lost = ?
429
+ WHERE sandbox_id = ? AND exited_at_ns IS NULL AND evidence_lost IS NULL`);
430
+ const endSandboxStmt = q(`UPDATE runtime_sandboxes SET ended_at_ms = MAX(COALESCE(started_at_ms, ?), ?) WHERE id = ? AND ended_at_ms IS NULL`);
431
+ const selectAcceptedAttribution = q(`SELECT id FROM runtime_attributions WHERE tool_call_id = ? AND event_id = ? AND status = 'accepted'`);
432
+ const insertAttribution = q(`INSERT INTO runtime_attributions (id, tool_call_id, event_id, method, confidence, status, basis_json,
433
+ attributor_version, created_at_ms, score, window_start_ms, window_end_ms) VALUES (?,?,?,?,?,'accepted',?,?,?,?,?,?)`);
434
+
435
+ /** One sandbox lifetime per container. Process identity (pid + start
436
+ * time) keeps a restarted container's reused pids apart regardless. */
437
+ function ensureSandbox(containerId, projectId = null) {
438
+ const found = selectSandbox.get(containerId);
439
+ if (found) { if (projectId && !found.project_id) setSandboxProject.run(projectId, containerId); return containerId; }
440
+ insertSandbox.run(containerId, containerId, projectId, Date.now());
441
+ return containerId;
442
+ }
443
+
444
+ /** Appends one collector event, once: the stream is the container and the
445
+ * sequence is the collector's own event id, so a replayed event is a no-op. */
446
+ function recordEvent({ sandboxId, processId = null, raw }) {
447
+ const streamId = `gvisor:${sandboxId}`;
448
+ const sequence = Number(raw?.event_id);
449
+ if (!Number.isInteger(sequence) || sequence < 0) return null;
450
+ const existing = selectEventId.get(streamId, sequence);
451
+ if (existing) return existing.id;
452
+ const id = `${streamId}:${sequence}`;
453
+ const tid = intOrNull(raw.tid);
454
+ insertEvent.run(id, sandboxId, processId, streamId, sequence, String(raw.kind || 'unknown'), nsText(raw.timestamp_ns), Date.now(),
455
+ tid && tid >= 1 ? tid : null, JSON.stringify(raw), DECODER_VERSION);
456
+ return id;
457
+ }
458
+
459
+ function findProcess(sandboxId, pid, startNs) { return selectProcess.get(sandboxId, pid, startNs); }
460
+
461
+ // Fill the index for captures that predate it (or a missed hook update).
462
+ if (!readOnly) indexGuarded(() => backfillSearchIndex());
463
+
210
464
  return {
211
465
  db, journal, recordExchange,
212
466
 
@@ -218,6 +472,12 @@ export function openEvidenceStore(file) {
218
472
  return rows.map(hydrate).reverse();
219
473
  },
220
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
+
221
481
  findExchange(exchangeId) {
222
482
  const record = selectExchange.get(exchangeId);
223
483
  if (!record) return undefined;
@@ -225,20 +485,264 @@ export function openEvidenceStore(file) {
225
485
  return { payload: row.request.payload, response: row.response.payload, provider: row.provider, route: row.route, session_id: row.session_id };
226
486
  },
227
487
 
488
+ // ---- runtime evidence writers (the gVisor forwarder)
489
+
490
+ /** A process began running a program (exec_succeeded), or tried to and
491
+ * failed (exec_failed). Records the process once, by pid + start time,
492
+ * and the event every time. Returns ids for attributing it. */
493
+ recordProcessStart({ containerId, projectId = null, raw, startedMs = null }) {
494
+ if (!containerId || !raw) return null;
495
+ return transaction(() => {
496
+ const sandboxId = ensureSandbox(containerId, projectId);
497
+ const pid = intOrNull(raw.pid);
498
+ if (pid == null || pid < 1) return { processId: null, eventId: recordEvent({ sandboxId, raw }) };
499
+ const startNs = nsText(raw.process_start_ns);
500
+ let process = findProcess(sandboxId, pid, startNs);
501
+ if (!process) {
502
+ const ppid = intOrNull(raw.ppid);
503
+ const parent = ppid != null ? selectLiveParent.get(sandboxId, ppid) : null;
504
+ const observed = nsText(raw.timestamp_ns) ?? startNs ?? '0';
505
+ const id = `${sandboxId}:${pid}:${startNs ?? `event-${raw.event_id}`}`;
506
+ insertProcess.run(id, sandboxId, pid, startNs, parent?.id ?? null, ppid != null && ppid >= 0 ? ppid : null, observed,
507
+ startNs ? 'pid+start_time' : 'pid+first_event (start time not reported)', Number.isFinite(startedMs) ? Math.round(startedMs) : null);
508
+ process = { id };
509
+ }
510
+ return { processId: process.id, eventId: recordEvent({ sandboxId, processId: process.id, raw }) };
511
+ });
512
+ },
513
+
514
+ /** Ties an observed process (its exec event) to the tool call it ran
515
+ * for. `method` is how: marker | window | text | inherited. */
516
+ attribute({ toolCallId, eventId, method, confidence = 'corroborated', score = null, windowStartMs = null, windowEndMs = null }) {
517
+ if (!toolCallId || !eventId || selectAcceptedAttribution.get(toolCallId, eventId)) return false;
518
+ insertAttribution.run(randomUUID(), toolCallId, eventId, method, confidence,
519
+ JSON.stringify({ method, score, window_start_ms: windowStartMs, window_end_ms: windowEndMs }), ATTRIBUTOR_VERSION, Date.now(),
520
+ score ?? null, windowStartMs ?? null, windowEndMs ?? null);
521
+ indexGuarded(() => indexCall(toolCallId));
522
+ return true;
523
+ },
524
+
525
+ /** A process exited. Found by pid + start time within its sandbox, so an
526
+ * exit still closes its process after a proxy restart. A process with no
527
+ * row (one that forked but never exec'd) is not recorded. */
528
+ recordProcessExit({ containerId, projectId = null, raw, endedMs = null, exit_code = null, signal = null }) {
529
+ if (!containerId || !raw) return false;
530
+ const closed = transaction(() => {
531
+ const sandboxId = ensureSandbox(containerId, projectId);
532
+ const pid = intOrNull(raw.pid);
533
+ const process = pid != null ? findProcess(sandboxId, pid, nsText(raw.process_start_ns)) : null;
534
+ if (!process || process.exited_at_ns != null) return null;
535
+ const exitSignal = Number.isInteger(signal) && signal > 0 ? signal : null;
536
+ const exitCode = exitSignal ? null : (Number.isInteger(exit_code) && exit_code >= 0 ? exit_code : null);
537
+ closeProcess.run(nsText(raw.timestamp_ns) ?? process.first_seen_ns, Number.isFinite(endedMs) ? Math.round(endedMs) : null,
538
+ exitCode, exitSignal, process.id);
539
+ recordEvent({ sandboxId, processId: process.id, raw });
540
+ return process.id;
541
+ });
542
+ if (!closed) return false;
543
+ checkReported({ processId: closed });
544
+ indexGuarded(() => indexProcessCalls(closed));
545
+ return true;
546
+ },
547
+
548
+ /** The evidence that would close a sandbox's open processes can no
549
+ * longer arrive. Marks them (never as failed) and records why. */
550
+ loseOpenProcesses({ containerId, reason, raw = null, ended = false }) {
551
+ if (!containerId) return 0;
552
+ const changes = transaction(() => {
553
+ const sandboxId = ensureSandbox(containerId);
554
+ if (raw) recordEvent({ sandboxId, raw });
555
+ const lost = Number(loseProcesses.run(String(reason || 'unknown'), sandboxId).changes);
556
+ if (ended) endSandboxStmt.run(Date.now(), Date.now(), sandboxId);
557
+ return lost;
558
+ });
559
+ if (changes) indexGuarded(() => {
560
+ const rows = q(`SELECT DISTINCT a.tool_call_id FROM runtime_attributions a
561
+ JOIN runtime_events ev ON ev.id = a.event_id JOIN runtime_processes p ON p.id = ev.process_id
562
+ WHERE p.sandbox_id = ? AND p.evidence_lost IS NOT NULL`).all(containerId);
563
+ for (const row of rows) indexCall(row.tool_call_id);
564
+ });
565
+ return changes;
566
+ },
567
+
568
+ /** The session's proposed calls that no process has been tied to yet,
569
+ * each with its causal window: from the request that proposed it to the
570
+ * first later request in the session that carried its result back (null
571
+ * while none has). `call_id` is the internal tool-call id. */
572
+ candidatesInWindow(startMs, endMs, { sessionId = null } = {}) {
573
+ if (!sessionId) return [];
574
+ const rows = q(`SELECT c.id, c.external_call_id, c.tool_name, c.arguments_sha, e.started_at_ms,
575
+ (SELECT MIN(r.started_at_ms) FROM agent_context_items ci JOIN agent_exchanges r ON r.id = ci.exchange_id
576
+ WHERE ci.external_call_id = c.external_call_id AND ci.kind IN (${marks(TOOL_RESULT_KINDS)})
577
+ AND r.session_id = e.session_id AND r.started_at_ms >= e.started_at_ms AND r.id != e.id) AS window_end
578
+ FROM agent_tool_calls c
579
+ JOIN agent_exchanges e ON e.id = c.exchange_id
580
+ JOIN agent_sessions s ON s.id = e.session_id
581
+ WHERE e.started_at_ms BETWEEN ? AND ? AND s.external_session_id = ?
582
+ AND NOT EXISTS (SELECT 1 FROM runtime_attributions a
583
+ WHERE a.tool_call_id = c.id AND a.status = 'accepted' AND a.method != 'inherited')
584
+ ORDER BY e.started_at_ms, c.output_index`).all(...TOOL_RESULT_KINDS, startMs, endMs, sessionId);
585
+ return rows.map((row) => ({ call_id: row.id, external_call_id: row.external_call_id, tool_name: row.tool_name, timestamp: row.started_at_ms,
586
+ args: getPayload(row.arguments_sha), window_start: row.started_at_ms, window_end: row.window_end ?? null }));
587
+ },
588
+
589
+ /** A session's sandbox processes that no call accounts for, first seen at
590
+ * or after `sinceMs`, oldest first, each with its first exec event, its
591
+ * parent process, and the call that parent is tied to (null when none). */
592
+ unattributedProcesses({ sessionId, sinceMs }) {
593
+ if (!sessionId) return [];
594
+ const accepted = (process) => `SELECT a.tool_call_id FROM runtime_attributions a JOIN runtime_events e ON e.id = a.event_id
595
+ WHERE e.process_id = ${process} AND a.status = 'accepted' LIMIT 1`;
596
+ return q(`SELECT p.id AS process_id, p.parent_process_id, p.first_seen_ms, ev.id AS event_id, ev.payload_json,
597
+ (${accepted('p.parent_process_id')}) AS parent_call_id
598
+ FROM runtime_processes p
599
+ JOIN runtime_sandboxes s ON s.id = p.sandbox_id
600
+ JOIN runtime_events ev ON ev.id = (SELECT e.id FROM runtime_events e
601
+ WHERE e.process_id = p.id AND e.event_kind = 'exec_succeeded' ORDER BY e.stream_sequence LIMIT 1)
602
+ WHERE s.project_id = ? AND p.first_seen_ms >= ? AND NOT EXISTS (${accepted('p.id')})
603
+ ORDER BY p.first_seen_ms, ev.stream_sequence`).all(sessionId, Math.round(sinceMs))
604
+ .map((row) => ({ process_id: row.process_id, parent_process_id: row.parent_process_id ?? null, event_id: row.event_id, first_seen_ms: row.first_seen_ms,
605
+ parent_call_id: row.parent_call_id ?? null, raw: fromJson(row.payload_json) ?? {} }));
606
+ },
607
+
228
608
  /** Changes whenever anything the trace list shows could have: a cheap
229
- * key for caching it. Counts only ever grow; a result reported back
230
- * changes a count too. */
609
+ * key for caching it. Counts only ever grow; a result reported back or a
610
+ * process exiting changes a count too. */
231
611
  dataVersion() {
232
612
  return Object.values(q(`SELECT (SELECT count(*) FROM agent_exchanges) AS exchanges,
233
- (SELECT count(*) FROM agent_tool_calls WHERE reported_result_sha IS NOT NULL) AS results`).get()).join(':');
613
+ (SELECT count(*) FROM agent_tool_calls WHERE reported_result_sha IS NOT NULL) AS results,
614
+ (SELECT count(*) FROM runtime_events) AS events, (SELECT count(*) FROM runtime_attributions) AS attributions,
615
+ (SELECT count(*) FROM workspace_snapshots) AS snapshots`).get()).join(':');
234
616
  },
235
617
 
618
+ // ---- workspace snapshots (a sandboxed Claude Code's hook)
619
+
620
+ /** Where the project folder stood after a call or at a prompt. The same
621
+ * snapshot sent twice (a resend after 409) is recorded once. */
622
+ recordSnapshot({ sessionId, agentSessionId = null, snapshot }) {
623
+ const id = createHash('sha256').update([sessionId, agentSessionId, snapshot.taken_on, snapshot.call_id, snapshot.commit, snapshot.taken_at].join('\0')).digest('hex');
624
+ q(`INSERT OR IGNORE INTO workspace_snapshots (id, session_id, agent_session_id, taken_on, call_id, commit_sha, parent_sha, changed, taken_at_ms, changes_json)
625
+ VALUES (?,?,?,?,?,?,?,?,?,?)`).run(id, sessionId, agentSessionId, snapshot.taken_on, snapshot.call_id ?? null, snapshot.commit,
626
+ snapshot.parent ?? null, snapshot.changed ? 1 : 0, Math.round(toMs(snapshot.taken_at) ?? Date.now()),
627
+ JSON.stringify({ changes: snapshot.changes ?? [], too_big: snapshot.too_big ?? [] }));
628
+ return id;
629
+ },
630
+
631
+ /** Every snapshot of one agent session filed under `sessionId`, oldest first. */
632
+ snapshotsForAgentSession({ sessionId, agentSessionId }) {
633
+ return q(`SELECT taken_on, call_id, commit_sha, parent_sha, changed, taken_at_ms FROM workspace_snapshots
634
+ WHERE session_id = ? AND agent_session_id = ? ORDER BY taken_at_ms`).all(sessionId, agentSessionId)
635
+ .map((row) => ({ taken_on: row.taken_on, call_id: row.call_id, commit: row.commit_sha, parent: row.parent_sha ?? null,
636
+ changed: row.changed === 1, taken_at_ms: row.taken_at_ms }));
637
+ },
638
+
639
+ /** The snapshot taken after each of these calls (external call ids), by call id. */
640
+ snapshotsForCalls(callIds, { sessionId } = {}) {
641
+ const list = [...new Set((callIds ?? []).filter(Boolean))];
642
+ if (!list.length) return new Map();
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);
652
+ return new Map(rows.map((row) => {
653
+ const body = fromJson(row.changes_json) ?? {};
654
+ return [row.call_id, { commit: row.commit_sha, parent: row.parent_sha, changed: row.changed === 1, taken_at: toIso(row.taken_at_ms),
655
+ changes: body.changes ?? [], too_big: body.too_big ?? [] }];
656
+ }));
657
+ },
658
+
659
+ // ---- readers (the dashboard)
660
+
661
+ /** Proposed vs observed for every call in these exchanges: the call, and
662
+ * the process it ran as (its accepted, non-inherited attribution). */
663
+ divergence(exchangeIds) {
664
+ if (!exchangeIds.length) return [];
665
+ return q(`SELECT c.external_call_id AS call_id, c.exchange_id AS span_id, c.output_index, c.tool_name AS name,
666
+ a.method, a.confidence, a.score, a.window_start_ms, a.window_end_ms, a.reported_check, a.event_id,
667
+ json_extract(ev.payload_json, '$.argv') AS attributed_argv_json,
668
+ p.id AS process_id, p.pid, p.start_time_ns, p.first_seen_ms, p.exited_at_ms, p.exited_at_ns, p.exit_code, p.exit_signal, p.evidence_lost,
669
+ ${PROCESS_FACTS},
670
+ (SELECT COUNT(*) FROM runtime_attributions d WHERE d.tool_call_id = c.id AND d.status = 'accepted' AND d.method = 'inherited') AS descendant_count
671
+ FROM agent_tool_calls c
672
+ LEFT JOIN runtime_attributions a ON a.id = (SELECT a2.id FROM runtime_attributions a2
673
+ WHERE a2.tool_call_id = c.id AND a2.status = 'accepted' AND a2.method != 'inherited' ORDER BY a2.created_at_ms LIMIT 1)
674
+ LEFT JOIN runtime_events ev ON ev.id = a.event_id
675
+ LEFT JOIN runtime_processes p ON p.id = ev.process_id
676
+ WHERE c.exchange_id IN (${marks(exchangeIds)}) ORDER BY c.exchange_id, c.output_index`).all(...exchangeIds)
677
+ .map((row) => {
678
+ const { status, error } = processOutcome(row);
679
+ return {
680
+ call_id: row.call_id, span_id: row.span_id, output_index: row.output_index, name: row.name,
681
+ outcome: row.event_id ? 'as_proposed' : 'not_executed',
682
+ status, error, source: row.event_id ? 'gvisor' : null,
683
+ match_score: row.score, match_basis: row.method === 'marker' ? 'id' : row.method ?? null,
684
+ kernel_confirmed: row.event_id ? 1 : 0, kernel_match_score: row.score,
685
+ tier: row.confidence ? TIER[row.confidence] : null,
686
+ pid: row.pid ?? null, exit_code: row.exit_code ?? null, reported_check: row.reported_check ?? null,
687
+ exec_id: row.event_id ?? null, start_time_ns: row.start_time_ns ?? null,
688
+ // The command that was matched to the call. A process can exec
689
+ // more than once (Codex's environment setup, then the command it
690
+ // was asked to run), and the matched exec is the one to show.
691
+ started_at: toIso(row.first_seen_ms), ended_at: toIso(row.exited_at_ms), argv: fromJson(row.attributed_argv_json ?? row.argv_json),
692
+ window_start_ms: row.window_start_ms ?? null, window_end_ms: row.window_end_ms ?? null,
693
+ descendant_count: row.descendant_count ?? 0,
694
+ };
695
+ });
696
+ },
697
+
698
+ /** Processes that ran underneath each call in these exchanges (inherited
699
+ * attributions), in the order they started. */
700
+ descendants(exchangeIds) {
701
+ if (!exchangeIds.length) return [];
702
+ return q(`SELECT c.external_call_id AS parent_call_id, ev.id AS event_id, a.confidence,
703
+ json_extract(ev.payload_json, '$.argv') AS attributed_argv_json,
704
+ p.id AS process_id, p.pid, p.observed_ppid, p.start_time_ns, p.first_seen_ms, p.exited_at_ms, p.exited_at_ns,
705
+ p.exit_code, p.exit_signal, p.evidence_lost, ${PROCESS_FACTS}
706
+ FROM runtime_attributions a
707
+ JOIN agent_tool_calls c ON c.id = a.tool_call_id
708
+ JOIN runtime_events ev ON ev.id = a.event_id
709
+ JOIN runtime_processes p ON p.id = ev.process_id
710
+ WHERE a.status = 'accepted' AND a.method = 'inherited' AND c.exchange_id IN (${marks(exchangeIds)})
711
+ ORDER BY c.external_call_id, p.first_seen_ms, p.pid`).all(...exchangeIds)
712
+ .map((row) => ({ parent_call_id: row.parent_call_id, id: row.event_id, tier: TIER[row.confidence] ?? 'corroborated',
713
+ pid: row.pid, ppid: row.observed_ppid, start_time_ns: row.start_time_ns, argv: fromJson(row.attributed_argv_json ?? row.argv_json) ?? [],
714
+ ...processOutcome(row), started_at: toIso(row.first_seen_ms), ended_at: toIso(row.exited_at_ms) }));
715
+ },
716
+
717
+ /** Which call each of a sandbox's processes belongs to, for annotating
718
+ * its process tree. A process with no accepted attribution comes back
719
+ * with both call ids null: it ran, and nothing accounts for it. */
720
+ attributionsForProcesses({ containerId, pids }) {
721
+ const list = [...new Set((pids ?? []).filter(Number.isInteger))];
722
+ if (!containerId || !list.length) return [];
723
+ return q(`SELECT p.pid, p.start_time_ns,
724
+ (SELECT c.external_call_id FROM runtime_attributions a JOIN runtime_events ev ON ev.id = a.event_id
725
+ JOIN agent_tool_calls c ON c.id = a.tool_call_id
726
+ WHERE ev.process_id = p.id AND a.status = 'accepted' AND a.method != 'inherited' LIMIT 1) AS call_id,
727
+ (SELECT c.external_call_id FROM runtime_attributions a JOIN runtime_events ev ON ev.id = a.event_id
728
+ JOIN agent_tool_calls c ON c.id = a.tool_call_id
729
+ WHERE ev.process_id = p.id AND a.status = 'accepted' AND a.method = 'inherited' LIMIT 1) AS parent_call_id,
730
+ (SELECT a.confidence FROM runtime_attributions a JOIN runtime_events ev ON ev.id = a.event_id
731
+ WHERE ev.process_id = p.id AND a.status = 'accepted' LIMIT 1) AS confidence,
732
+ (SELECT a.method FROM runtime_attributions a JOIN runtime_events ev ON ev.id = a.event_id
733
+ WHERE ev.process_id = p.id AND a.status = 'accepted' AND a.method != 'inherited' LIMIT 1) AS method
734
+ FROM runtime_processes p WHERE p.sandbox_id = ? AND p.pid IN (${marks(list)})`).all(containerId, ...list)
735
+ .map((row) => ({ pid: row.pid, start_time_ns: row.start_time_ns, call_id: row.call_id ?? null, parent_call_id: row.parent_call_id ?? null,
736
+ tier: row.confidence ? TIER[row.confidence] : 'unverified', match_basis: row.method === 'marker' ? 'id' : row.method ?? null }));
737
+ },
236
738
 
237
739
  // ---- auxiliary features
238
740
 
239
741
  recordProxyError(row) {
240
- q('INSERT INTO proxy_errors (trace_id, occurred_at_ms, provider, route, error, cause_json) VALUES (?,?,?,?,?,?)')
742
+ const inserted = q('INSERT INTO proxy_errors (trace_id, occurred_at_ms, provider, route, error, cause_json) VALUES (?,?,?,?,?,?)')
241
743
  .run(row.trace_id ?? null, toMs(row.timestamp), row.provider ?? null, row.route ?? null, row.error ?? null, asJson(row.cause));
744
+ indexGuarded(() => indexProxyErrorRow({ rowid: Number(inserted.lastInsertRowid), occurred_at_ms: toMs(row.timestamp),
745
+ provider: row.provider ?? null, route: row.route ?? null, error: row.error ?? null, cause_json: asJson(row.cause) }));
242
746
  },
243
747
  saveExperiment(job) {
244
748
  q(`INSERT OR REPLACE INTO lab_experiments (id, exchange_id, created_at_ms, status, kind, model, body_json) VALUES (?,?,?,?,?,?,?)`)
@@ -257,8 +761,18 @@ export function openEvidenceStore(file) {
257
761
  summaryForSpan(exchangeId) {
258
762
  return fromJson(q('SELECT body_json FROM exchange_summaries WHERE exchange_id = ? ORDER BY created_at_ms DESC LIMIT 1').get(exchangeId)?.body_json ?? null);
259
763
  },
764
+ /** Model-written sentence for a sandbox command no rule could describe,
765
+ * keyed by the command so the same command is never paid for twice. */
766
+ getCommandDescription(command) {
767
+ return q('SELECT description FROM command_descriptions WHERE key = ?').get(sha256(String(command)))?.description ?? null;
768
+ },
769
+ putCommandDescription(command, description, model = null) {
770
+ q('INSERT OR REPLACE INTO command_descriptions (key, command, description, model, created_at_ms) VALUES (?,?,?,?,?)')
771
+ .run(sha256(String(command)), String(command), String(description), model, Date.now());
772
+ },
260
773
  /** What each tool call asked for and what the agent was told back, keyed
261
- * by the provider's call id. */
774
+ * by the external call id the attribution rows carry. The raw material for
775
+ * a Jev assessment; call-assessment.mjs decides how much of it to send. */
262
776
  toolCallContexts(externalCallIds) {
263
777
  const list = [...new Set((externalCallIds ?? []).filter((id) => typeof id === 'string' && id))];
264
778
  if (!list.length) return new Map();
@@ -269,6 +783,64 @@ export function openEvidenceStore(file) {
269
783
  return new Map(rows.map((row) => [row.external_call_id, {
270
784
  tool_name: row.tool_name, args: getPayload(row.arguments_sha), result: getPayload(row.reported_result_sha) }]));
271
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
+ },
825
+ getCallAssessment(key) { return fromJson(q('SELECT body_json FROM call_assessments WHERE key = ?').get(key)?.body_json ?? null); },
826
+ putCallAssessment(key, callId, model, value) {
827
+ q('INSERT OR REPLACE INTO call_assessments (key, call_id, model, created_at_ms, body_json) VALUES (?,?,?,?,?)')
828
+ .run(key, callId ?? null, model ?? null, Date.now(), JSON.stringify(value));
829
+ },
830
+
831
+ /** Splunk-style search over the derived index (proxy/search.mjs). */
832
+ search(options) { return runSearch(db, options); },
833
+ failureSignatures(options) { return topFailureSignatures(db, options); },
834
+ /** Rebuild the derived search index from the evidence tables. */
835
+ reindexSearch() {
836
+ return transaction(() => {
837
+ db.exec('DELETE FROM search_events');
838
+ for (const call of q('SELECT id FROM agent_tool_calls').all()) indexCall(call.id);
839
+ for (const turn of q('SELECT id FROM agent_turns').all()) indexTurn(turn.id);
840
+ for (const row of q('SELECT rowid, * FROM proxy_errors').all()) indexProxyErrorRow(row);
841
+ return q('SELECT COUNT(*) AS n FROM search_events').get().n;
842
+ });
843
+ },
272
844
 
273
845
  stats() {
274
846
  const one = (sql) => db.prepare(sql).get();
@@ -277,9 +849,108 @@ export function openEvidenceStore(file) {
277
849
  turns: one('SELECT COUNT(*) AS n FROM agent_turns').n,
278
850
  exchanges: one('SELECT COUNT(*) AS n FROM agent_exchanges').n,
279
851
  payloads: one('SELECT COUNT(*) AS n, COALESCE(SUM(length(content)),0) AS bytes FROM agent_payloads'),
852
+ processes: one('SELECT COUNT(*) AS n FROM runtime_processes').n,
280
853
  };
281
854
  },
282
855
 
856
+ /** Deletes these sessions (agent_sessions.external_session_id: a local
857
+ * sandbox's rtp- id, or a Claude Code session id) and all that hangs off
858
+ * them -- turns, exchanges, tool calls, the sandbox's recorded processes
859
+ * and events, snapshots and search rows -- then any payload nothing
860
+ * refers to any more (payloads are shared by content, so one another
861
+ * session uses stays). Returns how many sessions went. Used when a local
862
+ * sandbox is destroyed with its logs. */
863
+ forgetSessions(sessionIds) {
864
+ if (!sessionIds.length) return 0;
865
+ // A sandbox's Playground forks (lab_experiments, kind fork) go with it,
866
+ // and so do their own sessions, which are filed under the fork's id.
867
+ const parents = sessionIds.map(() => '?').join(',');
868
+ const forks = q(`SELECT id FROM lab_experiments WHERE kind = 'fork' AND json_extract(body_json, '$.parent') IN (${parents})`)
869
+ .all(...sessionIds).map((row) => row.id);
870
+ const externalIds = [...sessionIds, ...forks];
871
+ const marks = externalIds.map(() => '?').join(',');
872
+ // Runtime events, syscalls and their classifications are append-only
873
+ // (schema/runtime_evidence.sql, classification.sql):
874
+ // nothing may change recorded evidence. Their owner deleting a whole
875
+ // sandbox is the one exception, so those guards are lifted for these
876
+ // deletes and put back as they were, in the same transaction: if any of
877
+ // it fails, nothing changed and the guards were never off.
878
+ const guards = q(`SELECT sql FROM sqlite_schema WHERE type = 'trigger'
879
+ AND name IN ('runtime_events_no_delete', 'runtime_syscall_calls_no_delete', 'classification_results_no_delete')`).all().map((row) => row.sql);
880
+ return transaction(() => {
881
+ db.exec('DROP TRIGGER IF EXISTS runtime_events_no_delete; DROP TRIGGER IF EXISTS runtime_syscall_calls_no_delete; DROP TRIGGER IF EXISTS classification_results_no_delete;');
882
+ const sessions = `SELECT id FROM agent_sessions WHERE external_session_id IN (${marks})`;
883
+ const exchanges = `SELECT id FROM agent_exchanges WHERE session_id IN (${sessions})`;
884
+ const calls = `SELECT id FROM agent_tool_calls WHERE exchange_id IN (${exchanges})`;
885
+ const boxes = `SELECT id FROM runtime_sandboxes WHERE project_id IN (${marks})`;
886
+ for (const sql of [
887
+ `DELETE FROM search_events WHERE session_external IN (${marks})`,
888
+ `DELETE FROM workspace_snapshots WHERE session_id IN (${marks})`,
889
+ `DELETE FROM runtime_attributions WHERE tool_call_id IN (${calls})
890
+ OR event_id IN (SELECT id FROM runtime_events WHERE sandbox_id IN (${boxes}))`,
891
+ `DELETE FROM classification_results WHERE syscall_call_id IN (SELECT id FROM runtime_syscall_calls WHERE sandbox_id IN (${boxes}))`,
892
+ `DELETE FROM file_label_assignments WHERE target_id IN (SELECT id FROM file_operation_targets WHERE sandbox_id IN (${boxes}))`,
893
+ `DELETE FROM file_operation_targets WHERE sandbox_id IN (${boxes})`,
894
+ `DELETE FROM file_objects WHERE sandbox_id IN (${boxes})`,
895
+ `DELETE FROM runtime_syscall_calls WHERE sandbox_id IN (${boxes})`,
896
+ `DELETE FROM runtime_events WHERE sandbox_id IN (${boxes})`,
897
+ `DELETE FROM runtime_processes WHERE sandbox_id IN (${boxes})`,
898
+ `DELETE FROM runtime_sandboxes WHERE project_id IN (${marks})`,
899
+ `DELETE FROM agent_context_items WHERE exchange_id IN (${exchanges})`,
900
+ `DELETE FROM agent_tool_calls WHERE exchange_id IN (${exchanges})`,
901
+ `DELETE FROM exchange_summaries WHERE exchange_id IN (${exchanges})`,
902
+ `DELETE FROM lab_experiments WHERE exchange_id IN (${exchanges}) OR id IN (${marks})`,
903
+ `DELETE FROM agent_exchanges WHERE session_id IN (${sessions})`,
904
+ `DELETE FROM agent_turns WHERE session_id IN (${sessions})`,
905
+ ]) {
906
+ const uses = (sql.match(/\?/g) || []).length / externalIds.length;
907
+ q(sql).run(...Array.from({ length: uses }, () => externalIds).flat());
908
+ }
909
+ const gone = q(`DELETE FROM agent_sessions WHERE external_session_id IN (${marks})`).run(...externalIds).changes;
910
+ db.exec(`DELETE FROM agent_payloads WHERE sha NOT IN (
911
+ SELECT user_prompt_sha FROM agent_turns WHERE user_prompt_sha IS NOT NULL
912
+ UNION SELECT final_response_sha FROM agent_turns WHERE final_response_sha IS NOT NULL
913
+ UNION SELECT request_sha FROM agent_exchanges WHERE request_sha IS NOT NULL
914
+ UNION SELECT response_sha FROM agent_exchanges WHERE response_sha IS NOT NULL
915
+ UNION SELECT tools_sha FROM agent_exchanges WHERE tools_sha IS NOT NULL
916
+ UNION SELECT arguments_sha FROM agent_tool_calls WHERE arguments_sha IS NOT NULL
917
+ UNION SELECT reported_result_sha FROM agent_tool_calls WHERE reported_result_sha IS NOT NULL
918
+ UNION SELECT payload_sha FROM agent_context_items)`);
919
+ for (const sql of guards) db.exec(sql);
920
+ return gone;
921
+ });
922
+ },
923
+
283
924
  close() { db.close(); },
284
925
  };
926
+
927
+ /** Compares the agent's own report of a finished call (the runner's exit
928
+ * code and wall time) with the observed exit of the process the call ran
929
+ * as. Runs whenever either side arrives. Duration is exec-to-exit on the
930
+ * proxy clock with one offset, so clock skew between the proxy and the
931
+ * sandbox cannot distort it. Leaves the check null when nothing comparable
932
+ * was reported (a command still running, no runner header). */
933
+ function checkReported({ toolCallId = null, processId = null }) {
934
+ const rows = q(`SELECT a.id, c.reported_result_sha, p.exit_code, p.exit_signal, p.exited_at_ns, p.first_seen_ms, p.exited_at_ms
935
+ FROM runtime_attributions a
936
+ JOIN runtime_events ev ON ev.id = a.event_id
937
+ JOIN runtime_processes p ON p.id = ev.process_id
938
+ JOIN agent_tool_calls c ON c.id = a.tool_call_id
939
+ WHERE a.status = 'accepted' AND a.method != 'inherited' AND a.reported_check IS NULL
940
+ AND ${toolCallId ? 'c.id = ?' : 'p.id = ?'}`).all(toolCallId ?? processId);
941
+ for (const row of rows) {
942
+ if (!row.reported_result_sha || row.exited_at_ns == null || row.exit_code == null) continue;
943
+ const reported = toolResultFacts(getPayload(row.reported_result_sha));
944
+ if (reported.exitCode === null) continue;
945
+ let verdict = reported.exitCode === row.exit_code ? 'agrees' : 'exit_code_differs';
946
+ const observedMs = Number.isFinite(row.first_seen_ms) && Number.isFinite(row.exited_at_ms) ? row.exited_at_ms - row.first_seen_ms : null;
947
+ if (verdict === 'agrees' && reported.wallMs !== null && observedMs !== null && observedMs >= 0) {
948
+ // Generous on purpose: the runner starts its clock before the spawn
949
+ // the runtime sees, and a false "differs" costs more trust than it earns.
950
+ const tolerance = 0.2 * Math.max(observedMs, reported.wallMs) + 250;
951
+ if (Math.abs(observedMs - reported.wallMs) > tolerance) verdict = 'duration_differs';
952
+ }
953
+ q('UPDATE runtime_attributions SET reported_check = ? WHERE id = ?').run(verdict, row.id);
954
+ }
955
+ }
285
956
  }