@raytrace-cli/cli 0.4.0 → 0.6.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 (137) hide show
  1. package/README.md +155 -123
  2. package/bin/raytrace.mjs +110 -22
  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-Dc3LTk8b.js +38 -0
  50. package/dist/dashboard/assets/index-DtV3UdEB.css +1 -0
  51. package/dist/dashboard/index.html +2 -2
  52. package/package.json +4 -1
  53. package/proxy/agent-intent-schema.test.mjs +142 -0
  54. package/proxy/call-assessment.mjs +385 -0
  55. package/proxy/call-assessment.test.mjs +167 -0
  56. package/proxy/call-category.mjs +461 -0
  57. package/proxy/capture.mjs +38 -0
  58. package/proxy/capture.test.mjs +49 -0
  59. package/proxy/claude-code-adapter.mjs +65 -3
  60. package/proxy/claude-code-hook.mjs +3 -1
  61. package/proxy/codex-config.mjs +5 -0
  62. package/proxy/codex.mjs +3 -2
  63. package/proxy/evidence-schema.test.mjs +233 -0
  64. package/proxy/evidence-store.mjs +704 -33
  65. package/proxy/evidence-store.test.mjs +304 -0
  66. package/proxy/exec-narrative.mjs +625 -0
  67. package/proxy/exec-narrative.test.mjs +262 -0
  68. package/proxy/execution-correlation.mjs +185 -0
  69. package/proxy/execution-correlation.test.mjs +146 -0
  70. package/proxy/execution-runner.test.mjs +38 -0
  71. package/proxy/experiment-engine.mjs +7 -4
  72. package/proxy/experiment-engine.test.mjs +93 -0
  73. package/proxy/explanations.test.mjs +20 -0
  74. package/proxy/failure-signature.mjs +56 -0
  75. package/proxy/gvisor-forwarder.mjs +454 -0
  76. package/proxy/gvisor-forwarder.test.mjs +368 -0
  77. package/proxy/init-evidence-db.mjs +166 -12
  78. package/proxy/local-sandboxes.mjs +94 -0
  79. package/proxy/local-token.mjs +30 -0
  80. package/proxy/playground-recovery.test.mjs +130 -0
  81. package/proxy/playground.mjs +439 -0
  82. package/proxy/prompt-context.mjs +12 -7
  83. package/proxy/prompt-traces.mjs +6 -0
  84. package/proxy/prompt-traces.test.mjs +32 -0
  85. package/proxy/providers.test.mjs +76 -0
  86. package/proxy/proxy.integration.test.mjs +135 -0
  87. package/proxy/raytace-proxy.mjs +512 -188
  88. package/proxy/request-metrics.test.mjs +19 -0
  89. package/proxy/request-policy.mjs +45 -0
  90. package/proxy/request-policy.test.mjs +47 -0
  91. package/proxy/run-recap.mjs +139 -0
  92. package/proxy/runtime-attribution.mjs +110 -0
  93. package/proxy/sandbox-bridge.mjs +49 -0
  94. package/proxy/schema/EVIDENCE_DATABASE.md +276 -0
  95. package/proxy/schema/auxiliary.sql +48 -1
  96. package/proxy/schema/classification.sql +89 -0
  97. package/proxy/schema/file_context.sql +53 -0
  98. package/proxy/schema/runtime_evidence.sql +201 -0
  99. package/proxy/schema/search.sql +66 -0
  100. package/proxy/search.mjs +418 -0
  101. package/proxy/search.test.mjs +161 -0
  102. package/proxy/smoke.test.mjs +93 -0
  103. package/proxy/step-attribution.mjs +380 -0
  104. package/proxy/step-lab.test.mjs +38 -0
  105. package/proxy/summaries.test.mjs +69 -0
  106. package/proxy/tool-metadata.mjs +36 -0
  107. package/proxy/tool-metadata.test.mjs +38 -0
  108. package/proxy/trace-view.mjs +308 -0
  109. package/proxy/trace-view.test.mjs +72 -0
  110. package/proxy/typesafe.mjs +63 -0
  111. package/proxy/typesafe.test.mjs +39 -0
  112. package/src/claude-code.mjs +38 -1
  113. package/src/commands.mjs +133 -20
  114. package/src/config.mjs +16 -7
  115. package/src/export.mjs +200 -0
  116. package/src/lima.mjs +176 -0
  117. package/src/local-sandbox.mjs +339 -0
  118. package/src/paths.mjs +8 -8
  119. package/src/proxy-process.mjs +45 -3
  120. package/src/sandbox.mjs +37 -9
  121. package/src/upload.mjs +198 -0
  122. package/worker/sandbox/Dockerfile +8 -0
  123. package/worker/sandbox/SYSCALL_CATALOG.md +197 -0
  124. package/worker/sandbox/claude-hook.mjs +364 -0
  125. package/worker/sandbox/collector.py +357 -0
  126. package/worker/sandbox/dns_forwarder.py +255 -0
  127. package/worker/sandbox/engine.py +940 -0
  128. package/worker/sandbox/file_scan.py +491 -0
  129. package/worker/sandbox/lima.yaml +29 -0
  130. package/worker/sandbox/network.py +90 -0
  131. package/worker/sandbox/projects.py +679 -0
  132. package/worker/sandbox/setup.py +159 -0
  133. package/worker/sandbox/syscall_catalog.sql +985 -0
  134. package/worker/sandbox/transcript-delivery.test.mjs +153 -0
  135. package/worker/sandbox/viewer.py +151 -0
  136. package/dist/dashboard/assets/index-BQ9_JxGq.js +0 -27
  137. package/dist/dashboard/assets/index-L5cUAvhE.css +0 -1
@@ -1,5 +1,5 @@
1
1
  import { createHash, randomUUID } from 'node:crypto';
2
- import { TOOL_RESULT_KINDS } from './tool-metadata.mjs';
2
+ import { TOOL_RESULT_KINDS, nativeFileOperation } from './tool-metadata.mjs';
3
3
 
4
4
  export const digest = (value) => createHash('sha256').update(JSON.stringify(value)).digest('hex');
5
5
  const callTypes = new Set(['function_call', 'custom_tool_call', 'tool_use']);
@@ -26,9 +26,12 @@ export function describeCall(argsRaw) {
26
26
  /** The command a tool call proposed, as close to verbatim as its arguments
27
27
  * allow, for showing next to the process that actually ran. Shell tools carry
28
28
  * it as `cmd`/`command` (a string, or an argv whose `bash -lc` wrapper never
29
- * appears in what the model meant); anything else, such as a patch, falls
30
- * back to describeCall's plain-English reading. */
31
- export function proposedCommand(argsRaw) {
29
+ * appears in what the model meant); a native file tool (pass its `name`)
30
+ * carries the file it worked on; anything else, such as a patch, falls back
31
+ * to describeCall's plain-English reading. */
32
+ export function proposedCommand(argsRaw, name) {
33
+ const native = name ? nativeFileOperation(name, argsRaw) : null;
34
+ if (native) return clip(native.text, 200);
32
35
  let args = argsRaw;
33
36
  if (typeof args === 'string') { try { args = JSON.parse(args); } catch { /* raw string args */ } }
34
37
  const value = args && typeof args === 'object' && !Array.isArray(args) ? (args.cmd ?? args.command ?? args.script) : args;
@@ -0,0 +1,93 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { createExperiment, evidenceFor, makeVariant, matchesTarget, outcome, replayEligibility, runExperiment, summarize, validateTarget, wilson } from './experiment-engine.mjs';
4
+
5
+ const response = (name = 'read_file', args = '{"path":"auth.ts"}') => ({ status: 'completed', output: [{ type: 'function_call', name, arguments: args }] });
6
+ const entry = () => ({ provider: 'openai', route: '/v1/responses', payload: { model: 'fixture-model', stream: true, reasoning: { effort: 'medium' }, tools: [{ type: 'function', name: 'read_file' }], input: [
7
+ { type: 'message', role: 'user', content: 'Search found auth.ts' },
8
+ { type: 'function_call', name: 'read_file', call_id: 'call-1', arguments: '{"path":"auth.ts"}' },
9
+ { type: 'function_call_output', call_id: 'call-1', output: 'session validator' },
10
+ { type: 'message', role: 'user', content: 'Fix the login bug.' },
11
+ ] }, response: response() });
12
+ const config = (overrides = {}) => ({ exchange_id: 'capture', evidence_id: 'capture:0', repetitions: 5, target: { type: 'original_action' }, ...overrides });
13
+
14
+ test('withholding output preserves call/result pairing and original request', () => {
15
+ const source = entry(); const before = structuredClone(source.payload);
16
+ const evidence = evidenceFor(source.payload, 'capture').find((item) => item.index === 2);
17
+ const changed = makeVariant(source.payload, evidence);
18
+ assert.equal(changed.input[2].output, ''); assert.equal(changed.input[2].call_id, 'call-1');
19
+ assert.equal(changed.input.length, 4); assert.equal(evidence.source_call.name, 'read_file');
20
+ assert.deepEqual(source.payload, before);
21
+ assert.equal(makeVariant(source.payload, evidenceFor(source.payload, 'capture')[0]).input.length, 3);
22
+ });
23
+
24
+ test('Wilson intervals are bounded and remain uncertain at zero/all successes', () => {
25
+ assert.equal(wilson(0,0), null);
26
+ assert.ok(wilson(0,20)[1] > .16 && wilson(0,20)[1] < .162);
27
+ assert.ok(wilson(20,20)[0] > .838 && wilson(20,20)[0] < .84);
28
+ assert.ok(wilson(16,20)[0] < .59 && wilson(16,20)[1] > .91);
29
+ });
30
+
31
+ test('16/20 vs 5/20 yields 55 percentage points and a positive difference interval', () => {
32
+ const trials = ['baseline','intervention'].flatMap((arm) => Array.from({length:20}, (_, i) => ({ arm, status:'succeeded', matches: i < (arm === 'baseline' ? 16 : 5), outcome: {key:'call',label:'read_file'} })));
33
+ trials.push({ arm:'baseline', status:'failed' });
34
+ const summary = summarize(trials);
35
+ assert.equal(summary.baseline.rate, .8); assert.equal(summary.intervention.rate, .25);
36
+ assert.equal(summary.baseline.failed, 1); assert.equal(summary.baseline.successful, 20);
37
+ assert.ok(Math.abs(summary.effect.difference - .55) < 1e-10);
38
+ assert.ok(summary.effect.interval[0] > 0);
39
+ assert.equal(summarize([]).effect, null);
40
+ });
41
+
42
+ test('same tool with different file arguments differs; canonical JSON key order does not', () => {
43
+ const recorded = outcome(response('read_file', '{"path":"auth.ts","start":1}'));
44
+ const target = validateTarget({type:'original_action'}, recorded);
45
+ assert.equal(matchesTarget(outcome(response('read_file','{"start":1,"path":"auth.ts"}')), target), true);
46
+ assert.equal(matchesTarget(outcome(response('read_file','{"path":"billing.ts"}')), target), false);
47
+ assert.equal(matchesTarget(outcome(response()), {type:'tool_contains',name:'read_file',contains:'auth.ts'}), true);
48
+ const answer = outcome({status:'completed',output:[{type:'message',content:[{type:'output_text',text:'The session is valid'}]}]});
49
+ assert.equal(matchesTarget(answer, {type:'answer_contains',contains:'SESSION'}), true);
50
+ assert.throws(() => outcome({status:'incomplete',output:[]}), /incomplete/);
51
+ assert.throws(() => outcome({status:'completed',output:[]}), /No observable/);
52
+ });
53
+
54
+ test('reject unsupported/stateful/hosted tool snapshots and invalid trial budgets', () => {
55
+ const source = entry();
56
+ assert.equal(replayEligibility(source), null);
57
+ assert.match(replayEligibility({...source, provider:'anthropic'}), /Responses/);
58
+ source.payload.previous_response_id = 'resp_old'; assert.match(replayEligibility(source), /server-side/); delete source.payload.previous_response_id;
59
+ source.payload.tools.push({type:'web_search'}); assert.match(replayEligibility(source), /server-executed/);
60
+ assert.throws(() => createExperiment(entry(), config({repetitions:21})), /2–20/);
61
+ assert.throws(() => createExperiment(entry(), config({evidence_id:'wrong:0'})), /exact request/);
62
+ });
63
+
64
+ test('repeated trials invoke both arms and never use the recorded response as a trial', async () => {
65
+ const source = entry(); const original = structuredClone(source.payload); const job = createExperiment(source, config());
66
+ let count = 0;
67
+ await runExperiment(job, source, { random: () => .2, invoke: async (payload) => {
68
+ count++; assert.equal(payload.stream,true); assert.deepEqual(payload.reasoning,{effort:'medium'});
69
+ return payload.input.some((item)=>item.content === 'Search found auth.ts') ? response() : response('search', '{}');
70
+ }});
71
+ assert.equal(count,10); assert.equal(job.status,'completed'); assert.equal(job.summary.baseline.hits,5);
72
+ assert.equal(job.summary.intervention.hits,0); assert.deepEqual(source.payload,original);
73
+ assert.notEqual(job.snapshot_hash,job.variant_hash);
74
+ });
75
+
76
+ test('cancellation and provider errors stop future paid requests and preserve partial counts', async () => {
77
+ const source = entry(); const job = createExperiment(source, config()); const controller = new AbortController();
78
+ await runExperiment(job,source,{signal:controller.signal,invoke:async()=>response(),onUpdate:async()=>{if(job.trials.length===1)controller.abort();}});
79
+ assert.equal(job.status,'cancelled'); assert.equal(job.trials.length,1);
80
+ const failed = createExperiment(source,config());
81
+ await runExperiment(failed,source,{random:()=>0,invoke:async()=>{throw new Error('provider failed');}});
82
+ assert.equal(failed.status,'failed'); assert.equal(failed.trials.length,1);
83
+ assert.equal(failed.summary.baseline.failed,1); assert.equal(failed.summary.baseline.rate,null);
84
+ });
85
+
86
+ test('proposedCommand shows the command a call proposed, without the shell wrapper', async () => {
87
+ const { proposedCommand } = await import('./experiment-engine.mjs');
88
+ assert.equal(proposedCommand('{"cmd":"rm notes.md","workdir":"/workspace"}'), 'rm notes.md');
89
+ assert.equal(proposedCommand({ command: ['bash', '-lc', 'npm test'] }), 'npm test');
90
+ assert.equal(proposedCommand({ command: ['/bin/zsh', '-lc', 'git status'] }), 'git status');
91
+ assert.equal(proposedCommand({ command: ['ls', '-la'] }), 'ls -la');
92
+ assert.equal(proposedCommand('*** Begin Patch\n*** Update File: src/app.ts\n*** End Patch'), 'edited src/app.ts');
93
+ });
@@ -0,0 +1,20 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { explanationRequest, parseExplanations } from './explanations.mjs';
4
+ const sources = [{ evidence_id: 'a', text: 'transaction.js defines returnPayment()' }];
5
+ const hypothesis = { evidence_id: 'a', title: 'The search identified the payment implementation', explanation: 'This earlier search result identifies a file relevant to the task.', excerpt: 'transaction.js defines returnPayment()' };
6
+ const response = (hypotheses) => ({ status: 'completed', output: [{ type: 'message', content: [{ text: JSON.stringify({ hypotheses }) }] }] });
7
+ test('explanations require valid source IDs and exact quotes and remove duplicate titles', () => {
8
+ const result = parseExplanations(response([hypothesis, hypothesis, { ...hypothesis, title: 'Invented', excerpt: 'not in source' }, { ...hypothesis, title: 'Wrong source', evidence_id: 'b' }]), sources);
9
+ assert.equal(result.hypotheses.length, 1);
10
+ assert.equal(result.reported_cost, null);
11
+ assert.deepEqual(parseExplanations(response([]), sources).hypotheses, []);
12
+ assert.throws(() => parseExplanations({ status: 'incomplete' }, sources), /incomplete/);
13
+ });
14
+ test('request is bounded and cache key changes with configured model', () => {
15
+ const step = { decision: { label: 'read transaction.js' }, hypotheses: [], evidence: Array.from({length: 30}, (_, i) => ({ id: String(i), kind: 'user', content: 'x'.repeat(10000) })) };
16
+ const a = explanationRequest(step, 'a/model'); const b = explanationRequest(step, 'b/model');
17
+ assert.notEqual(a.key, b.key);
18
+ assert.ok(a.sources.reduce((sum, item) => sum + item.text.length, 0) <= 16000);
19
+ assert.equal(a.payload.model, 'a/model'); assert.equal(a.payload.tools, undefined);
20
+ });
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Failure signatures: collapse repeat failures ("ENOENT /work/a/x.js",
3
+ * "ENOENT /work/b/x.js") into one cluster, Splunk `cluster`-style.
4
+ * Deliberately conservative (under-clusters): volatile parts only --
5
+ * absolute directory prefixes, hex/uuids, bare numbers, quoted temp
6
+ * names -- are normalized; the failing program, error name and file
7
+ * basename survive, so distinct failures stay distinct.
8
+ */
9
+ import { createHash } from 'node:crypto';
10
+
11
+ const ERRORISH = /error|failed|failure|exception|traceback|not found|no such|denied|enoent|eacces|eperm|econn|timeout|timed out|exit(?:ed)? (?:with )?code|panic|fatal|cannot|unable|invalid|syntaxerror|typeerror|referenceerror/i;
12
+
13
+ const RUNNER_HEADER = /^(wall time:|process exited with code|process running with session|chunk id:|output:$|exit code -?\d+$)/i;
14
+
15
+ function pickLine(text) {
16
+ const all = String(text ?? '').split('\n').map((line) => line.trim()).filter(Boolean);
17
+ // The runner's header ("Process exited with code 1") would cluster every
18
+ // failure of a tool together; the output below it is the real signature.
19
+ const lines = all.filter((line) => !RUNNER_HEADER.test(line));
20
+ const pool = lines.length ? lines : all;
21
+ if (!pool.length) return '';
22
+ return pool.find((line) => ERRORISH.test(line)) ?? pool[0];
23
+ }
24
+
25
+ export function normalizeErrorLine(text) {
26
+ let line = pickLine(text).toLowerCase();
27
+ line = line
28
+ .replace(/\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/gi, '<uuid>')
29
+ .replace(/\b0x[0-9a-f]+\b/gi, '<hex>')
30
+ .replace(/\b[0-9a-f]{16,}\b/gi, '<hex>')
31
+ // Absolute paths: keep only the basename (the file that mattered).
32
+ .replace(/(?:\/[\w.@+~-]+){2,}\/([\w.@+~-]+)/g, '<dir>/$1')
33
+ .replace(/\b\d{4}-\d{2}-\d{2}(?:[t ]\d{2}:\d{2}(?::\d{2})?(?:\.\d+)?z?)?\b/g, '<date>')
34
+ .replace(/\b\d+(?:\.\d+)?\s*(?:ms|s|sec|seconds|bytes|kb|mb|gb)\b/g, '<n>$1')
35
+ .replace(/:\d+(?::\d+)?\b/g, ':<n>') // file:line:col
36
+ .replace(/\bpid[= ]\d+\b/g, 'pid=<n>')
37
+ .replace(/\s+/g, ' ')
38
+ .trim()
39
+ .slice(0, 240);
40
+ return line;
41
+ }
42
+
43
+ /**
44
+ * The cluster for one failure. `signature` is stable across runs of the
45
+ * same failure; `label` is the human line shown for the cluster.
46
+ * Returns null when there is no error text to sign.
47
+ */
48
+ export function failureSignature({ errorText, exitCode = null, toolName = null } = {}) {
49
+ const label = normalizeErrorLine(errorText);
50
+ if (!label && exitCode == null) return null;
51
+ const shown = exitCode != null && !/exit/.test(label) ? `exit ${String(exitCode)} · ${label}`.slice(0, 240) : (label || `exit ${String(exitCode)}`);
52
+ const signature = createHash('sha256')
53
+ .update(JSON.stringify([toolName ?? '', exitCode ?? '', label]))
54
+ .digest('hex').slice(0, 16);
55
+ return { signature, label: shown };
56
+ }
@@ -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
+ }