@raytrace-cli/cli 0.11.1 → 0.13.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,4 @@
1
- <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
2
- <path d="M22 19.2727C22 20.779 20.779 22 19.2727 22H14.7273C13.221 22 12 20.779 12 19.2727V12H19.2727C20.779 12 22 13.221 22 14.7273V19.2727Z" fill="#68C4FF"/>
3
- <path d="M20 2C21.1046 2 22 2.89543 22 4V7C22 8.10457 21.1046 9 20 9H17C15.8954 9 15 8.10457 15 7V4C15 2.89543 15.8954 2 17 2H20Z" fill="#0C79D8"/>
4
- <path d="M7 15C8.10457 15 9 15.8954 9 17V20C9 21.1046 8.10457 22 7 22H4C2.89543 22 2 21.1046 2 20V17C2 15.8954 2.89543 15 4 15H7Z" fill="#0C79D8"/>
5
- <path d="M12 12H4.72727C3.22104 12 2 10.779 2 9.27273V4.72727C2 3.22104 3.22104 2 4.72727 2H9.27273C10.779 2 12 3.22104 12 4.72727V12Z" fill="#2E9EFF"/>
6
- </svg>
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 42 44">
2
+ <style>.top{fill:#edf5dd}.left{fill:#d8e9b7}.right{fill:#b7cf92}.faces{stroke:#647b40}.marks{stroke:#49652a}@media(prefers-color-scheme:dark){.top{fill:#283222}.left{fill:#131b10}.right{fill:#080e07}.faces{stroke:#94b568}.marks{stroke:#e2ffa8}}</style>
3
+ <g class="faces" stroke-width=".7" stroke-linejoin="round"><path class="top" d="M21 2 39 12.5 21 23 3 12.5Z"/><path class="left" d="M3 12.5 21 23V42L3 31.5Z"/><path class="right" d="M21 23 39 12.5V31.5L21 42Z"/></g>
4
+ <g class="marks" fill="none" stroke-width="1.6" stroke-linecap="round"><g transform="matrix(.68 .395 -.68 .395 21 3)"><path d="m10.586 5.414-5.172 5.172m13.172 2.828-5.172 5.172M6 12h12"/><circle cx="12" cy="20" r="2"/><circle cx="12" cy="4" r="2"/><circle cx="20" cy="12" r="2"/><circle cx="4" cy="12" r="2"/></g><g transform="matrix(.68 .395 0 .71 4 13.5)"><path d="m10.586 5.414-5.172 5.172m13.172 2.828-5.172 5.172M6 12h12"/><circle cx="12" cy="20" r="2"/><circle cx="12" cy="4" r="2"/><circle cx="20" cy="12" r="2"/><circle cx="4" cy="12" r="2"/></g><g transform="matrix(.68 -.395 0 .71 22 23)"><path d="m10.586 5.414-5.172 5.172m13.172 2.828-5.172 5.172M6 12h12"/><circle cx="12" cy="20" r="2"/><circle cx="12" cy="4" r="2"/><circle cx="20" cy="12" r="2"/><circle cx="4" cy="12" r="2"/></g></g></svg>
@@ -5,9 +5,9 @@
5
5
  <meta name="viewport" content="width=device-width, initial-scale=1" />
6
6
  <title>RayTrace — Agent trace forensics</title>
7
7
  <meta name="description" content="Evidence-backed traces and live counterfactual forks for coding agents." />
8
- <link rel="icon" href="/favicon.svg" type="image/svg+xml" />
9
- <script type="module" crossorigin src="/assets/index-DepcI8Fi.js"></script>
10
- <link rel="stylesheet" crossorigin href="/assets/index-H97VLD5l.css">
8
+ <link rel="icon" href="/favicon.svg?v=raytrace-box-1" type="image/svg+xml" />
9
+ <script type="module" crossorigin src="/assets/index-DF_klLF4.js"></script>
10
+ <link rel="stylesheet" crossorigin href="/assets/index-CM-3AX0c.css">
11
11
  </head>
12
12
  <body class="antialiased">
13
13
  <div id="root"></div>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@raytrace-cli/cli",
3
- "version": "0.11.1",
3
+ "version": "0.13.0",
4
4
  "description": "See what your coding agent did: traces, tool calls, cost and step-by-step evidence for Claude Code and Codex.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -12,7 +12,8 @@
12
12
  "src/",
13
13
  "proxy/",
14
14
  "worker/",
15
- "dist/dashboard/"
15
+ "dist/dashboard/",
16
+ "THIRD_PARTY_NOTICES.md"
16
17
  ],
17
18
  "engines": {
18
19
  "node": ">=22.13.0"
@@ -37,6 +38,7 @@
37
38
  "class-variance-authority": "0.7.1",
38
39
  "clsx": "2.1.1",
39
40
  "lucide-react": "1.31.0",
41
+ "motion": "^14.14.0",
40
42
  "react": "19.2.6",
41
43
  "react-dom": "19.2.6",
42
44
  "tailwind-merge": "3.6.0",
@@ -56,7 +56,11 @@ function previewOf(item) {
56
56
  * Never upgrades missing evidence into an outcome. */
57
57
  function processOutcome(row) {
58
58
  if (!row?.process_id) return { status: null, error: null };
59
- if (!row.exec_ok && row.failed_errno != null) return { status: 'failed', error: `exec failed: errno ${row.failed_errno}` };
59
+ // A failure the collector inferred has no errno (gVisor reports none for a
60
+ // missing or non-executable program); one gVisor reported has.
61
+ if (!row.exec_ok && (row.failed_errno != null || row.exec_failed)) {
62
+ return { status: 'failed', error: `exec failed: ${row.failed_errno != null ? `errno ${row.failed_errno}` : 'no program started (errno not reported)'}` };
63
+ }
60
64
  if (row.exited_at_ns != null) {
61
65
  if (row.exit_signal) return { status: 'failed', error: `killed by signal ${row.exit_signal}` };
62
66
  if (row.exit_code === 0) return { status: 'completed', error: null };
@@ -74,7 +78,8 @@ const PROCESS_FACTS = `
74
78
  WHERE ev.process_id = p.id AND ev.event_kind IN ('exec_succeeded','exec_failed') ORDER BY ev.stream_sequence LIMIT 1) AS argv_json,
75
79
  (SELECT json_extract(ev.payload_json, '$.errno') FROM runtime_events ev
76
80
  WHERE ev.process_id = p.id AND ev.event_kind = 'exec_failed' ORDER BY ev.stream_sequence DESC LIMIT 1) AS failed_errno,
77
- EXISTS (SELECT 1 FROM runtime_events ev WHERE ev.process_id = p.id AND ev.event_kind = 'exec_succeeded') AS exec_ok`;
81
+ EXISTS (SELECT 1 FROM runtime_events ev WHERE ev.process_id = p.id AND ev.event_kind = 'exec_succeeded') AS exec_ok,
82
+ EXISTS (SELECT 1 FROM runtime_events ev WHERE ev.process_id = p.id AND ev.event_kind = 'exec_failed') AS exec_failed`;
78
83
 
79
84
  export function openEvidenceStore(file, { readOnly = false } = {}) {
80
85
  let journal = 'wal';
@@ -242,6 +242,17 @@ test('a failed execve reads as exec failed on its process', () => withStore((sto
242
242
  assert.deepEqual([child.status, child.error], ['failed', 'exec failed: errno 13']);
243
243
  }));
244
244
 
245
+ test('a failed execve the collector inferred (no errno) still reads as exec failed', () => withStore((store) => {
246
+ const raw = { event_id: 1, kind: 'exec_failed', pid: 61, ppid: 1, argv: ['./missing'], errno: null, inferred: 'no program started after this exec attempt',
247
+ container_id: CONTAINER, process_start_ns: '10', timestamp_ns: '20' };
248
+ store.recordProcessStart({ containerId: CONTAINER, raw, startedMs: 1 });
249
+ captureDemo(store);
250
+ const [candidate] = store.candidatesInWindow(0, Number.MAX_SAFE_INTEGER, { sessionId: SESSION });
251
+ store.attribute({ toolCallId: candidate.call_id, eventId: `gvisor:${CONTAINER}:1`, method: 'inherited' });
252
+ const [child] = store.descendants(['e1']);
253
+ assert.deepEqual([child.status, child.error], ['failed', 'exec failed: no program started (errno not reported)']);
254
+ }));
255
+
245
256
  test('auxiliary features round trip', () => withStore((store) => {
246
257
  store.saveExperiment({ id: 'x1', created_at: new Date().toISOString(), status: 'completed', exchange_id: 'e1', model: 'm' });
247
258
  assert.equal(store.loadExperiments()[0].id, 'x1');
@@ -135,7 +135,9 @@ export function toFailedExec(event, clock = UNMEASURED_CLOCK) {
135
135
  timestamp: observed - clock.offsetMs,
136
136
  start_time_ns: typeof event.process_start_ns === 'string' ? event.process_start_ns : null,
137
137
  status: 'failed',
138
- error: `exec failed: errno ${Number.isFinite(Number(event.errno)) ? Number(event.errno) : 'unknown'}`,
138
+ // The collector infers a failure gVisor reports no errno for (a missing or
139
+ // non-executable program): errno is null there, never 0.
140
+ error: `exec failed: ${event.errno != null && Number.isFinite(Number(event.errno)) ? `errno ${Number(event.errno)}` : 'no program started (errno not reported)'}`,
139
141
  ended_at: at,
140
142
  container_id: typeof event.container_id === 'string' ? event.container_id : null,
141
143
  raw: event,
@@ -313,6 +313,8 @@ test('a failed execve under a matched command gets its own failed row instead of
313
313
  assert.equal(descended[0].exec.ended_at, new Date(BASE + 5).toISOString());
314
314
  assert.equal(tracker.live.has(101), false, 'nothing ran, so nothing is tracked');
315
315
  assert.equal(toFailedExec({ ...failed, argv: [], executable: '' }), null);
316
+ // Inferred by the collector: gVisor gave no errno, and null must not read as errno 0.
317
+ assert.equal(toFailedExec({ ...failed, errno: null }).error, 'exec failed: no program started (errno not reported)');
316
318
  });
317
319
 
318
320
  test('an exit with no in-memory link (proxy restarted) is closed by pid + start time', async () => {
package/src/lima.mjs CHANGED
@@ -107,7 +107,7 @@ export async function checks({ vmRunning = false, runInVm = null } = {}) {
107
107
  const row = (ok, label, detail, fix) => rows.push({ ok, label, detail, fix });
108
108
  const platform = process.platform;
109
109
 
110
- if (platform === 'win32') row(null, 'platform', 'Windows: local sandboxes are experimental here (Lima on Windows is)');
110
+ if (platform === 'win32') row(null, 'platform', 'Windows: local sandboxes are experimental here (Lima on Windows is); the workable paths are WSL2 and cloud sandboxes: https://github.com/Godcreatebugs/raytrace-cli/blob/main/docs/windows.md');
111
111
  else if (platform !== 'darwin' && platform !== 'linux') row(false, 'platform', `${platform} is not supported for local sandboxes`);
112
112
 
113
113
  const lima = findLima();
@@ -115,7 +115,10 @@ export async function checks({ vmRunning = false, runInVm = null } = {}) {
115
115
  else if (canDownload()) {
116
116
  row(null, 'lima', `${lima?.old ? `${lima.old} is older than ${MINIMUM.join('.')}` : 'not installed'}; RayTrace downloads Lima ${LIMA_VERSION} on the first \`raytrace sandbox create --local\``);
117
117
  } else {
118
- row(false, 'lima', lima?.old ? `${lima.old} is older than ${MINIMUM.join('.')}` : 'not installed', 'install Lima: https://lima-vm.io/docs/installation/');
118
+ row(false, 'lima', lima?.old ? `${lima.old} is older than ${MINIMUM.join('.')}` : 'not installed',
119
+ platform === 'win32'
120
+ ? 'Lima has no native Windows build and RayTrace does not download it there; use WSL2 or a cloud sandbox: https://github.com/Godcreatebugs/raytrace-cli/blob/main/docs/windows.md'
121
+ : 'install Lima: https://lima-vm.io/docs/installation/');
119
122
  }
120
123
 
121
124
  if (platform === 'darwin') {
package/src/report.mjs ADDED
@@ -0,0 +1,178 @@
1
+ // `raytrace report <trace-id> [--pr <n>]`: a short pull-request comment for one
2
+ // recorded prompt: the commands it ran with their exit codes, the files it
3
+ // changed, what failed and what it cost, and (with --link, for a cloud
4
+ // sandbox) a share link. Only command text and file paths go in, never tool
5
+ // output, and the text is scanned for secrets before it leaves this machine.
6
+ //
7
+ // The trace comes from this machine's evidence database, as `raytrace export`
8
+ // reads it, or from RayTrace cloud for a cloud sandbox (--sandbox rtp-…).
9
+ // Posting goes through the GitHub CLI (`gh`), signed in as you: the comment
10
+ // it made before on that pull request is updated, never another comment.
11
+ import { spawnSync } from 'node:child_process';
12
+ import { existsSync } from 'node:fs';
13
+ import { paths } from './paths.mjs';
14
+ import { call } from './api.mjs';
15
+
16
+ const SANDBOX = /^rtp-[a-f0-9]{32}$/;
17
+ export const MARKER = '<!-- raytrace-report -->';
18
+ const DASHBOARD = process.env.RAYTRACE_DASHBOARD_URL || 'https://app.raytracer.si';
19
+ const MAX_COMMANDS = 30;
20
+ const MAX_FILES = 40;
21
+ const COMMAND_CHARS = 120;
22
+ const WRITE_TOOLS = new Set(['Write', 'Edit', 'MultiEdit', 'NotebookEdit', 'apply_patch']);
23
+
24
+ // What a key or token looks like. A `name=value` match keeps the name.
25
+ const SECRETS = [
26
+ /-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z ]*PRIVATE KEY-----|$)/g,
27
+ /\bsk-ant-[A-Za-z0-9_-]{16,}/g,
28
+ /\bsk-or-[A-Za-z0-9_-]{16,}/g,
29
+ /\bsk-(?:proj-)?[A-Za-z0-9_-]{20,}/g,
30
+ /\bgh[pousr]_[A-Za-z0-9]{20,}/g,
31
+ /\bgithub_pat_[A-Za-z0-9_]{20,}/g,
32
+ /\b(?:AKIA|ASIA)[A-Z0-9]{16}\b/g,
33
+ /\bxox[abprs]-[A-Za-z0-9-]{10,}/g,
34
+ /\b[Bb]earer\s+[A-Za-z0-9._~+/-]{16,}=*/g,
35
+ ];
36
+ const NAMED_SECRET = /((?:api[_-]?key|access[_-]?key|token|secret|password|passwd|pwd)["']?\s*[:=]\s*["']?)(?!\[REDACTED\])[^\s"'&]{8,}/gi;
37
+
38
+ /** The text with anything that looks like a secret replaced, and how many were. */
39
+ export function redactSecrets(text) {
40
+ let count = 0;
41
+ let out = String(text ?? '');
42
+ for (const pattern of SECRETS) out = out.replace(pattern, () => { count += 1; return '[REDACTED]'; });
43
+ out = out.replace(NAMED_SECRET, (_, name) => { count += 1; return `${name}[REDACTED]`; });
44
+ return { text: out, count };
45
+ }
46
+
47
+ const oneLine = (text, max) => {
48
+ const flat = String(text ?? '').replace(/\s+/g, ' ').trim();
49
+ return flat.length > max ? `${flat.slice(0, max - 1)}…` : flat;
50
+ };
51
+ // Inside a table cell: no pipes or backticks can end the cell or the code.
52
+ const cell = (text) => `<code>${text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\|/g, '&#124;')}</code>`;
53
+
54
+ function outcome(call) {
55
+ if (typeof call.exit_code === 'number') return { label: call.exit_code === 0 ? '✅ 0' : `❌ ${call.exit_code}`, failed: call.exit_code !== 0 };
56
+ if (call.status === 'failed' || call.error) return { label: '❌ failed', failed: true };
57
+ if (!call.verified) return { label: '⚪ not seen', failed: false };
58
+ return { label: '✅ ran', failed: false };
59
+ }
60
+
61
+ /** What the comment says, worked out from a trace (proxy/trace-view.mjs). */
62
+ export function summarize(trace) {
63
+ const calls = trace.callVerifications ?? [];
64
+ const commands = calls.filter((c) => c.kind === 'command' && c.proposed).map((c) => ({ text: c.proposed, ...outcome(c) }));
65
+ const files = new Map();
66
+ for (const c of calls) {
67
+ for (const change of c.snapshot?.changes ?? []) {
68
+ if (typeof change?.path === 'string') files.set(change.path, { status: change.status ?? null, added: change.added ?? null, removed: change.removed ?? null });
69
+ }
70
+ if (c.kind === 'file' && WRITE_TOOLS.has(c.name) && typeof c.proposed === 'string' && !files.has(c.proposed)) files.set(c.proposed, { status: null });
71
+ }
72
+ let cost = null;
73
+ for (const r of trace.requests ?? []) if (r.cost != null) cost = (cost ?? 0) + r.cost;
74
+ return { commands, failed: commands.filter((c) => c.failed).length, files: [...files].map(([path, info]) => ({ path, ...info })), cost };
75
+ }
76
+
77
+ /** The comment's Markdown, secrets already removed. `link`: {url, expires} or null. */
78
+ export function formatReport(trace, { link = null, linkNote = null } = {}) {
79
+ const { commands, failed, files, cost } = summarize(trace);
80
+ const lines = [MARKER, '### RayTrace run report', ''];
81
+ lines.push(`**Status:** ${trace.status ?? 'unknown'} · **Model:** ${trace.model ?? 'unknown'} · **Cost:** ${cost != null ? `$${cost.toFixed(4)}` : 'unknown'}`);
82
+ lines.push(`**Commands:** ${commands.length} · **Failed:** ${failed} · **Files changed:** ${files.length}`);
83
+ lines.push('');
84
+ if (commands.length) {
85
+ lines.push('| Exit | Command |', '| --- | --- |');
86
+ // Failures first: they are what a reviewer needs.
87
+ const ordered = [...commands.filter((c) => c.failed), ...commands.filter((c) => !c.failed)];
88
+ for (const c of ordered.slice(0, MAX_COMMANDS)) lines.push(`| ${c.label} | ${cell(oneLine(c.text, COMMAND_CHARS))} |`);
89
+ if (commands.length > MAX_COMMANDS) lines.push('', `…and ${commands.length - MAX_COMMANDS} more commands.`);
90
+ lines.push('');
91
+ } else lines.push('No commands were run.', '');
92
+ if (files.length) {
93
+ lines.push(`<details><summary>Files changed (${files.length})</summary>`, '');
94
+ for (const f of files.slice(0, MAX_FILES)) {
95
+ const size = f.added != null || f.removed != null ? ` +${f.added ?? 0} −${f.removed ?? 0}` : '';
96
+ lines.push(`- ${cell(oneLine(f.path, 200))}${f.status ? ` ${f.status}` : ''}${size}`);
97
+ }
98
+ if (files.length > MAX_FILES) lines.push(`- …and ${files.length - MAX_FILES} more`);
99
+ lines.push('', '</details>', '');
100
+ }
101
+ if (link) {
102
+ const expires = link.expires ? ` (the link expires ${new Date(link.expires * 1000).toISOString().replace('T', ' ').slice(0, 16)} UTC)` : '';
103
+ lines.push(`[Open this run in RayTrace](${link.url})${expires}`, '');
104
+ } else if (linkNote) lines.push(`_${linkNote}_`, '');
105
+ lines.push(`<sub>Trace \`${oneLine(trace.id, 80).replace(/`/g, '')}\` · recorded by RayTrace: commands as the agent ran them, exit codes as the sandbox saw them.</sub>`);
106
+ const { text, count } = redactSecrets(lines.join('\n'));
107
+ return count ? `${text}\n\n_${count} value${count === 1 ? '' : 's'} that looked like secrets ${count === 1 ? 'was' : 'were'} hidden._` : text;
108
+ }
109
+
110
+ async function localTrace(traceId) {
111
+ if (!existsSync(paths.database)) return null;
112
+ const { openEvidenceStore } = await import('../proxy/evidence-store.mjs');
113
+ const { readTraces } = await import('../proxy/trace-view.mjs');
114
+ const store = openEvidenceStore(paths.database, { readOnly: true });
115
+ try {
116
+ return (await readTraces(store, { turnId: traceId, includeHistory: true, evidence: true })).find((t) => t.id === traceId) ?? null;
117
+ } finally { store.close(); }
118
+ }
119
+
120
+ async function cloudTrace(traceId, sandbox, api) {
121
+ const data = await api('GET', `/v1/evidence/traces?sandbox=${sandbox}&scope=history&evidence=1`);
122
+ return (data.traces ?? []).find((t) => t.id === traceId) ?? null;
123
+ }
124
+
125
+ /** A share link, or why there is none: the link is only ever extra. */
126
+ async function shareLink(trace, api) {
127
+ if (!SANDBOX.test(trace.sandboxId ?? '')) return { link: null, note: 'No share link: this run was in a local sandbox.' };
128
+ try {
129
+ const made = await api('POST', '/v1/shares', { body: JSON.stringify({ trace_id: trace.id, sandbox_id: trace.sandboxId, allow_fork: false }),
130
+ headers: { 'content-type': 'application/json' } });
131
+ return { link: { url: new URL(made.url, DASHBOARD).href, expires: made.share?.expires ?? null }, note: null };
132
+ } catch (error) {
133
+ if (error?.data?.code === 'share_limit') return { link: null, note: 'No share link: your plan\'s share links are all in use.' };
134
+ return { link: null, note: `No share link: ${oneLine(error?.message, 120)}.` };
135
+ }
136
+ }
137
+
138
+ function gh(args, input) {
139
+ const run = spawnSync('gh', args, { input, encoding: 'utf8', maxBuffer: 32 * 1024 * 1024 });
140
+ if (run.error?.code === 'ENOENT') throw Object.assign(new Error('GitHub CLI (gh) not found'), { code: 'ENOENT' });
141
+ if (run.status !== 0) throw new Error(`gh ${args[0]} failed: ${oneLine(run.stderr || run.stdout, 300)}`);
142
+ return run.stdout;
143
+ }
144
+
145
+ /** Posts the report on pull request `pr`, or updates the one this user posted there before. */
146
+ export function postComment(pr, body, run = gh) {
147
+ const login = run(['api', 'user', '--jq', '.login']).trim();
148
+ const pages = JSON.parse(run(['api', `repos/{owner}/{repo}/issues/${pr}/comments`, '--paginate', '--slurp']) || '[]');
149
+ const mine = pages.flat().filter((c) => c?.user?.login === login && String(c.body ?? '').startsWith(MARKER)).at(-1);
150
+ const payload = JSON.stringify({ body });
151
+ if (mine) run(['api', '-X', 'PATCH', `repos/{owner}/{repo}/issues/comments/${mine.id}`, '--input', '-', '--silent'], payload);
152
+ else run(['api', '-X', 'POST', `repos/{owner}/{repo}/issues/${pr}/comments`, '--input', '-', '--silent'], payload);
153
+ return mine ? 'updated' : 'created';
154
+ }
155
+
156
+ export async function reportCommand(traceId, { pr = null, sandbox = null, link = false, dryRun = false } = {},
157
+ { loadLocal = localTrace, api = call, post = postComment, say = console.log } = {}) {
158
+ const id = String(traceId ?? '').trim();
159
+ if (!id) throw new Error('Trace ID is required. Usage: raytrace report <trace-id> [--pr <number>] [--sandbox <rtp-id>] [--link] [--dry-run]');
160
+ if (sandbox != null && !SANDBOX.test(sandbox)) throw new Error(`Not a cloud sandbox id: ${sandbox}. It looks like rtp- and 32 letters and digits.`);
161
+ if (pr != null && !/^[1-9]\d{0,9}$/.test(String(pr))) throw new Error(`Not a pull request number: ${pr}`);
162
+ const trace = (await loadLocal(id)) ?? (sandbox ? await cloudTrace(id, sandbox, api) : null);
163
+ if (!trace) throw new Error(sandbox ? `Trace not found in sandbox ${sandbox}: ${id}` : `Trace not found on this machine: ${id}. For a cloud sandbox, add --sandbox <rtp-id>.`);
164
+ // A link uses up one of the plan's share links, so only on request, and never on a dry run.
165
+ const shared = link && !dryRun ? await shareLink(trace, api) : { link: null, note: null };
166
+ const body = formatReport(trace, { link: shared.link, linkNote: shared.note });
167
+ if (!pr || dryRun) { say(body); return { body, posted: null }; }
168
+ try {
169
+ const posted = post(pr, body);
170
+ say(`Report ${posted} on pull request #${pr}.`);
171
+ return { body, posted };
172
+ } catch (error) {
173
+ if (error.code !== 'ENOENT') throw error;
174
+ say('The GitHub CLI (gh) is not installed, so nothing was posted. Here is the comment to paste:\n');
175
+ say(body);
176
+ return { body, posted: null };
177
+ }
178
+ }
@@ -87,7 +87,7 @@ infer them from the collector host.
87
87
  | `capture` | Meaning | Rows |
88
88
  | --- | --- | --- |
89
89
  | `yes` | Its gVisor trace point is subscribed, with the optional fields in `capture_fields`. | `open`, `openat`, `creat`, `connect`, `listen`, `setuid`, `setgid`, `setresuid`, `setresgid` |
90
- | `watcher` | Only its raw exit point is subscribed: which process, when, and whether it was refused. gVisor does not decode its path, so the host's file watcher supplies the name. | `unlink`, `unlinkat`, `rmdir`, `rename`, `renameat`, `renameat2`, `truncate`, `ftruncate`, `mkdir`, `mkdirat`, `chmod`, `fchmod`, `fchmodat` |
90
+ | `watcher` | Its raw points are subscribed: which process, when, and whether it was refused. Both of them, because gVisor fills the exit event's process and sandbox from the fields asked of the enter point; the enter event itself is discarded. gVisor does not decode its path, so the host's file watcher supplies the name. | `unlink`, `unlinkat`, `rmdir`, `rename`, `renameat`, `renameat2`, `truncate`, `ftruncate`, `mkdir`, `mkdirat`, `chmod`, `fchmod`, `fchmodat` |
91
91
  | `sentry` | Seen through gVisor's own process points (clone, exec, exit), whatever syscall caused them. | `clone`, `clone3`, `fork`, `vfork`, `execve`, `execveat`, `exit`, `exit_group` |
92
92
  | `no` | Not captured. | everything else |
93
93
 
@@ -150,7 +150,7 @@ outcome. A missing exit result is unknown, not success. Apply the row-specific
150
150
  | `connect_effect` | Decode the address family, IP address and port. A zero result is a connection on a stream socket and only a default peer on a datagram socket. `EINPROGRESS` is an attempt whose outcome this call does not report. A destination in a range the sandbox firewall rejects is a refused attempt. The address is never a host name: a name shown beside it comes from DNS evidence and is a best match. No payload is captured. |
151
151
  | `listen_effect` | Success means the process accepts connections on the bound address. Nothing outside the sandbox network is routed to it. |
152
152
  | `identity_effect` | Record the requested IDs and the result. Success changes the identity the process acts as; the sandbox has no capabilities, so a successful change away from its one user is unexpected, and a failure is an attempt. |
153
- | `process_lifecycle` | gVisor's clone, exec and exit points report every task, program start and exit, whichever syscall caused it. A successful exec proves a program started, not what it did; a zero result on the exec syscall point is not treated as success. Keep arguments as observed and, of the environment, only the two `RAYTRACE_` markers. |
153
+ | `process_lifecycle` | gVisor's clone, exec and exit points report every task, program start and exit, whichever syscall caused it. A successful exec proves a program started, not what it did; a zero result on the exec syscall point is not treated as success, since gVisor's execve returns 0 before it loads the program. A missing or non-executable program is therefore inferred: an attempt no program start follows, by the time the process tries other arguments or exits, is recorded as `exec_failed` with no errno (`collector.py` `ExecAttempts`). Keep arguments as observed and, of the environment, only the two `RAYTRACE_` markers. |
154
154
  | `not_classified` | The call is listed and grouped, and nothing is collected for it. No fact records its use and none rules it out. |
155
155
 
156
156
  For example, successful `unlinkat` can display **L3 · Delete · Succeeded**;
@@ -55,12 +55,42 @@ const MAX_QUEUED_BYTES = 128 * 1024;
55
55
  const listed = (value) => (Array.isArray(value) ? value.filter((file) => typeof file === 'string' && file) : []);
56
56
  let restricted = [];
57
57
  let watched = [];
58
+ // `blocked`: programs the owner forbids; a command that starts one is refused.
59
+ let blocked = [];
58
60
  try {
59
61
  const lists = JSON.parse(readFileSync(new URL('./guardrails.json', import.meta.url), 'utf8'));
60
62
  restricted = listed(lists.restricted);
61
63
  watched = listed(lists.watched);
64
+ blocked = listed(lists.blocked);
62
65
  } catch { /* nothing is restricted or watched */ }
63
66
 
67
+ // Prefixes that start the program after them rather than being the program.
68
+ const WRAPPERS = new Set(['sudo', 'doas', 'env', 'nohup', 'time', 'nice', 'exec', 'command', 'builtin', 'stdbuf']);
69
+ // A wrapper's options that take the next word as their value (sudo -u root, nice -n 5).
70
+ const VALUED = new Set(['-u', '-g', '-n', '-C', '-p']);
71
+
72
+ /** The programs a command line starts, by name: the first word of each part
73
+ * between ; & | ( ) ` and new lines, past VAR=value and wrappers, with any
74
+ * path taken off (/usr/bin/curl is curl). Text only: `sh -c 'curl ...'` names
75
+ * sh, which is why the kernel's view (facts.py) is the check that holds. */
76
+ function firstPrograms(command) {
77
+ const programs = [];
78
+ for (const part of String(command).split(/[;&|()`\n]+/)) {
79
+ let value = false;
80
+ for (const raw of part.trim().split(/\s+/)) {
81
+ const word = raw.replace(/^\\/, '').replace(/^['"]+|['"]+$/g, '');
82
+ if (value) { value = false; continue; }
83
+ if (!word || /^[A-Za-z_][A-Za-z0-9_]*=/.test(word)) continue;
84
+ const name = word.split('/').pop();
85
+ if (word.startsWith('-')) { value = VALUED.has(word); continue; }
86
+ if (WRAPPERS.has(name)) continue;
87
+ if (name) programs.push(name);
88
+ break;
89
+ }
90
+ }
91
+ return programs;
92
+ }
93
+
64
94
  /** A file the tool named, relative to the project; null when it is outside it. */
65
95
  const inside = (named) => {
66
96
  if (typeof named !== 'string' || !named) return null;
@@ -97,14 +127,23 @@ if (input.hook_event_name === 'PreToolUse') {
97
127
  // says what it mentions, not what it does. The file lock is what stops it.
98
128
  if (input.tool_name === 'Bash' && typeof command === 'string') {
99
129
  for (const path of restricted.slice(0, 200)) if (command.includes(path)) queue({ kind: 'named', path });
130
+ // A program the owner blocked is refused before anything else answers for the command.
131
+ const refused = blocked.length ? firstPrograms(command).find((program) => blocked.includes(program)) : undefined;
132
+ if (refused) {
133
+ queue({ kind: 'command_blocked', path: refused });
134
+ process.stdout.write(JSON.stringify({ hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny',
135
+ permissionDecisionReason: `RayTrace: ${refused} is blocked by this project's owner and cannot be run. `
136
+ + 'Do not try another way to run it (a full path, sh -c, another tool): the sandbox records every program that runs. '
137
+ + 'Tell the user it has to be unblocked under Initial scan in the RayTrace dashboard.' } }));
138
+ process.exit(0);
139
+ }
100
140
  }
101
141
  if (input.tool_name === 'Bash' && /^[A-Za-z0-9_-]{1,128}$/.test(id ?? '') && typeof command === 'string') {
102
142
  // An input change needs a decision with it. Only a session that already
103
143
  // skips permission prompts gets "allow"; any other still asks as usual,
104
- // unless running in headless/CI agent mode (CI, GitHub Actions, or RAYTRACE_ALLOW_ALL/RAYTRACE_HEADLESS=1).
105
- const isCI = process.env.CI === 'true' || process.env.CI === '1' || Boolean(process.env.GITHUB_ACTIONS);
106
- const allowAll = isCI || process.env.RAYTRACE_ALLOW_ALL === '1' || process.env.RAYTRACE_ALLOW_ALL === 'true'
107
- || process.env.RAYTRACE_HEADLESS === '1' || process.env.HEADLESS === '1';
144
+ // unless RAYTRACE_ALLOW_ALL is set on purpose. Ambient variables (CI, GITHUB_ACTIONS, HEADLESS) are set by
145
+ // runners and wrappers without anyone choosing to skip the prompts, so they are not honoured.
146
+ const allowAll = process.env.RAYTRACE_ALLOW_ALL === '1' || process.env.RAYTRACE_ALLOW_ALL === 'true';
108
147
  const isBypass = input.permission_mode === 'bypassPermissions' || input.permission_mode === 'dontAsk';
109
148
  const decision = (isBypass || allowAll) ? 'allow' : 'ask';
110
149
  process.stdout.write(JSON.stringify({ hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: decision,
@@ -225,6 +225,69 @@ def with_raw(event, packet):
225
225
  return event
226
226
 
227
227
 
228
+ class ExecAttempts:
229
+ """Tells a failed exec from the events around it, one sandbox at a time.
230
+
231
+ gVisor never reports that an exec failed for want of a program. Its execve
232
+ returns 0 at once and loads the program afterwards (kernel/task_exec.go),
233
+ so the call's exit point says errno 0 whether the file was there or not,
234
+ and a missing or non-executable file only shows as what does not follow:
235
+ no `exec_succeeded` (sentry/execve) for that process. So an attempt is
236
+ held until the process says which it was:
237
+
238
+ exec_succeeded the attempt, and any before it with the same
239
+ arguments (a shell trying each folder of PATH), led
240
+ to a program: nothing failed
241
+ another attempt with other arguments: the held ones failed
242
+ process_exit the held ones failed
243
+
244
+ A failure found this way is an `exec_failed` event with no errno (gVisor
245
+ gave none) and `inferred` saying why. The folders of one PATH search are
246
+ one failure, listed in `tried`, not one each. An attempt still held when
247
+ the stream ends is dropped: nothing says how it went."""
248
+ LIMIT = 20_000
249
+
250
+ def __init__(self):
251
+ self.held = {} # pid -> [the attempts since its last program started]
252
+
253
+ def see(self, event):
254
+ """The failed execs this event settles, as events to record."""
255
+ kind, pid = event.get('kind'), event.get('pid')
256
+ if kind == 'exec_attempt':
257
+ held = self.held.get(pid)
258
+ failed = self.failures(self.held.pop(pid)) if held and held[-1].get('argv') != event.get('argv') else []
259
+ if len(self.held) >= self.LIMIT: # exits that never arrived
260
+ self.held.clear()
261
+ self.held.setdefault(pid, []).append(event)
262
+ return failed
263
+ if kind == 'exec_failed':
264
+ # gVisor did report this one (a bad pointer, a path too long): it is recorded as it came.
265
+ held = self.held.get(pid)
266
+ if held:
267
+ held.pop()
268
+ if not held:
269
+ del self.held[pid]
270
+ return []
271
+ if kind == 'exec_succeeded':
272
+ self.held.pop(pid, None)
273
+ return []
274
+ if kind == 'process_exit':
275
+ return self.failures(self.held.pop(pid, []))
276
+ return []
277
+
278
+ @staticmethod
279
+ def failures(attempts):
280
+ found = []
281
+ for attempt in attempts:
282
+ if found and found[-1].get('argv') == attempt.get('argv'):
283
+ if len(found[-1]['tried']) < 32:
284
+ found[-1]['tried'].append(attempt.get('executable'))
285
+ continue
286
+ found.append({**attempt, 'kind': 'exec_failed', 'errno': None, 'tried': [attempt.get('executable')],
287
+ 'inferred': 'no program started after this exec attempt; gVisor reports no errno for it'})
288
+ return found
289
+
290
+
228
291
  def init_db(path):
229
292
  db = sqlite3.connect(path, timeout=10)
230
293
  db.execute('PRAGMA journal_mode=WAL')
@@ -291,8 +354,41 @@ class Writer(threading.Thread):
291
354
  if wrote_heartbeat:
292
355
  self.last_heartbeat = now
293
356
 
357
+ def close_orphaned_streams(self, db):
358
+ """Ends the streams an earlier collector left open, at their last heartbeat.
359
+
360
+ A connection records its own collector_disconnected when gVisor closes
361
+ it, but that runs on a daemon thread: when the collector itself stops
362
+ (a restart, an update, a crash) nothing is written, and the stream looks
363
+ open forever. gVisor does not reconnect a running sandbox to the new
364
+ collector, so recording has stopped until that sandbox restarts. Record
365
+ the cut-out in the earlier collector's name, at the last moment it was
366
+ known to be alive. Only safe once this collector holds the socket, so no
367
+ other collector can still be writing. Returns the streams it closed."""
368
+ with db:
369
+ orphans = db.execute('SELECT id, collector_id, container_id, heartbeat_ms FROM capture_streams '
370
+ 'WHERE ended_ms IS NULL AND collector_id <> ?', (self.instance_id,)).fetchall()
371
+ for connection, collector, container, heartbeat in orphans:
372
+ db.execute('UPDATE capture_streams SET ended_ms=? WHERE id=?', (heartbeat, connection))
373
+ if not container:
374
+ continue # no event ever named its sandbox: nothing to tell a consumer
375
+ gone = {'kind': 'collector_disconnected', 'container_id': container, 'coverage': 'not_certified',
376
+ 'reason': 'collector stopped', 'source_instance_id': collector,
377
+ 'source_connection_id': connection, 'received_ms': heartbeat}
378
+ db.execute('INSERT INTO runtime_events(connection,received_ms,container_id,kind,body) VALUES(?,?,?,?,?)',
379
+ (connection, heartbeat, container, 'collector_disconnected', json.dumps(gone)))
380
+ return [row[0] for row in orphans]
381
+
294
382
  def run(self):
295
383
  db = init_db(self.database)
384
+ while True:
385
+ try:
386
+ for connection in self.close_orphaned_streams(db):
387
+ print(f'RayTrace collector: stream {connection} was left open by a stopped collector; ended it at its last heartbeat', flush=True)
388
+ break
389
+ except sqlite3.Error as error:
390
+ print(f'RayTrace collector: earlier streams not closed ({error}); retrying', flush=True)
391
+ time.sleep(1)
296
392
  while True:
297
393
  try:
298
394
  batch = [self.rows.get(timeout=5)]
@@ -353,6 +449,7 @@ def serve(endpoint, database):
353
449
  record({'kind': 'collector_connected', 'source': 'collector'})
354
450
  previous_dropped = 0
355
451
  previous_received = int(time.time()*1000)
452
+ attempts = ExecAttempts()
356
453
  while True:
357
454
  packet, _, flags, _ = conn.recvmsg(MAX_PACKET)
358
455
  if not packet:
@@ -369,6 +466,8 @@ def serve(endpoint, database):
369
466
  taken(gap)
370
467
  previous_dropped = event['dropped_count']
371
468
  previous_received = int(time.time()*1000)
469
+ for failed in attempts.see(event):
470
+ record(failed)
372
471
  if not taken(event):
373
472
  record(with_raw(event, packet))
374
473
  except Exception as error:
@@ -356,6 +356,8 @@ class Engine(threading.Thread):
356
356
  try:
357
357
  kind = event.get('kind')
358
358
  own = kind in OWN_KINDS or (kind in ('syscall_return', 'syscall_enter') and event.get('sysno') in self.numbered)
359
+ if own and kind == 'syscall_enter':
360
+ return True # subscribed only so that its exit names the process (setup.py): nothing to keep
359
361
  if own or kind in PROCESS_KINDS:
360
362
  try:
361
363
  self.inbox.put_nowait(event)
@@ -186,7 +186,7 @@ def lock(root, path, on):
186
186
  finally:
187
187
  os.close(at)
188
188
 
189
- def guardrails(sid, state, restricted=None, watched=None):
189
+ def guardrails(sid, state, restricted=None, watched=None, blocked=None):
190
190
  """Applies a sandbox's restricted files: the new list, or the stored one
191
191
  again. The Claude Code hook gets the list at once and refuses the edit
192
192
  with the reason. The lock that holds for every tool is put on only while
@@ -194,8 +194,9 @@ def guardrails(sid, state, restricted=None, watched=None):
194
194
  of a file while it runs, and a file locked under it stops being readable.
195
195
  A file no longer restricted is unlocked now. `watched` are the files whose
196
196
  owner wants to hear of a read or a change: the hook reports an attempt on
197
- them and nothing is locked. Returns {hook: the hook has the list,
198
- read_only: the files locked}."""
197
+ them and nothing is locked. `blocked` are the programs the hook refuses
198
+ to start (None keeps the stored list). Returns {hook: the hook has the
199
+ list, read_only: the files locked}."""
199
200
  GUARDRAILS.mkdir(parents=True, exist_ok=True, mode=0o700)
200
201
  stored = GUARDRAILS / (sid+'.json')
201
202
  kept = json.loads(stored.read_text()) if stored.exists() else {}
@@ -204,14 +205,16 @@ def guardrails(sid, state, restricted=None, watched=None):
204
205
  restricted = before
205
206
  if watched is None:
206
207
  watched = kept.get('watched', [])
208
+ if blocked is None:
209
+ blocked = kept.get('blocked', [])
207
210
  root = subprocess.check_output(['docker', 'volume', 'inspect', '-f', '{{.Mountpoint}}', sid+'-workspace'], text=True).strip()
208
211
  running = state['State']['Running']
209
212
  for path in set(before) - set(restricted):
210
213
  lock(root, path, False)
211
214
  read_only = [path for path in restricted if lock(root, path, None if running else True)]
212
- lists = json.dumps({'restricted': restricted, 'watched': watched})
215
+ lists = json.dumps({'restricted': restricted, 'watched': watched, 'blocked': blocked})
213
216
  stored.write_text(lists)
214
- if running and (restricted or before or watched or kept.get('watched')):
217
+ if running and (restricted or before or watched or kept.get('watched') or blocked or kept.get('blocked')):
215
218
  write_as_root(sid, GUARDRAILS_IN_SANDBOX, lists.encode())
216
219
  return {'hook': bool(running), 'read_only': read_only}
217
220
 
@@ -612,7 +615,12 @@ def main():
612
615
  if not isinstance(sent.get(key), list) or len(sent[key]) > cap:
613
616
  raise ValueError('Invalid '+key+' list')
614
617
  lists[key] = [safe_path(path)[len('/workspace/'):] for path in sent[key]]
615
- return print(json.dumps(guardrails(opts.id, state, lists['restricted'], lists['watched'])))
618
+ # blocked?: program names. Absent (an older caller, or a change to files only): keep the host's.
619
+ blocked = sent.get('blocked')
620
+ if blocked is not None and not (isinstance(blocked, list) and len(blocked) <= 200 and all(
621
+ isinstance(name, str) and re.fullmatch(r'[A-Za-z0-9._+-]{1,64}', name) and name not in ('.', '..') for name in blocked)):
622
+ raise ValueError('Invalid blocked list')
623
+ return print(json.dumps(guardrails(opts.id, state, lists['restricted'], lists['watched'], blocked)))
616
624
  if opts.action == 'guardrails':
617
625
  return print(json.dumps(guardrails(opts.id, inspect(opts.id))))
618
626
  if opts.action == 'set-token':
@@ -73,6 +73,15 @@ def trace_config(arch, catalog_sql, endpoint, calls=True):
73
73
  fields = [field for field in json.loads(wanted) if field in json.loads(offered or '[]')] if capture == 'yes' else []
74
74
  if fields:
75
75
  entry['optional_fields'] = fields
76
+ if capture == 'watcher':
77
+ # gVisor fills a raw exit event's context (which sandbox, which
78
+ # process, when) from the fields asked of the same call's raw
79
+ # ENTER point (kernel/task_syscall.go: the exit path reads
80
+ # SyscallRawEnter's field set). With only the exit subscribed the
81
+ # event names nobody, and the engine cannot say who deleted or
82
+ # renamed a file. So the enter point is subscribed with the same
83
+ # fields; the collector reads its exit and discards the enter.
84
+ configured.append({'name': f'syscall/sysno/{number[name]}/enter', 'context_fields': entry['context_fields']})
76
85
  configured.append(entry)
77
86
  # gVisor never waits long for the collector: when its socket is full it
78
87
  # tries again a few times, each wait twice the last (25 microseconds at