@raytrace-cli/cli 0.9.0 → 0.11.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.
@@ -6,7 +6,7 @@
6
6
  <title>RayTrace — Agent trace forensics</title>
7
7
  <meta name="description" content="Evidence-backed traces and live counterfactual forks for coding agents." />
8
8
  <link rel="icon" href="/favicon.svg" type="image/svg+xml" />
9
- <script type="module" crossorigin src="/assets/index-TqrxOY-Y.js"></script>
9
+ <script type="module" crossorigin src="/assets/index-DepcI8Fi.js"></script>
10
10
  <link rel="stylesheet" crossorigin href="/assets/index-H97VLD5l.css">
11
11
  </head>
12
12
  <body class="antialiased">
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@raytrace-cli/cli",
3
- "version": "0.9.0",
3
+ "version": "0.11.0",
4
4
  "description": "See what your coding agent did: traces, tool calls, cost and step-by-step evidence for Claude Code and Codex.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -0,0 +1,30 @@
1
+ /** Recording health describes selected events, never certifies completeness. */
2
+ export const sourceStreamId = (sandbox, raw) => raw?.source_instance_id && raw?.source_connection_id
3
+ ? `gvisor:${sandbox}:${raw.source_instance_id}:${raw.source_connection_id}` : `gvisor:${sandbox}`;
4
+ export function captureHealth({sessionId,streams=[],checkpoints=[],events=[],since,until,now=Date.now()}) {
5
+ const applicable=/^rt[pf]-[a-f0-9]{32}$/.test(sessionId ?? '');
6
+ const base={live:applicable?'unknown':'not_applicable',history:applicable?'unknown':'not_applicable',issues:[],lastHeartbeatAt:null,checkedAt:now,scope:'Selected recorded events; completeness is not certified'};
7
+ if(!applicable) return base;
8
+ const from=Number(since), to=Number(until);
9
+ const latest=[...checkpoints].sort((a,b)=>(b.checked_at_ms??0)-(a.checked_at_ms??0))[0];
10
+ const current=streams.filter(s=>s.collector_id===latest?.source_instance_id && !s.ended_ms);
11
+ const beat=Math.max(0,...current.map(s=>Number(s.heartbeat_ms)||0));
12
+ base.lastHeartbeatAt=beat||null;
13
+ const described=streams.filter(s=>s.capabilities);
14
+ base.capabilities=described.length?Object.fromEntries(['processes','files','network'].map(key=>[key,described.every(s=>s.capabilities[key]===true)])):null;
15
+ if(latest?.imported || current.some(s=>!s.clock_measured)) base.live='unknown';
16
+ else if(latest?.unavailable || (beat && now-beat>15000)) base.live='not_reporting';
17
+ else if(current.length && beat && now-beat<=15000) base.live=Number(latest?.cursor)<Number(latest?.latest)?'catching_up':'reporting';
18
+ else if(streams.some(s=>!s.ended_ms) && latest?.source_instance_id) base.live='not_reporting';
19
+ else if(streams.length && streams.every(s=>s.ended_ms)) base.live='ended';
20
+ if(!Number.isFinite(from)||!Number.isFinite(to)||to<from) return base;
21
+ const markers=events.filter(e=>Number.isFinite(e.recorded_at_ms)&&e.recorded_at_ms>=from && (e.kind==='collection_gap' && Number.isFinite(e.gap_from_ms) ? e.gap_from_ms : e.recorded_at_ms)<=to);
22
+ base.issues=markers.map(e=>({reason:e.kind,eventId:e.event_id,at:e.recorded_at_ms,dropped:e.kind==='collection_gap'?e.dropped_delta:null}));
23
+ if(markers.some(e=>['collection_gap','collection_error'].includes(e.kind))) base.history='gaps_detected';
24
+ else {
25
+ const covering=streams.filter(s=>s.clock_measured && s.started_ms<=from && Math.min(s.ended_ms??Infinity,s.heartbeat_ms)>=to);
26
+ const synced=covering.length && covering.every(s=>checkpoints.some(c=>c.source_instance_id===s.collector_id && Number(c.forwarded_through_ms)>=to));
27
+ if(synced && !markers.some(e=>e.kind==='collector_disconnected')) base.history='no_known_gaps';
28
+ }
29
+ return base;
30
+ }
@@ -0,0 +1,44 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import {captureHealth,sourceStreamId} from './capture-health.mjs';
4
+ import {openEvidenceStore} from './evidence-store.mjs';
5
+ import {mkdtempSync,rmSync} from 'node:fs';
6
+ import {tmpdir} from 'node:os';
7
+ import {join} from 'node:path';
8
+ const sessionId='rtp-'+'a'.repeat(32);
9
+ const stream={id:'conn',collector_id:'boot',started_ms:100,heartbeat_ms:1000,ended_ms:null,clock_measured:true};
10
+ const checkpoint={source_instance_id:'boot',checked_at_ms:1000,latest:5,cursor:5,forwarded_through_ms:1000};
11
+ const sample=(extra={})=>captureHealth({sessionId,streams:[stream],checkpoints:[checkpoint],events:[],since:200,until:800,now:1100,...extra});
12
+ test('live liveness and historic interval are independent',()=>{
13
+ assert.equal(sample().live,'reporting');assert.equal(sample().history,'no_known_gaps');
14
+ const old=sample({now:17000});assert.equal(old.live,'not_reporting');assert.equal(old.history,'no_known_gaps');
15
+ assert.equal(sample({checkpoints:[{...checkpoint,cursor:4}]}).live,'catching_up');
16
+ });
17
+ test('unknown start, missing clock, legacy recording and imported data never claim live health',()=>{
18
+ assert.equal(sample({streams:[]}).history,'unknown');
19
+ assert.equal(sample({streams:[{...stream,clock_measured:false}]}).history,'unknown');
20
+ assert.equal(sample({checkpoints:[{...checkpoint,imported:true}]}).live,'unknown');
21
+ assert.equal(captureHealth({sessionId:'host-session'}).history,'not_applicable');
22
+ });
23
+ test('gaps are scoped to the run, including the interval before the dropped-count report',()=>{
24
+ assert.equal(sample({events:[{kind:'collection_gap',recorded_at_ms:900,gap_from_ms:700,dropped_delta:2}]}).history,'gaps_detected');
25
+ assert.equal(sample({events:[{kind:'collection_gap',recorded_at_ms:1100,gap_from_ms:1001}]}).history,'no_known_gaps');
26
+ assert.equal(sample({events:[{kind:'collector_disconnected',recorded_at_ms:700}]}).history,'unknown');
27
+ });
28
+ test('source identities survive event-id reuse after a collector restart',()=>{
29
+ assert.notEqual(sourceStreamId('box',{source_instance_id:'a',source_connection_id:'c'}),sourceStreamId('box',{source_instance_id:'b',source_connection_id:'c'}));
30
+ });
31
+ test('SQLite progress survives reopening and deleting one sandbox removes its metadata only',()=>{
32
+ const dir=mkdtempSync(join(tmpdir(),'recording-health-'));const file=join(dir,'evidence.db');let db=openEvidenceStore(file);
33
+ try {
34
+ db.saveCaptureProgress({containerId:'box',projectId:sessionId,sourceId:'boot',cursor:5,coverage:{...checkpoint,streams:[stream]}});
35
+ db.saveCaptureProgress({containerId:'other',projectId:'rtp-'+'b'.repeat(32),sourceId:'boot',cursor:3,coverage:{...checkpoint,streams:[{...stream,id:'other'}]}});
36
+ db.close();db=openEvidenceStore(file);assert.equal(db.captureCheckpoint('box','boot'),5);
37
+ assert.equal(db.captureHealth(sessionId,{since:200,until:800,now:1100}).history,'no_known_gaps');
38
+ db.forgetSessions([sessionId]);assert.equal(db.captureCheckpoint('box','boot'),0);assert.equal(db.captureCheckpoint('other','boot'),3);
39
+ }finally{db.close();rmSync(dir,{recursive:true,force:true});}
40
+ });
41
+ test('a current outage or later backlog cannot invalidate a previously forwarded historical interval',()=>{
42
+ const health=sample({checkpoints:[{...checkpoint,unavailable:true,latest:100}],now:50000});
43
+ assert.equal(health.live,'not_reporting');assert.equal(health.history,'no_known_gaps');
44
+ });
@@ -59,9 +59,9 @@ function result(db, id, callId, extra = {}) {
59
59
  effect_status: 'confirmed', reason: 'Test fixture, not automatic classification', classified_at_ms: 101, ...extra });
60
60
  }
61
61
 
62
- test('33 tables, catalog seeds and repeat initialization preserve evidence', () => isolated((db, path) => {
62
+ test('35 tables, catalog seeds and repeat initialization preserve evidence', () => isolated((db, path) => {
63
63
  fixtures(db); call(db, 'delete');
64
- assert.equal(db.prepare("SELECT count(*) n FROM sqlite_schema WHERE type='table' AND name NOT LIKE 'sqlite_%'").get().n, 33); // 20 evidence + 7 auxiliary + search_events + FTS5 (virtual + 4 shadows)
64
+ assert.equal(db.prepare("SELECT count(*) n FROM sqlite_schema WHERE type='table' AND name NOT LIKE 'sqlite_%'").get().n, 35); // 20 evidence + 7 auxiliary + search_events + FTS5 (virtual + 4 shadows)
65
65
  for (const [table, count] of [['classification_impact_levels', 4], ['classification_categories', 34], ['classification_syscall_rules', 353], ['file_labels', 6], ['classification_results', 0]]) {
66
66
  assert.equal(db.prepare(`SELECT count(*) n FROM ${table}`).get().n, count);
67
67
  }
@@ -207,7 +207,7 @@ test('initializer rejects unrelated/changed databases and rolls back on verifica
207
207
  test('a version-2 database is upgraded in place to add call_assessments, keeping its data', () => isolated((db, path) => {
208
208
  // Recreate exactly what a v2 database looked like: no call_assessments, and
209
209
  // none of the later tables either.
210
- db.exec('DROP INDEX call_assessments_call; DROP TABLE call_assessments; DROP TABLE workspace_snapshots; DROP TRIGGER search_events_ai; DROP TRIGGER search_events_ad; DROP TRIGGER search_events_au; DROP TABLE search_fts; DROP TABLE search_events; PRAGMA user_version=2');
210
+ db.exec('DROP TABLE runtime_capture_checkpoints; DROP TABLE runtime_capture_streams; DROP INDEX call_assessments_call; DROP TABLE call_assessments; DROP TABLE workspace_snapshots; DROP TRIGGER search_events_ai; DROP TRIGGER search_events_ad; DROP TRIGGER search_events_au; DROP TABLE search_fts; DROP TABLE search_events; PRAGMA user_version=2');
211
211
  insert(db, 'command_descriptions', { key: 'k', command: 'ls', description: 'listed files', created_at_ms: 1 });
212
212
  const result = initializeEvidenceDatabase(path);
213
213
  assert.equal(result.schemaVersion, SCHEMA_VERSION);
@@ -231,3 +231,10 @@ test('same catalog version with changed content is rejected without rewriting hi
231
231
  // A rollback releases the write transaction even while this reader stays open.
232
232
  db.exec('BEGIN IMMEDIATE; ROLLBACK');
233
233
  }));
234
+
235
+ test('a version-6 database upgrades recording metadata without inventing healthy history',()=>isolated((db,path)=>{
236
+ db.exec('DROP TABLE runtime_capture_checkpoints; DROP TABLE runtime_capture_streams; PRAGMA user_version=6');
237
+ initializeEvidenceDatabase(path);
238
+ assert.equal(db.prepare('PRAGMA user_version').get().user_version,7);
239
+ assert.equal(db.prepare('SELECT COUNT(*) n FROM runtime_capture_streams').get().n,0);
240
+ }));
@@ -1,3 +1,4 @@
1
+ import { captureHealth, sourceStreamId } from './capture-health.mjs';
1
2
  /**
2
3
  * RayTrace storage layer over the evidence database (proxy/schema/*.sql,
3
4
  * created and verified by init-evidence-db.mjs). This module is the only
@@ -403,9 +404,12 @@ export function openEvidenceStore(file, { readOnly = false } = {}) {
403
404
  WHERE ${ROUTES} ${scoped ? 'AND e.session_id = ?' : ''} ORDER BY e.started_at_ms DESC LIMIT ?`);
404
405
  const recentAll = turnExchangesQuery(false);
405
406
  const recentBySession = turnExchangesQuery(true);
407
+ const recentByExternalId = q(`SELECT ${EXCHANGE_COLUMNS} FROM agent_exchanges e
408
+ JOIN agent_sessions s ON s.id = e.session_id JOIN agent_turns t ON t.id = e.turn_id
409
+ WHERE ${ROUTES} AND s.external_session_id = ? ORDER BY e.started_at_ms DESC LIMIT ?`);
406
410
  const exchangesForTurn = q(`SELECT ${EXCHANGE_COLUMNS} FROM agent_exchanges e
407
411
  JOIN agent_sessions s ON s.id = e.session_id JOIN agent_turns t ON t.id = e.turn_id
408
- WHERE ${ROUTES} AND (e.turn_id = ? OR t.id = ? OR e.id = ?) ORDER BY e.started_at_ms ASC, e.id ASC`);
412
+ WHERE ${ROUTES} AND (e.turn_id = ? OR t.id = ? OR e.id = ?) ORDER BY e.started_at_ms ASC, e.id ASC LIMIT ?`);
409
413
  const selectExchange = q(`SELECT ${EXCHANGE_COLUMNS} FROM agent_exchanges e
410
414
  JOIN agent_sessions s ON s.id = e.session_id LEFT JOIN agent_turns t ON t.id = e.turn_id WHERE e.id = ?`);
411
415
 
@@ -444,7 +448,7 @@ export function openEvidenceStore(file, { readOnly = false } = {}) {
444
448
  /** Appends one collector event, once: the stream is the container and the
445
449
  * sequence is the collector's own event id, so a replayed event is a no-op. */
446
450
  function recordEvent({ sandboxId, processId = null, raw }) {
447
- const streamId = `gvisor:${sandboxId}`;
451
+ const streamId = sourceStreamId(sandboxId, raw);
448
452
  const sequence = Number(raw?.event_id);
449
453
  if (!Number.isInteger(sequence) || sequence < 0) return null;
450
454
  const existing = selectEventId.get(streamId, sequence);
@@ -466,16 +470,17 @@ export function openEvidenceStore(file, { readOnly = false } = {}) {
466
470
 
467
471
  /** Captured exchanges that belong to a turn, newest-first bounded,
468
472
  * returned oldest-first. Scoped to the latest session unless `history`. */
469
- exchangeRows({ history = false, limit = history ? 2000 : 400 } = {}) {
473
+ exchangeRows({ history = false, limit = history ? 2000 : 400, externalSession = null } = {}) {
470
474
  const session = history ? null : latestSession.get()?.session_id ?? null;
471
- const rows = session ? recentBySession.all(session, limit) : recentAll.all(limit);
475
+ const rows = externalSession ? recentByExternalId.all(externalSession, limit)
476
+ : session ? recentBySession.all(session, limit) : recentAll.all(limit);
472
477
  return rows.map(hydrate).reverse();
473
478
  },
474
479
 
475
480
  /** All captured exchanges belonging to one turn (trace), ordered oldest-first. */
476
- turnExchanges(turnId) {
481
+ turnExchanges(turnId, {limit = 2001} = {}) {
477
482
  if (!turnId) return [];
478
- return exchangesForTurn.all(turnId, turnId, turnId).map(hydrate);
483
+ return exchangesForTurn.all(turnId, turnId, turnId, limit).map(hydrate);
479
484
  },
480
485
 
481
486
  findExchange(exchangeId) {
@@ -485,6 +490,35 @@ export function openEvidenceStore(file, { readOnly = false } = {}) {
485
490
  return { payload: row.request.payload, response: row.response.payload, provider: row.provider, route: row.route, session_id: row.session_id };
486
491
  },
487
492
 
493
+ captureCheckpoint(containerId, sourceId) {
494
+ return q('SELECT cursor FROM runtime_capture_checkpoints WHERE sandbox_id=? AND source_id=?').get(containerId, sourceId)?.cursor ?? 0;
495
+ },
496
+ saveCaptureProgress({containerId, projectId, sourceId, cursor, coverage}) {
497
+ transaction(() => {
498
+ ensureSandbox(containerId, projectId);
499
+ const previous=q('SELECT body_json FROM runtime_capture_checkpoints WHERE sandbox_id=? AND source_id=?').get(containerId,sourceId);
500
+ const before=previous?JSON.parse(previous.body_json):{};
501
+ coverage={...coverage,forwarded_through_ms:Math.max(before.forwarded_through_ms??0,coverage?.forwarded_through_ms??0)||null};
502
+ for (const stream of coverage?.streams ?? []) q(`INSERT INTO runtime_capture_streams VALUES(?,?,?)
503
+ ON CONFLICT(id) DO UPDATE SET body_json=excluded.body_json`).run(`${containerId}:${stream.collector_id}:${stream.id}`, containerId, JSON.stringify({...stream,session_id:projectId}));
504
+ q(`INSERT INTO runtime_capture_checkpoints VALUES(?,?,?,?) ON CONFLICT(sandbox_id,source_id)
505
+ DO UPDATE SET cursor=excluded.cursor,body_json=excluded.body_json`).run(containerId, sourceId, cursor, JSON.stringify(coverage));
506
+ });
507
+ },
508
+ recordCaptureEvent({containerId, projectId, raw}) {
509
+ return transaction(() => recordEvent({sandboxId: ensureSandbox(containerId, projectId), raw}));
510
+ },
511
+ captureHealth(sessionId, {since, until, now} = {}) {
512
+ const boxes = q("SELECT id FROM runtime_sandboxes WHERE project_id=? OR id IN (SELECT sandbox_id FROM runtime_capture_streams WHERE json_extract(body_json,'$.session_id')=?)").all(sessionId,sessionId).map(r=>r.id);
513
+ const streams=[], checkpoints=[], events=[];
514
+ for(const box of boxes) {
515
+ streams.push(...q('SELECT body_json FROM runtime_capture_streams WHERE sandbox_id=?').all(box).map(r=>JSON.parse(r.body_json)));
516
+ checkpoints.push(...q('SELECT body_json,cursor FROM runtime_capture_checkpoints WHERE sandbox_id=?').all(box).map(r=>({...JSON.parse(r.body_json),cursor:r.cursor})));
517
+ events.push(...q("SELECT payload_json FROM runtime_events WHERE sandbox_id=? AND event_kind IN ('collection_gap','collection_error','collector_disconnected')").all(box).map(r=>JSON.parse(r.payload_json)));
518
+ }
519
+ return captureHealth({sessionId,streams,checkpoints,events,since,until,now});
520
+ },
521
+
488
522
  // ---- runtime evidence writers (the gVisor forwarder)
489
523
 
490
524
  /** A process began running a program (exec_succeeded), or tried to and
@@ -612,7 +646,8 @@ export function openEvidenceStore(file, { readOnly = false } = {}) {
612
646
  return Object.values(q(`SELECT (SELECT count(*) FROM agent_exchanges) AS exchanges,
613
647
  (SELECT count(*) FROM agent_tool_calls WHERE reported_result_sha IS NOT NULL) AS results,
614
648
  (SELECT count(*) FROM runtime_events) AS events, (SELECT count(*) FROM runtime_attributions) AS attributions,
615
- (SELECT count(*) FROM workspace_snapshots) AS snapshots`).get()).join(':');
649
+ (SELECT count(*) FROM workspace_snapshots) AS snapshots,
650
+ (SELECT COALESCE(MAX(json_extract(body_json,'$.checked_at_ms')),0) FROM runtime_capture_checkpoints) AS health`).get()).join(':');
616
651
  },
617
652
 
618
653
  // ---- workspace snapshots (a sandboxed Claude Code's hook)
@@ -895,6 +930,8 @@ export function openEvidenceStore(file, { readOnly = false } = {}) {
895
930
  `DELETE FROM runtime_syscall_calls WHERE sandbox_id IN (${boxes})`,
896
931
  `DELETE FROM runtime_events WHERE sandbox_id IN (${boxes})`,
897
932
  `DELETE FROM runtime_processes WHERE sandbox_id IN (${boxes})`,
933
+ `DELETE FROM runtime_capture_streams WHERE sandbox_id IN (${boxes})`,
934
+ `DELETE FROM runtime_capture_checkpoints WHERE sandbox_id IN (${boxes})`,
898
935
  `DELETE FROM runtime_sandboxes WHERE project_id IN (${marks})`,
899
936
  `DELETE FROM agent_context_items WHERE exchange_id IN (${exchanges})`,
900
937
  `DELETE FROM agent_tool_calls WHERE exchange_id IN (${exchanges})`,
@@ -1,6 +1,5 @@
1
1
  import { test } from 'node:test';
2
2
  import assert from 'node:assert/strict';
3
- import { chmodSync, statSync } from 'node:fs';
4
3
  import { mkdtemp, rm } from 'node:fs/promises';
5
4
  import { tmpdir } from 'node:os';
6
5
  import { join } from 'node:path';
@@ -50,7 +49,7 @@ const exit = (event_id, pid, startNs, exit_code, ms) => ({ event_id, kind: 'proc
50
49
 
51
50
  test('a fresh store is a current-version evidence database', () => withStore((store) => {
52
51
  assert.equal(one(store, 'PRAGMA user_version').user_version, SCHEMA_VERSION);
53
- assert.equal(one(store, "SELECT count(*) n FROM sqlite_schema WHERE type='table' AND name NOT LIKE 'sqlite_%'").n, 33);
52
+ assert.equal(one(store, "SELECT count(*) n FROM sqlite_schema WHERE type='table' AND name NOT LIKE 'sqlite_%'").n, 35);
54
53
  }));
55
54
 
56
55
  test('tool call contexts and Jev assessments round-trip through the store', () => withStore((store) => {
@@ -259,9 +258,7 @@ test('reopening an existing evidence database keeps its rows; an old-format one
259
258
  try {
260
259
  const file = join(dir, 'evidence.db');
261
260
  let store = openEvidenceStore(file); captureDemo(store); store.close();
262
- chmodSync(file, 0o644); // an install from before these were closed
263
261
  store = openEvidenceStore(file); assert.equal(store.stats().exchanges, 3); store.close();
264
- assert.equal(statSync(file).mode & 0o777, 0o600);
265
262
  const { DatabaseSync } = await import('node:sqlite');
266
263
  const oldFile = join(dir, 'old.db');
267
264
  const old = new DatabaseSync(oldFile); old.exec('CREATE TABLE exchanges (span_id TEXT); PRAGMA user_version = 8'); old.close();
@@ -28,8 +28,9 @@
28
28
  * with the real exit code. Until the exit arrives the UI keeps showing its
29
29
  * text heuristic for that call rather than asserting an outcome it lacks.
30
30
  */
31
+ import { readFileSync } from 'node:fs';
31
32
 
32
- // rtp- a project's sandbox, rtf- a Playground fork of one (worker/sandbox/projects.py).
33
+ // rtp- a project's sandbox, rtf- a Playground fork of one (worker/gvisor/projects.py).
33
34
  export const SANDBOX_ID = /^rt[pf]-[a-f0-9]{32}$/;
34
35
  export const CONTAINER_ID = /^[a-f0-9]{64}$/;
35
36
 
@@ -54,6 +55,8 @@ export function clockFromSamples(samples) {
54
55
  * which is how a pid (reused across sandboxes) is scoped back to its own. */
55
56
  export const rowPrefix = (containerId) => `gvisor-${typeof containerId === 'string' && containerId ? containerId.slice(0, 12) : 'unknown'}-`;
56
57
 
58
+ const eventRowId = event => `${rowPrefix(event.container_id)}${event.source_instance_id && event.source_connection_id ? `${event.source_instance_id}:${event.source_connection_id}:` : ''}${Number(event.event_id)}`;
59
+
57
60
  /** ns-since-epoch (as the collector's string) -> ms, or null if unparseable. */
58
61
  export function msFromNs(ns) {
59
62
  if (ns == null || ns === '') return null;
@@ -65,7 +68,6 @@ export function msFromNs(ns) {
65
68
 
66
69
  /** The call id a command's own text exports, or null. */
67
70
  export function commandMarker(command) {
68
- // Claude Code runs the command as `eval '<it>'`, so the export may follow the quote.
69
71
  return /(?:^|[\s;'])export RAYTRACE_CALL_ID=([A-Za-z0-9_-]{1,128})(?=[\s;]|$)/.exec(String(command ?? ''))?.[1] ?? null;
70
72
  }
71
73
 
@@ -85,17 +87,17 @@ export function toExecutionEvent(event, clock = UNMEASURED_CLOCK) {
85
87
  const eventId = Number(event.event_id);
86
88
  if (!command || timestamp == null || !Number.isFinite(pid) || !Number.isFinite(eventId)) return null;
87
89
  // `markers` is the collector's allowlisted RAYTRACE_* env (see
88
- // worker/sandbox/collector.py MARKER_KEYS). When RAYTRACE_CALL_ID is present
90
+ // worker/gvisor/collector.py MARKER_KEYS). When RAYTRACE_CALL_ID is present
89
91
  // it IS the answer -- the call id travelled with the process -- and the
90
92
  // text matcher is skipped entirely. Absent on every event until something
91
93
  // in the spawn path stamps it, which is why the matcher stays the default.
92
94
  // A sandboxed Claude Code stamps it in the command itself (`export
93
- // RAYTRACE_CALL_ID=...`, worker/sandbox/claude-hook.mjs): the shell that
95
+ // RAYTRACE_CALL_ID=...`, worker/gvisor/claude-hook.mjs): the shell that
94
96
  // runs the command carries it in argv, the programs it starts in env.
95
97
  const marker = (event.markers && typeof event.markers === 'object' ? event.markers.RAYTRACE_CALL_ID : null)
96
98
  ?? commandMarker(command);
97
99
  return {
98
- id: `${rowPrefix(event.container_id)}${eventId}`,
100
+ id: eventRowId(event),
99
101
  pid,
100
102
  ppid: Number.isFinite(Number(event.ppid)) ? Number(event.ppid) : null,
101
103
  command,
@@ -125,7 +127,7 @@ export function toFailedExec(event, clock = UNMEASURED_CLOCK) {
125
127
  if (!argv.length || observed == null || !Number.isFinite(pid) || !Number.isFinite(eventId)) return null;
126
128
  const at = new Date(observed - clock.offsetMs).toISOString();
127
129
  return {
128
- id: `${rowPrefix(event.container_id)}${eventId}`,
130
+ id: eventRowId(event),
129
131
  pid,
130
132
  ppid: Number.isFinite(Number(event.ppid)) ? Number(event.ppid) : null,
131
133
  command: argv.join(' ').trim(),
@@ -185,14 +187,20 @@ export class SandboxTracker {
185
187
  * @param {{offsetMs: number, marginMs: number}} [deps.clock] - VM->proxy clock mapping
186
188
  * @returns {Promise<{forwarded: number, matched: number, finished: number, descendants: number, unattributed: number, failedExecs: number, lost: number}>}
187
189
  */
188
- export async function processEvents(events, { sessionId, tracker, ingest, finish, descend = () => {}, finishByProcess = () => false, lose = () => 0, clock = UNMEASURED_CLOCK }) {
190
+ export async function processEvents(events, { sessionId, tracker, ingest, finish, descend = () => {}, finishByProcess = () => false, lose = () => 0, recordCapture = async () => {}, clock = UNMEASURED_CLOCK }) {
189
191
  const counts = { forwarded: 0, matched: 0, finished: 0, descendants: 0, unattributed: 0, failedExecs: 0, lost: 0 };
190
192
  const ordered = (Array.isArray(events) ? events : [])
191
193
  .filter((event) => Number.isFinite(Number(event?.event_id)) && Number(event.event_id) > tracker.cursor)
192
194
  .sort((a, b) => Number(a.event_id) - Number(b.event_id));
193
195
 
194
- for (const event of ordered) {
195
- tracker.cursor = Number(event.event_id);
196
+ for (const sourceEvent of ordered) {
197
+ const event=clock.measured && Number.isFinite(sourceEvent.received_ms) ? {...sourceEvent,
198
+ recorded_at_ms:Math.round(sourceEvent.received_ms-clock.offsetMs),
199
+ ...(Number.isFinite(sourceEvent.gap_from_ms)?{gap_from_ms:Math.round(sourceEvent.gap_from_ms-clock.offsetMs)}:{})} : sourceEvent;
200
+ const previousLive = new Map(tracker.live);
201
+ const restoreLive = () => { tracker.live.clear(); for (const [pid,entry] of previousLive) tracker.live.set(pid,entry); };
202
+ let failed = false;
203
+ try {
196
204
  if (event.kind === 'exec_succeeded') {
197
205
  const exec = toExecutionEvent(event, clock);
198
206
  if (!exec) continue;
@@ -269,29 +277,50 @@ export async function processEvents(events, { sessionId, tracker, ingest, finish
269
277
  counts.lost += Number(await lose({ container_id: event.container_id, session_id: sessionId, reason: 'collector disconnected', raw: event })) || 0;
270
278
  tracker.live.clear();
271
279
  }
280
+ } catch (error) { failed = true; restoreLive(); throw error; }
281
+ finally {
282
+ if (!failed) {
283
+ try { await recordCapture({containerId:event.container_id,projectId:sessionId,raw:event}); }
284
+ catch (error) { restoreLive(); throw error; }
285
+ tracker.cursor = Number(event.event_id);
286
+ }
287
+ }
272
288
  }
273
289
  return counts;
274
290
  }
275
291
 
292
+ /** What a request to the viewer carries (worker/gvisor/viewer.py): the token
293
+ * from the control plane's env, or the one in `file`, which sandbox setup makes.
294
+ * Read each time, as setup may come after this process starts. */
295
+ export function viewerAuth(file) {
296
+ let token = process.env.RAYTACE_VIEWER_TOKEN;
297
+ if (!token && file) try { token = readFileSync(file, 'utf8').trim(); } catch { /* no sandboxes set up yet */ }
298
+ return token ? { authorization: `Bearer ${token}` } : {};
299
+ }
300
+
276
301
  /**
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
302
+ * Discovers sandboxes from the Mac-side manager (:8799, `/api/projects`
303
+ * maps each rtp- id to its container id), tails each container's events
279
304
  * from the evidence viewer (:8798), and runs them through processEvents().
280
305
  * Best-effort throughout: the manager or viewer being down just means no
281
306
  * gVisor evidence for now -- logged once per outage, never fatal to the
282
307
  * proxy, never a wrong row.
283
308
  */
284
309
  export function startGvisorForwarder({
310
+ listProjects,
285
311
  managerBase = 'http://127.0.0.1:8799',
286
- listProjects = null,
287
312
  viewerBase = 'http://127.0.0.1:8798',
288
313
  ingest,
289
314
  finish,
290
315
  descend,
291
316
  finishByProcess,
292
317
  lose,
318
+ recordCapture,
319
+ loadCheckpoint = async () => 0,
320
+ saveProgress = async () => {},
293
321
  log = (message) => console.error(message),
294
322
  fetchImpl = globalThis.fetch,
323
+ viewerHeaders = () => ({}),
295
324
  pollMs = 1500,
296
325
  discoverMs = 10_000,
297
326
  // First discovery is deferred a little so a proxy that starts with no
@@ -310,24 +339,12 @@ export function startGvisorForwarder({
310
339
  let polling = null;
311
340
  let stopped = false;
312
341
 
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}`);
342
+ const getJson = async (url, headers = {}) => {
343
+ const res = await fetchImpl(url, { headers, signal: AbortSignal.timeout(8000) });
344
+ if (!res.ok) throw Object.assign(new Error(`${res.status} from ${url}`),{status:res.status});
316
345
  return res.json();
317
346
  };
318
347
 
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
348
  const discover = () => {
332
349
  if (stopped) return Promise.resolve();
333
350
  if (discovering) return discovering;
@@ -340,7 +357,7 @@ export function startGvisorForwarder({
340
357
  const sampleClock = async () => {
341
358
  try {
342
359
  const sent = Date.now();
343
- const body = await getJson(`${viewerBase}/time`);
360
+ const body = await getJson(`${viewerBase}/time`, viewerHeaders());
344
361
  const received = Date.now();
345
362
  const vmMs = msFromNs(body?.realtime_ns);
346
363
  if (vmMs == null) throw new Error('no realtime_ns in /time response');
@@ -358,7 +375,7 @@ export function startGvisorForwarder({
358
375
 
359
376
  const discoverOnce = async () => {
360
377
  try {
361
- const projects = listProjects ? await listProjects() : await getJson(`${managerBase}/api/projects`);
378
+ const projects = typeof listProjects==='function' ? await listProjects() : await getJson(`${managerBase}/api/projects`);
362
379
  await sampleClock();
363
380
  const present = new Set();
364
381
  for (const project of Array.isArray(projects) ? projects : []) {
@@ -371,15 +388,8 @@ export function startGvisorForwarder({
371
388
  present.add(containerId);
372
389
  if (!sandboxes.has(containerId)) {
373
390
  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);
391
+ // Source identity and the durable checkpoint are loaded on poll.
392
+ tracker.cursor = 0; // Backfill safely until a durable source checkpoint is loaded.
383
393
  sandboxes.set(containerId, { sessionId, tracker });
384
394
  log(`[raytace][gvisor] forwarding evidence for sandbox ${sessionId} (container ${containerId.slice(0, 12)}) from event ${tracker.cursor}`);
385
395
  }
@@ -397,9 +407,7 @@ export function startGvisorForwarder({
397
407
  } catch (error) {
398
408
  if (!managerDown) {
399
409
  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`);
410
+ log(`[raytace][gvisor] sandbox manager not reachable at ${managerBase} (${error.message}) -- gVisor evidence forwarding idle until it is. Start it with: npm run sandbox:manager`);
403
411
  }
404
412
  }
405
413
  };
@@ -407,17 +415,41 @@ export function startGvisorForwarder({
407
415
  const poll = () => {
408
416
  if (stopped || !sandboxes.size) return Promise.resolve();
409
417
  if (polling) return polling;
410
- polling = pollOnce().finally(() => { polling = null; });
418
+ polling = pollOnce().catch(error=>log(`[raytace][gvisor] recording progress could not be saved: ${error.message}`)).finally(() => { polling = null; });
411
419
  return polling;
412
420
  };
413
421
  const pollOnce = async () => {
414
422
  for (const [containerId, { sessionId, tracker }] of sandboxes) {
423
+ let coverage;
424
+ try { coverage = await getJson(`${viewerBase}/coverage?container=${containerId}`, viewerHeaders()); }
425
+ catch(error) {
426
+ if(error.status!==404) {
427
+ if(tracker.sourceId) await saveProgress({containerId,projectId:sessionId,sourceId:tracker.sourceId,cursor:tracker.cursor,
428
+ coverage:{streams:[],source_instance_id:tracker.sourceId,unavailable:true,checked_at_ms:Date.now()}});
429
+ continue;
430
+ }
431
+ coverage={streams:[],source_instance_id:'legacy',latest:0,checked_at_ms:Date.now()};
432
+ }
433
+ const sourceId=coverage.source_instance_id || 'legacy';
434
+ if(tracker.sourceId !== sourceId) {
435
+ tracker.cursor=Number(await loadCheckpoint(containerId,sourceId,sessionId)) || 0;
436
+ tracker.sourceId=sourceId; tracker.live.clear();
437
+ }
415
438
  const url = `${viewerBase}/events?container=${containerId}&after=${tracker.cursor}&limit=500&processes=1`;
416
439
  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?`); }
440
+ try { page = await getJson(url, viewerHeaders()); } catch (error) {
441
+ await saveProgress({containerId,projectId:sessionId,sourceId,cursor:tracker.cursor,
442
+ coverage:{...coverage,streams:[],unavailable:true,checked_at_ms:Date.now()}});
443
+ if (!viewerDown) { viewerDown = true; log(`[raytace][gvisor] evidence viewer not reachable at ${viewerBase} (${error.message})`); }
419
444
  continue;
420
445
  }
446
+ if(sourceId==='legacy' && page?.coverage?.source_instance_id) coverage=page.coverage;
447
+ coverage={...coverage,checked_at_ms:Date.now(),clock_measured:clock.measured,
448
+ heartbeat_ms:clock.measured && coverage.heartbeat_ms ? Math.round(coverage.heartbeat_ms-clock.offsetMs) : null,
449
+ streams:(coverage.streams??[]).map(stream=>({...stream,clock_measured:clock.measured,
450
+ started_ms:Math.round(stream.started_ms-clock.offsetMs),
451
+ ended_ms:stream.ended_ms==null?null:Math.round(stream.ended_ms-clock.offsetMs),
452
+ heartbeat_ms:Math.round(stream.heartbeat_ms-clock.offsetMs)}))};
421
453
  if (viewerDown) { viewerDown = false; log('[raytace][gvisor] evidence viewer reachable again'); }
422
454
  // An ingest/finish failure (e.g. a DB error) must not stall the loop
423
455
  // or leave the cursor wedged; log it and move on to the next poll.
@@ -425,7 +457,14 @@ export function startGvisorForwarder({
425
457
  const counts = await processEvents(page?.events, { sessionId, tracker, ingest, finish, descend,
426
458
  ...(typeof finishByProcess === 'function' ? { finishByProcess } : {}),
427
459
  ...(typeof lose === 'function' ? { lose } : {}),
428
- clock });
460
+ ...(typeof recordCapture === 'function' ? {recordCapture} : {}), clock });
461
+ // Exhausted selected events: acknowledge excluded source rows too,
462
+ // otherwise a non-process event would keep us catching up forever.
463
+ if(!page.next_after) {
464
+ tracker.cursor=Math.max(tracker.cursor,Number(page.coverage?.latest??coverage.latest)||0);
465
+ if(clock.measured)coverage.forwarded_through_ms=coverage.heartbeat_ms;
466
+ }
467
+ await saveProgress({containerId,projectId:sessionId,sourceId,cursor:tracker.cursor,coverage});
429
468
  if (counts.matched || counts.finished || counts.descendants || counts.unattributed || counts.failedExecs || counts.lost) {
430
469
  log(`[raytace][gvisor] ${sessionId.slice(0, 12)}: ${counts.matched} exec(s) matched to proposed calls, `
431
470
  + `${counts.descendants} descendant(s), ${counts.unattributed} unattributed, ${counts.failedExecs} failed exec(s), `