@raytrace-cli/cli 0.3.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 +155 -132
- package/bin/raytrace.mjs +51 -26
- 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/auth.mjs +8 -1
- package/src/commands.mjs +80 -12
- 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
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Recap: what one prompt's run did, and the observer's reading of why.
|
|
3
|
+
*
|
|
4
|
+
* A stronger model than the ones that label single steps (the observer) reads
|
|
5
|
+
* the run as a sequence of short step lines, not the transcript, and writes:
|
|
6
|
+
*
|
|
7
|
+
* happened what the run did, each sentence tied to the steps it covers
|
|
8
|
+
* reasoning why the agent probably went that way: a reading, not a
|
|
9
|
+
* measurement, each with how sure the observer is
|
|
10
|
+
* flags where what the agent said and what was observed disagree
|
|
11
|
+
*
|
|
12
|
+
* outline the run, compressed: the prompt, each tool call with what it
|
|
13
|
+
* asked for, what came back, what the sandbox saw of it, the
|
|
14
|
+
* files it changed, and what the agent said just before it
|
|
15
|
+
* request one chat request for the observer; its key changes when the
|
|
16
|
+
* outline, the model or this version does
|
|
17
|
+
* parse the answer, checked: a sentence must name steps that exist,
|
|
18
|
+
* and may not state a percentage (none was measured here)
|
|
19
|
+
*
|
|
20
|
+
* Pure functions; the proxy and the hosted evidence service do the I/O.
|
|
21
|
+
*/
|
|
22
|
+
import { digest } from './experiment-engine.mjs';
|
|
23
|
+
|
|
24
|
+
export const RECAP_VERSION = 1;
|
|
25
|
+
export const DEFAULT_OBSERVER = 'anthropic/claude-sonnet-5.5';
|
|
26
|
+
const MAX_STEPS = 80;
|
|
27
|
+
const KEEP_FIRST = 30;
|
|
28
|
+
const clip = (text, max) => { const line = String(text ?? '').replace(/\s+/g, ' ').trim(); return line.length > max ? `${line.slice(0, max - 1)}…` : line; };
|
|
29
|
+
|
|
30
|
+
function parsed(raw) { try { return JSON.parse(raw); } catch { return null; } }
|
|
31
|
+
|
|
32
|
+
/** What the agent was told back for one call, from the trace's events. */
|
|
33
|
+
function reported(resultsByCall, callId) {
|
|
34
|
+
const raw = resultsByCall.get(callId);
|
|
35
|
+
if (!raw) return null;
|
|
36
|
+
const output = typeof raw.output === 'string' ? raw.output : JSON.stringify(raw.output ?? '');
|
|
37
|
+
const code = Number(output.match(/Process exited with code (\d+)/)?.[1] ?? NaN);
|
|
38
|
+
const failed = Number.isFinite(code) ? code !== 0 : /^\s*(error|failed)|Rejected\(/i.test(output.slice(0, 120));
|
|
39
|
+
return { state: failed ? 'failed' : 'ok', says: clip(output, 160) };
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** The run as the observer reads it, or null when there is nothing to recap
|
|
43
|
+
* (no tool calls: the answer is the whole story). */
|
|
44
|
+
export function recapOutline(trace) {
|
|
45
|
+
const calls = trace?.callVerifications ?? [];
|
|
46
|
+
if (!calls.length) return null;
|
|
47
|
+
const events = trace.events ?? [];
|
|
48
|
+
const resultsByCall = new Map();
|
|
49
|
+
// What the agent wrote in the response that proposed a call: its own account of why.
|
|
50
|
+
const notesByExchange = new Map();
|
|
51
|
+
for (const event of events) {
|
|
52
|
+
if (event.title?.startsWith('Tool result:')) { const raw = parsed(event.raw); if (raw?.call_id) resultsByCall.set(raw.call_id, raw); }
|
|
53
|
+
else if (event.title === 'Model answer' && event.exchange_id && event.detail) {
|
|
54
|
+
notesByExchange.set(event.exchange_id, [...(notesByExchange.get(event.exchange_id) ?? []), event.detail]);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
const told = new Set();
|
|
58
|
+
const steps = calls.map((call, index) => {
|
|
59
|
+
const note = !told.has(call.exchange_id) ? (notesByExchange.get(call.exchange_id) ?? []).join(' ') : '';
|
|
60
|
+
told.add(call.exchange_id);
|
|
61
|
+
const changes = call.snapshot?.changed ? (call.snapshot.changes ?? []) : [];
|
|
62
|
+
// Only a sandbox can contradict the agent: outside one, nothing independent watched.
|
|
63
|
+
const observed = !trace.sandboxId ? undefined
|
|
64
|
+
: call.kernel_confirmed || call.verified ? { ran: true, ...(call.exit_code != null ? { exit_code: call.exit_code } : {}) }
|
|
65
|
+
: call.name === 'Bash' || /exec|shell/i.test(call.name) ? { ran: false } : undefined;
|
|
66
|
+
return {
|
|
67
|
+
step: index + 1, tool: call.name, asked: clip(call.proposed ?? call.name, 220),
|
|
68
|
+
...(note ? { agent_said_before: clip(note, 260) } : {}),
|
|
69
|
+
...(reported(resultsByCall, call.call_id) ? { agent_was_told: reported(resultsByCall, call.call_id) } : {}),
|
|
70
|
+
...(observed ? { sandbox_observed: observed } : {}),
|
|
71
|
+
...(changes.length ? { files_changed: changes.slice(0, 6).map((change) => `${change.status} ${change.path}`), ...(changes.length > 6 ? { more_files: changes.length - 6 } : {}) } : {}),
|
|
72
|
+
};
|
|
73
|
+
});
|
|
74
|
+
// A long run keeps its start and its end; the middle is counted, not sent.
|
|
75
|
+
const shown = steps.length > MAX_STEPS ? [...steps.slice(0, KEEP_FIRST), ...steps.slice(-(MAX_STEPS - KEEP_FIRST))] : steps;
|
|
76
|
+
return {
|
|
77
|
+
prompt: clip(trace.title, 1500), agent: trace.provider, model: trace.model, in_sandbox: Boolean(trace.sandboxId),
|
|
78
|
+
steps: shown, total_steps: steps.length, ...(steps.length > MAX_STEPS ? { omitted_steps: `${KEEP_FIRST + 1}-${steps.length - (MAX_STEPS - KEEP_FIRST)}` } : {}),
|
|
79
|
+
final_answer: trace.answer ? clip(trace.answer, 1200) : null,
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export const RECAP_INSTRUCTIONS = [
|
|
84
|
+
'You are an observer reading the record of one run of a coding agent. Someone who did not watch the run wants to know what it did and, as far as the record shows, why.',
|
|
85
|
+
'The record is JSON: the prompt, numbered steps (what the agent asked a tool to do, what it said just before, what it was told back, and, when the run was in a sandbox, what the sandbox itself observed and which files changed), and the final answer.',
|
|
86
|
+
'Reply with one JSON object and nothing else:',
|
|
87
|
+
'{"headline": string, "happened": [{"text": string, "steps": [number]}], "reasoning": [{"text": string, "steps": [number], "confidence": "likely" | "possible" | "unclear"}], "flags": [{"text": string, "steps": [number]}]}',
|
|
88
|
+
'headline: one plain sentence, at most 25 words, saying what the run achieved or failed to achieve.',
|
|
89
|
+
'happened: 3 to 7 sentences that together tell the run in order. Group steps that did one thing into one sentence. State only what the record shows. Prefer what the sandbox observed over what the agent was told or said.',
|
|
90
|
+
'reasoning: 2 to 4 sentences on why the agent most probably went the way it did: what it seemed to be working toward, and what it reacted to (the prompt, something a step returned, its own earlier plan). This is your reading of the sequence, so say "probably" or "appears to" where the record does not settle it, and use "unclear" when it does not say.',
|
|
91
|
+
'flags: only real disagreements in the record, such as the agent reporting success where the sandbox saw a non-zero exit, a command the sandbox never saw run, or an answer that claims something no step did. Usually empty.',
|
|
92
|
+
'Every item lists the step numbers it rests on, which must be numbers from the record. Never state a percentage or a probability as a number: none was measured. Do not invent steps, files, commands or results. Plain sentences, no markdown.',
|
|
93
|
+
].join('\n');
|
|
94
|
+
|
|
95
|
+
/** One chat request for the observer; `key` identifies this outline, model and version. */
|
|
96
|
+
export function recapRequest(outline, model = DEFAULT_OBSERVER) {
|
|
97
|
+
const input = JSON.stringify(outline);
|
|
98
|
+
return { key: digest({ version: RECAP_VERSION, kind: 'run-recap', model, input }), payload: {
|
|
99
|
+
model, max_tokens: 1100, temperature: 0.2,
|
|
100
|
+
messages: [{ role: 'system', content: RECAP_INSTRUCTIONS }, { role: 'user', content: input }],
|
|
101
|
+
} };
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** The observer's text out of a chat completion (or a Responses-style body). */
|
|
105
|
+
export function recapText(response) {
|
|
106
|
+
const content = response?.choices?.[0]?.message?.content;
|
|
107
|
+
if (typeof content === 'string') return content;
|
|
108
|
+
if (Array.isArray(content)) return content.map((part) => part?.text ?? '').join('');
|
|
109
|
+
return (response?.output ?? []).filter((item) => item?.type === 'message').map((item) => (item.content ?? []).map((part) => part?.text ?? '').join('')).join('');
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** The recap, checked against the outline; null when the answer is not usable. */
|
|
113
|
+
export function parseRecap(text, outline) {
|
|
114
|
+
const body = String(text ?? '');
|
|
115
|
+
const value = parsed(body.slice(body.indexOf('{'), body.lastIndexOf('}') + 1));
|
|
116
|
+
if (!value || typeof value !== 'object') return null;
|
|
117
|
+
const known = new Set(outline.steps.map((step) => step.step));
|
|
118
|
+
const sentence = (item, max) => {
|
|
119
|
+
const said = typeof item?.text === 'string' ? clip(item.text, max) : '';
|
|
120
|
+
// No number here was measured, so a percentage would be made up.
|
|
121
|
+
if (!said || /\d\s?%|\bpercent\b/i.test(said)) return null;
|
|
122
|
+
const steps = [...new Set((Array.isArray(item.steps) ? item.steps : []).filter((step) => known.has(step)))].sort((a, b) => a - b);
|
|
123
|
+
// A sentence that names steps, none of them real, rests on nothing.
|
|
124
|
+
if (Array.isArray(item.steps) && item.steps.length && !steps.length) return null;
|
|
125
|
+
return { text: said, steps };
|
|
126
|
+
};
|
|
127
|
+
const list = (items, max, limit, extra = () => ({})) => (Array.isArray(items) ? items : []).slice(0, limit)
|
|
128
|
+
.map((item) => { const kept = sentence(item, max); return kept && { ...kept, ...extra(item) }; }).filter(Boolean);
|
|
129
|
+
const happened = list(value.happened, 360, 8);
|
|
130
|
+
if (!happened.length) return null;
|
|
131
|
+
return {
|
|
132
|
+
headline: typeof value.headline === 'string' && !/\d\s?%/.test(value.headline) ? clip(value.headline, 220) : null,
|
|
133
|
+
happened,
|
|
134
|
+
reasoning: list(value.reasoning, 420, 5, (item) => ({ confidence: ['likely', 'possible', 'unclear'].includes(item.confidence) ? item.confidence : 'possible' })),
|
|
135
|
+
// A flag must point at the steps that disagree.
|
|
136
|
+
flags: list(value.flags, 320, 4).filter((flag) => flag.steps.length),
|
|
137
|
+
steps_read: outline.steps.length, total_steps: outline.total_steps,
|
|
138
|
+
};
|
|
139
|
+
}
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Ties sandbox processes the gVisor forwarder observed to the tool calls they
|
|
3
|
+
* ran for. Shared by the local proxy (raytace-proxy.mjs, its SQLite store)
|
|
4
|
+
* and the hosted evidence service (RayTrace's cloud, a
|
|
5
|
+
* Postgres store bound to one org); `db` is either, and every call into it is
|
|
6
|
+
* awaited, which a synchronous store answers at once.
|
|
7
|
+
*/
|
|
8
|
+
import { matchBatch, OPEN_WINDOW_CAP_MS } from './execution-correlation.mjs';
|
|
9
|
+
import { commandMarker } from './gvisor-forwarder.mjs';
|
|
10
|
+
|
|
11
|
+
// Tools that run a command. Only their calls are matched to a process by its
|
|
12
|
+
// text: Claude Code's Read reads the file itself, so a `cat` that ran nearby
|
|
13
|
+
// (its own shell setup runs several) is never that call. A call recorded
|
|
14
|
+
// without a tool name is still considered, as before. Call-id markers are
|
|
15
|
+
// exact and need no such check.
|
|
16
|
+
const COMMAND_TOOLS = /^(bash|shell|exec_command|local_shell|container\.exec)$/i;
|
|
17
|
+
const runsCommands = (candidate) => !candidate.tool_name || COMMAND_TOOLS.test(candidate.tool_name);
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Records sandbox processes the gVisor forwarder observed and ties each to
|
|
21
|
+
* the proposed tool call it ran for, when one can be identified. Every
|
|
22
|
+
* process is recorded whether or not it matches: a process with no
|
|
23
|
+
* attribution is what "ran, but no tool call accounts for it" means.
|
|
24
|
+
*
|
|
25
|
+
* Candidates are the session's proposed calls not yet tied to a process,
|
|
26
|
+
* each with its causal window (proposal -> result sent back). A process
|
|
27
|
+
* carrying RAYTRACE_CALL_ID needs no matching: the call id travelled with
|
|
28
|
+
* it, so that join is exact and overrides the text match. It is still
|
|
29
|
+
* checked against this session's own candidates, so a forged or stale
|
|
30
|
+
* marker cannot attach a process to a call in another session.
|
|
31
|
+
* Returns exec id -> match for whatever matched; see
|
|
32
|
+
* execution-correlation.mjs for why this is not a plain id lookup.
|
|
33
|
+
*/
|
|
34
|
+
export async function ingestExecutions(db, events, { sessionId = null } = {}) {
|
|
35
|
+
const matches = new Map();
|
|
36
|
+
if (!Array.isArray(events) || !events.length) return matches;
|
|
37
|
+
const recorded = new Map();
|
|
38
|
+
for (const event of events) {
|
|
39
|
+
recorded.set(event.id, await db.recordProcessStart({
|
|
40
|
+
containerId: event.container_id, projectId: sessionId, raw: event.raw, startedMs: event.timestamp }));
|
|
41
|
+
}
|
|
42
|
+
const timestamps = events.map((e) => e.timestamp).filter(Number.isFinite);
|
|
43
|
+
if (!sessionId || !timestamps.length) return matches;
|
|
44
|
+
// The pool reaches back as far as an open window may stay open, plus the
|
|
45
|
+
// clock margin between the proxy and the sandbox.
|
|
46
|
+
const margin = Math.max(0, ...events.map((e) => e.margin).filter(Number.isFinite));
|
|
47
|
+
const candidates = await db.candidatesInWindow(Math.min(...timestamps) - OPEN_WINDOW_CAP_MS - margin, Math.max(...timestamps) + margin, { sessionId });
|
|
48
|
+
const found = matchBatch(events, candidates.filter(runsCommands));
|
|
49
|
+
const byExternalId = new Map(candidates.map((c) => [c.external_call_id, c.call_id]));
|
|
50
|
+
for (const event of events) {
|
|
51
|
+
const eventId = recorded.get(event.id)?.eventId;
|
|
52
|
+
const markedCall = event.call_marker ? byExternalId.get(event.call_marker) : null;
|
|
53
|
+
const match = markedCall ? { call_id: markedCall, score: 1, basis: 'marker' } : found.get(event.id);
|
|
54
|
+
if (!match || !eventId) continue; // no confident match: the process stays recorded, unattributed -- never a guess
|
|
55
|
+
await db.attribute({ toolCallId: match.call_id, eventId, method: match.basis === 'id' ? 'marker' : match.basis,
|
|
56
|
+
// A marker join is exact; a text match that gVisor itself observed is
|
|
57
|
+
// corroborated. Recorded at capture, never promoted later.
|
|
58
|
+
confidence: markedCall ? 'exact' : 'corroborated', score: match.score,
|
|
59
|
+
windowStartMs: match.window_start ?? null, windowEndMs: match.window_end ?? null });
|
|
60
|
+
matches.set(event.id, match);
|
|
61
|
+
}
|
|
62
|
+
return matches;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Ties a sandbox's processes to the calls they ran for, after the fact.
|
|
67
|
+
* Claude Code starts a tool before its answer has finished streaming, and a
|
|
68
|
+
* call is only recorded once the answer is complete, so the gVisor forwarder
|
|
69
|
+
* has usually seen the process before the call it belongs to exists. Once
|
|
70
|
+
* the call is recorded, the same rules apply as at exec time: the call id the
|
|
71
|
+
* process carries (checked against this session's own calls), else a process
|
|
72
|
+
* started by one already tied to a call inherits it, else the text match.
|
|
73
|
+
*/
|
|
74
|
+
export async function attributeLateProcesses(db, sessionId, log = console.log) {
|
|
75
|
+
const now = Date.now();
|
|
76
|
+
const candidates = await db.candidatesInWindow(now - 24 * 3_600_000, now + 60_000, { sessionId });
|
|
77
|
+
if (!candidates.length) return;
|
|
78
|
+
const margin = 2_000;
|
|
79
|
+
const processes = await db.unattributedProcesses({ sessionId, sinceMs: Math.min(...candidates.map((c) => c.window_start)) - margin });
|
|
80
|
+
const byExternalId = new Map(candidates.map((c) => [c.external_call_id, c]));
|
|
81
|
+
const claimed = new Set();
|
|
82
|
+
const callOfProcess = new Map(); // process id -> call id, for children within this pass
|
|
83
|
+
const unmatched = [];
|
|
84
|
+
let tied = 0;
|
|
85
|
+
for (const proc of processes) {
|
|
86
|
+
const argv = Array.isArray(proc.raw.argv) ? proc.raw.argv.filter((part) => typeof part === 'string') : [];
|
|
87
|
+
const command = argv.join(' ').trim();
|
|
88
|
+
const marker = proc.raw.markers?.RAYTRACE_CALL_ID ?? commandMarker(command);
|
|
89
|
+
const marked = marker ? byExternalId.get(marker) : null;
|
|
90
|
+
const parentCall = proc.parent_call_id ?? callOfProcess.get(proc.parent_process_id);
|
|
91
|
+
let call = null; let method = null;
|
|
92
|
+
if (marked && !claimed.has(marked.call_id)) { call = marked.call_id; method = 'marker'; claimed.add(call); }
|
|
93
|
+
else if (parentCall) { call = parentCall; method = 'inherited'; }
|
|
94
|
+
else if (marked) { call = marked.call_id; method = 'inherited'; }
|
|
95
|
+
if (call) {
|
|
96
|
+
await db.attribute({ toolCallId: call, eventId: proc.event_id, method, confidence: method === 'marker' ? 'exact' : 'corroborated', score: method === 'marker' ? 1 : null });
|
|
97
|
+
callOfProcess.set(proc.process_id, call);
|
|
98
|
+
tied += 1;
|
|
99
|
+
} else if (command && Number.isFinite(proc.first_seen_ms)) unmatched.push({ id: proc.event_id, command, timestamp: proc.first_seen_ms, margin, process_id: proc.process_id });
|
|
100
|
+
}
|
|
101
|
+
const found = matchBatch(unmatched, candidates.filter((c) => !claimed.has(c.call_id) && runsCommands(c)));
|
|
102
|
+
for (const exec of unmatched) {
|
|
103
|
+
const match = found.get(exec.id);
|
|
104
|
+
if (!match) continue;
|
|
105
|
+
await db.attribute({ toolCallId: match.call_id, eventId: exec.id, method: match.basis === 'id' ? 'marker' : match.basis, confidence: 'corroborated',
|
|
106
|
+
score: match.score, windowStartMs: match.window_start ?? null, windowEndMs: match.window_end ?? null });
|
|
107
|
+
tied += 1;
|
|
108
|
+
}
|
|
109
|
+
if (tied) log(`[raytace][claude-code] ${sessionId.slice(0, 12)}: tied ${tied} sandbox process(es) to calls recorded after they ran`);
|
|
110
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The sandbox bridge: where a local sandbox's Claude Code hook
|
|
3
|
+
* (worker/sandbox/claude-hook.mjs) sends its transcript. A sandbox in the
|
|
4
|
+
* Lima VM reaches this machine's loopback at 192.168.5.2, and the VM's
|
|
5
|
+
* firewall (worker/sandbox/network.py) lets it reach this one port and no
|
|
6
|
+
* other, so it listens on 127.0.0.1 only.
|
|
7
|
+
*
|
|
8
|
+
* Each request carries the sandbox's token (set at create, kept in
|
|
9
|
+
* ~/.raytrace/sandboxes.json), which names the sandbox, and the transcript's
|
|
10
|
+
* next whole lines from `offset`. `ingest(sandbox, note)` does the rest (the
|
|
11
|
+
* proxy's ingestFromSandbox): an offset that is not where its copy ends is
|
|
12
|
+
* answered 409 with the copy's size, and the hook resends from there.
|
|
13
|
+
*/
|
|
14
|
+
import { createServer } from 'node:http';
|
|
15
|
+
import { readFile } from 'node:fs/promises';
|
|
16
|
+
import { join } from 'node:path';
|
|
17
|
+
|
|
18
|
+
const MAX_BODY = 4_500_000;
|
|
19
|
+
|
|
20
|
+
export function startSandboxBridge({ dataDir, port, ingest }) {
|
|
21
|
+
async function sandboxFor(token) {
|
|
22
|
+
if (typeof token !== 'string' || token.length < 40) return null;
|
|
23
|
+
try {
|
|
24
|
+
const boxes = JSON.parse(await readFile(join(dataDir, 'sandboxes.json'), 'utf8'));
|
|
25
|
+
return Object.keys(boxes).find((id) => boxes[id]?.token === token) ?? null;
|
|
26
|
+
} catch { return null; }
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const server = createServer(async (req, res) => {
|
|
30
|
+
const json = (status, body) => { res.writeHead(status, { 'content-type': 'application/json' }); res.end(JSON.stringify(body)); };
|
|
31
|
+
if (req.method !== 'POST' || req.url !== '/raytace/ingest/claude-code') return json(404, { error: 'Unknown endpoint.' });
|
|
32
|
+
const sandbox = await sandboxFor(req.headers['x-raytace-sandbox-token']);
|
|
33
|
+
if (!sandbox) return json(403, { error: 'Unknown sandbox token.' });
|
|
34
|
+
const chunks = []; let size = 0;
|
|
35
|
+
for await (const part of req) { size += part.length; if (size > MAX_BODY) return json(413, { error: 'Request too large.' }); chunks.push(part); }
|
|
36
|
+
let note;
|
|
37
|
+
try { note = JSON.parse(Buffer.concat(chunks).toString('utf8')); } catch { return json(400, { error: 'Invalid JSON.' }); }
|
|
38
|
+
try {
|
|
39
|
+
const { status, body } = await ingest(sandbox, note);
|
|
40
|
+
json(status, body);
|
|
41
|
+
} catch (error) { json(500, { error: error.message }); }
|
|
42
|
+
});
|
|
43
|
+
server.on('error', (error) => console.error(`Sandbox bridge on :${port} did not start: ${error.message}. Local sandboxes' Claude Code sessions will not reach the dashboard.`));
|
|
44
|
+
server.listen(port, '127.0.0.1', () => console.log(`Sandbox bridge listening on http://127.0.0.1:${port}`));
|
|
45
|
+
return server;
|
|
46
|
+
}
|
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
# Evidence database — version 6
|
|
2
|
+
|
|
3
|
+
Version 6 adds the derived search index (`search.sql`): `search_events`, one
|
|
4
|
+
denormalized event per tool call, turn and proxy error with its failure
|
|
5
|
+
outcome decided at index time (`proxy/search.mjs`), plus the `search_fts`
|
|
6
|
+
FTS5 table over its text. These rows are derived, never evidence — the store
|
|
7
|
+
rebuilds them from the tables below on open (backfill) or on demand
|
|
8
|
+
(`reindexSearch`), so they may be dropped freely.
|
|
9
|
+
|
|
10
|
+
This is RayTrace's database: **20 evidence tables plus 7 auxiliary tables** in
|
|
11
|
+
one SQLite file, `.raytace/evidence.db`, created on the proxy's first start.
|
|
12
|
+
It describes agent intent, observed runtime activity, interpretation rules and
|
|
13
|
+
results, file context, and shared payloads; `auxiliary.sql` holds the lab's
|
|
14
|
+
experiment jobs and cached summaries, explanations, command descriptions and
|
|
15
|
+
Jev command assessments (`call_assessments`), and where a sandboxed Claude
|
|
16
|
+
Code session's project folder stood after each tool call (`workspace_snapshots`).
|
|
17
|
+
|
|
18
|
+
`proxy/evidence-store.mjs` is the only module that reads or writes it. The
|
|
19
|
+
agent-intent tables are filled as model requests are captured; the runtime
|
|
20
|
+
tables (`runtime_sandboxes`, `runtime_processes`, `runtime_events`,
|
|
21
|
+
`runtime_attributions`) by the gVisor forwarder. Nothing yet captures file
|
|
22
|
+
syscalls, normalizes `runtime_syscall_calls`, classifies, or labels files, so
|
|
23
|
+
those tables stay empty.
|
|
24
|
+
|
|
25
|
+
Version 2 added the columns the proxy and dashboard need: turn detection
|
|
26
|
+
(`agent_turns.prompt_key`), request routing and the request split
|
|
27
|
+
(`agent_exchanges.route`, `method`, `tools_sha`, `input_key`, `transport_json`),
|
|
28
|
+
the sandbox-to-session join (`runtime_sandboxes.project_id`), proxy-clock times
|
|
29
|
+
and lost-evidence marking on processes, and match details on attributions
|
|
30
|
+
(`score`, the causal window, `reported_check`).
|
|
31
|
+
|
|
32
|
+
Version 3 added `call_assessments`, the cache of Jev (TypeSafe) severity and
|
|
33
|
+
step labels per tool call (`proxy/call-assessment.mjs`). It is the first
|
|
34
|
+
version with a migration: a version-2 database gains that one table in place,
|
|
35
|
+
inside the initializer's transaction, and is then checked against the schema
|
|
36
|
+
files exactly as before. A database at any other version is still refused
|
|
37
|
+
untouched; delete it to start fresh.
|
|
38
|
+
|
|
39
|
+
Version 4 added `workspace_snapshots`: after each tool call that could change
|
|
40
|
+
files, the commit in the sandbox's own snapshot history that the project
|
|
41
|
+
folder stood at, and which files changed (`worker/gvisor/claude-hook.mjs`). The
|
|
42
|
+
lab uses it to put the folder back as it was at any step. A version-2 or
|
|
43
|
+
version-3 database gains it in place, the same way.
|
|
44
|
+
|
|
45
|
+
## Initialize and validate
|
|
46
|
+
|
|
47
|
+
From the repository root, with the project's Node version:
|
|
48
|
+
|
|
49
|
+
```sh
|
|
50
|
+
evidence_dir=$(mktemp -d)
|
|
51
|
+
node --disable-warning=ExperimentalWarning proxy/init-evidence-db.mjs "$evidence_dir/evidence.db"
|
|
52
|
+
node --disable-warning=ExperimentalWarning --test proxy/evidence-schema.test.mjs proxy/agent-intent-schema.test.mjs
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
An explicit file path is required; the parent directory must already exist.
|
|
56
|
+
There is no default pointing at a live database. The initializer rejects the
|
|
57
|
+
known live paths, unrelated schemas, and incompatible versions. It does not
|
|
58
|
+
delete existing files. A failed first import can leave an empty file; table
|
|
59
|
+
creation, seeding, and `user_version` are rolled back together.
|
|
60
|
+
|
|
61
|
+
The initializer owns one transaction for all modules. The existing agent-only
|
|
62
|
+
SQL retains its direct-import transaction; the loader removes that known wrapper
|
|
63
|
+
when composing it. Other modules are fragments loaded by the initializer in
|
|
64
|
+
agent → runtime → classification → file context → shared storage order.
|
|
65
|
+
|
|
66
|
+
`PRAGMA user_version=1` identifies the combined schema. Repeat initialization
|
|
67
|
+
compares schema objects (including triggers and indexes), verifies the seeded
|
|
68
|
+
catalog and file labels, and preserves all rows. It does not repair unexpected
|
|
69
|
+
changes. Even semantically equivalent manual DDL edits may fail this strict
|
|
70
|
+
comparison. Enable `PRAGMA foreign_keys=ON` on every writer connection.
|
|
71
|
+
|
|
72
|
+
The initializer imports the original `worker/gvisor/syscall_catalog.sql` into an
|
|
73
|
+
in-memory staging DB, then maps its 4 levels, 34 categories, and 353 rules. No
|
|
74
|
+
second manually maintained syscall list exists. Required-evidence prose becomes
|
|
75
|
+
a one-element JSON array. SHA-256 of the sorted canonical seed representation
|
|
76
|
+
identifies catalog contents. Version `syscall-catalog-v2` (catalog version 2:
|
|
77
|
+
every syscall group, not files only) has classifier version `not-implemented`;
|
|
78
|
+
initialization creates **zero classification results**. The catalog's capture
|
|
79
|
+
decisions, numbers and coverage stay in the catalog: the sandbox host reads them
|
|
80
|
+
there (`worker/gvisor/setup.py`, `engine.py`) and keeps the facts it draws.
|
|
81
|
+
A changed catalog needs a new version identifier and a deliberate initializer
|
|
82
|
+
update, never an overwrite under the old identifier. A database made with
|
|
83
|
+
schema version 4 holds `filesystem-catalog-v1-only`, the 84 file rules; opening
|
|
84
|
+
it adds version 2 beside it, since these tables are append-only.
|
|
85
|
+
|
|
86
|
+
## Field guide
|
|
87
|
+
|
|
88
|
+
`PK` = primary key, `FK` = foreign key, `?` = nullable. IDs are non-null text.
|
|
89
|
+
JSON is stored as validated text; packets are optional binary blobs. Timestamps
|
|
90
|
+
ending in `_ms` are integer epoch milliseconds. `_ns` values are canonical,
|
|
91
|
+
nonnegative decimal text; comparisons use digit length then binary lexical order
|
|
92
|
+
to avoid floating-point precision loss. Return values use canonical signed
|
|
93
|
+
decimal text. Unknown values stay null rather than becoming zero or success.
|
|
94
|
+
|
|
95
|
+
### Agent intent — 4 tables
|
|
96
|
+
|
|
97
|
+
| Table | Fields and meaning |
|
|
98
|
+
| --- | --- |
|
|
99
|
+
| `agent_sessions` | `id` PK; `external_session_id?` provider identifier; `agent_name?`; `started_at_ms`; `ended_at_ms?`; `metadata_json?` additional session metadata. |
|
|
100
|
+
| `agent_turns` | `id` PK; `session_id` FK to sessions; `sequence_number` position within session; `user_prompt_sha?` and `final_response_sha?` FKs to payloads; `started_at_ms`; `ended_at_ms?`; `status` agent lifecycle. |
|
|
101
|
+
| `agent_exchanges` | `id` PK; `session_id` FK; `turn_id?` with session-scoped FK to turns; `provider`; `model?`; `started_at_ms`; `completed_at_ms?`; `http_status?`; `request_sha?` and `response_sha?` FKs to payloads; `metrics_json?`. |
|
|
102
|
+
| `agent_tool_calls` | `id` PK; `exchange_id` FK; `external_call_id?`; `output_index` position within response; `tool_name`; `arguments_sha?` and `reported_result_sha?` FKs to payloads; `proposed_at_ms?`. |
|
|
103
|
+
|
|
104
|
+
Turn status is `unknown`, `active`, `completed`, `failed`, or `cancelled`.
|
|
105
|
+
External identifiers are not globally unique. Reported results are not
|
|
106
|
+
independent evidence of execution. See [agent schema guide](README.md) for details.
|
|
107
|
+
|
|
108
|
+
### Runtime evidence — 5 tables
|
|
109
|
+
|
|
110
|
+
| Table | Fields and meaning |
|
|
111
|
+
| --- | --- |
|
|
112
|
+
| `runtime_sandboxes` | `id` PK for one lifetime; `external_container_id` runtime container identifier; `runtime_name`; `runtime_version`; `runtime_build_digest?` custom build identity; `architecture` (`aarch64`/`x86_64`); `started_at_ms?`; `ended_at_ms?`; `capture_config_json` fixed monitoring configuration. |
|
|
113
|
+
| `runtime_processes` | `id` PK; `sandbox_id` FK; `pid`; `start_time_ns?`; `parent_process_id?` FK within the same sandbox; `observed_ppid?` unresolved numeric parent; `first_seen_ns`; `exited_at_ns?`; `exit_code?`; `exit_signal?`; `identity_basis` how the lifetime was distinguished. |
|
|
114
|
+
| `runtime_events` | `id` PK; `sandbox_id?` FK; `process_id?` sandbox-scoped FK; `stream_id` collector stream; `stream_sequence` collector-assigned position; `event_kind`; `observed_at_ns?` runtime time; `received_at_ms` collection time; `tid?` thread; `payload_json` decoded object; `retained_packet?` original bytes when permitted; `decoder_version`. |
|
|
115
|
+
| `runtime_syscall_calls` | `id` PK; `sandbox_id` FK; `process_id?` sandbox-scoped FK; `tid?`; `syscall_name?`; `syscall_number`; `entry_event_id?` and `exit_event_id?` sandbox-scoped FKs; `arguments_json` object; `return_value?`; `errno?`; `outcome`; `correlation_status`; `normalizer_version`. |
|
|
116
|
+
| `runtime_attributions` | `id` PK; `tool_call_id` FK to agent calls; `event_id` FK to observations; `method` matching technique; `confidence` strength; `status` candidate/accepted/rejected; `basis_json` supporting details; `attributor_version`; `created_at_ms`. |
|
|
117
|
+
|
|
118
|
+
Sandbox times describe the sandbox, not a prompt. An unknown end does not prove
|
|
119
|
+
it is running. A restarted lifetime gets a new internal ID. Configuration cannot
|
|
120
|
+
be updated in place; runtime version/build records what produced the evidence.
|
|
121
|
+
|
|
122
|
+
PID alone is not unique. Start identity is immutable, including an unknown start;
|
|
123
|
+
future reconciliation must be explicit rather than silently changing process
|
|
124
|
+
identity. Multiple exec events may describe executable changes in one process.
|
|
125
|
+
Normal exit code and terminating signal are mutually exclusive, and require an
|
|
126
|
+
exit time. A process reference always requires sandbox context.
|
|
127
|
+
|
|
128
|
+
Events are append-only, unique by `(stream_id, stream_sequence)`. Stream IDs must
|
|
129
|
+
be globally unique per collection connection/lifetime; their sequence is not a
|
|
130
|
+
kernel completeness guarantee. Collector-wide gaps may have neither sandbox nor
|
|
131
|
+
process. `event_kind` is extensible; normalized syscall phases are specifically
|
|
132
|
+
`syscall_enter` and `syscall_exit`. This differs from the old collector's return
|
|
133
|
+
label and will require an adapter in later integration.
|
|
134
|
+
|
|
135
|
+
For syscall evidence, decoded `payload_json` reserves these keys:
|
|
136
|
+
|
|
137
|
+
```json
|
|
138
|
+
{"syscall_number":35,"syscall_name":"unlinkat","return_value":"0","errno":0}
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
The number above is an ARM64 example. Entry events omit return information.
|
|
142
|
+
Number/name may be absent if undecoded; present known identities must match the
|
|
143
|
+
normalized call. Known outcomes require matching textual `return_value` and
|
|
144
|
+
integer `errno` in the exit payload. No pathname or contents are invented by SQL.
|
|
145
|
+
|
|
146
|
+
Syscall states:
|
|
147
|
+
|
|
148
|
+
| Correlation | Evidence | Allowed outcome |
|
|
149
|
+
| --- | --- | --- |
|
|
150
|
+
| `paired` | Entry and exit | `succeeded`, `failed`, `unknown` |
|
|
151
|
+
| `entry_only` | Entry only | `unknown` |
|
|
152
|
+
| `exit_only` | Exit only | `succeeded`, `failed`, `unknown` |
|
|
153
|
+
| `uncertain` | At least one observation | `unknown` |
|
|
154
|
+
|
|
155
|
+
Known process/thread identities and phases must agree even if the normalized
|
|
156
|
+
call omits those identities. Exit time cannot precede entry time. A known outcome
|
|
157
|
+
requires a decoded return; success requires errno 0, failure errno > 0. An
|
|
158
|
+
exit-only call can have a known outcome while its arguments/path remain unknown.
|
|
159
|
+
|
|
160
|
+
Normalized calls are append-only snapshots. If later evidence permits a better
|
|
161
|
+
reconstruction, insert a new row referencing the same observations; do not edit
|
|
162
|
+
evidence underlying existing classifications. This schema does not choose a
|
|
163
|
+
current reconstruction or deduplicate such snapshots automatically. A future
|
|
164
|
+
normalizer must define that selection before user-facing aggregation.
|
|
165
|
+
|
|
166
|
+
Attribution confidence is `exact`, `corroborated`, or `inferred`. Status is
|
|
167
|
+
`candidate`, `accepted`, or `rejected`; only accepted associations should be
|
|
168
|
+
presented as the chosen match. No match leaves the observation intact. This
|
|
169
|
+
schema does not assert that a shared process automatically belongs to one turn.
|
|
170
|
+
|
|
171
|
+
### Classification — 5 tables
|
|
172
|
+
|
|
173
|
+
| Table | Fields and meaning |
|
|
174
|
+
| --- | --- |
|
|
175
|
+
| `classification_versions` | `id` PK; `catalog_version`; `classifier_version`; `content_sha256` canonical rule content digest; `created_at_ms`; `description`. |
|
|
176
|
+
| `classification_impact_levels` | `level` PK, integer 0–3; `label`; `description`. |
|
|
177
|
+
| `classification_categories` | `id` PK, stable operation name; `label`; `description`. |
|
|
178
|
+
| `classification_syscall_rules` | composite PK `(version_id, syscall_name)`; `version_id` FK; `description`; `category_id` FK; `default_impact_level?` FK; `rule_identifier`; `required_evidence_json` array; `interpretation_notes`. |
|
|
179
|
+
| `classification_results` | `id` PK; `syscall_call_id` FK; `version_id` FK; `input_sha256` digest of classifier input; `category_id?` FK; `operation_level?` and `confirmed_effect_level?` FKs; `effect_status`; `reason`; `classified_at_ms`. |
|
|
180
|
+
|
|
181
|
+
Version, rule, result, category and impact rows reject updates, deletes, and key
|
|
182
|
+
replacement. New versions/results are new rows; additions within a version must
|
|
183
|
+
be completed by its publisher before use. SQL does not compute arbitrary new
|
|
184
|
+
version digests; publication tooling must verify them. Initializer-owned seeds
|
|
185
|
+
are verified on every repeat initialization.
|
|
186
|
+
|
|
187
|
+
Result uniqueness is `(syscall_call_id, version_id, input_sha256)`. The future
|
|
188
|
+
classifier computes the digest over its canonical input, including relevant
|
|
189
|
+
evidence/context; SQL validates digest shape, not the hash calculation. States:
|
|
190
|
+
`confirmed`, `no_effect`, `unknown`, `not_applicable`. Only `confirmed` can and must
|
|
191
|
+
have a confirmed-effect level, and it requires a successful syscall. SQL success
|
|
192
|
+
alone is insufficient to infer a changed file: the classifier must still apply
|
|
193
|
+
the catalog's evidence rules. Impact 0 is observation, 1 creation, 2 modification,
|
|
194
|
+
3 removal/replacement. Impact is not maliciousness or a security risk score.
|
|
195
|
+
|
|
196
|
+
### File context — 4 tables
|
|
197
|
+
|
|
198
|
+
| Table | Fields and meaning |
|
|
199
|
+
| --- | --- |
|
|
200
|
+
| `file_objects` | `id` PK; `sandbox_id` FK; `object_type`; `filesystem_identity?`; `inode_number?`; `generation?`; `identity_basis`; `first_seen_ns`; `last_seen_ns`. |
|
|
201
|
+
| `file_operation_targets` | `id` PK; `syscall_call_id` and `sandbox_id` form a scoped FK; `sandbox_id` also references sandbox; `file_object_id?` scoped FK; `target_role`; `supplied_path?`; `observed_path?`; `dirfd?`; `fd?`; `base_path?`; `resolution_status`; `identity_basis_json?`. |
|
|
202
|
+
| `file_labels` | `id` PK; `label`; `description`. |
|
|
203
|
+
| `file_label_assignments` | `id` PK; `target_id` FK; `label_id` FK; `basis` source of label; `confidence`; `rule_version`; `reason`; `assigned_at_ms`. |
|
|
204
|
+
|
|
205
|
+
Object types: `regular`, `directory`, `symlink`, `pipe`, `socket`, `device`,
|
|
206
|
+
`unknown`. Filesystem identity, inode, and generation are opaque text; none alone
|
|
207
|
+
is a global permanent identity. Paths can be reused, and multiple hard links can
|
|
208
|
+
refer to one object. Do not merge objects without supporting evidence.
|
|
209
|
+
|
|
210
|
+
Targets can be `target`, `source`, `destination`, or `replaced_destination`;
|
|
211
|
+
rename/copy can reference multiple rows. A missing object ID does not discard a
|
|
212
|
+
path observation. File objects and calls must belong to the target's sandbox.
|
|
213
|
+
Resolution states: `unresolved`, `supplied_only`, `lexical`, `runtime_resolved`.
|
|
214
|
+
Supplied-only requires a supplied path; lexical/resolved requires an observed
|
|
215
|
+
path. Lexical joining is not actual resolution through symlinks. Negative `dirfd`
|
|
216
|
+
values accommodate special constants such as `AT_FDCWD`; ordinary FDs are
|
|
217
|
+
nonnegative. No uniqueness constraint makes pathname an identity.
|
|
218
|
+
|
|
219
|
+
Labels initially include source code, configuration, potentially sensitive,
|
|
220
|
+
documentation, generated output, and temporary. Assignment confidence uses
|
|
221
|
+
`exact`, `corroborated`, `inferred`; basis might be `user`, `filename_rule`, or
|
|
222
|
+
`content_inspection`. Multiple labels are allowed. Labels attach to target
|
|
223
|
+
observations so a rename need not rewrite historical labels. This step performs
|
|
224
|
+
no content inspection or automatic labeling.
|
|
225
|
+
|
|
226
|
+
### Shared storage — 2 tables
|
|
227
|
+
|
|
228
|
+
| Table | Fields and meaning |
|
|
229
|
+
| --- | --- |
|
|
230
|
+
| `agent_payloads` | `sha` PK, SHA-256 supplied by the writer; `content` validated JSON text. Shared despite its existing agent-prefixed name. |
|
|
231
|
+
| `agent_context_items` | composite PK `(exchange_id, position)`; `exchange_id` FK; nonnegative `position`; `role?`; `kind?`; `external_call_id?`; `payload_sha` FK; `preview?`. |
|
|
232
|
+
|
|
233
|
+
Context items preserve conversation ordering; external call IDs are reported
|
|
234
|
+
identifiers, not automatic runtime links. JSON strings represent plain text.
|
|
235
|
+
Writers must redact before hashing/storage and verify hashes; SQL cannot redact
|
|
236
|
+
or independently calculate SHA-256. Retained runtime packets must still obey
|
|
237
|
+
existing environment/secret withholding rules. No buffer contents are required.
|
|
238
|
+
|
|
239
|
+
## Example investigation query
|
|
240
|
+
|
|
241
|
+
This joins a selected syscall reconstruction to accepted tool attribution,
|
|
242
|
+
classification, targets, and optional labels. Supplying the chosen reconstruction
|
|
243
|
+
and classifier version avoids silently aggregating alternative snapshots.
|
|
244
|
+
|
|
245
|
+
```sql
|
|
246
|
+
SELECT tc.id AS tool_call_id, tc.tool_name,
|
|
247
|
+
sc.id AS syscall_call_id, sc.syscall_name, sc.outcome,
|
|
248
|
+
p.pid, target.observed_path, target.supplied_path,
|
|
249
|
+
category.label AS operation_category,
|
|
250
|
+
result.operation_level, result.confirmed_effect_level,
|
|
251
|
+
result.effect_status, labels.label AS file_label
|
|
252
|
+
FROM runtime_syscall_calls sc
|
|
253
|
+
LEFT JOIN runtime_processes p ON p.id = sc.process_id
|
|
254
|
+
LEFT JOIN runtime_attributions attribution
|
|
255
|
+
ON attribution.event_id = sc.exit_event_id AND attribution.status = 'accepted'
|
|
256
|
+
LEFT JOIN agent_tool_calls tc ON tc.id = attribution.tool_call_id
|
|
257
|
+
LEFT JOIN classification_results result
|
|
258
|
+
ON result.syscall_call_id = sc.id AND result.version_id = :version_id
|
|
259
|
+
LEFT JOIN classification_categories category ON category.id = result.category_id
|
|
260
|
+
LEFT JOIN file_operation_targets target ON target.syscall_call_id = sc.id
|
|
261
|
+
LEFT JOIN file_label_assignments assignment ON assignment.target_id = target.id
|
|
262
|
+
LEFT JOIN file_labels labels ON labels.id = assignment.label_id
|
|
263
|
+
WHERE sc.id = :syscall_call_id;
|
|
264
|
+
```
|
|
265
|
+
|
|
266
|
+
Multiple labels, classifications with different input hashes, or accepted
|
|
267
|
+
attributions can yield multiple rows; they are not additional syscall executions.
|
|
268
|
+
This query uses exit attribution; entry-only investigations can instead use
|
|
269
|
+
`entry_event_id`. Production code must select the intended classification input
|
|
270
|
+
and attribution rather than assuming all historical associations are current.
|
|
271
|
+
|
|
272
|
+
All domains live in one database here, so ordinary foreign keys work. A later
|
|
273
|
+
host/VM deployment split will require explicit replication and application-level
|
|
274
|
+
validation of cross-database relationships. Missing observations are not proof of
|
|
275
|
+
non-execution. These constraints preserve what is supplied; they cannot certify
|
|
276
|
+
collector completeness, resolve paths, or make untrusted input true.
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
--
|
|
5
5
|
-- exchange_id columns name an agent_exchanges.id but are not foreign keys:
|
|
6
6
|
-- these rows are caches and job documents that must still save when the
|
|
7
|
-
-- exchange they mention was never captured (a replay
|
|
7
|
+
-- exchange they mention was never captured (a replay, an expired snapshot).
|
|
8
8
|
|
|
9
9
|
CREATE TABLE lab_experiments (
|
|
10
10
|
id TEXT NOT NULL PRIMARY KEY,
|
|
@@ -32,6 +32,53 @@ CREATE TABLE step_explanations (
|
|
|
32
32
|
body_json TEXT NOT NULL CHECK (json_valid(body_json))
|
|
33
33
|
);
|
|
34
34
|
|
|
35
|
+
-- Model-written sentences for sandbox commands the deterministic rules in
|
|
36
|
+
-- exec-narrative.mjs could not describe, keyed by a digest of the command so
|
|
37
|
+
-- the same command is paid for once. Rule-derived sentences are never cached.
|
|
38
|
+
CREATE TABLE command_descriptions (
|
|
39
|
+
key TEXT NOT NULL PRIMARY KEY,
|
|
40
|
+
command TEXT NOT NULL,
|
|
41
|
+
description TEXT NOT NULL,
|
|
42
|
+
model TEXT,
|
|
43
|
+
created_at_ms INTEGER NOT NULL CHECK (typeof(created_at_ms)='integer')
|
|
44
|
+
);
|
|
45
|
+
|
|
46
|
+
-- Jev (TypeSafe) severity and step labels for the commands one tool call ran,
|
|
47
|
+
-- keyed by a digest of the exact state sent, so the same call is paid for
|
|
48
|
+
-- once. body_json keeps the raw answers next to the combined levels, so a
|
|
49
|
+
-- level can always be traced back to the rule or probability behind it.
|
|
50
|
+
-- Added in schema version 3 (see MIGRATIONS in init-evidence-db.mjs).
|
|
51
|
+
CREATE TABLE call_assessments (
|
|
52
|
+
key TEXT NOT NULL PRIMARY KEY,
|
|
53
|
+
call_id TEXT,
|
|
54
|
+
model TEXT,
|
|
55
|
+
created_at_ms INTEGER NOT NULL CHECK (typeof(created_at_ms)='integer'),
|
|
56
|
+
body_json TEXT NOT NULL CHECK (json_valid(body_json))
|
|
57
|
+
);
|
|
58
|
+
CREATE INDEX call_assessments_call ON call_assessments(call_id, created_at_ms);
|
|
59
|
+
|
|
60
|
+
-- Where the project folder stood after a tool call (or when a prompt was
|
|
61
|
+
-- sent) in a sandboxed Claude Code session: a commit in the sandbox's own
|
|
62
|
+
-- snapshot history (worker/gvisor/claude-hook.mjs), and the files that call
|
|
63
|
+
-- changed. Written by a hook beside the agent, not above it, so it is a lab
|
|
64
|
+
-- tool for putting the folder back, not evidence of what ran. changes_json
|
|
65
|
+
-- holds {changes: [{path, status, added, removed}], too_big: [path]}; a file
|
|
66
|
+
-- in too_big kept its previous version. Added in schema version 4.
|
|
67
|
+
CREATE TABLE workspace_snapshots (
|
|
68
|
+
id TEXT NOT NULL PRIMARY KEY,
|
|
69
|
+
session_id TEXT NOT NULL,
|
|
70
|
+
agent_session_id TEXT,
|
|
71
|
+
taken_on TEXT NOT NULL CHECK (taken_on IN ('prompt','tool')),
|
|
72
|
+
call_id TEXT,
|
|
73
|
+
commit_sha TEXT NOT NULL,
|
|
74
|
+
parent_sha TEXT,
|
|
75
|
+
changed INTEGER NOT NULL CHECK (changed IN (0,1)),
|
|
76
|
+
taken_at_ms INTEGER NOT NULL CHECK (typeof(taken_at_ms)='integer'),
|
|
77
|
+
changes_json TEXT NOT NULL CHECK (json_valid(changes_json))
|
|
78
|
+
);
|
|
79
|
+
CREATE INDEX workspace_snapshots_session ON workspace_snapshots(session_id, taken_at_ms);
|
|
80
|
+
CREATE INDEX workspace_snapshots_call ON workspace_snapshots(call_id);
|
|
81
|
+
|
|
35
82
|
CREATE TABLE proxy_errors (
|
|
36
83
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
37
84
|
trace_id TEXT,
|