@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.
Files changed (103) hide show
  1. package/README.md +155 -132
  2. package/bin/raytrace.mjs +51 -26
  3. package/dist/dashboard/assets/dm-sans-latin-400-normal-BwCSEQnW.woff +0 -0
  4. package/dist/dashboard/assets/dm-sans-latin-400-normal-CW0RaeGs.woff2 +0 -0
  5. package/dist/dashboard/assets/dm-sans-latin-500-normal-B9HHJjqV.woff2 +0 -0
  6. package/dist/dashboard/assets/dm-sans-latin-500-normal-Dr3UlScf.woff +0 -0
  7. package/dist/dashboard/assets/dm-sans-latin-600-normal-Aqo67rzb.woff2 +0 -0
  8. package/dist/dashboard/assets/dm-sans-latin-600-normal-BmdmIIQ2.woff +0 -0
  9. package/dist/dashboard/assets/dm-sans-latin-700-normal-CUSSCpQX.woff +0 -0
  10. package/dist/dashboard/assets/dm-sans-latin-700-normal-DvUfVpUG.woff2 +0 -0
  11. package/dist/dashboard/assets/dm-sans-latin-ext-400-normal-BjWJ59Pq.woff +0 -0
  12. package/dist/dashboard/assets/dm-sans-latin-ext-400-normal-BtiwyxMk.woff2 +0 -0
  13. package/dist/dashboard/assets/dm-sans-latin-ext-500-normal-BJfUCQsA.woff2 +0 -0
  14. package/dist/dashboard/assets/dm-sans-latin-ext-500-normal-DR84L5F-.woff +0 -0
  15. package/dist/dashboard/assets/dm-sans-latin-ext-600-normal-4vooXBpG.woff2 +0 -0
  16. package/dist/dashboard/assets/dm-sans-latin-ext-600-normal-DRtaDpgU.woff +0 -0
  17. package/dist/dashboard/assets/dm-sans-latin-ext-700-normal-BLI3TTWz.woff +0 -0
  18. package/dist/dashboard/assets/dm-sans-latin-ext-700-normal-CJIcxD6K.woff2 +0 -0
  19. package/dist/dashboard/assets/ibm-plex-mono-cyrillic-400-normal-BSMlKf0J.woff2 +0 -0
  20. package/dist/dashboard/assets/ibm-plex-mono-cyrillic-400-normal-CEL4l2ZJ.woff +0 -0
  21. package/dist/dashboard/assets/ibm-plex-mono-cyrillic-500-normal-Ael50iVv.woff +0 -0
  22. package/dist/dashboard/assets/ibm-plex-mono-cyrillic-500-normal-Bq9vWWag.woff2 +0 -0
  23. package/dist/dashboard/assets/ibm-plex-mono-cyrillic-600-normal-CTOM6hUh.woff2 +0 -0
  24. package/dist/dashboard/assets/ibm-plex-mono-cyrillic-600-normal-fLZuRloM.woff +0 -0
  25. package/dist/dashboard/assets/ibm-plex-mono-cyrillic-ext-400-normal-DMdlQ8Kv.woff +0 -0
  26. package/dist/dashboard/assets/ibm-plex-mono-cyrillic-ext-400-normal-xuaO2J-f.woff2 +0 -0
  27. package/dist/dashboard/assets/ibm-plex-mono-cyrillic-ext-500-normal-BIfNGwUT.woff +0 -0
  28. package/dist/dashboard/assets/ibm-plex-mono-cyrillic-ext-500-normal-BqneJy0T.woff2 +0 -0
  29. package/dist/dashboard/assets/ibm-plex-mono-cyrillic-ext-600-normal-9HEixskS.woff +0 -0
  30. package/dist/dashboard/assets/ibm-plex-mono-cyrillic-ext-600-normal-V-xxqcpd.woff2 +0 -0
  31. package/dist/dashboard/assets/ibm-plex-mono-latin-400-normal-CvHOgSBP.woff +0 -0
  32. package/dist/dashboard/assets/ibm-plex-mono-latin-400-normal-DMJ8VG8y.woff2 +0 -0
  33. package/dist/dashboard/assets/ibm-plex-mono-latin-500-normal-CB9ihrfo.woff +0 -0
  34. package/dist/dashboard/assets/ibm-plex-mono-latin-500-normal-DSY6xOcd.woff2 +0 -0
  35. package/dist/dashboard/assets/ibm-plex-mono-latin-600-normal-BgSNZQsw.woff2 +0 -0
  36. package/dist/dashboard/assets/ibm-plex-mono-latin-600-normal-DWFSQ4vo.woff +0 -0
  37. package/dist/dashboard/assets/ibm-plex-mono-latin-ext-400-normal-BmRBH3aV.woff2 +0 -0
  38. package/dist/dashboard/assets/ibm-plex-mono-latin-ext-400-normal-D3D2R8hC.woff +0 -0
  39. package/dist/dashboard/assets/ibm-plex-mono-latin-ext-500-normal-CAhNIIs5.woff2 +0 -0
  40. package/dist/dashboard/assets/ibm-plex-mono-latin-ext-500-normal-CZ70TYgx.woff +0 -0
  41. package/dist/dashboard/assets/ibm-plex-mono-latin-ext-600-normal-D38SheWl.woff2 +0 -0
  42. package/dist/dashboard/assets/ibm-plex-mono-latin-ext-600-normal-DmB0ttJJ.woff +0 -0
  43. package/dist/dashboard/assets/ibm-plex-mono-vietnamese-400-normal-BulugwFq.woff2 +0 -0
  44. package/dist/dashboard/assets/ibm-plex-mono-vietnamese-400-normal-DDuiU_S-.woff +0 -0
  45. package/dist/dashboard/assets/ibm-plex-mono-vietnamese-500-normal-C8zxqsMH.woff +0 -0
  46. package/dist/dashboard/assets/ibm-plex-mono-vietnamese-500-normal-DZ4AoWbu.woff2 +0 -0
  47. package/dist/dashboard/assets/ibm-plex-mono-vietnamese-600-normal-D2EvbN8M.woff2 +0 -0
  48. package/dist/dashboard/assets/ibm-plex-mono-vietnamese-600-normal-iLQfcSjf.woff +0 -0
  49. package/dist/dashboard/assets/index-DtV3UdEB.css +1 -0
  50. package/dist/dashboard/assets/index-jyV5iYHJ.js +38 -0
  51. package/dist/dashboard/index.html +2 -2
  52. package/package.json +3 -1
  53. package/proxy/call-assessment.mjs +385 -0
  54. package/proxy/call-category.mjs +461 -0
  55. package/proxy/capture.mjs +31 -0
  56. package/proxy/claude-code-adapter.mjs +46 -3
  57. package/proxy/evidence-store.mjs +617 -15
  58. package/proxy/exec-narrative.mjs +625 -0
  59. package/proxy/execution-correlation.mjs +185 -0
  60. package/proxy/experiment-engine.mjs +7 -4
  61. package/proxy/failure-signature.mjs +56 -0
  62. package/proxy/gvisor-forwarder.mjs +454 -0
  63. package/proxy/init-evidence-db.mjs +136 -12
  64. package/proxy/local-sandboxes.mjs +94 -0
  65. package/proxy/playground.mjs +411 -0
  66. package/proxy/prompt-context.mjs +12 -7
  67. package/proxy/prompt-traces.mjs +6 -0
  68. package/proxy/raytace-proxy.mjs +460 -176
  69. package/proxy/run-recap.mjs +139 -0
  70. package/proxy/runtime-attribution.mjs +110 -0
  71. package/proxy/sandbox-bridge.mjs +46 -0
  72. package/proxy/schema/EVIDENCE_DATABASE.md +276 -0
  73. package/proxy/schema/auxiliary.sql +48 -1
  74. package/proxy/schema/classification.sql +89 -0
  75. package/proxy/schema/file_context.sql +53 -0
  76. package/proxy/schema/runtime_evidence.sql +201 -0
  77. package/proxy/schema/search.sql +66 -0
  78. package/proxy/search.mjs +418 -0
  79. package/proxy/step-attribution.mjs +380 -0
  80. package/proxy/tool-metadata.mjs +36 -0
  81. package/proxy/trace-view.mjs +276 -0
  82. package/proxy/typesafe.mjs +63 -0
  83. package/src/auth.mjs +8 -1
  84. package/src/commands.mjs +80 -12
  85. package/src/lima.mjs +135 -0
  86. package/src/local-sandbox.mjs +324 -0
  87. package/src/proxy-process.mjs +20 -1
  88. package/src/sandbox.mjs +24 -6
  89. package/worker/sandbox/Dockerfile +8 -0
  90. package/worker/sandbox/SYSCALL_CATALOG.md +197 -0
  91. package/worker/sandbox/claude-hook.mjs +331 -0
  92. package/worker/sandbox/collector.py +357 -0
  93. package/worker/sandbox/dns_forwarder.py +255 -0
  94. package/worker/sandbox/engine.py +940 -0
  95. package/worker/sandbox/file_scan.py +491 -0
  96. package/worker/sandbox/lima.yaml +29 -0
  97. package/worker/sandbox/network.py +90 -0
  98. package/worker/sandbox/projects.py +678 -0
  99. package/worker/sandbox/setup.py +159 -0
  100. package/worker/sandbox/syscall_catalog.sql +985 -0
  101. package/worker/sandbox/viewer.py +132 -0
  102. package/dist/dashboard/assets/index-BQ9_JxGq.js +0 -27
  103. package/dist/dashboard/assets/index-L5cUAvhE.css +0 -1
@@ -0,0 +1,454 @@
1
+ /**
2
+ * Turns gVisor process evidence from a sandbox into RayTrace evidence rows
3
+ * (runtime_processes, runtime_events, runtime_attributions; see
4
+ * proxy/evidence-store.mjs), so a sandboxed Codex session gets a real
5
+ * per-tool-call verdict instead of every call defaulting to `not_executed`.
6
+ *
7
+ * gVisor is the only execution witness: its SecCheck stream reports every
8
+ * exec and every process exit from the layer that actually mediated the
9
+ * syscall, collected outside the workload into a SQLite file in the VM and
10
+ * served on the evidence viewer (:8798). This module tails that viewer.
11
+ *
12
+ * Correctness stance is the same as execution-correlation.mjs: a missed
13
+ * match only leaves a call `not_executed`; a wrong match mislabels real
14
+ * data. Three things keep this conservative:
15
+ * 1. Candidates are scoped to the sandbox's own session id (the rtp- id
16
+ * the broker stamps on every exchange), never the whole database.
17
+ * 2. Only *top-level* execs are matched. Codex runs each tool call as
18
+ * `/bin/bash -lc <cmd>`; that bash then forks `git`, `ls`, `node`...
19
+ * Children of an already-matched command inherit its call instead of
20
+ * being matched, and so does a re-exec in the same pid (bash exec()ing
21
+ * its last command in place), so a child's argv can never claim a
22
+ * *different* pending call.
23
+ * 3. Events are processed one at a time, in event-id order, so a parent
24
+ * always claims its candidate before its children are even considered.
25
+ *
26
+ * Outcome arrives in two steps because gVisor reports it in two events:
27
+ * `exec_succeeded` records the process, and its `process_exit` closes it
28
+ * with the real exit code. Until the exit arrives the UI keeps showing its
29
+ * text heuristic for that call rather than asserting an outcome it lacks.
30
+ */
31
+
32
+ // rtp- a project's sandbox, rtf- a Playground fork of one (worker/sandbox/projects.py).
33
+ export const SANDBOX_ID = /^rt[pf]-[a-f0-9]{32}$/;
34
+ export const CONTAINER_ID = /^[a-f0-9]{64}$/;
35
+
36
+ /** Mapping from the sandbox VM's clock to the proxy's. gVisor stamps events
37
+ * with the VM's realtime clock; exchanges are stamped by the proxy on the
38
+ * Mac. The two drift (notably after the Mac sleeps), so exec times are
39
+ * shifted by a measured offset before they are compared with exchange
40
+ * times, and `marginMs` is how uncertain that shift is. Unmeasured, the
41
+ * offset is assumed zero with a margin wide enough for ordinary drift. */
42
+ export const UNMEASURED_CLOCK = Object.freeze({ offsetMs: 0, marginMs: 2000, measured: false });
43
+
44
+ /** Picks the clock mapping from recent `/time` samples, NTP style: the
45
+ * sample with the shortest round trip has the least room for error. */
46
+ export function clockFromSamples(samples) {
47
+ const usable = (samples ?? []).filter((s) => Number.isFinite(s?.offsetMs) && Number.isFinite(s?.rttMs) && s.rttMs >= 0);
48
+ if (!usable.length) return UNMEASURED_CLOCK;
49
+ const best = usable.reduce((a, b) => (b.rttMs < a.rttMs ? b : a));
50
+ return { offsetMs: best.offsetMs, marginMs: best.rttMs / 2 + 250, measured: true };
51
+ }
52
+
53
+ /** `gvisor-<container12>-`: the id prefix every row from one sandbox shares,
54
+ * which is how a pid (reused across sandboxes) is scoped back to its own. */
55
+ export const rowPrefix = (containerId) => `gvisor-${typeof containerId === 'string' && containerId ? containerId.slice(0, 12) : 'unknown'}-`;
56
+
57
+ /** ns-since-epoch (as the collector's string) -> ms, or null if unparseable. */
58
+ export function msFromNs(ns) {
59
+ if (ns == null || ns === '') return null;
60
+ try {
61
+ const value = Number(BigInt(String(ns)) / 1_000_000n);
62
+ return Number.isFinite(value) && value > 0 ? value : null;
63
+ } catch { return null; }
64
+ }
65
+
66
+ /** The call id a command's own text exports, or null. */
67
+ export function commandMarker(command) {
68
+ // Claude Code runs the command as `eval '<it>'`, so the export may follow the quote.
69
+ return /(?:^|[\s;'])export RAYTRACE_CALL_ID=([A-Za-z0-9_-]{1,128})(?=[\s;]|$)/.exec(String(command ?? ''))?.[1] ?? null;
70
+ }
71
+
72
+ /** One collector `exec_succeeded` event -> the shape matchBatch() consumes,
73
+ * or null if it isn't one (other kinds, empty argv, no usable timestamp).
74
+ * The id is the collector's own autoincrement event id, prefixed so it can
75
+ * never collide with Codex's exec-<uuid> / call_id-reused ids and so
76
+ * re-ingesting the same event twice stays a no-op (recordExecution is
77
+ * INSERT OR REPLACE on id). */
78
+ export function toExecutionEvent(event, clock = UNMEASURED_CLOCK) {
79
+ if (!event || event.kind !== 'exec_succeeded') return null;
80
+ const argv = Array.isArray(event.argv) ? event.argv.filter((part) => typeof part === 'string') : [];
81
+ const command = argv.join(' ').trim();
82
+ const observed = msFromNs(event.timestamp_ns);
83
+ const timestamp = observed == null ? null : observed - clock.offsetMs;
84
+ const pid = Number(event.pid);
85
+ const eventId = Number(event.event_id);
86
+ if (!command || timestamp == null || !Number.isFinite(pid) || !Number.isFinite(eventId)) return null;
87
+ // `markers` is the collector's allowlisted RAYTRACE_* env (see
88
+ // worker/sandbox/collector.py MARKER_KEYS). When RAYTRACE_CALL_ID is present
89
+ // it IS the answer -- the call id travelled with the process -- and the
90
+ // text matcher is skipped entirely. Absent on every event until something
91
+ // in the spawn path stamps it, which is why the matcher stays the default.
92
+ // A sandboxed Claude Code stamps it in the command itself (`export
93
+ // RAYTRACE_CALL_ID=...`, worker/sandbox/claude-hook.mjs): the shell that
94
+ // runs the command carries it in argv, the programs it starts in env.
95
+ const marker = (event.markers && typeof event.markers === 'object' ? event.markers.RAYTRACE_CALL_ID : null)
96
+ ?? commandMarker(command);
97
+ return {
98
+ id: `${rowPrefix(event.container_id)}${eventId}`,
99
+ pid,
100
+ ppid: Number.isFinite(Number(event.ppid)) ? Number(event.ppid) : null,
101
+ command,
102
+ argv,
103
+ cwd: typeof event.cwd === 'string' ? event.cwd : null,
104
+ timestamp,
105
+ start_time_ns: typeof event.process_start_ns === 'string' ? event.process_start_ns : null,
106
+ call_marker: typeof marker === 'string' && marker ? marker : null,
107
+ margin: clock.marginMs,
108
+ // The collector event itself, for the evidence store: it is recorded
109
+ // as observed, alongside the process it describes.
110
+ container_id: typeof event.container_id === 'string' ? event.container_id : null,
111
+ raw: event,
112
+ };
113
+ }
114
+
115
+ /** One collector `exec_failed` event (an execve that returned an error, so
116
+ * the program never ran and the calling process carried on) -> a row that
117
+ * is already finished as failed, or null if unusable. */
118
+ export function toFailedExec(event, clock = UNMEASURED_CLOCK) {
119
+ if (!event || event.kind !== 'exec_failed') return null;
120
+ const argv = Array.isArray(event.argv) ? event.argv.filter((part) => typeof part === 'string') : [];
121
+ if (!argv.length && typeof event.executable === 'string' && event.executable) argv.push(event.executable);
122
+ const observed = msFromNs(event.timestamp_ns);
123
+ const pid = Number(event.pid);
124
+ const eventId = Number(event.event_id);
125
+ if (!argv.length || observed == null || !Number.isFinite(pid) || !Number.isFinite(eventId)) return null;
126
+ const at = new Date(observed - clock.offsetMs).toISOString();
127
+ return {
128
+ id: `${rowPrefix(event.container_id)}${eventId}`,
129
+ pid,
130
+ ppid: Number.isFinite(Number(event.ppid)) ? Number(event.ppid) : null,
131
+ command: argv.join(' ').trim(),
132
+ argv,
133
+ timestamp: observed - clock.offsetMs,
134
+ start_time_ns: typeof event.process_start_ns === 'string' ? event.process_start_ns : null,
135
+ status: 'failed',
136
+ error: `exec failed: errno ${Number.isFinite(Number(event.errno)) ? Number(event.errno) : 'unknown'}`,
137
+ ended_at: at,
138
+ container_id: typeof event.container_id === 'string' ? event.container_id : null,
139
+ raw: event,
140
+ };
141
+ }
142
+
143
+ /** One collector `process_exit` event -> the status/error to close the row
144
+ * with. Never guesses: an exit we can't read is 'unknown', not 'completed'. */
145
+ export function exitOutcome(event) {
146
+ if (typeof event?.signal === 'number' && event.signal > 0) return { status: 'failed', error: `killed by signal ${event.signal}`, exit_code: null };
147
+ if (typeof event?.exit_code === 'number') {
148
+ return event.exit_code === 0 ? { status: 'completed', error: null, exit_code: 0 } : { status: 'failed', error: `exit ${event.exit_code}`, exit_code: event.exit_code };
149
+ }
150
+ return { status: 'unknown', error: null, exit_code: null };
151
+ }
152
+
153
+ /** Per-sandbox tailing state: how far into the collector's event ids we've
154
+ * read, and which pids currently belong to a matched, still-running command.
155
+ * Each entry is `{ execId, callId }` -- `execId` is that pid's OWN row (so
156
+ * its exit closes the right one) and `callId` is the proposed call the whole
157
+ * subtree belongs to (so a child inherits attribution without re-matching).
158
+ * Same-pid re-execs still collapse onto the first entry: bash exec()ing its
159
+ * last command in place is one process doing one job, not a new one. */
160
+ export class SandboxTracker {
161
+ constructor() { this.cursor = 0; this.live = new Map(); }
162
+ }
163
+
164
+ /**
165
+ * Feeds a page of collector events (any order) through the matcher. Pure
166
+ * apart from the injected `ingest`/`finish`, so it's unit-testable without
167
+ * a proxy, a viewer, or a database.
168
+ *
169
+ * @param {Array<object>} events - raw viewer events for ONE container
170
+ * @param {object} deps
171
+ * @param {string} deps.sessionId - the sandbox's rtp- id, used to scope candidates
172
+ * @param {SandboxTracker} deps.tracker
173
+ * @param {(events: Array, opts: {sessionId: string}) => Promise<Map<string, object>>|Map<string, object>} deps.ingest
174
+ * - resolves executions to call_ids and records them; returns exec id -> match for the ones that matched
175
+ * @param {(row: {id: string, ended_at: string|null, status: string, error: string|null}) => Promise<boolean>|boolean} deps.finish
176
+ * @param {(row: {exec: object, parent_call_id: string|null, tier: string}) => Promise<void>|void} [deps.descend]
177
+ * - records a process that ran underneath a call, or underneath nothing.
178
+ * Defaults to a no-op so existing callers keep their behaviour.
179
+ * @param {(row: object) => Promise<boolean>|boolean} [deps.finishByProcess]
180
+ * - closes a process by its identity (pid + start time) when `tracker.live`
181
+ * holds no link to it (after a proxy restart, or an unattributed process,
182
+ * never tracked). Same row shape as `finish`.
183
+ * @param {(row: {container_id: string, session_id: string, reason: string, raw?: object, ended?: boolean}) => Promise<number>|number} [deps.lose]
184
+ * - marks a sandbox's open rows `unknown` once their exits can no longer arrive.
185
+ * @param {{offsetMs: number, marginMs: number}} [deps.clock] - VM->proxy clock mapping
186
+ * @returns {Promise<{forwarded: number, matched: number, finished: number, descendants: number, unattributed: number, failedExecs: number, lost: number}>}
187
+ */
188
+ export async function processEvents(events, { sessionId, tracker, ingest, finish, descend = () => {}, finishByProcess = () => false, lose = () => 0, clock = UNMEASURED_CLOCK }) {
189
+ const counts = { forwarded: 0, matched: 0, finished: 0, descendants: 0, unattributed: 0, failedExecs: 0, lost: 0 };
190
+ const ordered = (Array.isArray(events) ? events : [])
191
+ .filter((event) => Number.isFinite(Number(event?.event_id)) && Number(event.event_id) > tracker.cursor)
192
+ .sort((a, b) => Number(a.event_id) - Number(b.event_id));
193
+
194
+ for (const event of ordered) {
195
+ tracker.cursor = Number(event.event_id);
196
+ if (event.kind === 'exec_succeeded') {
197
+ const exec = toExecutionEvent(event, clock);
198
+ if (!exec) continue;
199
+ // Same pid already carrying a matched command: bash exec()ing its last
200
+ // command in place. Still one process doing one job -- recording it
201
+ // again would both double-count and re-point that pid's exit at the
202
+ // wrong row, so it stays collapsed onto the first entry.
203
+ if (tracker.live.has(exec.pid)) continue;
204
+
205
+ // A child of a command we already attributed. Before migration 005 this
206
+ // was `continue` -- the event was seen, recognised, and dropped, which
207
+ // is how a file deleted by an npm pretest hook ended up in gVisor's
208
+ // stream and nowhere in RayTrace. It now gets its own row hanging off
209
+ // the owning call, and joins `live` so ITS children inherit too (the
210
+ // deletion is a grandchild; a one-level check never reached it).
211
+ const owner = exec.ppid != null ? tracker.live.get(exec.ppid) : null;
212
+ if (owner) {
213
+ await descend({ exec, parent_call_id: owner.callId, tier: owner.callId ? 'corroborated' : 'unverified', session_id: sessionId });
214
+ tracker.live.set(exec.pid, { execId: exec.id, callId: owner.callId });
215
+ counts.descendants += 1;
216
+ continue;
217
+ }
218
+
219
+ counts.forwarded += 1;
220
+ const matches = await ingest([exec], { sessionId });
221
+ const match = matches && matches.get ? matches.get(exec.id) : null;
222
+ if (match) {
223
+ counts.matched += 1;
224
+ tracker.live.set(exec.pid, { execId: exec.id, callId: match.call_id });
225
+ } else {
226
+ // Ran inside the agent's own sandbox, matched no proposed call. Either
227
+ // the correlator failed or nothing proposed it; both are worth seeing
228
+ // and neither was storable before 005. Deliberately NOT tracked in
229
+ // `live`: leaving its children to face the matcher keeps every
230
+ // existing match outcome identical, so this path only adds rows.
231
+ await descend({ exec, parent_call_id: null, tier: 'unverified', session_id: sessionId });
232
+ counts.unattributed += 1;
233
+ }
234
+ } else if (event.kind === 'exec_failed') {
235
+ // The program never started, so there is no exec_succeeded and no row
236
+ // for it -- a forked child whose execve failed used to vanish. The
237
+ // calling process carries on (bash reports the error and exits), so
238
+ // its own row still closes normally. Not added to `live`: nothing ran.
239
+ const failed = toFailedExec(event, clock);
240
+ if (!failed) continue;
241
+ const owner = tracker.live.get(failed.pid) ?? (failed.ppid != null ? tracker.live.get(failed.ppid) : null);
242
+ await descend({ exec: failed, parent_call_id: owner?.callId ?? null, tier: owner?.callId ? 'corroborated' : 'unverified', session_id: sessionId });
243
+ counts.failedExecs += 1;
244
+ } else if (event.kind === 'process_exit') {
245
+ const pid = Number(event.pid);
246
+ const endedMs = msFromNs(event.timestamp_ns);
247
+ const ended_at = endedMs == null ? null : new Date(endedMs - clock.offsetMs).toISOString();
248
+ const { status, error, exit_code } = exitOutcome(event);
249
+ const exitRow = { ended_at, ended_ms: endedMs == null ? null : endedMs - clock.offsetMs, status, error, exit_code,
250
+ signal: typeof event.signal === 'number' && event.signal > 0 ? event.signal : null,
251
+ pid, start_time_ns: typeof event.process_start_ns === 'string' ? event.process_start_ns : null,
252
+ container_id: typeof event.container_id === 'string' ? event.container_id : null, session_id: sessionId, raw: event };
253
+ const entry = tracker.live.get(pid);
254
+ if (entry) {
255
+ tracker.live.delete(pid);
256
+ await finish({ id: entry.execId, ...exitRow });
257
+ counts.finished += 1;
258
+ } else if (exitRow.start_time_ns) {
259
+ // No in-memory link: the process was seen before a proxy restart, or
260
+ // was never tracked (unattributed). Found again by pid + start time.
261
+ const closed = await finishByProcess(exitRow);
262
+ if (closed) counts.finished += 1;
263
+ }
264
+ } else if (event.kind === 'collector_disconnected' && typeof event.container_id === 'string' && event.container_id) {
265
+ // This sandbox's evidence stream ended. Exits for processes still
266
+ // open can no longer arrive, so they become unknown -- not failed.
267
+ // A later exit on a new connection still closes them (see
268
+ // finishExecutionByProcess), since real evidence beats "lost".
269
+ counts.lost += Number(await lose({ container_id: event.container_id, session_id: sessionId, reason: 'collector disconnected', raw: event })) || 0;
270
+ tracker.live.clear();
271
+ }
272
+ }
273
+ return counts;
274
+ }
275
+
276
+ /**
277
+ * Discovers sandboxes from `listProjects()` (the local sandboxes, each rtp-
278
+ * id with its container id; or a manager's `/api/projects` at managerBase), tails each container's events
279
+ * from the evidence viewer (:8798), and runs them through processEvents().
280
+ * Best-effort throughout: the manager or viewer being down just means no
281
+ * gVisor evidence for now -- logged once per outage, never fatal to the
282
+ * proxy, never a wrong row.
283
+ */
284
+ export function startGvisorForwarder({
285
+ managerBase = 'http://127.0.0.1:8799',
286
+ listProjects = null,
287
+ viewerBase = 'http://127.0.0.1:8798',
288
+ ingest,
289
+ finish,
290
+ descend,
291
+ finishByProcess,
292
+ lose,
293
+ log = (message) => console.error(message),
294
+ fetchImpl = globalThis.fetch,
295
+ pollMs = 1500,
296
+ discoverMs = 10_000,
297
+ // First discovery is deferred a little so a proxy that starts with no
298
+ // manager running prints its "listening" line before, not interleaved
299
+ // with, the one-time "sandbox manager not reachable" notice.
300
+ initialDelayMs = 2000,
301
+ } = {}) {
302
+ if (typeof ingest !== 'function' || typeof finish !== 'function') throw new TypeError('startGvisorForwarder needs ingest() and finish()');
303
+ const sandboxes = new Map(); // container_id -> { sessionId, tracker }
304
+ let managerDown = false;
305
+ let viewerDown = false;
306
+ let clockDown = false;
307
+ let clock = UNMEASURED_CLOCK;
308
+ const clockSamples = []; // most recent last; bounded
309
+ let discovering = null; // in-flight promise, so a concurrent call awaits it instead of racing
310
+ let polling = null;
311
+ let stopped = false;
312
+
313
+ const getJson = async (url) => {
314
+ const res = await fetchImpl(url, { signal: AbortSignal.timeout(8000) });
315
+ if (!res.ok) throw new Error(`${res.status} from ${url}`);
316
+ return res.json();
317
+ };
318
+
319
+ /** Highest event id the collector currently holds for a container, used to
320
+ * seed a new tracker so tailing begins at "now". Falls back to 0 -- which
321
+ * replays history -- only if the viewer cannot be reached, since starting
322
+ * over-inclusive is recoverable and starting blind is not. */
323
+ const latestEventId = async (containerId) => {
324
+ try {
325
+ const page = await getJson(`${viewerBase}/events?container=${containerId}&limit=1&processes=1`);
326
+ const ids = (page?.events ?? []).map((e) => Number(e?.event_id)).filter(Number.isFinite);
327
+ return ids.length ? Math.max(...ids) : 0;
328
+ } catch { return 0; }
329
+ };
330
+
331
+ const discover = () => {
332
+ if (stopped) return Promise.resolve();
333
+ if (discovering) return discovering;
334
+ discovering = discoverOnce().finally(() => { discovering = null; });
335
+ return discovering;
336
+ };
337
+ /** One NTP-style sample of the VM clock against ours. Keeps the last few;
338
+ * a failed sample leaves the previous mapping in place, and with none at
339
+ * all the forwarder runs unmeasured (zero offset, wide margin). */
340
+ const sampleClock = async () => {
341
+ try {
342
+ const sent = Date.now();
343
+ const body = await getJson(`${viewerBase}/time`);
344
+ const received = Date.now();
345
+ const vmMs = msFromNs(body?.realtime_ns);
346
+ if (vmMs == null) throw new Error('no realtime_ns in /time response');
347
+ clockSamples.push({ offsetMs: vmMs - (sent + received) / 2, rttMs: received - sent });
348
+ if (clockSamples.length > 5) clockSamples.shift();
349
+ clock = clockFromSamples(clockSamples);
350
+ if (clockDown) { clockDown = false; log('[raytace][gvisor] sandbox clock measurable again'); }
351
+ } catch (error) {
352
+ if (!clockDown) {
353
+ clockDown = true;
354
+ log(`[raytace][gvisor] could not read the sandbox clock at ${viewerBase}/time (${error.message}) -- matching with a ${clock.marginMs} ms margin until it can`);
355
+ }
356
+ }
357
+ };
358
+
359
+ const discoverOnce = async () => {
360
+ try {
361
+ const projects = listProjects ? await listProjects() : await getJson(`${managerBase}/api/projects`);
362
+ await sampleClock();
363
+ const present = new Set();
364
+ for (const project of Array.isArray(projects) ? projects : []) {
365
+ const sessionId = project?.id;
366
+ const containerId = project?.container_id;
367
+ if (!SANDBOX_ID.test(sessionId || '') || !CONTAINER_ID.test(containerId || '')) continue;
368
+ // The manager keeps a deleted sandbox's record, but its container is
369
+ // gone: treat it as removed rather than tail it for good.
370
+ if (project?.status === 'deleted') continue;
371
+ present.add(containerId);
372
+ if (!sandboxes.has(containerId)) {
373
+ const tracker = new SandboxTracker();
374
+ // Start from the newest event, not from zero. The collector's
375
+ // evidence store lives in the VM and is append-only, so it outlives
376
+ // any proxy restart: a tracker that begins at 0 re-reads days of
377
+ // history on every start. Those old execs can never match anything
378
+ // -- the proxy was not capturing model traffic then, so no proposed
379
+ // call exists for them -- and since they now get written as
380
+ // unattributed rows rather than dropped, the replay floods the
381
+ // table and pushes the live session behind a backlog.
382
+ tracker.cursor = await latestEventId(containerId);
383
+ sandboxes.set(containerId, { sessionId, tracker });
384
+ log(`[raytace][gvisor] forwarding evidence for sandbox ${sessionId} (container ${containerId.slice(0, 12)}) from event ${tracker.cursor}`);
385
+ }
386
+ }
387
+ // A sandbox the manager no longer lists is gone, and so is any exit
388
+ // its open rows were waiting for. Only on a successful listing: an
389
+ // unreachable manager proves nothing about the sandboxes.
390
+ for (const [containerId, { sessionId }] of sandboxes) {
391
+ if (present.has(containerId)) continue;
392
+ sandboxes.delete(containerId);
393
+ const lost = typeof lose === 'function' ? Number(await lose({ container_id: containerId, session_id: sessionId, reason: 'sandbox removed', ended: true })) || 0 : 0;
394
+ log(`[raytace][gvisor] sandbox ${sessionId} is gone; stopped forwarding${lost ? `, ${lost} open execution(s) marked unknown` : ''}`);
395
+ }
396
+ if (managerDown) { managerDown = false; log('[raytace][gvisor] sandbox manager reachable again'); }
397
+ } catch (error) {
398
+ if (!managerDown) {
399
+ managerDown = true;
400
+ log(listProjects
401
+ ? `[raytace][gvisor] local sandboxes not reachable (${error.message}) -- gVisor evidence forwarding idle until they are`
402
+ : `[raytace][gvisor] sandbox manager not reachable at ${managerBase} (${error.message}) -- gVisor evidence forwarding idle until it is`);
403
+ }
404
+ }
405
+ };
406
+
407
+ const poll = () => {
408
+ if (stopped || !sandboxes.size) return Promise.resolve();
409
+ if (polling) return polling;
410
+ polling = pollOnce().finally(() => { polling = null; });
411
+ return polling;
412
+ };
413
+ const pollOnce = async () => {
414
+ for (const [containerId, { sessionId, tracker }] of sandboxes) {
415
+ const url = `${viewerBase}/events?container=${containerId}&after=${tracker.cursor}&limit=500&processes=1`;
416
+ let page;
417
+ try { page = await getJson(url); } catch (error) {
418
+ if (!viewerDown) { viewerDown = true; log(`[raytace][gvisor] evidence viewer not reachable at ${viewerBase} (${error.message}) -- is the sandbox VM running?`); }
419
+ continue;
420
+ }
421
+ if (viewerDown) { viewerDown = false; log('[raytace][gvisor] evidence viewer reachable again'); }
422
+ // An ingest/finish failure (e.g. a DB error) must not stall the loop
423
+ // or leave the cursor wedged; log it and move on to the next poll.
424
+ try {
425
+ const counts = await processEvents(page?.events, { sessionId, tracker, ingest, finish, descend,
426
+ ...(typeof finishByProcess === 'function' ? { finishByProcess } : {}),
427
+ ...(typeof lose === 'function' ? { lose } : {}),
428
+ clock });
429
+ if (counts.matched || counts.finished || counts.descendants || counts.unattributed || counts.failedExecs || counts.lost) {
430
+ log(`[raytace][gvisor] ${sessionId.slice(0, 12)}: ${counts.matched} exec(s) matched to proposed calls, `
431
+ + `${counts.descendants} descendant(s), ${counts.unattributed} unattributed, ${counts.failedExecs} failed exec(s), `
432
+ + `${counts.finished} closed out, ${counts.lost} marked unknown, ${counts.forwarded} top-level exec(s) considered`);
433
+ }
434
+ } catch (error) {
435
+ log(`[raytace][gvisor] ${sessionId.slice(0, 12)}: failed to record evidence: ${error.message}`);
436
+ }
437
+ }
438
+ };
439
+
440
+ const firstDiscover = setTimeout(discover, initialDelayMs);
441
+ const discoverTimer = setInterval(discover, discoverMs);
442
+ const pollTimer = setInterval(poll, pollMs);
443
+ firstDiscover.unref?.(); discoverTimer.unref?.(); pollTimer.unref?.();
444
+
445
+ return {
446
+ stop() { stopped = true; clearTimeout(firstDiscover); clearInterval(discoverTimer); clearInterval(pollTimer); },
447
+ /** Test/inspection hook: the sandboxes currently being tailed. */
448
+ sandboxes,
449
+ discover,
450
+ poll,
451
+ /** Test/inspection hook: the VM->proxy clock mapping in use. */
452
+ clock: () => clock,
453
+ };
454
+ }
@@ -1,14 +1,57 @@
1
1
  import { DatabaseSync } from 'node:sqlite';
2
+ import { createHash } from 'node:crypto';
2
3
  import { readFileSync, realpathSync, existsSync } from 'node:fs';
3
4
  import { resolve } from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
4
6
 
5
- // Bump with a forward step in MIGRATIONS (keyed by the version it upgrades
6
- // FROM) whenever a schema file changes. Each step must reproduce the schema
7
- // files exactly: the structure check below still runs afterwards, so a step
8
- // that drifts from the .sql text is refused rather than silently accepted.
9
- export const SCHEMA_VERSION = 1;
10
- const MIGRATIONS = {};
11
- const modules = ['agent_intent.sql', 'shared_storage.sql', 'auxiliary.sql'];
7
+ export const SCHEMA_VERSION = 6;
8
+ // Forward steps for databases created by an older schema, keyed by the
9
+ // version they upgrade FROM. Each must reproduce the schema files exactly:
10
+ // the structure check below still runs afterwards, so a step that drifts from
11
+ // the .sql text is refused rather than silently accepted.
12
+ const MIGRATIONS = {
13
+ 2: `CREATE TABLE call_assessments (
14
+ key TEXT NOT NULL PRIMARY KEY,
15
+ call_id TEXT,
16
+ model TEXT,
17
+ created_at_ms INTEGER NOT NULL CHECK (typeof(created_at_ms)='integer'),
18
+ body_json TEXT NOT NULL CHECK (json_valid(body_json))
19
+ );
20
+ CREATE INDEX call_assessments_call ON call_assessments(call_id, created_at_ms);`,
21
+ 3: `CREATE TABLE workspace_snapshots (
22
+ id TEXT NOT NULL PRIMARY KEY,
23
+ session_id TEXT NOT NULL,
24
+ agent_session_id TEXT,
25
+ taken_on TEXT NOT NULL CHECK (taken_on IN ('prompt','tool')),
26
+ call_id TEXT,
27
+ commit_sha TEXT NOT NULL,
28
+ parent_sha TEXT,
29
+ changed INTEGER NOT NULL CHECK (changed IN (0,1)),
30
+ taken_at_ms INTEGER NOT NULL CHECK (typeof(taken_at_ms)='integer'),
31
+ changes_json TEXT NOT NULL CHECK (json_valid(changes_json))
32
+ );
33
+ CREATE INDEX workspace_snapshots_session ON workspace_snapshots(session_id, taken_at_ms);
34
+ CREATE INDEX workspace_snapshots_call ON workspace_snapshots(call_id);`,
35
+ // No table changes. Version 5 seeds catalog version 2 (every syscall group,
36
+ // not files only) beside whatever catalog the database already holds: the
37
+ // classification tables are append-only, so the older rows stay.
38
+ 4: '',
39
+ // Version 6 adds the derived search index. Read from the schema file
40
+ // itself so the step cannot drift from what a fresh database gets.
41
+ 5: readFileSync(new URL('./schema/search.sql', import.meta.url), 'utf8'),
42
+ };
43
+ /** The version from which a database holds catalog version 2. */
44
+ const CATALOG_SINCE = 5;
45
+ export const CATALOG_VERSION_ID = 'syscall-catalog-v2';
46
+ const modules = ['agent_intent.sql', 'runtime_evidence.sql', 'classification.sql', 'file_context.sql', 'shared_storage.sql', 'auxiliary.sql', 'search.sql'];
47
+ const fileLabels = [
48
+ ['source_code', 'Source code', 'Program source files.'],
49
+ ['configuration', 'Configuration', 'Configuration for applications or tools.'],
50
+ ['potentially_sensitive', 'Potentially sensitive', 'May contain secrets or other sensitive information; not proof of contents.'],
51
+ ['documentation', 'Documentation', 'Project documentation and notes.'],
52
+ ['generated_output', 'Generated output', 'Files generated by tools or builds.'],
53
+ ['temporary', 'Temporary', 'Files intended for temporary use.'],
54
+ ];
12
55
 
13
56
  function schemaSql() {
14
57
  return modules.map(name => {
@@ -27,6 +70,24 @@ function structure(db) {
27
70
  return db.prepare("SELECT type,name,tbl_name,sql FROM sqlite_schema WHERE name NOT LIKE 'sqlite_%' ORDER BY type,name").all();
28
71
  }
29
72
 
73
+ function catalogSeed() {
74
+ const source = new DatabaseSync(':memory:');
75
+ try {
76
+ source.exec(readFileSync(new URL('../worker/sandbox/syscall_catalog.sql', import.meta.url), 'utf8'));
77
+ const versions = source.prepare('SELECT DISTINCT catalog_version FROM syscall_catalog').all();
78
+ if (versions.length !== 1 || versions[0].catalog_version !== 2) throw Error('Unsupported source catalog version');
79
+ const levels = source.prepare('SELECT level,label,description FROM syscall_impact_levels ORDER BY level').all();
80
+ const categories = source.prepare('SELECT category_id AS id,label,description FROM syscall_categories ORDER BY category_id').all();
81
+ const rules = source.prepare(`SELECT syscall_name,description,category_id,default_impact_level,
82
+ classification_rule AS rule_identifier,required_evidence,interpretation_notes
83
+ FROM syscall_catalog ORDER BY syscall_name`).all().map(({ required_evidence, ...row }) => ({
84
+ ...row, required_evidence_json: JSON.stringify([required_evidence]),
85
+ }));
86
+ const digest = createHash('sha256').update(JSON.stringify({ catalog_version: '2', levels, categories, rules })).digest('hex');
87
+ return { levels, categories, rules, digest };
88
+ } finally { source.close(); }
89
+ }
90
+
30
91
  function same(actual, expected, description) {
31
92
  // Compare values independent of object property insertion order.
32
93
  const canonical = value => Array.isArray(value) ? value.map(canonical)
@@ -36,13 +97,50 @@ function same(actual, expected, description) {
36
97
  }
37
98
  }
38
99
 
39
- /** Creates a new database, or verifies an existing compatible one. */
100
+ function insertOrVerify(db, table, key, row, fresh) {
101
+ const existing = db.prepare(`SELECT * FROM ${table} WHERE ${key}=?`).get(row[key]);
102
+ if (existing) same(existing, row, `${table} seed ${row[key]}`);
103
+ else {
104
+ if (!fresh) throw Error(`Missing ${table} seed ${row[key]}`);
105
+ db.prepare(`INSERT INTO ${table} (${Object.keys(row).join(',')}) VALUES (${Object.keys(row).map(() => '?').join(',')})`).run(...Object.values(row));
106
+ }
107
+ }
108
+
109
+ /** `adding` is true for a database that predates this catalog version: its
110
+ * new categories, version and rules are then added, not reported missing. */
111
+ function seed(db, data, fresh, adding = false) {
112
+ for (const row of data.levels) insertOrVerify(db, 'classification_impact_levels', 'level', row, fresh);
113
+ for (const row of data.categories) insertOrVerify(db, 'classification_categories', 'id', row, fresh || adding);
114
+ const version = db.prepare('SELECT * FROM classification_versions WHERE id=?').get(CATALOG_VERSION_ID);
115
+ if (version) {
116
+ same({ catalog_version: version.catalog_version, classifier_version: version.classifier_version, content_sha256: version.content_sha256 },
117
+ { catalog_version: '2', classifier_version: 'not-implemented', content_sha256: data.digest }, 'catalog version');
118
+ const rules = db.prepare(`SELECT syscall_name,description,category_id,default_impact_level,rule_identifier,
119
+ required_evidence_json,interpretation_notes FROM classification_syscall_rules WHERE version_id=? ORDER BY syscall_name`).all(CATALOG_VERSION_ID);
120
+ same(rules, data.rules, 'catalog rules');
121
+ } else {
122
+ if (!fresh && !adding) throw Error('Missing catalog version in initialized database');
123
+ db.prepare('INSERT INTO classification_versions VALUES (?,?,?,?,?,?)').run(
124
+ CATALOG_VERSION_ID, '2', 'not-implemented', data.digest, Date.now(),
125
+ 'Syscall catalog version 2, every group. No classifier writes results here: the sandbox host draws its facts from the same catalog.');
126
+ for (const row of data.rules) {
127
+ const full = { version_id: CATALOG_VERSION_ID, ...row };
128
+ db.prepare(`INSERT INTO classification_syscall_rules (${Object.keys(full).join(',')}) VALUES (${Object.keys(full).map(() => '?').join(',')})`).run(...Object.values(full));
129
+ }
130
+ }
131
+ for (const [id, label, description] of fileLabels) insertOrVerify(db, 'file_labels', 'id', { id, label, description }, fresh);
132
+ }
133
+
134
+ /** Creates a new standalone database, or verifies an existing compatible one. */
40
135
  export function initializeEvidenceDatabase(outputPath) {
41
136
  if (typeof outputPath !== 'string' || !outputPath.trim() || outputPath === ':memory:') {
42
- throw Error('An explicit database file path is required');
137
+ throw Error('An explicit standalone database file path is required');
43
138
  }
44
139
  const path = existsSync(outputPath) ? realpathSync(outputPath) : resolve(outputPath);
140
+ const livePaths = [resolve('.raytace/raytace.db'), '/var/lib/raytace/runtime.db'];
141
+ if (livePaths.includes(path)) throw Error('Refusing a live database path');
45
142
  const sql = schemaSql();
143
+ const data = catalogSeed();
46
144
  const reference = new DatabaseSync(':memory:');
47
145
  let db;
48
146
  try {
@@ -55,18 +153,44 @@ export function initializeEvidenceDatabase(outputPath) {
55
153
  const existing = structure(db);
56
154
  const version = db.prepare('PRAGMA user_version').get().user_version;
57
155
  const fresh = existing.length === 0 && version === 0;
156
+ // The RayTrace CLI's own first schema (version 1) was the agent-intent,
157
+ // shared-storage and auxiliary modules alone, before the CLI took the
158
+ // sandbox schema on. Everything it lacks is added; everything it has must
159
+ // match exactly, which the structure check below still makes sure of.
160
+ const cliFirst = !fresh && version === 1 && !existing.some((object) => object.name === 'runtime_sandboxes');
58
161
  if (fresh) db.exec(sql);
59
- else {
162
+ else if (cliFirst) {
163
+ const have = new Set(existing.map((object) => `${object.type}:${object.name}`));
164
+ const missing = expected.filter((object) => object.sql && !have.has(`${object.type}:${object.name}`));
165
+ for (const type of ['table', 'index', 'trigger', 'view']) {
166
+ // A full-text table makes its own shadow tables: one made that way is skipped.
167
+ const exists = db.prepare('SELECT 1 FROM sqlite_schema WHERE type = ? AND name = ?');
168
+ for (const object of missing.filter((item) => item.type === type)) if (!exists.get(object.type, object.name)) db.exec(object.sql);
169
+ }
170
+ same(structure(db), expected, 'schema structure');
171
+ } else {
60
172
  if (!(version in MIGRATIONS) && version !== SCHEMA_VERSION) throw Error(`Incompatible schema version ${version}`);
61
- for (let step = version; step < SCHEMA_VERSION; step += 1) db.exec(MIGRATIONS[step]);
173
+ for (let step = version; step < SCHEMA_VERSION; step += 1) if (MIGRATIONS[step]) db.exec(MIGRATIONS[step]);
62
174
  same(structure(db), expected, 'schema structure');
63
175
  }
176
+ seed(db, data, fresh || cliFirst, !fresh && version < CATALOG_SINCE);
64
177
  if (db.prepare('PRAGMA foreign_key_check').all().length) throw Error('Foreign key integrity check failed');
65
178
  db.exec(`PRAGMA user_version=${SCHEMA_VERSION}; COMMIT`);
66
- return { path, schemaVersion: SCHEMA_VERSION, tables: expected.filter(o => o.type === 'table').length, created: fresh };
179
+ return { path, schemaVersion: SCHEMA_VERSION, tables: expected.filter(o => o.type === 'table').length,
180
+ catalogVersion: CATALOG_VERSION_ID, catalogRules: data.rules.length, created: fresh };
67
181
  } catch (error) {
68
182
  db.exec('ROLLBACK');
69
183
  throw error;
70
184
  }
71
185
  } finally { db?.close(); reference.close(); }
72
186
  }
187
+
188
+ if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
189
+ if (process.argv.length !== 3) {
190
+ console.error('Usage: node proxy/init-evidence-db.mjs <standalone-database-path>');
191
+ process.exitCode = 1;
192
+ } else {
193
+ try { console.log(JSON.stringify(initializeEvidenceDatabase(process.argv[2]), null, 2)); }
194
+ catch (error) { console.error(error.message); process.exitCode = 1; }
195
+ }
196
+ }