@raytrace-cli/cli 0.4.0 → 0.5.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.
- package/README.md +132 -126
- package/bin/raytrace.mjs +41 -20
- package/dist/dashboard/assets/dm-sans-latin-400-normal-BwCSEQnW.woff +0 -0
- package/dist/dashboard/assets/dm-sans-latin-400-normal-CW0RaeGs.woff2 +0 -0
- package/dist/dashboard/assets/dm-sans-latin-500-normal-B9HHJjqV.woff2 +0 -0
- package/dist/dashboard/assets/dm-sans-latin-500-normal-Dr3UlScf.woff +0 -0
- package/dist/dashboard/assets/dm-sans-latin-600-normal-Aqo67rzb.woff2 +0 -0
- package/dist/dashboard/assets/dm-sans-latin-600-normal-BmdmIIQ2.woff +0 -0
- package/dist/dashboard/assets/dm-sans-latin-700-normal-CUSSCpQX.woff +0 -0
- package/dist/dashboard/assets/dm-sans-latin-700-normal-DvUfVpUG.woff2 +0 -0
- package/dist/dashboard/assets/dm-sans-latin-ext-400-normal-BjWJ59Pq.woff +0 -0
- package/dist/dashboard/assets/dm-sans-latin-ext-400-normal-BtiwyxMk.woff2 +0 -0
- package/dist/dashboard/assets/dm-sans-latin-ext-500-normal-BJfUCQsA.woff2 +0 -0
- package/dist/dashboard/assets/dm-sans-latin-ext-500-normal-DR84L5F-.woff +0 -0
- package/dist/dashboard/assets/dm-sans-latin-ext-600-normal-4vooXBpG.woff2 +0 -0
- package/dist/dashboard/assets/dm-sans-latin-ext-600-normal-DRtaDpgU.woff +0 -0
- package/dist/dashboard/assets/dm-sans-latin-ext-700-normal-BLI3TTWz.woff +0 -0
- package/dist/dashboard/assets/dm-sans-latin-ext-700-normal-CJIcxD6K.woff2 +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-cyrillic-400-normal-BSMlKf0J.woff2 +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-cyrillic-400-normal-CEL4l2ZJ.woff +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-cyrillic-500-normal-Ael50iVv.woff +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-cyrillic-500-normal-Bq9vWWag.woff2 +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-cyrillic-600-normal-CTOM6hUh.woff2 +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-cyrillic-600-normal-fLZuRloM.woff +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-cyrillic-ext-400-normal-DMdlQ8Kv.woff +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-cyrillic-ext-400-normal-xuaO2J-f.woff2 +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-cyrillic-ext-500-normal-BIfNGwUT.woff +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-cyrillic-ext-500-normal-BqneJy0T.woff2 +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-cyrillic-ext-600-normal-9HEixskS.woff +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-cyrillic-ext-600-normal-V-xxqcpd.woff2 +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-latin-400-normal-CvHOgSBP.woff +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-latin-400-normal-DMJ8VG8y.woff2 +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-latin-500-normal-CB9ihrfo.woff +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-latin-500-normal-DSY6xOcd.woff2 +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-latin-600-normal-BgSNZQsw.woff2 +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-latin-600-normal-DWFSQ4vo.woff +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-latin-ext-400-normal-BmRBH3aV.woff2 +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-latin-ext-400-normal-D3D2R8hC.woff +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-latin-ext-500-normal-CAhNIIs5.woff2 +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-latin-ext-500-normal-CZ70TYgx.woff +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-latin-ext-600-normal-D38SheWl.woff2 +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-latin-ext-600-normal-DmB0ttJJ.woff +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-vietnamese-400-normal-BulugwFq.woff2 +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-vietnamese-400-normal-DDuiU_S-.woff +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-vietnamese-500-normal-C8zxqsMH.woff +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-vietnamese-500-normal-DZ4AoWbu.woff2 +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-vietnamese-600-normal-D2EvbN8M.woff2 +0 -0
- package/dist/dashboard/assets/ibm-plex-mono-vietnamese-600-normal-iLQfcSjf.woff +0 -0
- package/dist/dashboard/assets/index-DtV3UdEB.css +1 -0
- package/dist/dashboard/assets/index-jyV5iYHJ.js +38 -0
- package/dist/dashboard/index.html +2 -2
- package/package.json +3 -1
- package/proxy/call-assessment.mjs +385 -0
- package/proxy/call-category.mjs +461 -0
- package/proxy/capture.mjs +31 -0
- package/proxy/claude-code-adapter.mjs +46 -3
- package/proxy/evidence-store.mjs +617 -15
- package/proxy/exec-narrative.mjs +625 -0
- package/proxy/execution-correlation.mjs +185 -0
- package/proxy/experiment-engine.mjs +7 -4
- package/proxy/failure-signature.mjs +56 -0
- package/proxy/gvisor-forwarder.mjs +454 -0
- package/proxy/init-evidence-db.mjs +136 -12
- package/proxy/local-sandboxes.mjs +94 -0
- package/proxy/playground.mjs +411 -0
- package/proxy/prompt-context.mjs +12 -7
- package/proxy/prompt-traces.mjs +6 -0
- package/proxy/raytace-proxy.mjs +460 -176
- package/proxy/run-recap.mjs +139 -0
- package/proxy/runtime-attribution.mjs +110 -0
- package/proxy/sandbox-bridge.mjs +46 -0
- package/proxy/schema/EVIDENCE_DATABASE.md +276 -0
- package/proxy/schema/auxiliary.sql +48 -1
- package/proxy/schema/classification.sql +89 -0
- package/proxy/schema/file_context.sql +53 -0
- package/proxy/schema/runtime_evidence.sql +201 -0
- package/proxy/schema/search.sql +66 -0
- package/proxy/search.mjs +418 -0
- package/proxy/step-attribution.mjs +380 -0
- package/proxy/tool-metadata.mjs +36 -0
- package/proxy/trace-view.mjs +276 -0
- package/proxy/typesafe.mjs +63 -0
- package/src/commands.mjs +73 -4
- package/src/lima.mjs +135 -0
- package/src/local-sandbox.mjs +324 -0
- package/src/proxy-process.mjs +20 -1
- package/src/sandbox.mjs +24 -6
- package/worker/sandbox/Dockerfile +8 -0
- package/worker/sandbox/SYSCALL_CATALOG.md +197 -0
- package/worker/sandbox/claude-hook.mjs +331 -0
- package/worker/sandbox/collector.py +357 -0
- package/worker/sandbox/dns_forwarder.py +255 -0
- package/worker/sandbox/engine.py +940 -0
- package/worker/sandbox/file_scan.py +491 -0
- package/worker/sandbox/lima.yaml +29 -0
- package/worker/sandbox/network.py +90 -0
- package/worker/sandbox/projects.py +678 -0
- package/worker/sandbox/setup.py +159 -0
- package/worker/sandbox/syscall_catalog.sql +985 -0
- package/worker/sandbox/viewer.py +132 -0
- package/dist/dashboard/assets/index-BQ9_JxGq.js +0 -27
- package/dist/dashboard/assets/index-L5cUAvhE.css +0 -1
package/proxy/evidence-store.mjs
CHANGED
|
@@ -3,11 +3,14 @@
|
|
|
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
|
-
*
|
|
7
|
-
*
|
|
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.
|
|
@@ -18,16 +21,27 @@ import { mkdirSync } from 'node:fs';
|
|
|
18
21
|
import { dirname } from 'node:path';
|
|
19
22
|
import { initializeEvidenceDatabase } 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,6 +51,29 @@ 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
78
|
export function openEvidenceStore(file) {
|
|
42
79
|
mkdirSync(dirname(file), { recursive: true });
|
|
@@ -96,6 +133,148 @@ export function openEvidenceStore(file) {
|
|
|
96
133
|
ORDER BY e.started_at_ms DESC LIMIT 1`);
|
|
97
134
|
const setReportedResult = q('UPDATE agent_tool_calls SET reported_result_sha = ? WHERE id = ?');
|
|
98
135
|
|
|
136
|
+
// ------------------------------------------------------------ search index
|
|
137
|
+
// Derived rows (search.sql), rebuilt from the evidence tables whenever
|
|
138
|
+
// either side of a call lands: its proposal/result (recordExchange) or
|
|
139
|
+
// its observed process (attribute/recordProcessExit). Indexing must
|
|
140
|
+
// never cost us evidence, so hook sites guard these calls; a missed
|
|
141
|
+
// update self-heals on the next open (backfill) or a full reindex.
|
|
142
|
+
|
|
143
|
+
const SEARCH_COLUMNS = ['id', 'kind', 'ts_ms', 'session_id', 'session_external', 'turn_id', 'exchange_id', 'call_id',
|
|
144
|
+
'external_call_id', 'output_index', 'agent', 'model', 'provider', 'tool_name', 'category', 'outcome',
|
|
145
|
+
'outcome_reported', 'outcome_observed', 'reported_check', 'exit_code', 'http_status', 'error_text',
|
|
146
|
+
'failure_signature', 'signature_label', 'command_text', 'file_paths', 'prompt_text', 'args_text',
|
|
147
|
+
'result_text', 'duration_ms', 'indexed_at_ms'];
|
|
148
|
+
const upsertSearchEvent = q(`INSERT INTO search_events (${SEARCH_COLUMNS.join(',')})
|
|
149
|
+
VALUES (${SEARCH_COLUMNS.map(() => '?').join(',')})
|
|
150
|
+
ON CONFLICT(id) DO UPDATE SET ${SEARCH_COLUMNS.filter((c) => c !== 'id').map((c) => `${c}=excluded.${c}`).join(',')}`);
|
|
151
|
+
const putSearchEvent = (event) => upsertSearchEvent.run(...SEARCH_COLUMNS.map((c) => event[c] ?? null));
|
|
152
|
+
|
|
153
|
+
const selectCallForIndex = q(`SELECT c.id AS call_pk, c.external_call_id, c.output_index, c.tool_name,
|
|
154
|
+
c.arguments_sha, c.reported_result_sha, c.proposed_at_ms,
|
|
155
|
+
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,
|
|
156
|
+
s.external_session_id, s.agent_name, t.user_prompt_sha
|
|
157
|
+
FROM agent_tool_calls c
|
|
158
|
+
JOIN agent_exchanges e ON e.id = c.exchange_id
|
|
159
|
+
JOIN agent_sessions s ON s.id = e.session_id
|
|
160
|
+
LEFT JOIN agent_turns t ON t.id = e.turn_id
|
|
161
|
+
WHERE c.id = ?`);
|
|
162
|
+
const selectCallProcess = q(`SELECT a.reported_check,
|
|
163
|
+
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,
|
|
164
|
+
${PROCESS_FACTS}
|
|
165
|
+
FROM runtime_attributions a
|
|
166
|
+
JOIN runtime_events ev ON ev.id = a.event_id
|
|
167
|
+
LEFT JOIN runtime_processes p ON p.id = ev.process_id
|
|
168
|
+
WHERE a.tool_call_id = ? AND a.status = 'accepted' AND a.method != 'inherited'
|
|
169
|
+
ORDER BY a.created_at_ms LIMIT 1`);
|
|
170
|
+
const selectSnapshotPaths = q('SELECT changes_json FROM workspace_snapshots WHERE call_id = ? ORDER BY taken_at_ms DESC LIMIT 1');
|
|
171
|
+
|
|
172
|
+
function indexCall(callPk) {
|
|
173
|
+
const row = selectCallForIndex.get(callPk);
|
|
174
|
+
if (!row) return;
|
|
175
|
+
const args = getPayload(row.arguments_sha);
|
|
176
|
+
const resultItem = getPayload(row.reported_result_sha);
|
|
177
|
+
const reported = reportedOutcome(resultItem);
|
|
178
|
+
const proc = selectCallProcess.get(callPk);
|
|
179
|
+
const observedStatus = proc ? processOutcome(proc) : { status: null, error: null };
|
|
180
|
+
const observed = observedOutcome(observedStatus.status);
|
|
181
|
+
const outcome = combineOutcomes(reported, observed);
|
|
182
|
+
const facts = resultItem != null ? toolResultFacts(resultItem) : { exitCode: null, wallMs: null };
|
|
183
|
+
const exitCode = proc?.exit_code ?? facts.exitCode ?? null;
|
|
184
|
+
const resultText = clipText(payloadToText(resultItem));
|
|
185
|
+
const failed = outcome === 'failed';
|
|
186
|
+
const errorText = failed ? clipText([observedStatus.error, resultText].filter(Boolean).join('\n'), 8000) : (observedStatus.error ?? null);
|
|
187
|
+
const sig = failed ? failureSignature({ errorText: resultText || errorText, exitCode, toolName: row.tool_name }) : null;
|
|
188
|
+
const files = pathsFromText(commandTextOf(args), extractFilePaths(args));
|
|
189
|
+
if (row.external_call_id) {
|
|
190
|
+
const snap = fromJson(selectSnapshotPaths.get(row.external_call_id)?.changes_json ?? null);
|
|
191
|
+
for (const change of snap?.changes ?? []) if (change?.path) files.add(change.path);
|
|
192
|
+
}
|
|
193
|
+
const observedMs = Number.isFinite(proc?.first_seen_ms) && Number.isFinite(proc?.exited_at_ms) ? proc.exited_at_ms - proc.first_seen_ms : null;
|
|
194
|
+
putSearchEvent({
|
|
195
|
+
id: `call:${callPk}`, kind: 'call', ts_ms: row.proposed_at_ms ?? row.completed_at_ms ?? row.started_at_ms,
|
|
196
|
+
session_id: row.session_id, session_external: row.external_session_id, turn_id: row.turn_id,
|
|
197
|
+
exchange_id: row.exchange_id, call_id: callPk, external_call_id: row.external_call_id,
|
|
198
|
+
output_index: row.output_index, agent: row.agent_name, model: row.model, provider: row.provider,
|
|
199
|
+
tool_name: row.tool_name, category: callCategory(row.tool_name, args)?.category ?? null,
|
|
200
|
+
outcome, outcome_reported: reported, outcome_observed: observed,
|
|
201
|
+
reported_check: proc?.reported_check ?? null, exit_code: exitCode, http_status: row.http_status,
|
|
202
|
+
error_text: errorText, failure_signature: sig?.signature ?? null, signature_label: sig?.label ?? null,
|
|
203
|
+
command_text: commandTextOf(args) || null, file_paths: [...files].join('\n') || null,
|
|
204
|
+
prompt_text: clipText(payloadToText(getPayload(row.user_prompt_sha)), 8000) || null,
|
|
205
|
+
args_text: clipText(payloadToText(args)) || null, result_text: resultText || null,
|
|
206
|
+
duration_ms: observedMs ?? facts.wallMs ?? null, indexed_at_ms: Date.now(),
|
|
207
|
+
});
|
|
208
|
+
if (row.turn_id) indexTurn(row.turn_id);
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
const selectTurnForIndex = q(`SELECT t.id, t.session_id, t.status, t.started_at_ms, t.ended_at_ms,
|
|
212
|
+
t.user_prompt_sha, t.final_response_sha, s.external_session_id, s.agent_name,
|
|
213
|
+
(SELECT e.model FROM agent_exchanges e WHERE e.turn_id = t.id ORDER BY e.started_at_ms DESC LIMIT 1) AS model,
|
|
214
|
+
(SELECT e.provider FROM agent_exchanges e WHERE e.turn_id = t.id ORDER BY e.started_at_ms DESC LIMIT 1) AS provider,
|
|
215
|
+
(SELECT MAX(e.http_status) FROM agent_exchanges e WHERE e.turn_id = t.id) AS http_status,
|
|
216
|
+
(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
|
|
217
|
+
FROM agent_turns t JOIN agent_sessions s ON s.id = t.session_id WHERE t.id = ?`);
|
|
218
|
+
|
|
219
|
+
function indexTurn(turnId) {
|
|
220
|
+
const row = selectTurnForIndex.get(turnId);
|
|
221
|
+
if (!row) return;
|
|
222
|
+
const failedCalls = q(`SELECT COUNT(*) AS n FROM search_events WHERE turn_id = ? AND kind = 'call' AND outcome = 'failed'`).get(turnId).n;
|
|
223
|
+
const outcome = row.status === 'failed' || failedCalls > 0 ? 'failed' : row.status === 'completed' ? 'ok' : 'unknown';
|
|
224
|
+
putSearchEvent({
|
|
225
|
+
id: `turn:${turnId}`, kind: 'turn', ts_ms: row.started_at_ms,
|
|
226
|
+
session_id: row.session_id, session_external: row.external_session_id, turn_id: turnId,
|
|
227
|
+
exchange_id: row.exchange_id, agent: row.agent_name, model: row.model, provider: row.provider,
|
|
228
|
+
outcome, outcome_reported: 'unknown', outcome_observed: 'unknown', http_status: row.http_status,
|
|
229
|
+
prompt_text: clipText(payloadToText(getPayload(row.user_prompt_sha)), 16_000) || null,
|
|
230
|
+
result_text: clipText(payloadToText(getPayload(row.final_response_sha)), 16_000) || null,
|
|
231
|
+
duration_ms: row.ended_at_ms != null ? row.ended_at_ms - row.started_at_ms : null,
|
|
232
|
+
indexed_at_ms: Date.now(),
|
|
233
|
+
});
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
function indexExchange(exchangeId) {
|
|
237
|
+
for (const call of q('SELECT id FROM agent_tool_calls WHERE exchange_id = ?').all(exchangeId)) indexCall(call.id);
|
|
238
|
+
const turn = q('SELECT turn_id FROM agent_exchanges WHERE id = ?').get(exchangeId);
|
|
239
|
+
if (turn?.turn_id) indexTurn(turn.turn_id);
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
function indexProcessCalls(processId) {
|
|
243
|
+
const rows = q(`SELECT DISTINCT a.tool_call_id FROM runtime_attributions a
|
|
244
|
+
JOIN runtime_events ev ON ev.id = a.event_id WHERE ev.process_id = ?`).all(processId);
|
|
245
|
+
for (const row of rows) indexCall(row.tool_call_id);
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
function indexProxyErrorRow(row) {
|
|
249
|
+
const sig = failureSignature({ errorText: row.error, toolName: 'proxy' });
|
|
250
|
+
putSearchEvent({
|
|
251
|
+
id: `proxy_error:${row.rowid}`, kind: 'proxy_error', ts_ms: row.occurred_at_ms ?? Date.now(),
|
|
252
|
+
provider: row.provider, outcome: 'failed', outcome_reported: 'unknown', outcome_observed: 'unknown',
|
|
253
|
+
error_text: clipText([row.route, row.error].filter(Boolean).join(' '), 8000) || null,
|
|
254
|
+
failure_signature: sig?.signature ?? null, signature_label: sig?.label ?? null,
|
|
255
|
+
result_text: clipText(payloadToText(fromJson(row.cause_json)), 8000) || null,
|
|
256
|
+
indexed_at_ms: Date.now(),
|
|
257
|
+
});
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
function indexGuarded(work) {
|
|
261
|
+
try { work(); } catch (error) { console.error('[raytace] search indexing failed:', error.message); }
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
function backfillSearchIndex() {
|
|
265
|
+
const missing = (sql) => q(sql).all();
|
|
266
|
+
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)`);
|
|
267
|
+
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)`);
|
|
268
|
+
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)`);
|
|
269
|
+
if (!calls.length && !turns.length && !errors.length) return 0;
|
|
270
|
+
return transaction(() => {
|
|
271
|
+
for (const call of calls) indexCall(call.id);
|
|
272
|
+
for (const turn of turns) indexTurn(turn.id);
|
|
273
|
+
for (const row of errors) indexProxyErrorRow(row);
|
|
274
|
+
return calls.length + turns.length + errors.length;
|
|
275
|
+
});
|
|
276
|
+
}
|
|
277
|
+
|
|
99
278
|
function ensureSession(row, startedMs) {
|
|
100
279
|
const external = typeof row.session_id === 'string' && row.session_id ? row.session_id : null;
|
|
101
280
|
const found = external ? selectSession.get(external) : null;
|
|
@@ -113,8 +292,9 @@ export function openEvidenceStore(file) {
|
|
|
113
292
|
function resolveTurn(sessionId, row, request, startedMs) {
|
|
114
293
|
const prompt = promptInfo(request);
|
|
115
294
|
if (!prompt) return null;
|
|
116
|
-
//
|
|
117
|
-
//
|
|
295
|
+
// A sandbox files every Claude Code session under one rtp- id, and two
|
|
296
|
+
// sessions given the same prompt start identically, so the agent's own
|
|
297
|
+
// session id is part of the key when a row has one: a session never
|
|
118
298
|
// continues another's turn. Rows without one keep their original key.
|
|
119
299
|
const key = sha256(JSON.stringify([row.provider ?? null, request?.model ?? null, prompt.prefix,
|
|
120
300
|
...(row.agent_session_id ? [row.agent_session_id] : [])]));
|
|
@@ -139,8 +319,8 @@ export function openEvidenceStore(file) {
|
|
|
139
319
|
const output = Array.isArray(response?.output) ? response.output : [];
|
|
140
320
|
const proposals = output.map((item, index) => [item, index]).filter(([item]) => item?.call_id && CALL_TYPES.test(item?.type || ''));
|
|
141
321
|
|
|
142
|
-
transaction(() => {
|
|
143
|
-
if (selectExchangeId.get(row.span_id)) return;
|
|
322
|
+
const answered = transaction(() => {
|
|
323
|
+
if (selectExchangeId.get(row.span_id)) return [];
|
|
144
324
|
const sessionId = ensureSession(row, startedMs);
|
|
145
325
|
const turnId = resolveTurn(sessionId, row, request, startedMs);
|
|
146
326
|
const responseSha = putPayload(response);
|
|
@@ -151,6 +331,7 @@ export function openEvidenceStore(file) {
|
|
|
151
331
|
request: { headers: row.request?.headers ?? null, bytes: row.request?.bytes ?? null, sha256: row.request?.sha256 ?? null },
|
|
152
332
|
response: { headers: row.response?.headers ?? null, bytes: row.response?.bytes ?? null, sha256: row.response?.sha256 ?? null } }));
|
|
153
333
|
|
|
334
|
+
const answeredCalls = [];
|
|
154
335
|
for (const [position, item] of items.entries()) {
|
|
155
336
|
const payloadSha = putPayload(item);
|
|
156
337
|
insertContext.run(row.span_id, position, item?.role ?? null, item?.type ?? null, item?.call_id ?? null, payloadSha, previewOf(item));
|
|
@@ -158,7 +339,7 @@ export function openEvidenceStore(file) {
|
|
|
158
339
|
// did -- recorded on the call as a report, never as evidence.
|
|
159
340
|
if (item?.call_id && TOOL_RESULT_KINDS.includes(item?.type)) {
|
|
160
341
|
const call = selectAnsweredCall.get(item.call_id, sessionId, startedMs);
|
|
161
|
-
if (call) setReportedResult.run(payloadSha, call.id);
|
|
342
|
+
if (call) { setReportedResult.run(payloadSha, call.id); answeredCalls.push(call.id); }
|
|
162
343
|
}
|
|
163
344
|
}
|
|
164
345
|
for (const [item, outputIndex] of proposals) {
|
|
@@ -166,12 +347,16 @@ export function openEvidenceStore(file) {
|
|
|
166
347
|
putPayload(item.arguments ?? item.input ?? item.function?.arguments ?? null), completedMs);
|
|
167
348
|
}
|
|
168
349
|
if (turnId) {
|
|
169
|
-
// A response that proposes nothing more is the agent's answer.
|
|
350
|
+
// A response that proposes nothing more is the agent's answer. This
|
|
351
|
+
// closes the turn for the agent; processes it started may still run.
|
|
170
352
|
const failed = Number(row.response?.status) >= 400;
|
|
171
353
|
const status = failed ? 'failed' : proposals.length ? 'active' : 'completed';
|
|
172
354
|
updateTurn.run(status, completedMs, status === 'completed' ? responseSha : null, turnId);
|
|
173
355
|
}
|
|
356
|
+
return answeredCalls;
|
|
174
357
|
});
|
|
358
|
+
for (const callId of answered) checkReported({ toolCallId: callId });
|
|
359
|
+
indexGuarded(() => { indexExchange(row.span_id); for (const callId of answered) indexCall(callId); });
|
|
175
360
|
}
|
|
176
361
|
|
|
177
362
|
// Rebuild the capture-time row shape the dashboard and lab consume.
|
|
@@ -207,6 +392,58 @@ export function openEvidenceStore(file) {
|
|
|
207
392
|
const selectExchange = q(`SELECT ${EXCHANGE_COLUMNS} FROM agent_exchanges e
|
|
208
393
|
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
394
|
|
|
395
|
+
// --------------------------------------------------------- runtime evidence
|
|
396
|
+
|
|
397
|
+
const selectSandbox = q('SELECT id, project_id FROM runtime_sandboxes WHERE id = ?');
|
|
398
|
+
const insertSandbox = q(`INSERT INTO runtime_sandboxes (id, external_container_id, project_id, runtime_name, started_at_ms)
|
|
399
|
+
VALUES (?, ?, ?, 'gvisor', ?)`);
|
|
400
|
+
const setSandboxProject = q('UPDATE runtime_sandboxes SET project_id = ? WHERE id = ? AND project_id IS NULL');
|
|
401
|
+
const selectEventId = q('SELECT id FROM runtime_events WHERE stream_id = ? AND stream_sequence = ?');
|
|
402
|
+
const insertEvent = q(`INSERT INTO runtime_events (id, sandbox_id, process_id, stream_id, stream_sequence, event_kind,
|
|
403
|
+
observed_at_ns, received_at_ms, tid, payload_json, decoder_version) VALUES (?,?,?,?,?,?,?,?,?,?,?)`);
|
|
404
|
+
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');
|
|
405
|
+
const selectLiveParent = q(`SELECT id FROM runtime_processes WHERE sandbox_id = ? AND pid = ? AND exited_at_ns IS NULL
|
|
406
|
+
ORDER BY first_seen_ms DESC LIMIT 1`);
|
|
407
|
+
const insertProcess = q(`INSERT INTO runtime_processes (id, sandbox_id, pid, start_time_ns, parent_process_id, observed_ppid,
|
|
408
|
+
first_seen_ns, identity_basis, first_seen_ms) VALUES (?,?,?,?,?,?,?,?,?)`);
|
|
409
|
+
const closeProcess = q(`UPDATE runtime_processes SET exited_at_ns = ?, exited_at_ms = ?, exit_code = ?, exit_signal = ?, evidence_lost = NULL
|
|
410
|
+
WHERE id = ? AND exited_at_ns IS NULL`);
|
|
411
|
+
const loseProcesses = q(`UPDATE runtime_processes SET evidence_lost = ?
|
|
412
|
+
WHERE sandbox_id = ? AND exited_at_ns IS NULL AND evidence_lost IS NULL`);
|
|
413
|
+
const endSandboxStmt = q(`UPDATE runtime_sandboxes SET ended_at_ms = MAX(COALESCE(started_at_ms, ?), ?) WHERE id = ? AND ended_at_ms IS NULL`);
|
|
414
|
+
const selectAcceptedAttribution = q(`SELECT id FROM runtime_attributions WHERE tool_call_id = ? AND event_id = ? AND status = 'accepted'`);
|
|
415
|
+
const insertAttribution = q(`INSERT INTO runtime_attributions (id, tool_call_id, event_id, method, confidence, status, basis_json,
|
|
416
|
+
attributor_version, created_at_ms, score, window_start_ms, window_end_ms) VALUES (?,?,?,?,?,'accepted',?,?,?,?,?,?)`);
|
|
417
|
+
|
|
418
|
+
/** One sandbox lifetime per container. Process identity (pid + start
|
|
419
|
+
* time) keeps a restarted container's reused pids apart regardless. */
|
|
420
|
+
function ensureSandbox(containerId, projectId = null) {
|
|
421
|
+
const found = selectSandbox.get(containerId);
|
|
422
|
+
if (found) { if (projectId && !found.project_id) setSandboxProject.run(projectId, containerId); return containerId; }
|
|
423
|
+
insertSandbox.run(containerId, containerId, projectId, Date.now());
|
|
424
|
+
return containerId;
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
/** Appends one collector event, once: the stream is the container and the
|
|
428
|
+
* sequence is the collector's own event id, so a replayed event is a no-op. */
|
|
429
|
+
function recordEvent({ sandboxId, processId = null, raw }) {
|
|
430
|
+
const streamId = `gvisor:${sandboxId}`;
|
|
431
|
+
const sequence = Number(raw?.event_id);
|
|
432
|
+
if (!Number.isInteger(sequence) || sequence < 0) return null;
|
|
433
|
+
const existing = selectEventId.get(streamId, sequence);
|
|
434
|
+
if (existing) return existing.id;
|
|
435
|
+
const id = `${streamId}:${sequence}`;
|
|
436
|
+
const tid = intOrNull(raw.tid);
|
|
437
|
+
insertEvent.run(id, sandboxId, processId, streamId, sequence, String(raw.kind || 'unknown'), nsText(raw.timestamp_ns), Date.now(),
|
|
438
|
+
tid && tid >= 1 ? tid : null, JSON.stringify(raw), DECODER_VERSION);
|
|
439
|
+
return id;
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
function findProcess(sandboxId, pid, startNs) { return selectProcess.get(sandboxId, pid, startNs); }
|
|
443
|
+
|
|
444
|
+
// Fill the index for captures that predate it (or a missed hook update).
|
|
445
|
+
indexGuarded(() => backfillSearchIndex());
|
|
446
|
+
|
|
210
447
|
return {
|
|
211
448
|
db, journal, recordExchange,
|
|
212
449
|
|
|
@@ -225,20 +462,257 @@ export function openEvidenceStore(file) {
|
|
|
225
462
|
return { payload: row.request.payload, response: row.response.payload, provider: row.provider, route: row.route, session_id: row.session_id };
|
|
226
463
|
},
|
|
227
464
|
|
|
465
|
+
// ---- runtime evidence writers (the gVisor forwarder)
|
|
466
|
+
|
|
467
|
+
/** A process began running a program (exec_succeeded), or tried to and
|
|
468
|
+
* failed (exec_failed). Records the process once, by pid + start time,
|
|
469
|
+
* and the event every time. Returns ids for attributing it. */
|
|
470
|
+
recordProcessStart({ containerId, projectId = null, raw, startedMs = null }) {
|
|
471
|
+
if (!containerId || !raw) return null;
|
|
472
|
+
return transaction(() => {
|
|
473
|
+
const sandboxId = ensureSandbox(containerId, projectId);
|
|
474
|
+
const pid = intOrNull(raw.pid);
|
|
475
|
+
if (pid == null || pid < 1) return { processId: null, eventId: recordEvent({ sandboxId, raw }) };
|
|
476
|
+
const startNs = nsText(raw.process_start_ns);
|
|
477
|
+
let process = findProcess(sandboxId, pid, startNs);
|
|
478
|
+
if (!process) {
|
|
479
|
+
const ppid = intOrNull(raw.ppid);
|
|
480
|
+
const parent = ppid != null ? selectLiveParent.get(sandboxId, ppid) : null;
|
|
481
|
+
const observed = nsText(raw.timestamp_ns) ?? startNs ?? '0';
|
|
482
|
+
const id = `${sandboxId}:${pid}:${startNs ?? `event-${raw.event_id}`}`;
|
|
483
|
+
insertProcess.run(id, sandboxId, pid, startNs, parent?.id ?? null, ppid != null && ppid >= 0 ? ppid : null, observed,
|
|
484
|
+
startNs ? 'pid+start_time' : 'pid+first_event (start time not reported)', Number.isFinite(startedMs) ? Math.round(startedMs) : null);
|
|
485
|
+
process = { id };
|
|
486
|
+
}
|
|
487
|
+
return { processId: process.id, eventId: recordEvent({ sandboxId, processId: process.id, raw }) };
|
|
488
|
+
});
|
|
489
|
+
},
|
|
490
|
+
|
|
491
|
+
/** Ties an observed process (its exec event) to the tool call it ran
|
|
492
|
+
* for. `method` is how: marker | window | text | inherited. */
|
|
493
|
+
attribute({ toolCallId, eventId, method, confidence = 'corroborated', score = null, windowStartMs = null, windowEndMs = null }) {
|
|
494
|
+
if (!toolCallId || !eventId || selectAcceptedAttribution.get(toolCallId, eventId)) return false;
|
|
495
|
+
insertAttribution.run(randomUUID(), toolCallId, eventId, method, confidence,
|
|
496
|
+
JSON.stringify({ method, score, window_start_ms: windowStartMs, window_end_ms: windowEndMs }), ATTRIBUTOR_VERSION, Date.now(),
|
|
497
|
+
score ?? null, windowStartMs ?? null, windowEndMs ?? null);
|
|
498
|
+
indexGuarded(() => indexCall(toolCallId));
|
|
499
|
+
return true;
|
|
500
|
+
},
|
|
501
|
+
|
|
502
|
+
/** A process exited. Found by pid + start time within its sandbox, so an
|
|
503
|
+
* exit still closes its process after a proxy restart. A process with no
|
|
504
|
+
* row (one that forked but never exec'd) is not recorded. */
|
|
505
|
+
recordProcessExit({ containerId, projectId = null, raw, endedMs = null, exit_code = null, signal = null }) {
|
|
506
|
+
if (!containerId || !raw) return false;
|
|
507
|
+
const closed = transaction(() => {
|
|
508
|
+
const sandboxId = ensureSandbox(containerId, projectId);
|
|
509
|
+
const pid = intOrNull(raw.pid);
|
|
510
|
+
const process = pid != null ? findProcess(sandboxId, pid, nsText(raw.process_start_ns)) : null;
|
|
511
|
+
if (!process || process.exited_at_ns != null) return null;
|
|
512
|
+
const exitSignal = Number.isInteger(signal) && signal > 0 ? signal : null;
|
|
513
|
+
const exitCode = exitSignal ? null : (Number.isInteger(exit_code) && exit_code >= 0 ? exit_code : null);
|
|
514
|
+
closeProcess.run(nsText(raw.timestamp_ns) ?? process.first_seen_ns, Number.isFinite(endedMs) ? Math.round(endedMs) : null,
|
|
515
|
+
exitCode, exitSignal, process.id);
|
|
516
|
+
recordEvent({ sandboxId, processId: process.id, raw });
|
|
517
|
+
return process.id;
|
|
518
|
+
});
|
|
519
|
+
if (!closed) return false;
|
|
520
|
+
checkReported({ processId: closed });
|
|
521
|
+
indexGuarded(() => indexProcessCalls(closed));
|
|
522
|
+
return true;
|
|
523
|
+
},
|
|
524
|
+
|
|
525
|
+
/** The evidence that would close a sandbox's open processes can no
|
|
526
|
+
* longer arrive. Marks them (never as failed) and records why. */
|
|
527
|
+
loseOpenProcesses({ containerId, reason, raw = null, ended = false }) {
|
|
528
|
+
if (!containerId) return 0;
|
|
529
|
+
const changes = transaction(() => {
|
|
530
|
+
const sandboxId = ensureSandbox(containerId);
|
|
531
|
+
if (raw) recordEvent({ sandboxId, raw });
|
|
532
|
+
const lost = Number(loseProcesses.run(String(reason || 'unknown'), sandboxId).changes);
|
|
533
|
+
if (ended) endSandboxStmt.run(Date.now(), Date.now(), sandboxId);
|
|
534
|
+
return lost;
|
|
535
|
+
});
|
|
536
|
+
if (changes) indexGuarded(() => {
|
|
537
|
+
const rows = q(`SELECT DISTINCT a.tool_call_id FROM runtime_attributions a
|
|
538
|
+
JOIN runtime_events ev ON ev.id = a.event_id JOIN runtime_processes p ON p.id = ev.process_id
|
|
539
|
+
WHERE p.sandbox_id = ? AND p.evidence_lost IS NOT NULL`).all(containerId);
|
|
540
|
+
for (const row of rows) indexCall(row.tool_call_id);
|
|
541
|
+
});
|
|
542
|
+
return changes;
|
|
543
|
+
},
|
|
544
|
+
|
|
545
|
+
/** The session's proposed calls that no process has been tied to yet,
|
|
546
|
+
* each with its causal window: from the request that proposed it to the
|
|
547
|
+
* first later request in the session that carried its result back (null
|
|
548
|
+
* while none has). `call_id` is the internal tool-call id. */
|
|
549
|
+
candidatesInWindow(startMs, endMs, { sessionId = null } = {}) {
|
|
550
|
+
if (!sessionId) return [];
|
|
551
|
+
const rows = q(`SELECT c.id, c.external_call_id, c.tool_name, c.arguments_sha, e.started_at_ms,
|
|
552
|
+
(SELECT MIN(r.started_at_ms) FROM agent_context_items ci JOIN agent_exchanges r ON r.id = ci.exchange_id
|
|
553
|
+
WHERE ci.external_call_id = c.external_call_id AND ci.kind IN (${marks(TOOL_RESULT_KINDS)})
|
|
554
|
+
AND r.session_id = e.session_id AND r.started_at_ms >= e.started_at_ms AND r.id != e.id) AS window_end
|
|
555
|
+
FROM agent_tool_calls c
|
|
556
|
+
JOIN agent_exchanges e ON e.id = c.exchange_id
|
|
557
|
+
JOIN agent_sessions s ON s.id = e.session_id
|
|
558
|
+
WHERE e.started_at_ms BETWEEN ? AND ? AND s.external_session_id = ?
|
|
559
|
+
AND NOT EXISTS (SELECT 1 FROM runtime_attributions a
|
|
560
|
+
WHERE a.tool_call_id = c.id AND a.status = 'accepted' AND a.method != 'inherited')
|
|
561
|
+
ORDER BY e.started_at_ms, c.output_index`).all(...TOOL_RESULT_KINDS, startMs, endMs, sessionId);
|
|
562
|
+
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,
|
|
563
|
+
args: getPayload(row.arguments_sha), window_start: row.started_at_ms, window_end: row.window_end ?? null }));
|
|
564
|
+
},
|
|
565
|
+
|
|
566
|
+
/** A session's sandbox processes that no call accounts for, first seen at
|
|
567
|
+
* or after `sinceMs`, oldest first, each with its first exec event, its
|
|
568
|
+
* parent process, and the call that parent is tied to (null when none). */
|
|
569
|
+
unattributedProcesses({ sessionId, sinceMs }) {
|
|
570
|
+
if (!sessionId) return [];
|
|
571
|
+
const accepted = (process) => `SELECT a.tool_call_id FROM runtime_attributions a JOIN runtime_events e ON e.id = a.event_id
|
|
572
|
+
WHERE e.process_id = ${process} AND a.status = 'accepted' LIMIT 1`;
|
|
573
|
+
return q(`SELECT p.id AS process_id, p.parent_process_id, p.first_seen_ms, ev.id AS event_id, ev.payload_json,
|
|
574
|
+
(${accepted('p.parent_process_id')}) AS parent_call_id
|
|
575
|
+
FROM runtime_processes p
|
|
576
|
+
JOIN runtime_sandboxes s ON s.id = p.sandbox_id
|
|
577
|
+
JOIN runtime_events ev ON ev.id = (SELECT e.id FROM runtime_events e
|
|
578
|
+
WHERE e.process_id = p.id AND e.event_kind = 'exec_succeeded' ORDER BY e.stream_sequence LIMIT 1)
|
|
579
|
+
WHERE s.project_id = ? AND p.first_seen_ms >= ? AND NOT EXISTS (${accepted('p.id')})
|
|
580
|
+
ORDER BY p.first_seen_ms, ev.stream_sequence`).all(sessionId, Math.round(sinceMs))
|
|
581
|
+
.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,
|
|
582
|
+
parent_call_id: row.parent_call_id ?? null, raw: fromJson(row.payload_json) ?? {} }));
|
|
583
|
+
},
|
|
584
|
+
|
|
228
585
|
/** 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. */
|
|
586
|
+
* key for caching it. Counts only ever grow; a result reported back or a
|
|
587
|
+
* process exiting changes a count too. */
|
|
231
588
|
dataVersion() {
|
|
232
589
|
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
|
|
590
|
+
(SELECT count(*) FROM agent_tool_calls WHERE reported_result_sha IS NOT NULL) AS results,
|
|
591
|
+
(SELECT count(*) FROM runtime_events) AS events, (SELECT count(*) FROM runtime_attributions) AS attributions,
|
|
592
|
+
(SELECT count(*) FROM workspace_snapshots) AS snapshots`).get()).join(':');
|
|
593
|
+
},
|
|
594
|
+
|
|
595
|
+
// ---- workspace snapshots (a sandboxed Claude Code's hook)
|
|
596
|
+
|
|
597
|
+
/** Where the project folder stood after a call or at a prompt. The same
|
|
598
|
+
* snapshot sent twice (a resend after 409) is recorded once. */
|
|
599
|
+
recordSnapshot({ sessionId, agentSessionId = null, snapshot }) {
|
|
600
|
+
const id = createHash('sha256').update([sessionId, agentSessionId, snapshot.taken_on, snapshot.call_id, snapshot.commit, snapshot.taken_at].join('\0')).digest('hex');
|
|
601
|
+
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)
|
|
602
|
+
VALUES (?,?,?,?,?,?,?,?,?,?)`).run(id, sessionId, agentSessionId, snapshot.taken_on, snapshot.call_id ?? null, snapshot.commit,
|
|
603
|
+
snapshot.parent ?? null, snapshot.changed ? 1 : 0, Math.round(toMs(snapshot.taken_at) ?? Date.now()),
|
|
604
|
+
JSON.stringify({ changes: snapshot.changes ?? [], too_big: snapshot.too_big ?? [] }));
|
|
605
|
+
return id;
|
|
606
|
+
},
|
|
607
|
+
|
|
608
|
+
/** Every snapshot of one agent session filed under `sessionId`, oldest first. */
|
|
609
|
+
snapshotsForAgentSession({ sessionId, agentSessionId }) {
|
|
610
|
+
return q(`SELECT taken_on, call_id, commit_sha, parent_sha, changed, taken_at_ms FROM workspace_snapshots
|
|
611
|
+
WHERE session_id = ? AND agent_session_id = ? ORDER BY taken_at_ms`).all(sessionId, agentSessionId)
|
|
612
|
+
.map((row) => ({ taken_on: row.taken_on, call_id: row.call_id, commit: row.commit_sha, parent: row.parent_sha ?? null,
|
|
613
|
+
changed: row.changed === 1, taken_at_ms: row.taken_at_ms }));
|
|
614
|
+
},
|
|
615
|
+
|
|
616
|
+
/** The snapshot taken after each of these calls (external call ids), by call id. */
|
|
617
|
+
snapshotsForCalls(callIds) {
|
|
618
|
+
const list = [...new Set((callIds ?? []).filter(Boolean))];
|
|
619
|
+
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);
|
|
622
|
+
return new Map(rows.map((row) => {
|
|
623
|
+
const body = fromJson(row.changes_json) ?? {};
|
|
624
|
+
return [row.call_id, { commit: row.commit_sha, parent: row.parent_sha, changed: row.changed === 1, taken_at: toIso(row.taken_at_ms),
|
|
625
|
+
changes: body.changes ?? [], too_big: body.too_big ?? [] }];
|
|
626
|
+
}));
|
|
627
|
+
},
|
|
628
|
+
|
|
629
|
+
// ---- readers (the dashboard)
|
|
630
|
+
|
|
631
|
+
/** Proposed vs observed for every call in these exchanges: the call, and
|
|
632
|
+
* the process it ran as (its accepted, non-inherited attribution). */
|
|
633
|
+
divergence(exchangeIds) {
|
|
634
|
+
if (!exchangeIds.length) return [];
|
|
635
|
+
return q(`SELECT c.external_call_id AS call_id, c.exchange_id AS span_id, c.output_index, c.tool_name AS name,
|
|
636
|
+
a.method, a.confidence, a.score, a.window_start_ms, a.window_end_ms, a.reported_check, a.event_id,
|
|
637
|
+
json_extract(ev.payload_json, '$.argv') AS attributed_argv_json,
|
|
638
|
+
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,
|
|
639
|
+
${PROCESS_FACTS},
|
|
640
|
+
(SELECT COUNT(*) FROM runtime_attributions d WHERE d.tool_call_id = c.id AND d.status = 'accepted' AND d.method = 'inherited') AS descendant_count
|
|
641
|
+
FROM agent_tool_calls c
|
|
642
|
+
LEFT JOIN runtime_attributions a ON a.id = (SELECT a2.id FROM runtime_attributions a2
|
|
643
|
+
WHERE a2.tool_call_id = c.id AND a2.status = 'accepted' AND a2.method != 'inherited' ORDER BY a2.created_at_ms LIMIT 1)
|
|
644
|
+
LEFT JOIN runtime_events ev ON ev.id = a.event_id
|
|
645
|
+
LEFT JOIN runtime_processes p ON p.id = ev.process_id
|
|
646
|
+
WHERE c.exchange_id IN (${marks(exchangeIds)}) ORDER BY c.exchange_id, c.output_index`).all(...exchangeIds)
|
|
647
|
+
.map((row) => {
|
|
648
|
+
const { status, error } = processOutcome(row);
|
|
649
|
+
return {
|
|
650
|
+
call_id: row.call_id, span_id: row.span_id, output_index: row.output_index, name: row.name,
|
|
651
|
+
outcome: row.event_id ? 'as_proposed' : 'not_executed',
|
|
652
|
+
status, error, source: row.event_id ? 'gvisor' : null,
|
|
653
|
+
match_score: row.score, match_basis: row.method === 'marker' ? 'id' : row.method ?? null,
|
|
654
|
+
kernel_confirmed: row.event_id ? 1 : 0, kernel_match_score: row.score,
|
|
655
|
+
tier: row.confidence ? TIER[row.confidence] : null,
|
|
656
|
+
pid: row.pid ?? null, exit_code: row.exit_code ?? null, reported_check: row.reported_check ?? null,
|
|
657
|
+
exec_id: row.event_id ?? null, start_time_ns: row.start_time_ns ?? null,
|
|
658
|
+
// The command that was matched to the call. A process can exec
|
|
659
|
+
// more than once (Codex's environment setup, then the command it
|
|
660
|
+
// was asked to run), and the matched exec is the one to show.
|
|
661
|
+
started_at: toIso(row.first_seen_ms), ended_at: toIso(row.exited_at_ms), argv: fromJson(row.attributed_argv_json ?? row.argv_json),
|
|
662
|
+
window_start_ms: row.window_start_ms ?? null, window_end_ms: row.window_end_ms ?? null,
|
|
663
|
+
descendant_count: row.descendant_count ?? 0,
|
|
664
|
+
};
|
|
665
|
+
});
|
|
666
|
+
},
|
|
667
|
+
|
|
668
|
+
/** Processes that ran underneath each call in these exchanges (inherited
|
|
669
|
+
* attributions), in the order they started. */
|
|
670
|
+
descendants(exchangeIds) {
|
|
671
|
+
if (!exchangeIds.length) return [];
|
|
672
|
+
return q(`SELECT c.external_call_id AS parent_call_id, ev.id AS event_id, a.confidence,
|
|
673
|
+
json_extract(ev.payload_json, '$.argv') AS attributed_argv_json,
|
|
674
|
+
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,
|
|
675
|
+
p.exit_code, p.exit_signal, p.evidence_lost, ${PROCESS_FACTS}
|
|
676
|
+
FROM runtime_attributions a
|
|
677
|
+
JOIN agent_tool_calls c ON c.id = a.tool_call_id
|
|
678
|
+
JOIN runtime_events ev ON ev.id = a.event_id
|
|
679
|
+
JOIN runtime_processes p ON p.id = ev.process_id
|
|
680
|
+
WHERE a.status = 'accepted' AND a.method = 'inherited' AND c.exchange_id IN (${marks(exchangeIds)})
|
|
681
|
+
ORDER BY c.external_call_id, p.first_seen_ms, p.pid`).all(...exchangeIds)
|
|
682
|
+
.map((row) => ({ parent_call_id: row.parent_call_id, id: row.event_id, tier: TIER[row.confidence] ?? 'corroborated',
|
|
683
|
+
pid: row.pid, ppid: row.observed_ppid, start_time_ns: row.start_time_ns, argv: fromJson(row.attributed_argv_json ?? row.argv_json) ?? [],
|
|
684
|
+
...processOutcome(row), started_at: toIso(row.first_seen_ms), ended_at: toIso(row.exited_at_ms) }));
|
|
234
685
|
},
|
|
235
686
|
|
|
687
|
+
/** Which call each of a sandbox's processes belongs to, for annotating
|
|
688
|
+
* its process tree. A process with no accepted attribution comes back
|
|
689
|
+
* with both call ids null: it ran, and nothing accounts for it. */
|
|
690
|
+
attributionsForProcesses({ containerId, pids }) {
|
|
691
|
+
const list = [...new Set((pids ?? []).filter(Number.isInteger))];
|
|
692
|
+
if (!containerId || !list.length) return [];
|
|
693
|
+
return q(`SELECT p.pid, p.start_time_ns,
|
|
694
|
+
(SELECT c.external_call_id FROM runtime_attributions a JOIN runtime_events ev ON ev.id = a.event_id
|
|
695
|
+
JOIN agent_tool_calls c ON c.id = a.tool_call_id
|
|
696
|
+
WHERE ev.process_id = p.id AND a.status = 'accepted' AND a.method != 'inherited' LIMIT 1) AS call_id,
|
|
697
|
+
(SELECT c.external_call_id FROM runtime_attributions a JOIN runtime_events ev ON ev.id = a.event_id
|
|
698
|
+
JOIN agent_tool_calls c ON c.id = a.tool_call_id
|
|
699
|
+
WHERE ev.process_id = p.id AND a.status = 'accepted' AND a.method = 'inherited' LIMIT 1) AS parent_call_id,
|
|
700
|
+
(SELECT a.confidence FROM runtime_attributions a JOIN runtime_events ev ON ev.id = a.event_id
|
|
701
|
+
WHERE ev.process_id = p.id AND a.status = 'accepted' LIMIT 1) AS confidence,
|
|
702
|
+
(SELECT a.method FROM runtime_attributions a JOIN runtime_events ev ON ev.id = a.event_id
|
|
703
|
+
WHERE ev.process_id = p.id AND a.status = 'accepted' AND a.method != 'inherited' LIMIT 1) AS method
|
|
704
|
+
FROM runtime_processes p WHERE p.sandbox_id = ? AND p.pid IN (${marks(list)})`).all(containerId, ...list)
|
|
705
|
+
.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,
|
|
706
|
+
tier: row.confidence ? TIER[row.confidence] : 'unverified', match_basis: row.method === 'marker' ? 'id' : row.method ?? null }));
|
|
707
|
+
},
|
|
236
708
|
|
|
237
709
|
// ---- auxiliary features
|
|
238
710
|
|
|
239
711
|
recordProxyError(row) {
|
|
240
|
-
q('INSERT INTO proxy_errors (trace_id, occurred_at_ms, provider, route, error, cause_json) VALUES (?,?,?,?,?,?)')
|
|
712
|
+
const inserted = q('INSERT INTO proxy_errors (trace_id, occurred_at_ms, provider, route, error, cause_json) VALUES (?,?,?,?,?,?)')
|
|
241
713
|
.run(row.trace_id ?? null, toMs(row.timestamp), row.provider ?? null, row.route ?? null, row.error ?? null, asJson(row.cause));
|
|
714
|
+
indexGuarded(() => indexProxyErrorRow({ rowid: Number(inserted.lastInsertRowid), occurred_at_ms: toMs(row.timestamp),
|
|
715
|
+
provider: row.provider ?? null, route: row.route ?? null, error: row.error ?? null, cause_json: asJson(row.cause) }));
|
|
242
716
|
},
|
|
243
717
|
saveExperiment(job) {
|
|
244
718
|
q(`INSERT OR REPLACE INTO lab_experiments (id, exchange_id, created_at_ms, status, kind, model, body_json) VALUES (?,?,?,?,?,?,?)`)
|
|
@@ -257,8 +731,18 @@ export function openEvidenceStore(file) {
|
|
|
257
731
|
summaryForSpan(exchangeId) {
|
|
258
732
|
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
733
|
},
|
|
734
|
+
/** Model-written sentence for a sandbox command no rule could describe,
|
|
735
|
+
* keyed by the command so the same command is never paid for twice. */
|
|
736
|
+
getCommandDescription(command) {
|
|
737
|
+
return q('SELECT description FROM command_descriptions WHERE key = ?').get(sha256(String(command)))?.description ?? null;
|
|
738
|
+
},
|
|
739
|
+
putCommandDescription(command, description, model = null) {
|
|
740
|
+
q('INSERT OR REPLACE INTO command_descriptions (key, command, description, model, created_at_ms) VALUES (?,?,?,?,?)')
|
|
741
|
+
.run(sha256(String(command)), String(command), String(description), model, Date.now());
|
|
742
|
+
},
|
|
260
743
|
/** What each tool call asked for and what the agent was told back, keyed
|
|
261
|
-
* by the
|
|
744
|
+
* by the external call id the attribution rows carry. The raw material for
|
|
745
|
+
* a Jev assessment; call-assessment.mjs decides how much of it to send. */
|
|
262
746
|
toolCallContexts(externalCallIds) {
|
|
263
747
|
const list = [...new Set((externalCallIds ?? []).filter((id) => typeof id === 'string' && id))];
|
|
264
748
|
if (!list.length) return new Map();
|
|
@@ -269,6 +753,25 @@ export function openEvidenceStore(file) {
|
|
|
269
753
|
return new Map(rows.map((row) => [row.external_call_id, {
|
|
270
754
|
tool_name: row.tool_name, args: getPayload(row.arguments_sha), result: getPayload(row.reported_result_sha) }]));
|
|
271
755
|
},
|
|
756
|
+
getCallAssessment(key) { return fromJson(q('SELECT body_json FROM call_assessments WHERE key = ?').get(key)?.body_json ?? null); },
|
|
757
|
+
putCallAssessment(key, callId, model, value) {
|
|
758
|
+
q('INSERT OR REPLACE INTO call_assessments (key, call_id, model, created_at_ms, body_json) VALUES (?,?,?,?,?)')
|
|
759
|
+
.run(key, callId ?? null, model ?? null, Date.now(), JSON.stringify(value));
|
|
760
|
+
},
|
|
761
|
+
|
|
762
|
+
/** Splunk-style search over the derived index (proxy/search.mjs). */
|
|
763
|
+
search(options) { return runSearch(db, options); },
|
|
764
|
+
failureSignatures(options) { return topFailureSignatures(db, options); },
|
|
765
|
+
/** Rebuild the derived search index from the evidence tables. */
|
|
766
|
+
reindexSearch() {
|
|
767
|
+
return transaction(() => {
|
|
768
|
+
db.exec('DELETE FROM search_events');
|
|
769
|
+
for (const call of q('SELECT id FROM agent_tool_calls').all()) indexCall(call.id);
|
|
770
|
+
for (const turn of q('SELECT id FROM agent_turns').all()) indexTurn(turn.id);
|
|
771
|
+
for (const row of q('SELECT rowid, * FROM proxy_errors').all()) indexProxyErrorRow(row);
|
|
772
|
+
return q('SELECT COUNT(*) AS n FROM search_events').get().n;
|
|
773
|
+
});
|
|
774
|
+
},
|
|
272
775
|
|
|
273
776
|
stats() {
|
|
274
777
|
const one = (sql) => db.prepare(sql).get();
|
|
@@ -277,9 +780,108 @@ export function openEvidenceStore(file) {
|
|
|
277
780
|
turns: one('SELECT COUNT(*) AS n FROM agent_turns').n,
|
|
278
781
|
exchanges: one('SELECT COUNT(*) AS n FROM agent_exchanges').n,
|
|
279
782
|
payloads: one('SELECT COUNT(*) AS n, COALESCE(SUM(length(content)),0) AS bytes FROM agent_payloads'),
|
|
783
|
+
processes: one('SELECT COUNT(*) AS n FROM runtime_processes').n,
|
|
280
784
|
};
|
|
281
785
|
},
|
|
282
786
|
|
|
787
|
+
/** Deletes these sessions (agent_sessions.external_session_id: a local
|
|
788
|
+
* sandbox's rtp- id, or a Claude Code session id) and all that hangs off
|
|
789
|
+
* them -- turns, exchanges, tool calls, the sandbox's recorded processes
|
|
790
|
+
* and events, snapshots and search rows -- then any payload nothing
|
|
791
|
+
* refers to any more (payloads are shared by content, so one another
|
|
792
|
+
* session uses stays). Returns how many sessions went. Used when a local
|
|
793
|
+
* sandbox is destroyed with its logs. */
|
|
794
|
+
forgetSessions(sessionIds) {
|
|
795
|
+
if (!sessionIds.length) return 0;
|
|
796
|
+
// A sandbox's Playground forks (lab_experiments, kind fork) go with it,
|
|
797
|
+
// and so do their own sessions, which are filed under the fork's id.
|
|
798
|
+
const parents = sessionIds.map(() => '?').join(',');
|
|
799
|
+
const forks = q(`SELECT id FROM lab_experiments WHERE kind = 'fork' AND json_extract(body_json, '$.parent') IN (${parents})`)
|
|
800
|
+
.all(...sessionIds).map((row) => row.id);
|
|
801
|
+
const externalIds = [...sessionIds, ...forks];
|
|
802
|
+
const marks = externalIds.map(() => '?').join(',');
|
|
803
|
+
// Runtime events, syscalls and their classifications are append-only
|
|
804
|
+
// (schema/runtime_evidence.sql, classification.sql):
|
|
805
|
+
// nothing may change recorded evidence. Their owner deleting a whole
|
|
806
|
+
// sandbox is the one exception, so those guards are lifted for these
|
|
807
|
+
// deletes and put back as they were, in the same transaction: if any of
|
|
808
|
+
// it fails, nothing changed and the guards were never off.
|
|
809
|
+
const guards = q(`SELECT sql FROM sqlite_schema WHERE type = 'trigger'
|
|
810
|
+
AND name IN ('runtime_events_no_delete', 'runtime_syscall_calls_no_delete', 'classification_results_no_delete')`).all().map((row) => row.sql);
|
|
811
|
+
return transaction(() => {
|
|
812
|
+
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;');
|
|
813
|
+
const sessions = `SELECT id FROM agent_sessions WHERE external_session_id IN (${marks})`;
|
|
814
|
+
const exchanges = `SELECT id FROM agent_exchanges WHERE session_id IN (${sessions})`;
|
|
815
|
+
const calls = `SELECT id FROM agent_tool_calls WHERE exchange_id IN (${exchanges})`;
|
|
816
|
+
const boxes = `SELECT id FROM runtime_sandboxes WHERE project_id IN (${marks})`;
|
|
817
|
+
for (const sql of [
|
|
818
|
+
`DELETE FROM search_events WHERE session_external IN (${marks})`,
|
|
819
|
+
`DELETE FROM workspace_snapshots WHERE session_id IN (${marks})`,
|
|
820
|
+
`DELETE FROM runtime_attributions WHERE tool_call_id IN (${calls})
|
|
821
|
+
OR event_id IN (SELECT id FROM runtime_events WHERE sandbox_id IN (${boxes}))`,
|
|
822
|
+
`DELETE FROM classification_results WHERE syscall_call_id IN (SELECT id FROM runtime_syscall_calls WHERE sandbox_id IN (${boxes}))`,
|
|
823
|
+
`DELETE FROM file_label_assignments WHERE target_id IN (SELECT id FROM file_operation_targets WHERE sandbox_id IN (${boxes}))`,
|
|
824
|
+
`DELETE FROM file_operation_targets WHERE sandbox_id IN (${boxes})`,
|
|
825
|
+
`DELETE FROM file_objects WHERE sandbox_id IN (${boxes})`,
|
|
826
|
+
`DELETE FROM runtime_syscall_calls WHERE sandbox_id IN (${boxes})`,
|
|
827
|
+
`DELETE FROM runtime_events WHERE sandbox_id IN (${boxes})`,
|
|
828
|
+
`DELETE FROM runtime_processes WHERE sandbox_id IN (${boxes})`,
|
|
829
|
+
`DELETE FROM runtime_sandboxes WHERE project_id IN (${marks})`,
|
|
830
|
+
`DELETE FROM agent_context_items WHERE exchange_id IN (${exchanges})`,
|
|
831
|
+
`DELETE FROM agent_tool_calls WHERE exchange_id IN (${exchanges})`,
|
|
832
|
+
`DELETE FROM exchange_summaries WHERE exchange_id IN (${exchanges})`,
|
|
833
|
+
`DELETE FROM lab_experiments WHERE exchange_id IN (${exchanges}) OR id IN (${marks})`,
|
|
834
|
+
`DELETE FROM agent_exchanges WHERE session_id IN (${sessions})`,
|
|
835
|
+
`DELETE FROM agent_turns WHERE session_id IN (${sessions})`,
|
|
836
|
+
]) {
|
|
837
|
+
const uses = (sql.match(/\?/g) || []).length / externalIds.length;
|
|
838
|
+
q(sql).run(...Array.from({ length: uses }, () => externalIds).flat());
|
|
839
|
+
}
|
|
840
|
+
const gone = q(`DELETE FROM agent_sessions WHERE external_session_id IN (${marks})`).run(...externalIds).changes;
|
|
841
|
+
db.exec(`DELETE FROM agent_payloads WHERE sha NOT IN (
|
|
842
|
+
SELECT user_prompt_sha FROM agent_turns WHERE user_prompt_sha IS NOT NULL
|
|
843
|
+
UNION SELECT final_response_sha FROM agent_turns WHERE final_response_sha IS NOT NULL
|
|
844
|
+
UNION SELECT request_sha FROM agent_exchanges WHERE request_sha IS NOT NULL
|
|
845
|
+
UNION SELECT response_sha FROM agent_exchanges WHERE response_sha IS NOT NULL
|
|
846
|
+
UNION SELECT tools_sha FROM agent_exchanges WHERE tools_sha IS NOT NULL
|
|
847
|
+
UNION SELECT arguments_sha FROM agent_tool_calls WHERE arguments_sha IS NOT NULL
|
|
848
|
+
UNION SELECT reported_result_sha FROM agent_tool_calls WHERE reported_result_sha IS NOT NULL
|
|
849
|
+
UNION SELECT payload_sha FROM agent_context_items)`);
|
|
850
|
+
for (const sql of guards) db.exec(sql);
|
|
851
|
+
return gone;
|
|
852
|
+
});
|
|
853
|
+
},
|
|
854
|
+
|
|
283
855
|
close() { db.close(); },
|
|
284
856
|
};
|
|
857
|
+
|
|
858
|
+
/** Compares the agent's own report of a finished call (the runner's exit
|
|
859
|
+
* code and wall time) with the observed exit of the process the call ran
|
|
860
|
+
* as. Runs whenever either side arrives. Duration is exec-to-exit on the
|
|
861
|
+
* proxy clock with one offset, so clock skew between the proxy and the
|
|
862
|
+
* sandbox cannot distort it. Leaves the check null when nothing comparable
|
|
863
|
+
* was reported (a command still running, no runner header). */
|
|
864
|
+
function checkReported({ toolCallId = null, processId = null }) {
|
|
865
|
+
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
|
|
866
|
+
FROM runtime_attributions a
|
|
867
|
+
JOIN runtime_events ev ON ev.id = a.event_id
|
|
868
|
+
JOIN runtime_processes p ON p.id = ev.process_id
|
|
869
|
+
JOIN agent_tool_calls c ON c.id = a.tool_call_id
|
|
870
|
+
WHERE a.status = 'accepted' AND a.method != 'inherited' AND a.reported_check IS NULL
|
|
871
|
+
AND ${toolCallId ? 'c.id = ?' : 'p.id = ?'}`).all(toolCallId ?? processId);
|
|
872
|
+
for (const row of rows) {
|
|
873
|
+
if (!row.reported_result_sha || row.exited_at_ns == null || row.exit_code == null) continue;
|
|
874
|
+
const reported = toolResultFacts(getPayload(row.reported_result_sha));
|
|
875
|
+
if (reported.exitCode === null) continue;
|
|
876
|
+
let verdict = reported.exitCode === row.exit_code ? 'agrees' : 'exit_code_differs';
|
|
877
|
+
const observedMs = Number.isFinite(row.first_seen_ms) && Number.isFinite(row.exited_at_ms) ? row.exited_at_ms - row.first_seen_ms : null;
|
|
878
|
+
if (verdict === 'agrees' && reported.wallMs !== null && observedMs !== null && observedMs >= 0) {
|
|
879
|
+
// Generous on purpose: the runner starts its clock before the spawn
|
|
880
|
+
// the runtime sees, and a false "differs" costs more trust than it earns.
|
|
881
|
+
const tolerance = 0.2 * Math.max(observedMs, reported.wallMs) + 250;
|
|
882
|
+
if (Math.abs(observedMs - reported.wallMs) > tolerance) verdict = 'duration_differs';
|
|
883
|
+
}
|
|
884
|
+
q('UPDATE runtime_attributions SET reported_check = ? WHERE id = ?').run(verdict, row.id);
|
|
885
|
+
}
|
|
886
|
+
}
|
|
285
887
|
}
|