@raytrace-cli/cli 0.10.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.
@@ -1,6 +1,6 @@
1
1
  import { test } from 'node:test';
2
2
  import assert from 'node:assert/strict';
3
- import { toExecutionEvent, toFailedExec, exitOutcome, msFromNs, processEvents, SandboxTracker, startGvisorForwarder, clockFromSamples, UNMEASURED_CLOCK } from './gvisor-forwarder.mjs';
3
+ import { toExecutionEvent, toFailedExec, exitOutcome, msFromNs, processEvents, SandboxTracker, startGvisorForwarder, viewerAuth, clockFromSamples, UNMEASURED_CLOCK } from './gvisor-forwarder.mjs';
4
4
 
5
5
  // Event shapes below mirror what worker/gvisor/collector.py writes and
6
6
  // viewer.py serves (see `decode()` there): timestamp_ns / process_start_ns
@@ -38,6 +38,12 @@ test('toExecutionEvent carries RAYTRACE_CALL_ID through, and ignores other marke
38
38
  assert.equal(toExecutionEvent({ ...exec(9, 10, 1, ['ls']), markers: { RAYTRACE_CALL_ID: '' } }).call_marker, null);
39
39
  });
40
40
 
41
+ test('recreated collector event IDs cannot overwrite earlier executions',()=>{
42
+ const raw={...exec(1,10,1,['ls']),source_instance_id:'boot-a',source_connection_id:'connection'};
43
+ assert.notEqual(toExecutionEvent(raw).id,toExecutionEvent({...raw,source_instance_id:'boot-b'}).id);
44
+ assert.notEqual(toExecutionEvent(raw).id,toExecutionEvent({...raw,source_connection_id:'replacement'}).id);
45
+ });
46
+
41
47
  test('toExecutionEvent rejects anything that is not a usable exec', () => {
42
48
  assert.equal(toExecutionEvent(exit(1, 10, 0)), null);
43
49
  assert.equal(toExecutionEvent(exec(2, 10, 1, [])), null);
@@ -203,6 +209,7 @@ test('startGvisorForwarder discovers sandboxes from the manager and tails each c
203
209
  // limit=1 is the cursor seed probe; this container has no history yet.
204
210
  if (url.includes('limit=1')) return { ok: true, json: async () => ({ events: [], next_before: null }) };
205
211
  if (url.includes('/events?')) return { ok: true, json: async () => ({ events: [exec(1, 5, 1, ['/bin/bash', '-lc', 'pwd']), exit(2, 5, 0)], next_before: null }) };
212
+ if(url.includes('/coverage?'))return {ok:false,status:404};
206
213
  throw new Error('unexpected ' + url);
207
214
  };
208
215
  const { ingest } = fakeIngest(['pwd']);
@@ -226,7 +233,7 @@ test('startGvisorForwarder discovers sandboxes from the manager and tails each c
226
233
  } finally { forwarder.stop(); }
227
234
  });
228
235
 
229
- test('a newly discovered sandbox starts at the newest event, not at zero', async () => {
236
+ test('a newly discovered sandbox resumes a durable checkpoint instead of skipping history', async () => {
230
237
  // The collector's evidence store lives in the VM and is append-only, so it
231
238
  // outlives the proxy. Beginning at 0 re-reads every past session: none of it
232
239
  // can match (no proposed calls were captured then), so it all lands as
@@ -239,13 +246,13 @@ test('a newly discovered sandbox starts at the newest event, not at zero', async
239
246
  return { ok: true, json: async () => ({ events: [] }) };
240
247
  };
241
248
  const logs = [];
242
- const forwarder = startGvisorForwarder({ ingest: async () => new Map(), finish: async () => true, fetchImpl, log: (m) => logs.push(m), pollMs: 60_000, discoverMs: 60_000 });
249
+ const forwarder = startGvisorForwarder({ ingest: async () => new Map(), finish: async () => true, loadCheckpoint:async()=>4096, fetchImpl, log: (m) => logs.push(m), pollMs: 60_000, discoverMs: 60_000 });
243
250
  try {
244
251
  await forwarder.discover();
245
- assert.equal(forwarder.sandboxes.get(CONTAINER).tracker.cursor, 4096, 'seeded past the backlog');
252
+ assert.equal(forwarder.sandboxes.get(CONTAINER).tracker.cursor, 0, 'does not skip history at discovery');
246
253
  await forwarder.poll();
247
254
  assert.ok(requested.some((u) => u.includes('&after=4096&')), 'tails forward from there');
248
- assert.ok(logs.some((m) => m.includes('from event 4096')));
255
+ assert.equal(forwarder.sandboxes.get(CONTAINER).tracker.cursor,4096,'loads the saved checkpoint on first poll');
249
256
  } finally { forwarder.stop(); }
250
257
  });
251
258
 
@@ -342,6 +349,7 @@ test('startGvisorForwarder measures the VM clock, falls back when it cannot, and
342
349
  return { ok: true, json: async () => ({ realtime_ns: NS(Date.now() + 3000) }) };
343
350
  }
344
351
  if (url.includes('/events?')) return { ok: true, json: async () => ({ events: [] }) };
352
+ if(url.includes('/coverage?'))return {ok:false,status:404};
345
353
  throw new Error('unexpected ' + url);
346
354
  };
347
355
  const lost = [];
@@ -366,3 +374,60 @@ test('startGvisorForwarder measures the VM clock, falls back when it cannot, and
366
374
  assert.ok(logs.some((m) => m.includes('is gone') && m.includes('1 open execution(s) marked unknown')));
367
375
  } finally { forwarder.stop(); }
368
376
  });
377
+
378
+ test('the viewer gets its token and the manager does not', async () => {
379
+ const seen = [];
380
+ const fetchImpl = async (url, init) => {
381
+ seen.push([url, init.headers.authorization]);
382
+ if (url.endsWith('/api/projects')) return { ok: true, json: async () => [{ id: SESSION, container_id: CONTAINER }] };
383
+ if (url.endsWith('/time')) return { ok: true, json: async () => ({ realtime_ns: String(Date.now() * 1e6) }) };
384
+ return { ok: true, json: async () => ({ events: [] }) };
385
+ };
386
+ const forwarder = startGvisorForwarder({ ingest: async () => new Map(), finish: async () => true, fetchImpl, viewerHeaders: () => ({ authorization: 'Bearer viewer' }), log: () => {}, pollMs: 1e6, discoverMs: 1e6, initialDelayMs: 1e6 });
387
+ try {
388
+ await forwarder.discover();
389
+ await forwarder.poll();
390
+ assert.ok(seen.some(([url]) => url.includes('/events?')));
391
+ for (const [url, header] of seen) assert.equal(header, url.endsWith('/api/projects') ? undefined : 'Bearer viewer', url);
392
+ } finally { forwarder.stop(); }
393
+ });
394
+
395
+ test('viewerAuth prefers the environment and sends nothing without a token', () => {
396
+ const saved = process.env.RAYTACE_VIEWER_TOKEN;
397
+ try {
398
+ process.env.RAYTACE_VIEWER_TOKEN = 'from-env';
399
+ assert.deepEqual(viewerAuth('/nonexistent'), { authorization: 'Bearer from-env' });
400
+ delete process.env.RAYTACE_VIEWER_TOKEN;
401
+ assert.deepEqual(viewerAuth('/nonexistent'), {});
402
+ } finally { if (saved) process.env.RAYTACE_VIEWER_TOKEN = saved; }
403
+ });
404
+
405
+ test('a failed evidence write leaves the cursor unchanged and a retry records the event',async()=>{
406
+ const tracker=new SandboxTracker();let fails=true;
407
+ const deps={sessionId:SESSION,tracker,ingest:async()=>new Map(),finish:()=>{},descend:async()=>{if(fails)throw Error('disk full');}};
408
+ const rows=[exec(10,20,1,['npm','test'])];
409
+ await assert.rejects(processEvents(rows,deps),/disk full/);assert.equal(tracker.cursor,0);
410
+ fails=false;await processEvents(rows,deps);assert.equal(tracker.cursor,10);
411
+ });
412
+ test('a failed final raw-event write is retried without advancing past it',async()=>{
413
+ const tracker=new SandboxTracker();const event={event_id:1,kind:'collection_gap',container_id:CONTAINER,received_ms:100};
414
+ await assert.rejects(processEvents([event],{sessionId:SESSION,tracker,ingest:async()=>new Map(),finish:()=>{},recordCapture:async()=>{throw Error('write failed');}}));
415
+ assert.equal(tracker.cursor,0);
416
+ });
417
+
418
+ test('a failed exit write restores the tracked process for retry',async()=>{
419
+ const tracker=new SandboxTracker();tracker.live.set(20,{execId:'execution',callId:'call'});
420
+ let fail=true,finished=0;
421
+ const deps={sessionId:SESSION,tracker,ingest:async()=>new Map(),finish:async()=>{if(fail)throw Error('disk full');finished++;}};
422
+ const event={event_id:2,kind:'process_exit',pid:20,exit_code:1,container_id:CONTAINER};
423
+ await assert.rejects(processEvents([event],deps),/disk full/);
424
+ assert.equal(tracker.cursor,0);assert.equal(tracker.live.get(20).execId,'execution');
425
+ fail=false;await processEvents([event],deps);assert.equal(finished,1);assert.equal(tracker.cursor,2);
426
+ });
427
+
428
+ test('a source checkpoint failure does not reject the background poll and retries on the next poll',async()=>{
429
+ let fail=true,saved=0;
430
+ const fetchImpl=async url=>({ok:true,json:async()=>url.endsWith('/api/projects')?[{id:SESSION,container_id:CONTAINER}]:url.includes('/coverage?')?{source_instance_id:'boot',streams:[],latest:0}:{events:[]}});
431
+ const forwarder=startGvisorForwarder({ingest:async()=>new Map(),finish:()=>{},fetchImpl,log:()=>{},saveProgress:async()=>{if(fail)throw Error('disk full');saved++;},pollMs:60000,discoverMs:60000});
432
+ try{await forwarder.discover();await assert.doesNotReject(forwarder.poll());fail=false;await forwarder.poll();assert.equal(saved,1);}finally{forwarder.stop();}
433
+ });
@@ -4,12 +4,13 @@ import { readFileSync, realpathSync, existsSync } from 'node:fs';
4
4
  import { resolve } from 'node:path';
5
5
  import { fileURLToPath } from 'node:url';
6
6
 
7
- export const SCHEMA_VERSION = 6;
7
+ export const SCHEMA_VERSION = 7;
8
8
  // Forward steps for databases created by an older schema, keyed by the
9
9
  // version they upgrade FROM. Each must reproduce the schema files exactly:
10
10
  // the structure check below still runs afterwards, so a step that drifts from
11
11
  // the .sql text is refused rather than silently accepted.
12
12
  const MIGRATIONS = {
13
+ 6: readFileSync(new URL('./schema/capture_health.sql', import.meta.url), 'utf8'),
13
14
  2: `CREATE TABLE call_assessments (
14
15
  key TEXT NOT NULL PRIMARY KEY,
15
16
  call_id TEXT,
@@ -43,7 +44,7 @@ CREATE INDEX workspace_snapshots_call ON workspace_snapshots(call_id);`,
43
44
  /** The version from which a database holds catalog version 2. */
44
45
  const CATALOG_SINCE = 5;
45
46
  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 modules = ['agent_intent.sql', 'runtime_evidence.sql', 'classification.sql', 'file_context.sql', 'shared_storage.sql', 'auxiliary.sql', 'search.sql', 'capture_health.sql'];
47
48
  const fileLabels = [
48
49
  ['source_code', 'Source code', 'Program source files.'],
49
50
  ['configuration', 'Configuration', 'Configuration for applications or tools.'],
@@ -43,7 +43,7 @@ const summaryModel = process.env.RAYTACE_SUMMARY_MODEL
43
43
  : (routing.models.oss || routing.defaultModel);
44
44
  // Bumped whenever the dashboard needs endpoints an older proxy lacks; the
45
45
  // CLI restarts a proxy it started that reports less (src/proxy-process.mjs).
46
- const PROXY_API = 4;
46
+ const PROXY_API = 5;
47
47
  const fallbackSession = { session_id: randomUUID(), session_started_at: new Date().toISOString() };
48
48
 
49
49
  const port = Number(process.env.RAYTACE_PORT || 8797);
@@ -156,8 +156,8 @@ async function persistExperiment(job) { db.saveExperiment(redact(omitToolChunkId
156
156
  // so a poll with nothing new is answered 304 without sending anything.
157
157
  /** The trace view over this proxy's store; a replay is offered for exchanges
158
158
  * still held in memory (liveExchanges). */
159
- function readTraces(includeHistory = false, { evidence = true } = {}) {
160
- return traceView(db, { includeHistory, evidence, replayReason: (spanId) => {
159
+ function readTraces(includeHistory = false, { evidence = true, turnId = null } = {}) {
160
+ return traceView(db, { includeHistory, evidence, turnId, replayReason: (spanId) => {
161
161
  const live = liveExchanges.get(spanId);
162
162
  return live ? replayEligibility(live) : undefined;
163
163
  } });
@@ -169,7 +169,7 @@ const traceCache = new Map(); // url -> { version, body: Promise<string> }
169
169
  const resolveCategories = categoryResolver({ config: typesafe, ask: (request) => systemOne(typesafe, request) });
170
170
  let categoryAnswers = 0;
171
171
  function cachedTraces(url) {
172
- const version = `${db.dataVersion()}:${categoryAnswers}`;
172
+ const version = `${db.dataVersion()}:${categoryAnswers}:${Math.floor(Date.now()/5000)}`;
173
173
  const hit = traceCache.get(url);
174
174
  if (hit?.version === version) return hit;
175
175
  const body = readTraces(url !== '/raytace/traces', { evidence: url !== '/raytace/traces?scope=history' })
@@ -476,6 +476,12 @@ const server = createServer(async (req, res) => {
476
476
  return res.end(await feed.text());
477
477
  } catch { return json(503, { error: NO_VM }); }
478
478
  }
479
+ if(req.method==='GET' && req.url?.startsWith('/raytace/traces?') && new URL(req.url,'http://local').searchParams.has('trace')) {
480
+ const id=new URL(req.url,'http://local').searchParams.get('trace');
481
+ if(!/^[A-Za-z0-9_.:-]{1,160}$/.test(id??'')) return json(400,{error:'Invalid trace'});
482
+ const traces=await readTraces(true,{evidence:true,turnId:id});
483
+ return json(traces.length?200:404,{traces});
484
+ }
479
485
  if (req.method === 'GET' && req.url?.startsWith('/raytace/runtime?')) {
480
486
  const query = new URL(req.url, 'http://localhost').searchParams;
481
487
  const sandbox = query.get('sandbox');
@@ -498,7 +504,7 @@ const server = createServer(async (req, res) => {
498
504
  const evidence = await fromViewer(`${EVIDENCE_VIEWER}/events?container=${project.container_id}&before=${before}${window}&limit=${limit}&processes=1`, { signal: AbortSignal.timeout(10000) });
499
505
  if (!evidence.ok) throw new Error('Runtime collector unavailable');
500
506
  const page = await evidence.json();
501
- const base = { ...page, sandbox, container_id: project.container_id };
507
+ const base = { ...page, sandbox, container_id: project.container_id, captureHealth:db.captureHealth(sandbox,{since:Number(since)||undefined,until:Number(until)||Date.now()}) };
502
508
  // `raw=1` is the "show everything" escape hatch: the folded view must
503
509
  // always be auditable against what the collector actually recorded.
504
510
  if (raw) return json(200, base);
@@ -906,6 +912,9 @@ server.listen(port, '127.0.0.1', () => {
906
912
  // once and idles. RAYTACE_GVISOR_FORWARDER=0 turns it off entirely.
907
913
  const gvisorForwarder = process.env.RAYTACE_GVISOR_FORWARDER === '0' ? null : startGvisorForwarder({
908
914
  listProjects: () => sandboxes.list(),
915
+ recordCapture: row => db.recordCaptureEvent(row),
916
+ loadCheckpoint: (container,source) => db.captureCheckpoint(container,source),
917
+ saveProgress: row => db.saveCaptureProgress(row),
909
918
  viewerBase: EVIDENCE_VIEWER,
910
919
  fetchImpl: fromViewer,
911
920
  ingest: (events, { sessionId }) => ingestExecutions(db, events, { sessionId }),
@@ -0,0 +1,14 @@
1
+ -- Recording metadata is mutable; raw evidence remains append-only.
2
+ CREATE TABLE runtime_capture_streams (
3
+ id TEXT NOT NULL PRIMARY KEY,
4
+ sandbox_id TEXT NOT NULL REFERENCES runtime_sandboxes(id),
5
+ body_json TEXT NOT NULL CHECK (json_valid(body_json))
6
+ );
7
+ CREATE INDEX runtime_capture_streams_sandbox ON runtime_capture_streams(sandbox_id);
8
+ CREATE TABLE runtime_capture_checkpoints (
9
+ sandbox_id TEXT NOT NULL REFERENCES runtime_sandboxes(id),
10
+ source_id TEXT NOT NULL,
11
+ cursor INTEGER NOT NULL CHECK (cursor >= 0),
12
+ body_json TEXT NOT NULL CHECK (json_valid(body_json)),
13
+ PRIMARY KEY(sandbox_id,source_id)
14
+ );
@@ -76,7 +76,9 @@ export function splitExchange(row, replayReason = () => undefined) {
76
76
  return steps;
77
77
  }
78
78
  export async function readTraces(db, { includeHistory = false, evidence = true, replayReason = () => undefined, turnId = null } = {}) {
79
- const rows = (turnId && db?.turnExchanges ? await db.turnExchanges(turnId) : await db.exchangeRows({ history: includeHistory })).map(omitToolChunkIds);
79
+ let rows = (turnId && db?.turnExchanges ? await db.turnExchanges(turnId) : await db.exchangeRows({ history: includeHistory })).map(omitToolChunkIds);
80
+ const truncated=Boolean(turnId && rows.length>2000);
81
+ if(turnId) rows=rows.slice(0,2000);
80
82
  // Rows arrive already grouped: each carries its turn as trace_id and the
81
83
  // turn's prompt as promptTitle, decided once at capture (evidence-store.mjs).
82
84
  const groupedRows = rows;
@@ -86,14 +88,15 @@ export async function readTraces(db, { includeHistory = false, evidence = true,
86
88
  // A tool call proposed in one captured exchange comes back as evidence (its
87
89
  // result) in a later one. Index call_id -> the exchange that first proposed it
88
90
  // so the UI can jump from "this evidence" to "the decision that produced it".
89
- const origins = new Map();
91
+ const origins = [];
92
+ const originByCall = new Map();
90
93
  for (const row of exchangeRows) {
91
94
  const output = row.response?.payload?.output;
92
95
  if (!Array.isArray(output)) continue;
93
96
  for (const [outputIndex, item] of output.entries()) {
94
97
  if (item?.call_id && /function_call|tool_use|tool_call/i.test(item?.type || '')) {
95
98
  const scopedKey = `${row.session_id || ''}:${item.call_id}`;
96
- if (!origins.has(scopedKey) || !origins.has(item.call_id)) {
99
+ {
97
100
  const args = item.arguments ?? item.input ?? item.function?.arguments ?? '';
98
101
  const info = {
99
102
  call_id: item.call_id,
@@ -108,8 +111,9 @@ export async function readTraces(db, { includeHistory = false, evidence = true,
108
111
  category: callCategory(item.name, args),
109
112
  proposed: proposedCommand(args, item.name)
110
113
  };
111
- if (!origins.has(scopedKey)) origins.set(scopedKey, info);
112
- if (!origins.has(item.call_id)) origins.set(item.call_id, info);
114
+ origins.push(info);
115
+ // Reused IDs inside one session cannot identify a result reliably.
116
+ originByCall.set(scopedKey,originByCall.has(scopedKey)?null:info);
113
117
  }
114
118
  }
115
119
  }
@@ -117,13 +121,20 @@ export async function readTraces(db, { includeHistory = false, evidence = true,
117
121
  const grouped = new Map();
118
122
  const shownResultsByTrace = new Map(); // trace_id -> Set(call_id) already rendered once
119
123
  for (const row of exchangeRows) {
120
- const trace = grouped.get(row.trace_id) || { id: row.trace_id, provider: row.provider, model: row.request?.payload?.model || 'unknown model', title: promptAsWritten(row.promptTitle), promptRaw: row.promptTitle, startedAt: row.timestamp, status: row.turn_status || 'complete', events: [], evidence: [], requests: [] };
124
+ const trace = grouped.get(row.trace_id) || { id: row.trace_id, provider: row.provider, model: row.request?.payload?.model || 'unknown model', title: promptAsWritten(row.promptTitle), promptRaw: row.promptTitle, startedAt: row.timestamp, status: row.turn_status || 'complete', events: [], evidence: [], requests: [], ...(turnId ? {comparisonRequests:[],captureComplete:!truncated} : {}) };
121
125
  if (row.turn_status) trace.status = row.turn_status;
122
126
  const shownResults = shownResultsByTrace.get(row.trace_id) || new Set();
123
127
  // rtp- a project's sandbox; rtf- a Playground fork of one (playground.mjs).
124
128
  if (/^rt[pf]-[a-f0-9]{32}$/.test(row.session_id || '')) trace.sandboxId = row.session_id;
125
129
  if (/^rtf-[a-f0-9]{32}$/.test(row.session_id || '')) trace.forkId = row.session_id;
126
130
  shownResultsByTrace.set(row.trace_id, shownResults);
131
+ if(turnId) {
132
+ const payload=row.request?.payload ?? {};
133
+ trace.comparisonRequests.push({exchangeId:row.span_id,model:payload.model??null,
134
+ settings:Object.fromEntries(Object.entries(payload).filter(([key])=>!['input','messages','instructions','system','tools','stream','store','metadata','previous_response_id','conversation','client_request_id'].includes(key))),
135
+ instructions:payload.instructions??payload.system??null,tools:payload.tools??[],
136
+ context:evidenceFor(payload,row.span_id).filter(item=>item.kind!=='tool result')});
137
+ }
127
138
  trace.requests.push({ id: row.span_id, model: row.request?.payload?.model || 'unknown', startedAt: row.timestamp, completedAt: row.completed_at || null, ...(row.metrics || requestMetrics(row)) });
128
139
  // Rows are oldest-first, so the last request that produced text is the
129
140
  // turn's final answer, and the last completion is when the turn ended.
@@ -131,7 +142,7 @@ export async function readTraces(db, { includeHistory = false, evidence = true,
131
142
  try { const text = outcome(row.response?.payload || {}).text; if (text) trace.answer = text; } catch { /* incomplete capture */ }
132
143
  trace.events.push(...splitExchange(row, replayReason).map((step) => {
133
144
  if (!step.title.startsWith('Tool result:')) return step;
134
- const raw = JSON.parse(step.raw); const origin = origins.get(`${row.session_id || ''}:${raw.call_id}`) || origins.get(raw.call_id);
145
+ const raw = JSON.parse(step.raw); const origin = originByCall.get(`${row.session_id || ''}:${raw.call_id}`);
135
146
  // The tool result carries only a call_id and output, never the tool's
136
147
  // name — fall back to the exchange that originally proposed the call,
137
148
  // where the real name is known, instead of showing the raw id.
@@ -153,7 +164,7 @@ export async function readTraces(db, { includeHistory = false, evidence = true,
153
164
  return false;
154
165
  }));
155
166
  for (const item of evidence ? evidenceFor(row.request?.payload, row.span_id) : []) {
156
- const origin = item.call_id ? origins.get(item.call_id) : null;
167
+ const origin = item.call_id ? originByCall.get(`${row.session_id || ''}:${item.call_id}`) : null;
157
168
  trace.evidence.push({ ...item, origin: origin && origin.exchange_id !== row.span_id ? origin : null });
158
169
  }
159
170
  grouped.set(row.trace_id, trace);
@@ -167,7 +178,7 @@ export async function readTraces(db, { includeHistory = false, evidence = true,
167
178
  const shownResults = shownResultsByTrace.get(trace.id) || new Set();
168
179
  const traceOrigins = [...origins.values()].filter((origin) => origin.trace_id === trace.id);
169
180
  for (const origin of traceOrigins) {
170
- if (!shownResults.has(origin.call_id)) {
181
+ if (!shownResults.has(origin.call_id) && originByCall.get(`${origin.session_id || ''}:${origin.call_id}`)===origin) {
171
182
  const reported = db?.toolCallResult ? await db.toolCallResult(origin.call_id, { exchangeId: origin.exchange_id, sessionId: origin.session_id || trace.sandboxId }) : null;
172
183
  if (reported) {
173
184
  const rawItem = (reported && typeof reported === 'object')
@@ -304,5 +315,10 @@ export async function readTraces(db, { includeHistory = false, evidence = true,
304
315
  return { id: item.id, exchange_id: item.exchange_id, index: item.index, kind: item.kind, label: item.label, call_id: item.call_id ?? null, content_of: first.get(key) };
305
316
  });
306
317
  }
318
+ for(const trace of result) {
319
+ if(turnId && ['open','running'].includes(trace.status))trace.captureComplete=false;
320
+ trace.captureHealth=await db.captureHealth?.(trace.sandboxId ?? trace.id,
321
+ {since:Date.parse(trace.startedAt),until:Date.parse(trace.endedAt)});
322
+ }
307
323
  return result;
308
324
  }
@@ -2,6 +2,17 @@ import test from 'node:test';
2
2
  import assert from 'node:assert/strict';
3
3
  import { readTraces } from './trace-view.mjs';
4
4
 
5
+ test('reused call IDs stay session-scoped and ambiguous same-session IDs stay unavailable',async()=>{
6
+ const make=(id,session)=>({span_id:id,trace_id:id,session_id:session,provider:'test',timestamp:'2026-11-03T00:00:00Z',promptTitle:'test',request:{payload:{input:[]}},response:{payload:{output:[{type:'function_call',call_id:'reused',name:id,arguments:'{}'}]}}});
7
+ const rows=[make('one','a'),make('two','b')];
8
+ const db={exchangeRows:async()=>rows,divergence:async()=>[],descendants:async()=>[],snapshotsForCalls:async()=>new Map(),toolCallResult:async(id,{sessionId})=>({output:sessionId})};
9
+ let traces=await readTraces(db,{includeHistory:true});
10
+ assert.equal(JSON.parse(traces[0].events.find(e=>e.title==='Tool result: one').raw).output,'a');
11
+ assert.equal(JSON.parse(traces[1].events.find(e=>e.title==='Tool result: two').raw).output,'b');
12
+ rows[1].session_id='a';traces=await readTraces(db,{includeHistory:true});
13
+ assert.ok(traces.every(t=>!t.events.some(e=>e.title.startsWith('Tool result:'))));
14
+ });
15
+
5
16
  test('synthesizes terminal tool results for proposed calls with no subsequent exchange', async () => {
6
17
  const fakeRow = {
7
18
  span_id: 'span-1',
@@ -70,3 +81,12 @@ test('toolResultsFromTranscript extracts tool results from user messages', async
70
81
  output: 'file.txt'
71
82
  });
72
83
  });
84
+
85
+ test('selected-run detail keeps full prompt/settings and signals the 2000-exchange limit',async()=>{
86
+ const rows=Array.from({length:2001},(_,i)=>({span_id:`e${i}`,trace_id:'t',session_id:'host',provider:'test',timestamp:new Date(1000+i).toISOString(),promptTitle:'full prompt',
87
+ request:{payload:{model:'m',instructions:'system',tools:[{name:'tool'}],temperature:0,input:[{role:'user',content:'full prompt'}]}},response:{payload:{output:[]}}}));
88
+ const db={turnExchanges:async()=>rows,exchangeRows:async()=>[],divergence:async()=>[],descendants:async()=>[],snapshotsForCalls:async()=>new Map()};
89
+ const [trace]=await readTraces(db,{turnId:'t',includeHistory:true});
90
+ assert.equal(trace.captureComplete,false);assert.equal(trace.requests.length,2000);assert.equal(trace.promptRaw,'full prompt');
91
+ assert.equal(trace.comparisonRequests[0].instructions,'system');assert.equal(trace.comparisonRequests[0].tools[0].name,'tool');
92
+ });
package/src/commands.mjs CHANGED
@@ -2,7 +2,7 @@ import { spawn } from 'node:child_process';
2
2
  import { accessSync, constants, existsSync, mkdirSync, rmSync, statSync } from 'node:fs';
3
3
  import { homedir } from 'node:os';
4
4
  import { delimiter, join } from 'node:path';
5
- import { paths } from './paths.mjs';
5
+ import { install, paths } from './paths.mjs';
6
6
  import { portOf, proxyEnv, readConfig, writeConfig } from './config.mjs';
7
7
  import { checkRunningPid, dashboardLink, healthy, portInUse, PROXY_API, proxyApi, runningPid, start, status, stop } from './proxy-process.mjs';
8
8
  import { HOOK_COMMAND, hookState, setHook } from './claude-code.mjs';
@@ -60,7 +60,7 @@ export async function setup(flags) {
60
60
 
61
61
  if (hookClaude && !onPath('raytrace')) {
62
62
  say(`\n Warning: \`raytrace\` is not on your PATH, and Claude Code's hook runs \`${HOOK_COMMAND}\`.`);
63
- say(' Install it globally so the hook can find it: npm install -g @raytrace-cli/cli');
63
+ say(` Install it globally so the hook can find it: ${install.add}`);
64
64
  }
65
65
 
66
66
  // A proxy this CLI started is restarted so the new settings apply.
@@ -177,7 +177,7 @@ export async function doctor() {
177
177
  }
178
178
  }
179
179
  line(existsSync(paths.dashboard) ? true : false, 'dashboard', existsSync(paths.dashboard) ? 'built' : `missing from ${paths.dashboard}; reinstall`);
180
- line(onPath('raytrace') ? true : false, 'raytrace on PATH', onPath('raytrace') ? 'yes' : 'no: Claude Code\'s hook cannot run it (npm install -g @raytrace-cli/cli)');
180
+ line(onPath('raytrace') ? true : false, 'raytrace on PATH', onPath('raytrace') ? 'yes' : `no: Claude Code's hook cannot run it (${install.add})`);
181
181
 
182
182
  try {
183
183
  const hooks = hookState();
@@ -281,5 +281,5 @@ export async function uninstall(flags) {
281
281
  }
282
282
  else say(`Kept ${paths.home}.`);
283
283
  }
284
- say('To remove the command itself: npm uninstall -g @raytrace-cli/cli');
284
+ say(`To remove the command itself: ${install.remove}`);
285
285
  }
package/src/mcp.mjs CHANGED
@@ -23,7 +23,7 @@ import { call, hasApiKeyOverride } from './api.mjs';
23
23
  import { formatCreditDeadline } from './beta.mjs';
24
24
  import { findLima, LIMA_VERSION } from './lima.mjs';
25
25
  import { isLocal, localSandboxes, promptsLink, registry, sandboxName } from './local-sandbox.mjs';
26
- import { paths } from './paths.mjs';
26
+ import { install, paths } from './paths.mjs';
27
27
  import { openTerminal, shellQuote } from './terminal.mjs';
28
28
  import { AGENTS } from './agents.mjs';
29
29
  import { checkId, creditPlan, isCreditRefusal, listProject, liveSandboxes, packArchive, repoRoot, upload } from './sandbox.mjs';
@@ -487,8 +487,8 @@ async function destroyLocal(ref, deleteLogs, uploadFirst) {
487
487
 
488
488
  // ------------------------------------------------------------- connecting
489
489
 
490
- /** How the user would type `raytrace` themselves: the installed command, or npx when there is none. */
491
- const typed = () => (spawnSyncQuiet('sh', ['-c', 'command -v raytrace']) ? 'raytrace' : 'npx -y @raytrace-cli/cli');
490
+ /** How the user would type `raytrace` themselves: the installed command, or npx (uvx from pip) when there is none. */
491
+ const typed = () => (spawnSyncQuiet('sh', ['-c', 'command -v raytrace']) ? 'raytrace' : install.run);
492
492
  function spawnSyncQuiet(program, args) {
493
493
  try { return spawnSync(program, args, { stdio: 'ignore' }).status === 0; } catch { return false; }
494
494
  }
package/src/paths.mjs CHANGED
@@ -2,7 +2,7 @@
2
2
  // one; the user's data in ~/.raytrace (RAYTRACE_HOME overrides it, which is
3
3
  // also how to run a second, throwaway install side by side).
4
4
  import { homedir } from 'node:os';
5
- import { join } from 'node:path';
5
+ import { basename, dirname, join } from 'node:path';
6
6
  import { fileURLToPath } from 'node:url';
7
7
 
8
8
  const root = fileURLToPath(new URL('..', import.meta.url));
@@ -23,4 +23,11 @@ export const paths = {
23
23
  get database() { return join(home(), 'evidence.db'); },
24
24
  };
25
25
 
26
+ // How this copy was installed, for the commands we suggest: pip's wheel keeps
27
+ // the npm package in raytrace/app/ (python/build_wheels.py), next to its own Node.js.
28
+ const fromPip = basename(root) === 'app' && basename(dirname(root)) === 'raytrace';
29
+ export const install = fromPip
30
+ ? { add: 'pip install raytrace', remove: 'pip uninstall raytrace', run: 'uvx raytrace' }
31
+ : { add: 'npm install -g @raytrace-cli/cli', remove: 'npm uninstall -g @raytrace-cli/cli', run: 'npx -y @raytrace-cli/cli' };
32
+
26
33
  export const DEFAULT_PORT = 8797;
@@ -13,7 +13,7 @@ import { readToken } from '../proxy/local-token.mjs';
13
13
 
14
14
  // The proxy API this CLI's dashboard needs (proxy/raytace-proxy.mjs PROXY_API).
15
15
  // A proxy from an older install answers without it, or with less.
16
- export const PROXY_API = 4;
16
+ export const PROXY_API = 5;
17
17
 
18
18
  /** The running proxy's API version: 0 for one from before it said. */
19
19
  export async function proxyApi(port) {
@@ -232,6 +232,13 @@ def init_db(path):
232
232
  id INTEGER PRIMARY KEY, connection TEXT NOT NULL, received_ms INTEGER NOT NULL,
233
233
  container_id TEXT NOT NULL, kind TEXT NOT NULL, body TEXT NOT NULL)''')
234
234
  db.execute('CREATE INDEX IF NOT EXISTS runtime_container ON runtime_events(container_id,id)')
235
+ db.execute("CREATE TABLE IF NOT EXISTS collector_state (id INTEGER PRIMARY KEY CHECK(id=1), instance_id TEXT NOT NULL, heartbeat_ms INTEGER NOT NULL)")
236
+ db.execute("""CREATE TABLE IF NOT EXISTS capture_streams (
237
+ id TEXT PRIMARY KEY, collector_id TEXT NOT NULL, container_id TEXT NOT NULL,
238
+ started_ms INTEGER NOT NULL, ended_ms INTEGER, heartbeat_ms INTEGER NOT NULL,
239
+ dropped INTEGER NOT NULL DEFAULT 0, errors INTEGER NOT NULL DEFAULT 0,
240
+ capabilities_json TEXT NOT NULL)""")
241
+ db.execute('CREATE INDEX IF NOT EXISTS capture_stream_container ON capture_streams(container_id,started_ms)')
235
242
  db.commit()
236
243
  return db
237
244
 
@@ -244,26 +251,64 @@ class Writer(threading.Thread):
244
251
  super().__init__(daemon=True, name='raytace-writer')
245
252
  self.database = database
246
253
  self.rows = queue.SimpleQueue()
254
+ self.instance_id = str(uuid.uuid4())
255
+ self.last_heartbeat = None
256
+ self.capabilities = {'processes': True, 'files': False, 'network': False}
247
257
 
248
258
  def put(self, connection, event):
249
- self.rows.put((connection, int(time.time() * 1000), event.get('container_id', ''), event['kind'], json.dumps(event)))
259
+ now = int(time.time() * 1000)
260
+ event = {**event, 'source_instance_id': self.instance_id, 'source_connection_id': connection, 'received_ms': now}
261
+ self.rows.put((connection, now, event.get('container_id', ''), event['kind'], json.dumps(event)))
262
+
263
+ def write_batch(self, db, batch, now=None):
264
+ """Events and health progress commit together; idle heartbeats add no event rows."""
265
+ now = int(time.time() * 1000) if now is None else now
266
+ wrote_heartbeat = False
267
+ with db:
268
+ for connection, received, container, kind, body in batch:
269
+ db.execute('INSERT INTO runtime_events(connection,received_ms,container_id,kind,body) VALUES(?,?,?,?,?)',
270
+ (connection, received, container, kind, body))
271
+ event = json.loads(body)
272
+ db.execute("""INSERT INTO capture_streams VALUES(?,?,?,?,?,?,?,?,?)
273
+ ON CONFLICT(id) DO UPDATE SET
274
+ container_id=CASE WHEN excluded.container_id <> '' THEN excluded.container_id ELSE capture_streams.container_id END,
275
+ ended_ms=COALESCE(excluded.ended_ms,capture_streams.ended_ms),
276
+ heartbeat_ms=CASE WHEN excluded.ended_ms IS NOT NULL THEN excluded.ended_ms ELSE capture_streams.heartbeat_ms END,
277
+ dropped=capture_streams.dropped+excluded.dropped,
278
+ errors=capture_streams.errors+excluded.errors""",
279
+ (connection, self.instance_id, container, received,
280
+ received if kind == 'collector_disconnected' else None, received,
281
+ event.get('dropped_delta', 0) if kind == 'collection_gap' else 0,
282
+ 1 if kind == 'collection_error' else 0, json.dumps(self.capabilities)))
283
+ if container:
284
+ # The greeting precedes container identification. Bind only
285
+ # this connection's greeting once a real event names it.
286
+ db.execute("UPDATE runtime_events SET container_id=? WHERE connection=? AND container_id=''", (container, connection))
287
+ if self.rows.empty() and (self.last_heartbeat is None or now-self.last_heartbeat>=5000):
288
+ wrote_heartbeat = True
289
+ db.execute('INSERT INTO collector_state VALUES(1,?,?) ON CONFLICT(id) DO UPDATE SET instance_id=excluded.instance_id,heartbeat_ms=excluded.heartbeat_ms', (self.instance_id, now))
290
+ db.execute('UPDATE capture_streams SET heartbeat_ms=? WHERE collector_id=? AND ended_ms IS NULL', (now, self.instance_id))
291
+ if wrote_heartbeat:
292
+ self.last_heartbeat = now
250
293
 
251
294
  def run(self):
252
295
  db = init_db(self.database)
253
296
  while True:
254
- batch = [self.rows.get()]
297
+ try:
298
+ batch = [self.rows.get(timeout=5)]
299
+ except queue.Empty:
300
+ batch = []
255
301
  deadline = time.monotonic() + 0.25
256
- while len(batch) < 200:
302
+ while batch and len(batch) < 200:
257
303
  try:
258
304
  batch.append(self.rows.get(timeout=max(0.0, deadline - time.monotonic())))
259
305
  except queue.Empty:
260
306
  break
261
307
  while True:
262
308
  try:
263
- db.executemany('INSERT INTO runtime_events(connection,received_ms,container_id,kind,body) VALUES(?,?,?,?,?)', batch)
264
- db.commit()
309
+ self.write_batch(db, batch)
265
310
  break
266
- except sqlite3.Error as error: # a locked or full database: keep the batch and try again
311
+ except sqlite3.Error as error:
267
312
  print(f'RayTrace collector: runtime_events not written ({error}); retrying', flush=True)
268
313
  time.sleep(1)
269
314
 
@@ -283,6 +328,7 @@ def serve(endpoint, database):
283
328
  try:
284
329
  engine = facts_engine.Engine(database)
285
330
  engine.start()
331
+ writer.capabilities.update(files=True, network=True)
286
332
  except Exception as error:
287
333
  print(f'RayTrace collector: fact engine not started ({error}); recording processes only', flush=True)
288
334
 
@@ -306,6 +352,7 @@ def serve(endpoint, database):
306
352
  conn.settimeout(None)
307
353
  record({'kind': 'collector_connected', 'source': 'collector'})
308
354
  previous_dropped = 0
355
+ previous_received = int(time.time()*1000)
309
356
  while True:
310
357
  packet, _, flags, _ = conn.recvmsg(MAX_PACKET)
311
358
  if not packet:
@@ -317,10 +364,11 @@ def serve(endpoint, database):
317
364
  container = event['container_id']
318
365
  if event['dropped_count'] != previous_dropped:
319
366
  gap = {'kind': 'collection_gap', 'container_id': event['container_id'],
320
- 'dropped_delta': (event['dropped_count'] - previous_dropped) % (1 << 32)}
367
+ 'gap_from_ms': previous_received, 'dropped_delta': (event['dropped_count'] - previous_dropped) % (1 << 32)}
321
368
  record(gap)
322
369
  taken(gap)
323
370
  previous_dropped = event['dropped_count']
371
+ previous_received = int(time.time()*1000)
324
372
  if not taken(event):
325
373
  record(with_raw(event, packet))
326
374
  except Exception as error:
@@ -500,6 +500,14 @@ def evidence(container, forget=False):
500
500
  return
501
501
  with sqlite3.connect(RUNTIME_DB, timeout=30) as db:
502
502
  tables = {name for (name,) in db.execute("SELECT name FROM sqlite_master WHERE type='table'")}
503
+ if 'capture_streams' in tables:
504
+ if forget:
505
+ db.execute('DELETE FROM capture_streams WHERE container_id=?', (container,))
506
+ else:
507
+ for row in db.execute('SELECT id,collector_id,started_ms,ended_ms,heartbeat_ms,dropped,errors,capabilities_json FROM capture_streams WHERE container_id=?', (container,)):
508
+ names=('id','collector_id','started_ms','ended_ms','heartbeat_ms','dropped','errors','capabilities')
509
+ body=dict(zip(names,row)); body['capabilities']=json.loads(body['capabilities'])
510
+ print(json.dumps({'table':'capture_streams','body':body}))
503
511
  for table, columns in (('runtime_events', 'kind, received_ms, body'), ('facts', 'kind, at_ns, received_ms, body')):
504
512
  if table not in tables:
505
513
  continue