@raytrace-cli/cli 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/README.md +155 -132
  2. package/bin/raytrace.mjs +51 -26
  3. package/dist/dashboard/assets/dm-sans-latin-400-normal-BwCSEQnW.woff +0 -0
  4. package/dist/dashboard/assets/dm-sans-latin-400-normal-CW0RaeGs.woff2 +0 -0
  5. package/dist/dashboard/assets/dm-sans-latin-500-normal-B9HHJjqV.woff2 +0 -0
  6. package/dist/dashboard/assets/dm-sans-latin-500-normal-Dr3UlScf.woff +0 -0
  7. package/dist/dashboard/assets/dm-sans-latin-600-normal-Aqo67rzb.woff2 +0 -0
  8. package/dist/dashboard/assets/dm-sans-latin-600-normal-BmdmIIQ2.woff +0 -0
  9. package/dist/dashboard/assets/dm-sans-latin-700-normal-CUSSCpQX.woff +0 -0
  10. package/dist/dashboard/assets/dm-sans-latin-700-normal-DvUfVpUG.woff2 +0 -0
  11. package/dist/dashboard/assets/dm-sans-latin-ext-400-normal-BjWJ59Pq.woff +0 -0
  12. package/dist/dashboard/assets/dm-sans-latin-ext-400-normal-BtiwyxMk.woff2 +0 -0
  13. package/dist/dashboard/assets/dm-sans-latin-ext-500-normal-BJfUCQsA.woff2 +0 -0
  14. package/dist/dashboard/assets/dm-sans-latin-ext-500-normal-DR84L5F-.woff +0 -0
  15. package/dist/dashboard/assets/dm-sans-latin-ext-600-normal-4vooXBpG.woff2 +0 -0
  16. package/dist/dashboard/assets/dm-sans-latin-ext-600-normal-DRtaDpgU.woff +0 -0
  17. package/dist/dashboard/assets/dm-sans-latin-ext-700-normal-BLI3TTWz.woff +0 -0
  18. package/dist/dashboard/assets/dm-sans-latin-ext-700-normal-CJIcxD6K.woff2 +0 -0
  19. package/dist/dashboard/assets/ibm-plex-mono-cyrillic-400-normal-BSMlKf0J.woff2 +0 -0
  20. package/dist/dashboard/assets/ibm-plex-mono-cyrillic-400-normal-CEL4l2ZJ.woff +0 -0
  21. package/dist/dashboard/assets/ibm-plex-mono-cyrillic-500-normal-Ael50iVv.woff +0 -0
  22. package/dist/dashboard/assets/ibm-plex-mono-cyrillic-500-normal-Bq9vWWag.woff2 +0 -0
  23. package/dist/dashboard/assets/ibm-plex-mono-cyrillic-600-normal-CTOM6hUh.woff2 +0 -0
  24. package/dist/dashboard/assets/ibm-plex-mono-cyrillic-600-normal-fLZuRloM.woff +0 -0
  25. package/dist/dashboard/assets/ibm-plex-mono-cyrillic-ext-400-normal-DMdlQ8Kv.woff +0 -0
  26. package/dist/dashboard/assets/ibm-plex-mono-cyrillic-ext-400-normal-xuaO2J-f.woff2 +0 -0
  27. package/dist/dashboard/assets/ibm-plex-mono-cyrillic-ext-500-normal-BIfNGwUT.woff +0 -0
  28. package/dist/dashboard/assets/ibm-plex-mono-cyrillic-ext-500-normal-BqneJy0T.woff2 +0 -0
  29. package/dist/dashboard/assets/ibm-plex-mono-cyrillic-ext-600-normal-9HEixskS.woff +0 -0
  30. package/dist/dashboard/assets/ibm-plex-mono-cyrillic-ext-600-normal-V-xxqcpd.woff2 +0 -0
  31. package/dist/dashboard/assets/ibm-plex-mono-latin-400-normal-CvHOgSBP.woff +0 -0
  32. package/dist/dashboard/assets/ibm-plex-mono-latin-400-normal-DMJ8VG8y.woff2 +0 -0
  33. package/dist/dashboard/assets/ibm-plex-mono-latin-500-normal-CB9ihrfo.woff +0 -0
  34. package/dist/dashboard/assets/ibm-plex-mono-latin-500-normal-DSY6xOcd.woff2 +0 -0
  35. package/dist/dashboard/assets/ibm-plex-mono-latin-600-normal-BgSNZQsw.woff2 +0 -0
  36. package/dist/dashboard/assets/ibm-plex-mono-latin-600-normal-DWFSQ4vo.woff +0 -0
  37. package/dist/dashboard/assets/ibm-plex-mono-latin-ext-400-normal-BmRBH3aV.woff2 +0 -0
  38. package/dist/dashboard/assets/ibm-plex-mono-latin-ext-400-normal-D3D2R8hC.woff +0 -0
  39. package/dist/dashboard/assets/ibm-plex-mono-latin-ext-500-normal-CAhNIIs5.woff2 +0 -0
  40. package/dist/dashboard/assets/ibm-plex-mono-latin-ext-500-normal-CZ70TYgx.woff +0 -0
  41. package/dist/dashboard/assets/ibm-plex-mono-latin-ext-600-normal-D38SheWl.woff2 +0 -0
  42. package/dist/dashboard/assets/ibm-plex-mono-latin-ext-600-normal-DmB0ttJJ.woff +0 -0
  43. package/dist/dashboard/assets/ibm-plex-mono-vietnamese-400-normal-BulugwFq.woff2 +0 -0
  44. package/dist/dashboard/assets/ibm-plex-mono-vietnamese-400-normal-DDuiU_S-.woff +0 -0
  45. package/dist/dashboard/assets/ibm-plex-mono-vietnamese-500-normal-C8zxqsMH.woff +0 -0
  46. package/dist/dashboard/assets/ibm-plex-mono-vietnamese-500-normal-DZ4AoWbu.woff2 +0 -0
  47. package/dist/dashboard/assets/ibm-plex-mono-vietnamese-600-normal-D2EvbN8M.woff2 +0 -0
  48. package/dist/dashboard/assets/ibm-plex-mono-vietnamese-600-normal-iLQfcSjf.woff +0 -0
  49. package/dist/dashboard/assets/index-DtV3UdEB.css +1 -0
  50. package/dist/dashboard/assets/index-jyV5iYHJ.js +38 -0
  51. package/dist/dashboard/index.html +2 -2
  52. package/package.json +3 -1
  53. package/proxy/call-assessment.mjs +385 -0
  54. package/proxy/call-category.mjs +461 -0
  55. package/proxy/capture.mjs +31 -0
  56. package/proxy/claude-code-adapter.mjs +46 -3
  57. package/proxy/evidence-store.mjs +617 -15
  58. package/proxy/exec-narrative.mjs +625 -0
  59. package/proxy/execution-correlation.mjs +185 -0
  60. package/proxy/experiment-engine.mjs +7 -4
  61. package/proxy/failure-signature.mjs +56 -0
  62. package/proxy/gvisor-forwarder.mjs +454 -0
  63. package/proxy/init-evidence-db.mjs +136 -12
  64. package/proxy/local-sandboxes.mjs +94 -0
  65. package/proxy/playground.mjs +411 -0
  66. package/proxy/prompt-context.mjs +12 -7
  67. package/proxy/prompt-traces.mjs +6 -0
  68. package/proxy/raytace-proxy.mjs +460 -176
  69. package/proxy/run-recap.mjs +139 -0
  70. package/proxy/runtime-attribution.mjs +110 -0
  71. package/proxy/sandbox-bridge.mjs +46 -0
  72. package/proxy/schema/EVIDENCE_DATABASE.md +276 -0
  73. package/proxy/schema/auxiliary.sql +48 -1
  74. package/proxy/schema/classification.sql +89 -0
  75. package/proxy/schema/file_context.sql +53 -0
  76. package/proxy/schema/runtime_evidence.sql +201 -0
  77. package/proxy/schema/search.sql +66 -0
  78. package/proxy/search.mjs +418 -0
  79. package/proxy/step-attribution.mjs +380 -0
  80. package/proxy/tool-metadata.mjs +36 -0
  81. package/proxy/trace-view.mjs +276 -0
  82. package/proxy/typesafe.mjs +63 -0
  83. package/src/auth.mjs +8 -1
  84. package/src/commands.mjs +80 -12
  85. package/src/lima.mjs +135 -0
  86. package/src/local-sandbox.mjs +324 -0
  87. package/src/proxy-process.mjs +20 -1
  88. package/src/sandbox.mjs +24 -6
  89. package/worker/sandbox/Dockerfile +8 -0
  90. package/worker/sandbox/SYSCALL_CATALOG.md +197 -0
  91. package/worker/sandbox/claude-hook.mjs +331 -0
  92. package/worker/sandbox/collector.py +357 -0
  93. package/worker/sandbox/dns_forwarder.py +255 -0
  94. package/worker/sandbox/engine.py +940 -0
  95. package/worker/sandbox/file_scan.py +491 -0
  96. package/worker/sandbox/lima.yaml +29 -0
  97. package/worker/sandbox/network.py +90 -0
  98. package/worker/sandbox/projects.py +678 -0
  99. package/worker/sandbox/setup.py +159 -0
  100. package/worker/sandbox/syscall_catalog.sql +985 -0
  101. package/worker/sandbox/viewer.py +132 -0
  102. package/dist/dashboard/assets/index-BQ9_JxGq.js +0 -27
  103. package/dist/dashboard/assets/index-L5cUAvhE.css +0 -1
@@ -0,0 +1,94 @@
1
+ /**
2
+ * This machine's local sandboxes, for the proxy: what raytace's sandbox
3
+ * manager answers there, from the CLI's own records instead. Each sandbox is
4
+ * one the CLI made (`raytrace sandbox create --local`, kept in
5
+ * ~/.raytrace/sandboxes.json); its container and state come from the Lima VM
6
+ * (worker/sandbox/projects.py list), and what the kernel saw it do from the
7
+ * fact engine's records there (projects.py activity).
8
+ *
9
+ * limactl is the one the CLI resolved (src/lima.mjs): the user's own, or the
10
+ * one RayTrace downloaded.
11
+ */
12
+ import { spawn } from 'node:child_process';
13
+ import { readFile } from 'node:fs/promises';
14
+ import { join } from 'node:path';
15
+ import { findLima } from '../src/lima.mjs';
16
+
17
+ export const VM = process.env.RAYTRACE_VM || 'raytrace';
18
+ const SANDBOX = /^rtp-[a-f0-9]{32}$/;
19
+ // Listing goes through the VM, a few hundred milliseconds: the forwarder and
20
+ // the dashboard both poll it, so one answer serves for a few seconds.
21
+ const LIST_TTL_MS = 4000;
22
+
23
+ export const limactl = () => process.env.RAYTRACE_LIMACTL || findLima()?.binary || 'limactl';
24
+
25
+ function run(args, { input } = {}) {
26
+ return new Promise((resolve, reject) => {
27
+ const child = spawn(limactl(), args, { stdio: ['pipe', 'pipe', 'pipe'] });
28
+ const out = []; const err = [];
29
+ child.stdout.on('data', (chunk) => out.push(chunk));
30
+ child.stderr.on('data', (chunk) => err.push(chunk));
31
+ child.on('error', reject);
32
+ child.on('close', (code) => (code === 0 ? resolve(Buffer.concat(out).toString('utf8'))
33
+ : reject(new Error(Buffer.concat(err).toString('utf8').trim().split('\n').at(-1) || `limactl exited ${code}`))));
34
+ child.stdin.end(input ?? '');
35
+ });
36
+ }
37
+ const projects = (args) => run(['shell', '--workdir', '/', VM, 'sudo', 'python3', '/opt/raytace/projects.py', ...args]);
38
+
39
+ async function vmRunning() {
40
+ const listed = await run(['list', '--format', '{{.Name}} {{.Status}}']);
41
+ return listed.split('\n').some((line) => line === `${VM} Running`);
42
+ }
43
+
44
+ export function localSandboxes({ dataDir }) {
45
+ const registryFile = join(dataDir, 'sandboxes.json');
46
+ const registry = async () => { try { return JSON.parse(await readFile(registryFile, 'utf8')); } catch { return {}; } };
47
+ let cached = null;
48
+
49
+ /** Every local sandbox: {id, name, status, created, container_id}, and its
50
+ * Playground forks (with fork_of). Throws
51
+ * while the VM is stopped or unreachable, which says nothing about whether
52
+ * the sandboxes exist (the forwarder must not take them for removed). */
53
+ async function list() {
54
+ if (cached && Date.now() - cached.at < LIST_TTL_MS) return cached.value;
55
+ const boxes = await registry();
56
+ if (!Object.keys(boxes).length) return [];
57
+ if (!(await vmRunning())) throw new Error(`the ${VM} VM is not running`);
58
+ const containers = new Map(JSON.parse((await projects(['list'])) || '[]').map((box) => [box.id, box]));
59
+ const value = Object.entries(boxes).map(([id, box]) => {
60
+ const container = containers.get(id);
61
+ return { id, name: box.name, root: box.root ?? null, created: box.created, status: container?.status ?? 'missing',
62
+ container_id: container?.container_id ?? null, size_bytes: container?.size_bytes ?? null };
63
+ });
64
+ // Playground forks of these sandboxes: their own containers, which the
65
+ // forwarder tails like any sandbox. Not sandboxes of the user's: `fork_of` says so.
66
+ for (const box of containers.values()) {
67
+ if (/^rtf-[a-f0-9]{32}$/.test(box.id) && boxes[box.fork_of]) {
68
+ value.push({ id: box.id, name: null, fork_of: box.fork_of, created: box.created, status: box.status,
69
+ container_id: box.container_id ?? null, size_bytes: box.size_bytes ?? null });
70
+ }
71
+ }
72
+ cached = { at: Date.now(), value };
73
+ return value;
74
+ }
75
+
76
+ /** The registry alone, for a listing that must answer with the VM stopped. */
77
+ async function known() {
78
+ const boxes = await registry();
79
+ return Object.entries(boxes).map(([id, box]) => ({ id, name: box.name, root: box.root ?? null, created: box.created }));
80
+ }
81
+
82
+ /** What the kernel saw a sandbox do, by kind (files, network, lookups, ...);
83
+ * since/until are epoch ms, to scope it to one prompt. */
84
+ async function activity(id, { since = 0, until = 0 } = {}) {
85
+ if (!SANDBOX.test(id)) throw new Error('Invalid sandbox id');
86
+ const window = [...(since ? ['--since', String(since)] : []), ...(until ? ['--until', String(until)] : [])];
87
+ return JSON.parse(await projects(['activity', id, ...window]));
88
+ }
89
+
90
+ /** When a sandbox was created, for its session's start (the CLI's record). */
91
+ async function createdAt(id) { return (await registry())[id]?.created ?? null; }
92
+
93
+ return { list, known, activity, createdAt, invalidate: () => { cached = null; } };
94
+ }
@@ -0,0 +1,411 @@
1
+ /**
2
+ * Playground forks: rerun a sandboxed Claude Code session from one step, with
3
+ * that step's context or files changed, and compare where it ends up.
4
+ *
5
+ * A fork is its own sandbox (worker/sandbox/projects.py fork-*), so every path
6
+ * in the session means what it meant originally and the project's real
7
+ * workspace is out of reach. It starts from the snapshot the project folder
8
+ * was at just before the forked step (workspace_snapshots), resumes Claude
9
+ * Code from the session cut at that step (forkTranscript), and is compared
10
+ * file by file with the original run's final snapshot. With a check command
11
+ * (`npm test`, a script), that command then runs where the fork left the
12
+ * project, and its exit code is the fork's pass or fail.
13
+ *
14
+ * Models do not answer the same way twice, so one change can be run several
15
+ * times: a batch is that many forks sharing a `group`, queued and run one
16
+ * after another (one fork runs at a time), each from the same snapshot.
17
+ * A changed batch can bring a baseline: the same step run unchanged as many
18
+ * times, with the same check, interleaved with it so both see the same
19
+ * conditions. An unchanged batch already run that often is reused instead.
20
+ *
21
+ * Lifecycle: queued -> create -> run -> collect -> check (the fork's snapshot history moves into
22
+ * the project's own, so its files outlive it) -> stop. The newest fork is
23
+ * kept, stopped, for a day to look around in; any older one is deleted
24
+ * unless kept on purpose. Fork records are lab_experiments rows (kind fork).
25
+ */
26
+ import { spawn } from 'node:child_process';
27
+ import { limactl, VM } from './local-sandboxes.mjs';
28
+ import { randomBytes } from 'node:crypto';
29
+ import { readdir, readFile } from 'node:fs/promises';
30
+ import { join } from 'node:path';
31
+ import { forkTranscript } from './claude-code-adapter.mjs';
32
+
33
+ export const FORK_ID = /^rtf-[a-f0-9]{32}$/;
34
+ const PROJECT_ID = /^rtp-[a-f0-9]{32}$/;
35
+ // What the resumed session is asked: `claude -p` needs a prompt, so the
36
+ // forked step is one short user message away from the original request.
37
+ export const RESUME_PROMPT = 'Continue the task from where you left off.';
38
+ const KEEP_LATEST_MS = 24 * 3_600_000;
39
+ const DEFAULT_MINUTES = 10;
40
+ // The check has a limit of its own, apart from Claude Code's: a test suite
41
+ // that hangs is a failed check, not a fork stuck forever.
42
+ const CHECK_SECONDS = 10 * 60;
43
+ export const MAX_REPEAT = 10;
44
+ const MAX_EVENTS = 400;
45
+
46
+ /** The command that runs one projects.py action in the local sandbox VM. */
47
+ export function workerCommand(action, id) {
48
+ const args = [action, ...(id ? [id] : [])];
49
+ return [limactl(), ['shell', '--workdir', '/', VM, 'sudo', 'python3', '/opt/raytace/projects.py', ...args]];
50
+ }
51
+
52
+ /** Runs one projects.py action in the VM with a JSON stdin; resolves with its
53
+ * exit code and output. `onLine` sees stdout line by line as it arrives. */
54
+ export function vmAction(action, id, input, { onLine = null, signal = null } = {}) {
55
+ return new Promise((resolve, reject) => {
56
+ const child = spawn(...workerCommand(action, id), { stdio: ['pipe', 'pipe', 'pipe'] });
57
+ let stdout = ''; let stderr = ''; let pending = '';
58
+ child.stdout.on('data', (chunk) => {
59
+ const text = chunk.toString();
60
+ if (!onLine) { stdout += text; return; }
61
+ pending += text;
62
+ const lines = pending.split('\n'); pending = lines.pop();
63
+ for (const line of lines) if (line.trim()) onLine(line);
64
+ });
65
+ child.stderr.on('data', (chunk) => { stderr = (stderr + chunk.toString()).slice(-4000); });
66
+ child.on('error', reject);
67
+ child.on('close', (code) => { if (onLine && pending.trim()) onLine(pending); resolve({ code, stdout, stderr }); });
68
+ signal?.addEventListener('abort', () => child.kill('SIGTERM'), { once: true });
69
+ child.stdin.on('error', () => {});
70
+ child.stdin.end(input == null ? '' : JSON.stringify(input));
71
+ });
72
+ }
73
+
74
+ async function vmJson(action, id, input) {
75
+ const { code, stdout, stderr } = await vmAction(action, id, input);
76
+ if (code !== 0) throw new Error(`${action} failed: ${(stderr.trim().split('\n').at(-1) || `exit ${code}`).slice(0, 300)}`);
77
+ return JSON.parse(stdout.trim().split('\n').at(-1) || '{}');
78
+ }
79
+
80
+ /** The snapshot the project folder was at just before a step: after the last
81
+ * call proposed before it, or when its prompt was sent. Snapshots after a
82
+ * later call never qualify, whatever their time.
83
+ *
84
+ * With neither (a session whose prompt snapshot never arrived), the first
85
+ * snapshot after the step still knows the state just before its own call:
86
+ * its commit when that call changed nothing, else its parent. Only used when
87
+ * that first snapshot belongs to this step or later, so nothing that ran
88
+ * before the step is skipped. */
89
+ export function snapshotBefore(snapshots, { priorCalls, startedAt }) {
90
+ const prior = new Set(priorCalls);
91
+ const started = Date.parse(startedAt ?? '');
92
+ const eligible = snapshots.filter((snap) => (snap.call_id && prior.has(snap.call_id))
93
+ || (snap.taken_on === 'prompt' && Number.isFinite(started) && snap.taken_at_ms <= started + 5_000));
94
+ if (eligible.length) return eligible.at(-1);
95
+ const first = snapshots[0];
96
+ if (!first || (first.call_id && prior.has(first.call_id))) return null;
97
+ const commit = first.changed ? first.parent : first.commit;
98
+ return commit ? { ...first, commit, taken_on: 'before-first-call' } : null;
99
+ }
100
+
101
+ /** Claude Code's stream-json events -> the progress a fork shows while running. */
102
+ export function applyRunEvent(job, event) {
103
+ if (event?.type === 'assistant') {
104
+ for (const block of event.message?.content ?? []) {
105
+ if (block?.type === 'tool_use') {
106
+ job.progress.tool_calls += 1;
107
+ const input = block.input ?? {};
108
+ job.events.push({ at: new Date().toISOString(), kind: 'tool', name: block.name,
109
+ detail: String(input.command ?? input.file_path ?? input.pattern ?? input.url ?? JSON.stringify(input)).slice(0, 300) });
110
+ } else if (block?.type === 'text' && block.text?.trim()) {
111
+ job.events.push({ at: new Date().toISOString(), kind: 'text', detail: block.text.trim().slice(0, 600) });
112
+ }
113
+ }
114
+ } else if (event?.type === 'result') {
115
+ job.result = { text: String(event.result ?? '').slice(0, 20_000), is_error: event.is_error === true, turns: event.num_turns ?? null,
116
+ cost_usd: event.total_cost_usd ?? null, duration_ms: event.duration_ms ?? null };
117
+ }
118
+ if (job.events.length > MAX_EVENTS) job.events.splice(0, job.events.length - MAX_EVENTS);
119
+ }
120
+
121
+ /** `db` keeps the fork records and reads the snapshots. The hosted evidence
122
+ * service runs one Playground per organisation over a shared sandbox host,
123
+ * and passes what that needs: `records` (the organisation's forks, already
124
+ * loaded), `ownsSandbox` (which sandboxes' sessions it may fork), `exclusive`
125
+ * (runs one fork at a time across every Playground on the host), tighter
126
+ * `maxRepeat` and `maxMinutes`, and `orphans: false` (other organisations'
127
+ * forks on the host are not this one's to report). */
128
+ export function startPlayground({ db, transcriptsDir, hookSource, log = console.log, records = null, ownsSandbox = null, exclusive = null,
129
+ maxRepeat = MAX_REPEAT, maxMinutes = 30, orphans = true }) {
130
+ const forks = new Map((records ?? db.loadExperiments(500)).filter((job) => job.kind === 'fork').map((job) => [job.id, job]));
131
+ const controllers = new Map();
132
+ // Forks of a batch waiting their turn, with what they are run from. Only
133
+ // in memory: a restart interrupts them (recover), like a running one.
134
+ const queue = [];
135
+ const save = (job) => { job.updated_at = new Date().toISOString(); db.saveExperiment(job); };
136
+
137
+ /** Which sandboxed session a recorded step belongs to, cut at that step. */
138
+ async function locate(exchangeId, results) {
139
+ for (const sandbox of (await readdir(transcriptsDir).catch(() => [])).filter((name) => PROJECT_ID.test(name))) {
140
+ if (ownsSandbox && !(await ownsSandbox(sandbox))) continue;
141
+ for (const file of (await readdir(join(transcriptsDir, sandbox))).filter((name) => name.endsWith('.jsonl'))) {
142
+ const cut = forkTranscript(await readFile(join(transcriptsDir, sandbox, file), 'utf8'), { spanId: exchangeId, results });
143
+ if (cut) return { sandbox, ...cut };
144
+ }
145
+ }
146
+ return null;
147
+ }
148
+
149
+ /** What forking a step involves, before running anything: whether it can
150
+ * be forked (and why not), the tool results the model had seen by then
151
+ * (what can be edited), the model, and the snapshot it would start from. */
152
+ async function preview(exchangeId) {
153
+ const found = await locate(exchangeId, {});
154
+ if (!found) return { forkable: false, reason: 'Only steps of a Claude Code session run in the sandbox can be forked.' };
155
+ const snapshots = await db.snapshotsForAgentSession({ sessionId: found.sandbox, agentSessionId: found.session });
156
+ const start = snapshotBefore(snapshots, found);
157
+ const calls = new Map();
158
+ for (const line of found.text.split('\n')) {
159
+ let entry; try { entry = JSON.parse(line); } catch { continue; }
160
+ if (entry.isSidechain) continue;
161
+ for (const block of Array.isArray(entry.message?.content) ? entry.message.content : []) {
162
+ if (entry.type === 'assistant' && block?.type === 'tool_use') {
163
+ const input = block.input ?? {};
164
+ calls.set(block.id, { call_id: block.id, name: block.name, detail: String(input.command ?? input.file_path ?? input.pattern ?? input.url ?? JSON.stringify(input)).slice(0, 400), output: null });
165
+ } else if (entry.type === 'user' && block?.type === 'tool_result' && calls.has(block.tool_use_id)) {
166
+ const content = block.content;
167
+ calls.get(block.tool_use_id).output = typeof content === 'string' ? content
168
+ : Array.isArray(content) ? content.map((part) => (part?.type === 'text' ? part.text : part?.type === 'image' ? '[image]' : '')).join('\n') : '';
169
+ }
170
+ }
171
+ }
172
+ const LIMIT = 100_000;
173
+ return { forkable: Boolean(start), reason: start ? null : 'This run was recorded before snapshots existed, so the project cannot be put back as it was.',
174
+ sandbox: found.sandbox, session: found.session, model: found.model, start_snapshot: start?.commit ?? null,
175
+ original_final: snapshots.at(-1)?.commit ?? null, resume_prompt: RESUME_PROMPT,
176
+ results: [...calls.values()].filter((call) => call.output != null).map((call) => ({ ...call,
177
+ chars: call.output.length, truncated: call.output.length > LIMIT, output: call.output.slice(0, LIMIT) })) };
178
+ }
179
+
180
+ /** Read-only snapshot views (projects.py snapshot): list | show | diff. */
181
+ function snapshot(project, request) {
182
+ if (!PROJECT_ID.test(project)) return Promise.reject(new Error('Invalid project sandbox.'));
183
+ return vmJson('snapshot', project, request);
184
+ }
185
+
186
+ async function create(config) {
187
+ const results = config.results && typeof config.results === 'object' ? config.results : {};
188
+ const files = config.files && typeof config.files === 'object' ? config.files : {};
189
+ const workspacePath = (path) => typeof path === 'string' && path && !path.startsWith('/') && !path.split('/').includes('..') && path.length <= 1024;
190
+ for (const [path, text] of Object.entries(files)) {
191
+ if (typeof text !== 'string' || !workspacePath(path)) throw new Error(`Invalid file edit: ${path}`);
192
+ }
193
+ // Excluded files are taken out of the fork's project (their earlier
194
+ // outputs arrive as `results` edits); a message replaces the neutral
195
+ // resume prompt as what the model is told at the forked step.
196
+ const exclude = Array.isArray(config.exclude) ? config.exclude : [];
197
+ if (exclude.length > 200 || !exclude.every(workspacePath)) throw new Error('Invalid excluded file.');
198
+ const message = typeof config.message === 'string' ? config.message.trim() : '';
199
+ if (message.length > 4000) throw new Error('The message must be under 4000 characters.');
200
+ const command = typeof config.check === 'string' ? config.check.trim() : '';
201
+ if (command.length > 2000) throw new Error('The check command must be under 2000 characters.');
202
+ if (controllers.size || queue.length) throw new Error('A fork is already running. Wait for it or delete it first.');
203
+ const repeat = Math.min(maxRepeat, Math.max(1, Math.trunc(Number(config.repeat)) || 1));
204
+ const found = await locate(config.exchange_id, results);
205
+ if (!found) throw new Error('That step is not from a sandboxed Claude Code session, so it cannot be forked.');
206
+ if (found.missing.length) throw new Error(`No result to edit for call(s) before this step: ${found.missing.join(', ')}`);
207
+ const snapshots = await db.snapshotsForAgentSession({ sessionId: found.sandbox, agentSessionId: found.session });
208
+ const start = snapshotBefore(snapshots, found);
209
+ if (!start) throw new Error('No snapshot of the project before this step: the run was recorded before snapshots existed.');
210
+ const minutes = Math.min(maxMinutes, Math.max(1, Number(config.minutes) || DEFAULT_MINUTES));
211
+ const model = typeof config.model === 'string' && config.model ? config.model : found.model;
212
+ const unchanged = !Object.keys(results).length && !Object.keys(files).length && !exclude.length && !message && model === found.model;
213
+ const created_at = new Date().toISOString();
214
+ const batch = ({ transcript, prompt, edits, model: batchModel, unchanged: isUnchanged, baseline = null }) => {
215
+ const group = `rtg-${randomBytes(16).toString('hex')}`;
216
+ return Array.from({ length: repeat }, (_, index) => ({ id: `rtf-${randomBytes(16).toString('hex')}`, kind: 'fork',
217
+ status: 'queued', created_at, group, attempt: index + 1, attempts: repeat, unchanged: isUnchanged, baseline, exchange_id: config.exchange_id,
218
+ parent: found.sandbox, session: found.session, model: batchModel, prompt: prompt || RESUME_PROMPT, message: prompt || null, minutes,
219
+ start_snapshot: start.commit, original_final: snapshots.at(-1)?.commit ?? start.commit, edits, keep: false,
220
+ progress: { tool_calls: 0 }, events: [], result: null, comparison: null, error: null,
221
+ check: command ? { command, status: 'pending', exit_code: null, output: '', duration_ms: null } : null, _input: { transcript } }));
222
+ };
223
+ let base = [];
224
+ let baseline = null;
225
+ if (config.baseline === true && !unchanged) {
226
+ baseline = reusableBaseline({ exchangeId: config.exchange_id, model: found.model, command, runs: repeat });
227
+ if (!baseline) {
228
+ // The unchanged transcript: no tool result edited.
229
+ const plain = await locate(config.exchange_id, {});
230
+ base = batch({ transcript: plain.text, prompt: '', edits: { results: [], files: [], excluded: [] }, model: found.model, unchanged: true });
231
+ baseline = base[0].group;
232
+ }
233
+ }
234
+ const jobs = batch({ transcript: found.text, prompt: message, edits: { results: Object.keys(results), files: Object.keys(files), excluded: exclude },
235
+ model, unchanged, baseline });
236
+ // Change and baseline alternate, so neither gets all the early (or late) runs.
237
+ for (const [index, job] of jobs.entries()) for (const item of [job, base[index]].filter(Boolean)) {
238
+ const { _input, ...record } = item;
239
+ forks.set(record.id, record); save(record);
240
+ queue.push({ job: record, input: { ..._input, files: record.unchanged ? {} : files, exclude: record.unchanged ? [] : exclude } });
241
+ }
242
+ next();
243
+ return forks.get(jobs[0].id);
244
+ }
245
+
246
+ /** An unchanged batch from this step, with this model and check, that
247
+ * already has at least `runs` finished runs: a baseline to compare with. */
248
+ function reusableBaseline({ exchangeId, model, command, runs }) {
249
+ const groups = new Map();
250
+ for (const job of forks.values()) {
251
+ if (!job.unchanged || !job.group || job.exchange_id !== exchangeId || job.model !== model || (job.check?.command ?? '') !== command) continue;
252
+ if (['completed', 'failed'].includes(job.status)) groups.set(job.group, (groups.get(job.group) ?? 0) + 1);
253
+ }
254
+ let best = null;
255
+ for (const [group, count] of groups) if (count >= runs && (!best || count > best.count)) best = { group, count };
256
+ return best?.group ?? null;
257
+ }
258
+
259
+ /** Starts the next queued fork, once none is running. */
260
+ function next() {
261
+ if (controllers.size || !queue.length) return;
262
+ const { job, input } = queue.shift();
263
+ job.status = 'creating'; save(job);
264
+ const controller = new AbortController();
265
+ controllers.set(job.id, controller);
266
+ // On a shared host the fork waits its turn; one deleted meanwhile never starts.
267
+ const start = () => (controller.signal.aborted ? undefined : run(job, input, controller));
268
+ void Promise.resolve(exclusive ? exclusive(start) : start()).catch(() => {}).finally(() => { controllers.delete(job.id); next(); });
269
+ }
270
+
271
+ async function run(job, { transcript, files, exclude }, controller) {
272
+ const deadline = setTimeout(() => { job.timed_out = true; controller.abort(); }, job.minutes * 60_000);
273
+ try {
274
+ await vmJson('fork-create', job.id, { parent: job.parent, commit: job.start_snapshot, session: job.session, transcript, files, delete: exclude, hook: hookSource() });
275
+ job.status = 'running'; save(job);
276
+ log(`[raytace][playground] ${job.id.slice(0, 12)} forked ${job.parent.slice(0, 12)} at snapshot ${job.start_snapshot.slice(0, 8)}; running ${job.model}`);
277
+ let lastSave = 0;
278
+ const { code, stderr } = await vmAction('fork-run', job.id, { session: job.session, model: job.model, prompt: job.prompt }, {
279
+ signal: controller.signal,
280
+ onLine: (line) => {
281
+ try { applyRunEvent(job, JSON.parse(line)); } catch { return; }
282
+ if (Date.now() - lastSave > 1500) { lastSave = Date.now(); save(job); }
283
+ },
284
+ });
285
+ clearTimeout(deadline);
286
+ if (code !== 0 && !job.result) job.error = job.timed_out ? `Stopped after ${job.minutes} minutes.` : (stderr.trim().split('\n').at(-1) || `Claude Code exited with ${code}`).slice(0, 300);
287
+ job.status = 'collecting'; save(job);
288
+ // The Stop hook's last transcript send runs as Claude Code exits.
289
+ await new Promise((resolve) => setTimeout(resolve, 3000));
290
+ const collected = await vmJson('fork-collect', job.id, { original: job.original_final });
291
+ job.comparison = { original: job.original_final, fork: collected.final, changes: collected.changes ?? [],
292
+ same_files: collected.final ? (collected.changes ?? []).length === 0 : null };
293
+ // Checked even when Claude Code failed or ran out of time: what it left
294
+ // behind is still what gets graded.
295
+ if (job.check && !(controller.signal.aborted && !job.timed_out)) {
296
+ // Claude Code's time limit aborted the run's controller; the check
297
+ // gets a fresh one, which deleting the fork still stops.
298
+ if (controller.signal.aborted) { controller = new AbortController(); controllers.set(job.id, controller); }
299
+ await check(job, controller);
300
+ }
301
+ job.status = job.error ? 'failed' : 'completed';
302
+ } catch (error) {
303
+ job.status = 'failed'; job.error = String(error.message ?? error).slice(0, 400);
304
+ } finally {
305
+ clearTimeout(deadline);
306
+ // Never reached the check: the fork could not start, or was deleted.
307
+ if (job.check?.status === 'pending') job.check.status = 'skipped';
308
+ save(job);
309
+ await vmJson('fork-stop', job.id, null).catch(() => {});
310
+ await retire(job.id);
311
+ log(`[raytace][playground] ${job.id.slice(0, 12)} ${job.status}${job.comparison ? `, ${job.comparison.changes.length} file(s) differ from the original` : ''}${job.check ? `, check ${job.check.status}` : ''}${job.error ? `: ${job.error}` : ''}`);
312
+ }
313
+ }
314
+
315
+ /** Runs the fork's check command in its sandbox; exit 0 passes. */
316
+ async function check(job, controller) {
317
+ job.status = 'checking'; job.check.status = 'running'; save(job);
318
+ const started = Date.now();
319
+ try {
320
+ const { code, stdout, stderr } = await vmAction('fork-check', job.id, { command: job.check.command, seconds: CHECK_SECONDS }, { signal: controller.signal });
321
+ if (code !== 0) throw new Error((stderr.trim().split('\n').at(-1) || `exit ${code}`).slice(0, 300));
322
+ const outcome = JSON.parse(stdout.trim().split('\n').at(-1) || '{}');
323
+ Object.assign(job.check, { exit_code: outcome.exit_code, output: outcome.output ?? '',
324
+ status: outcome.timed_out ? 'timed_out' : outcome.exit_code === 0 ? 'passed' : 'failed' });
325
+ } catch (error) {
326
+ // The check could not run at all: neither a pass nor a fail.
327
+ Object.assign(job.check, { status: 'error', output: String(error.message ?? error).slice(0, 400) });
328
+ } finally {
329
+ job.check.duration_ms = Date.now() - started;
330
+ }
331
+ }
332
+
333
+ async function remove(id) {
334
+ const job = forks.get(id);
335
+ if (!job || !FORK_ID.test(id)) throw new Error('Fork not found.');
336
+ const waiting = queue.findIndex((item) => item.job.id === id);
337
+ if (waiting !== -1) {
338
+ // Never started: there is no sandbox to delete.
339
+ queue.splice(waiting, 1);
340
+ job.status = 'cancelled'; job.deleted_at = new Date().toISOString();
341
+ if (job.check) job.check.status = 'skipped';
342
+ save(job); return job;
343
+ }
344
+ controllers.get(id)?.abort();
345
+ await vmJson('fork-delete', id, null).catch((error) => { if (!/No such|not found|Invalid sandbox/i.test(error.message)) throw error; });
346
+ job.deleted_at = new Date().toISOString(); save(job);
347
+ return job;
348
+ }
349
+
350
+ /** Stops a whole batch and a baseline started with it: the queued forks
351
+ * are cancelled, the running one deleted. */
352
+ async function stopGroup(id) {
353
+ const fork = forks.get(id);
354
+ if (!fork?.group) return remove(id);
355
+ // With its baseline, or the change a baseline was started with: stopping
356
+ // one half leaves nothing to compare the other with.
357
+ const groups = new Set([fork.group, fork.baseline].filter(Boolean));
358
+ for (const job of forks.values()) if (job.baseline === fork.group && (queue.some((entry) => entry.job === job) || controllers.has(job.id))) groups.add(job.group);
359
+ for (const item of queue.filter((entry) => groups.has(entry.job.group))) await remove(item.job.id);
360
+ for (const job of forks.values()) if (groups.has(job.group) && controllers.has(job.id)) await remove(job.id);
361
+ return forks.get(id);
362
+ }
363
+
364
+ /** Keeps the newest fork (and any kept on purpose); deletes the rest, and
365
+ * the newest too once it is a day old. */
366
+ async function retire(newest = null) {
367
+ const now = Date.now();
368
+ for (const job of forks.values()) {
369
+ if (job.deleted_at || job.keep || job.status === 'queued' || controllers.has(job.id)) continue;
370
+ const stale = job.id !== newest && (newest || now - Date.parse(job.created_at) > KEEP_LATEST_MS);
371
+ if (stale) await remove(job.id).catch((error) => log(`[raytace][playground] could not delete ${job.id.slice(0, 12)}: ${error.message}`));
372
+ }
373
+ }
374
+
375
+ /** After a restart: a fork that was mid-run cannot be followed any more. */
376
+ async function recover() {
377
+ for (const job of forks.values()) {
378
+ if (['queued', 'creating', 'running', 'collecting', 'checking'].includes(job.status) && !controllers.has(job.id)) {
379
+ if (job.status === 'queued') job.deleted_at = new Date().toISOString(); // never had a sandbox
380
+ job.error = job.status === 'queued' ? 'RayTrace restarted before this run started.' : 'RayTrace restarted while this fork was running.';
381
+ job.status = 'interrupted';
382
+ if (job.check && ['pending', 'running'].includes(job.check.status)) job.check.status = 'error';
383
+ save(job);
384
+ }
385
+ }
386
+ // Fork sandboxes this database has no record of: reported, never deleted,
387
+ // since another RayTrace (a test run, another checkout) may own them.
388
+ const { code, stdout } = orphans ? await vmAction('list', null, null).catch(() => ({ code: 1 })) : { code: 1 };
389
+ if (code === 0) {
390
+ for (const box of JSON.parse(stdout || '[]')) {
391
+ if (FORK_ID.test(box.id) && !forks.has(box.id)) {
392
+ log(`[raytace][playground] fork sandbox ${box.id} is not in this RayTrace's records; delete it with: `
393
+ + workerCommand('fork-delete', box.id).flat().join(' '));
394
+ }
395
+ }
396
+ }
397
+ await retire();
398
+ }
399
+
400
+ return {
401
+ create, remove, stopGroup, recover, preview, snapshot,
402
+ get: (id) => forks.get(id) ?? null,
403
+ list: () => [...forks.values()].sort((a, b) => b.created_at.localeCompare(a.created_at) || (a.attempt ?? 1) - (b.attempt ?? 1)).slice(0, 100),
404
+ keep(id, value = true) {
405
+ const job = forks.get(id); if (!job) throw new Error('Fork not found.');
406
+ job.keep = value === true; save(job); return job;
407
+ },
408
+ /** The fork a sandboxed hook says it is, if it really forks that project. */
409
+ forkOf(forkId, parent) { const job = forks.get(forkId); return job && job.parent === parent && !job.deleted_at ? job : null; },
410
+ };
411
+ }
@@ -9,14 +9,17 @@
9
9
  *
10
10
  * Read from the last request of the turn, whose input is the whole
11
11
  * conversation by the time the answer was written. Deterministic: no model
12
- * call. File operations are inferred from the command text, not observed,
13
- * and "used later" is a
14
- * word-overlap hint, not a measure of what the model weighed.
12
+ * call. A native file tool (Read, Write, Edit) names its file in its
13
+ * arguments; for a shell command the file operations are inferred from the
14
+ * command text. Neither is observed -- the kernel file tables are not
15
+ * populated yet -- and "used later" is a word-overlap hint, not a measure of
16
+ * what the model weighed.
15
17
  *
16
18
  * Sizes are characters; the dashboard turns them into estimated tokens. (The
17
19
  * proxy's JSON redaction blanks any field whose name contains "token".)
18
20
  */
19
21
  import { digest, proposedCommand, textOf } from './experiment-engine.mjs';
22
+ import { nativeFileOperation } from './tool-metadata.mjs';
20
23
 
21
24
  const MAX_EXCERPT_CHARS = 1200;
22
25
  const MAX_EVIDENCE_WORDS = 3;
@@ -181,7 +184,9 @@ export function promptContext(entry, promptText, finalAnswer = '') {
181
184
  } else if (item?.role === 'assistant' && (item.type === 'message' || !item.type)) {
182
185
  answers.push({ index, when: when(index), text: text.slice(0, MAX_EXCERPT_CHARS), chars: text.length });
183
186
  } else if (callTypes.has(item?.type)) {
184
- calls.set(item.call_id, { index, command: fullCommand(item.arguments ?? item.input ?? ''), name: item.name });
187
+ const native = nativeFileOperation(item.name, item.arguments ?? item.input ?? '');
188
+ calls.set(item.call_id, { index, name: item.name, native,
189
+ command: native ? `${item.name} ${native.text}` : fullCommand(item.arguments ?? item.input ?? '') });
185
190
  }
186
191
  });
187
192
  if (tools.length) internals.push({ kind: 'Tools', context_index: 'tools', chars: toolsChars, share: share(toolsChars),
@@ -200,10 +205,10 @@ export function promptContext(entry, promptText, finalAnswer = '') {
200
205
  const call = calls.get(item.call_id);
201
206
  if (!call) return;
202
207
  const body = outputBody(itemText(item));
203
- const ops = fileOperations(call.command);
208
+ const ops = call.native ? [call.native] : fileOperations(call.command);
204
209
  // One output for several commands (`cat a; cat b; echo done`) cannot be
205
210
  // split between them, so each file is marked as sharing it.
206
- const shared = outputSegments(call.command) > 1;
211
+ const shared = !call.native && outputSegments(call.command) > 1;
207
212
  for (const { path, op } of ops) {
208
213
  const key = `${op}:${path}`;
209
214
  const seen = files.get(key);
@@ -213,7 +218,7 @@ export function promptContext(entry, promptText, finalAnswer = '') {
213
218
  const later = laterText(index);
214
219
  const used = [...words].filter((word) => later.includes(word)).slice(0, MAX_EVIDENCE_WORDS);
215
220
  if (!seen) {
216
- files.set(key, { path, op, when: when(index), reads: 1, lines, chars, share: share(chars), shared_output: op !== 'wrote' && shared,
221
+ files.set(key, { path, op, via: call.native ? 'tool' : 'command', when: when(index), reads: 1, lines, chars, share: share(chars), shared_output: op !== 'wrote' && shared,
217
222
  used_later: used, command: call.command, call_id: item.call_id, context_index: index, excerpt: body.slice(0, MAX_EXCERPT_CHARS) });
218
223
  } else {
219
224
  seen.reads += 1; seen.chars += chars; seen.share = share(seen.chars);
@@ -16,6 +16,12 @@ function isBackgroundPrompt(text) {
16
16
  (text.startsWith('Write a brief catch-up for a user returning to this Codex task.') && text.includes('Recent conversation:'));
17
17
  }
18
18
 
19
+ /** A prompt as its author wrote it: without the tags Claude Code wraps
20
+ * pasted text in, which would otherwise be the first line every view shows. */
21
+ export function promptAsWritten(text) {
22
+ return typeof text === 'string' ? text.replace(/<\/?pasted_content\b[^>\n]*>[ \t]*\n?/g, '').trim() || text : text;
23
+ }
24
+
19
25
  export function promptInfo(payload) {
20
26
  const input = payload?.input ?? payload?.messages;
21
27
  if (typeof input === 'string') return !input.trim() || isBackgroundPrompt(input.trim()) ? null : { title: input.trim(), prefix: input, continuation: false };