@raytrace-cli/cli 0.22.1 → 0.22.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -6,7 +6,7 @@
6
6
  <title>RayTrace — Agent trace forensics</title>
7
7
  <meta name="description" content="Evidence-backed traces and live counterfactual forks for coding agents." />
8
8
  <link rel="icon" href="/favicon.svg?v=raytrace-cube" type="image/svg+xml" />
9
- <script type="module" crossorigin src="/assets/index-Cfg6OwVA.js"></script>
9
+ <script type="module" crossorigin src="/assets/index-CZ8vbk1W.js"></script>
10
10
  <link rel="stylesheet" crossorigin href="/assets/index-Ci_pHYqV.css">
11
11
  </head>
12
12
  <body class="antialiased">
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@raytrace-cli/cli",
3
- "version": "0.22.1",
3
+ "version": "0.22.3",
4
4
  "mcpName": "io.github.Godcreatebugs/raytrace",
5
5
  "description": "See what your coding agent did: traces, tool calls, cost and step-by-step evidence for Claude Code and Codex.",
6
6
  "license": "MIT",
@@ -141,13 +141,15 @@ export function toolResultsFromTranscript(lines) {
141
141
  const results = new Map();
142
142
  for (const line of lines) {
143
143
  if (line?.type === 'user' && Array.isArray(line.message?.content)) {
144
+ const recordedAtMs = toMs(line.timestamp);
144
145
  for (const part of line.message.content) {
145
146
  if (part?.type === 'tool_result' && part.tool_use_id) {
146
147
  results.set(part.tool_use_id, {
147
148
  type: 'function_call_output',
148
149
  call_id: part.tool_use_id,
149
150
  output: toolOutput(part.content),
150
- ...(part.is_error ? { is_error: true } : {})
151
+ ...(part.is_error ? { is_error: true } : {}),
152
+ ...(recordedAtMs != null ? { recorded_at_ms: recordedAtMs } : {})
151
153
  });
152
154
  }
153
155
  }
@@ -185,7 +185,7 @@ export function openEvidenceStore(file, { readOnly = false } = {}) {
185
185
  JOIN runtime_events ev ON ev.id = a.event_id
186
186
  LEFT JOIN runtime_processes p ON p.id = ev.process_id
187
187
  WHERE a.tool_call_id = ? AND a.status = 'accepted' AND a.method != 'inherited'
188
- ORDER BY a.created_at_ms LIMIT 1`);
188
+ ORDER BY CASE WHEN a.confidence = 'exact' OR a.method = 'marker' THEN 0 ELSE 1 END, a.created_at_ms DESC LIMIT 1`);
189
189
  const selectSnapshotPaths = q('SELECT changes_json FROM workspace_snapshots WHERE call_id = ? ORDER BY taken_at_ms DESC LIMIT 1');
190
190
 
191
191
  function indexCall(callPk) {
@@ -551,9 +551,14 @@ export function openEvidenceStore(file, { readOnly = false } = {}) {
551
551
  },
552
552
 
553
553
  /** Ties an observed process (its exec event) to the tool call it ran
554
- * for. `method` is how: marker | window | text | inherited. */
554
+ * for. `method` is how: marker | window | text | inherited.
555
+ * An exact marker join supersedes any earlier weak window/text match. */
555
556
  attribute({ toolCallId, eventId, method, confidence = 'corroborated', score = null, windowStartMs = null, windowEndMs = null }) {
556
557
  if (!toolCallId || !eventId || selectAcceptedAttribution.get(toolCallId, eventId)) return false;
558
+ if (method === 'marker' || confidence === 'exact') {
559
+ q(`UPDATE runtime_attributions SET status = 'rejected'
560
+ WHERE tool_call_id = ? AND status = 'accepted' AND method NOT IN ('inherited', 'marker') AND confidence != 'exact'`).run(toolCallId);
561
+ }
557
562
  insertAttribution.run(randomUUID(), toolCallId, eventId, method, confidence,
558
563
  JSON.stringify({ method, score, window_start_ms: windowStartMs, window_end_ms: windowEndMs }), ATTRIBUTOR_VERSION, Date.now(),
559
564
  score ?? null, windowStartMs ?? null, windowEndMs ?? null);
@@ -610,14 +615,18 @@ export function openEvidenceStore(file, { readOnly = false } = {}) {
610
615
 
611
616
  /** The session's proposed calls that no process has been tied to yet,
612
617
  * each with its causal window: from the request that proposed it to the
613
- * first later request in the session that carried its result back (null
614
- * while none has). `call_id` is the internal tool-call id. */
618
+ * first later request in the session that carried its result back (or the
619
+ * recorded transcript tool-result timestamp, null while none has). */
615
620
  candidatesInWindow(startMs, endMs, { sessionId = null } = {}) {
616
621
  if (!sessionId) return [];
617
622
  const rows = q(`SELECT c.id, c.external_call_id, c.tool_name, c.arguments_sha, e.started_at_ms,
618
- (SELECT MIN(r.started_at_ms) FROM agent_context_items ci JOIN agent_exchanges r ON r.id = ci.exchange_id
619
- WHERE ci.external_call_id = c.external_call_id AND ci.kind IN (${marks(TOOL_RESULT_KINDS)})
620
- AND r.session_id = e.session_id AND r.started_at_ms >= e.started_at_ms AND r.id != e.id) AS window_end
623
+ COALESCE(
624
+ (SELECT MIN(r.started_at_ms) FROM agent_context_items ci JOIN agent_exchanges r ON r.id = ci.exchange_id
625
+ WHERE ci.external_call_id = c.external_call_id AND ci.kind IN (${marks(TOOL_RESULT_KINDS)})
626
+ AND r.session_id = e.session_id AND r.started_at_ms >= e.started_at_ms AND r.id != e.id),
627
+ (SELECT CAST(json_extract(rp.content, '$.recorded_at_ms') AS INTEGER) FROM agent_payloads rp
628
+ WHERE rp.sha = c.reported_result_sha AND json_extract(rp.content, '$.recorded_at_ms') IS NOT NULL)
629
+ ) AS window_end
621
630
  FROM agent_tool_calls c
622
631
  JOIN agent_exchanges e ON e.id = c.exchange_id
623
632
  JOIN agent_sessions s ON s.id = e.session_id
@@ -629,6 +638,36 @@ export function openEvidenceStore(file, { readOnly = false } = {}) {
629
638
  args: getPayload(row.arguments_sha), window_start: row.started_at_ms, window_end: row.window_end ?? null }));
630
639
  },
631
640
 
641
+ /** Calls in this session eligible for an exact RAYTRACE_CALL_ID marker join:
642
+ * any call that does not yet have an accepted exact/marker attribution,
643
+ * including calls currently holding only a weak window/text attribution. */
644
+ markerCandidates({ sessionId = null, externalCallIds = null, sinceMs = null } = {}) {
645
+ if (!sessionId) return [];
646
+ const list = Array.isArray(externalCallIds) ? [...new Set(externalCallIds.filter((id) => typeof id === 'string' && id))] : null;
647
+ if (list && !list.length) return [];
648
+ let sql = `SELECT c.id, c.external_call_id, c.tool_name, e.started_at_ms
649
+ FROM agent_tool_calls c
650
+ JOIN agent_exchanges e ON e.id = c.exchange_id
651
+ JOIN agent_sessions s ON s.id = e.session_id
652
+ WHERE s.external_session_id = ?
653
+ AND NOT EXISTS (SELECT 1 FROM runtime_attributions a
654
+ WHERE a.tool_call_id = c.id AND a.status = 'accepted' AND (a.method = 'marker' OR a.confidence = 'exact'))`;
655
+ const params = [sessionId];
656
+ if (list) {
657
+ sql += ` AND c.external_call_id IN (${marks(list)})`;
658
+ params.push(...list);
659
+ }
660
+ if (Number.isFinite(sinceMs)) {
661
+ sql += ' AND e.started_at_ms >= ?';
662
+ params.push(Math.round(sinceMs));
663
+ }
664
+ sql += ' ORDER BY e.started_at_ms, c.output_index';
665
+ return q(sql).all(...params).map((row) => ({
666
+ call_id: row.id, external_call_id: row.external_call_id, tool_name: row.tool_name,
667
+ timestamp: row.started_at_ms, window_start: row.started_at_ms, window_end: null,
668
+ }));
669
+ },
670
+
632
671
  /** A session's sandbox processes that no call accounts for, first seen at
633
672
  * or after `sinceMs`, oldest first, each with its first exec event, its
634
673
  * parent process, and the call that parent is tied to (null when none). */
@@ -714,7 +753,8 @@ export function openEvidenceStore(file, { readOnly = false } = {}) {
714
753
  (SELECT COUNT(*) FROM runtime_attributions d WHERE d.tool_call_id = c.id AND d.status = 'accepted' AND d.method = 'inherited') AS descendant_count
715
754
  FROM agent_tool_calls c
716
755
  LEFT JOIN runtime_attributions a ON a.id = (SELECT a2.id FROM runtime_attributions a2
717
- WHERE a2.tool_call_id = c.id AND a2.status = 'accepted' AND a2.method != 'inherited' ORDER BY a2.created_at_ms LIMIT 1)
756
+ WHERE a2.tool_call_id = c.id AND a2.status = 'accepted' AND a2.method != 'inherited'
757
+ ORDER BY CASE WHEN a2.confidence = 'exact' OR a2.method = 'marker' THEN 0 ELSE 1 END, a2.created_at_ms DESC LIMIT 1)
718
758
  LEFT JOIN runtime_events ev ON ev.id = a.event_id
719
759
  LEFT JOIN runtime_processes p ON p.id = ev.process_id
720
760
  WHERE c.exchange_id IN (${marks(exchangeIds)}) ORDER BY c.exchange_id, c.output_index`).all(...exchangeIds)
@@ -54,22 +54,57 @@ function longestCommonSubstringLength(a, b) {
54
54
  // (e.g. "/bin/zsh -lc <what the model actually asked for>") — that wrapper
55
55
  // text never appears in the model's proposed arguments, so it must be
56
56
  // stripped before comparing, or it dilutes even an exact match's score.
57
+ // Claude Code additionally wraps Bash calls in a shell snapshot + eval carrying
58
+ // `export RAYTRACE_CALL_ID=<id>\n<actual command>`.
57
59
  const SHELL_WRAPPER_PREFIX = /^\/bin\/(?:zsh|bash|sh)\s+-[a-z]+\s+/i;
60
+ const HOOK_EXPORT_PREFIX = /^export\s+raytrace_call_id=[a-z0-9_-]{1,128}[\s;]+/i;
61
+ const CLAUDE_EVAL_MARKER = /\beval\s+(['"])export\s+raytrace_call_id=[a-z0-9_-]{1,128}[\r\n;]+([\s\S]*?)\1/i;
58
62
 
59
- /** Similarity in [0, 1], normalized against the EXECUTED command's own
60
- * length (after stripping Codex's shell wrapper) rather than whichever side
61
- * happens to be shorter. This is intentionally asymmetric: the model's
62
- * proposed arguments may legitimately carry extra fields (a working
63
- * directory, a timeout, a justification string) that have nothing to do
64
- * with the command text itself and should not be allowed to drag the score
65
- * down just because they make the candidate's flattened text longer. 1.0
66
- * means the full executed command text appears verbatim inside whatever the
67
- * model proposed. */
63
+ // Common short pipeline/utility children (e.g. `tail -5`, `grep foo`, `wc -l`).
64
+ // When the proposed command is longer than the executed child, these must not
65
+ // steal a multi-step command just because their tiny text appears inside it.
66
+ const UTILITY_CHILD = /^(?:tail|head|grep|egrep|fgrep|rg|awk|sed|wc|cat|pwd|true|false|echo|sleep|tr|cut|sort|uniq|tee|xargs|basename|dirname)\b/i;
67
+ const SHORT_EXECUTED_LEN = 20;
68
+ const TINY_EXECUTED_LEN = 12;
69
+
70
+ function stripCommandWrapper(executedCommand) {
71
+ let command = String(executedCommand ?? '').toLowerCase().trim();
72
+ const evalMatch = CLAUDE_EVAL_MARKER.exec(command);
73
+ if (evalMatch) return evalMatch[2].trim();
74
+ command = command.replace(SHELL_WRAPPER_PREFIX, '').trim();
75
+ command = command.replace(HOOK_EXPORT_PREFIX, '').trim();
76
+ return command;
77
+ }
78
+
79
+ function proposedCommandText(candidateArgs) {
80
+ if (candidateArgs == null) return '';
81
+ if (typeof candidateArgs === 'string') return candidateArgs.toLowerCase().trim();
82
+ if (typeof candidateArgs === 'object' && !Array.isArray(candidateArgs)) {
83
+ if (candidateArgs.command != null) return flattenText(candidateArgs.command).trim();
84
+ if (candidateArgs.cmd != null) return flattenText(candidateArgs.cmd).trim();
85
+ }
86
+ return flattenText(candidateArgs).trim();
87
+ }
88
+
89
+ /** Similarity in [0, 1]. For substantial commands we normalize against the
90
+ * executed command's own length (so extra metadata fields in candidate args do
91
+ * not drag down a match). For short commands (< 20 chars) or common pipeline
92
+ * utilities that are shorter than the proposed command, we normalize against
93
+ * max(executed, proposed command) so a pipeline child like `tail -5` or
94
+ * `python3 -` cannot steal a much longer proposed command. */
68
95
  export function similarity(executedCommand, candidateArgs) {
69
- const command = String(executedCommand ?? '').toLowerCase().replace(SHELL_WRAPPER_PREFIX, '');
96
+ const command = stripCommandWrapper(executedCommand);
70
97
  const candidateText = flattenText(candidateArgs);
71
98
  if (!command || !candidateText) return 0;
72
- return longestCommonSubstringLength(command, candidateText) / command.length;
99
+ const proposed = proposedCommandText(candidateArgs) || candidateText;
100
+ const lcs = longestCommonSubstringLength(command, candidateText);
101
+ if (command.length < TINY_EXECUTED_LEN && lcs < command.length) {
102
+ return lcs / (command.length + proposed.length);
103
+ }
104
+ if (command.length < SHORT_EXECUTED_LEN || (UTILITY_CHILD.test(command) && proposed.length > command.length)) {
105
+ return lcs / Math.max(command.length, proposed.length);
106
+ }
107
+ return lcs / command.length;
73
108
  }
74
109
 
75
110
  const MATCH_THRESHOLD = 0.6; // below this, treat as "no confident match"
@@ -144,3 +144,39 @@ test('causal window: a window match carries the bounds that justified it', () =>
144
144
  assert.deepEqual(matchExecutionToCall({ command: 'rm notes.md', timestamp: 3_000 }, [{ call_id: 'call_a', timestamp: 0, args: RM }]),
145
145
  { call_id: 'call_a', score: 1, basis: 'text' });
146
146
  });
147
+
148
+ // Issue #152 regressions: short pipeline children must not steal multi-command calls.
149
+ test('similarity rejects short pipeline children like tail -5 and python3 - against long proposed commands', () => {
150
+ const proposed = { command: 'cat slugify.py test_slugify.py requirements.txt; python -m pytest -q 2>&1 | tail -30' };
151
+ assert.ok(similarity('tail -5', proposed) < 0.6, `expected tail -5 below 0.6, got ${similarity('tail -5', proposed)}`);
152
+ assert.ok(similarity('tail -3', proposed) < 0.6, `expected tail -3 below 0.6, got ${similarity('tail -3', proposed)}`);
153
+ assert.ok(similarity('python3 -', proposed) < 0.6, `expected python3 - below 0.6, got ${similarity('python3 -', proposed)}`);
154
+ assert.ok(similarity('python3 -', { command: 'python -m pytest' }) < 0.6);
155
+ // Exact short commands still match at 1.0 (important for Codex where there is no RAYTRACE_CALL_ID hook).
156
+ assert.equal(similarity('npm test', { command: 'npm test', workdir: '/workspace/long/path' }), 1);
157
+ assert.equal(similarity('ls -la', { command: 'ls -la' }), 1);
158
+ });
159
+
160
+ test('similarity strips Claude shell-snapshot eval wrapper carrying RAYTRACE_CALL_ID', () => {
161
+ const proposed = { command: 'curl -sS https://example.com' };
162
+ const wrapped = "/bin/bash -c source /home/node/.claude/shell-snapshots/snap.sh && eval 'export RAYTRACE_CALL_ID=toolu_01abc\ncurl -sS https://example.com'";
163
+ assert.equal(similarity(wrapped, proposed), 1);
164
+ });
165
+
166
+ test('matchBatch over overlapping open windows does not let short tail children steal other calls', () => {
167
+ const candidates = [
168
+ { call_id: 'call_1', timestamp: 1_000, window_start: 1_000, window_end: null,
169
+ args: { command: 'cat slugify.py test_slugify.py requirements.txt; python -m pytest -q 2>&1 | tail -30' } },
170
+ { call_id: 'call_2', timestamp: 2_000, window_start: 2_000, window_end: null,
171
+ args: { command: 'pip install -q -r requirements.txt 2>&1 | tail -3; python3 -m pytest -q 2>&1 | tail -15' } },
172
+ { call_id: 'call_3', timestamp: 3_000, window_start: 3_000, window_end: null,
173
+ args: { command: 'python3 -m pip install -q -r requirements.txt 2>&1 | tail -5; python3 -m ensurepip --version' } },
174
+ ];
175
+ const execs = [
176
+ { id: 'exec-tail-3', command: 'tail -3', timestamp: 2_200, margin: 250 },
177
+ { id: 'exec-tail-5', command: 'tail -5', timestamp: 3_200, margin: 250 },
178
+ { id: 'exec-py', command: 'python3 -', timestamp: 1_500, margin: 250 },
179
+ ];
180
+ const results = matchBatch(execs, candidates);
181
+ assert.equal(results.size, 0, `expected no loose matches, got ${JSON.stringify([...results.entries()])}`);
182
+ });
@@ -68,7 +68,7 @@ export function msFromNs(ns) {
68
68
 
69
69
  /** The call id a command's own text exports, or null. */
70
70
  export function commandMarker(command) {
71
- return /(?:^|[\s;'])export RAYTRACE_CALL_ID=([A-Za-z0-9_-]{1,128})(?=[\s;]|$)/.exec(String(command ?? ''))?.[1] ?? null;
71
+ return /(?:^|[\s;'"])export RAYTRACE_CALL_ID=([A-Za-z0-9_-]{1,128})(?=[\s;'"]|$)/.exec(String(command ?? ''))?.[1] ?? null;
72
72
  }
73
73
 
74
74
  /** One collector `exec_succeeded` event -> the shape matchBatch() consumes,
@@ -326,6 +326,7 @@ export function startGvisorForwarder({
326
326
  recordCapture,
327
327
  loadCheckpoint = async () => 0,
328
328
  saveProgress = async () => {},
329
+ onPoll = null,
329
330
  log = (message) => console.error(message),
330
331
  fetchImpl = globalThis.fetch,
331
332
  viewerHeaders = () => ({}),
@@ -477,6 +478,7 @@ export function startGvisorForwarder({
477
478
  log(`[raytace][gvisor] ${sessionId.slice(0, 12)}: ${counts.matched} exec(s) matched to proposed calls, `
478
479
  + `${counts.descendants} descendant(s), ${counts.unattributed} unattributed, ${counts.failedExecs} failed exec(s), `
479
480
  + `${counts.finished} closed out, ${counts.lost} marked unknown, ${counts.forwarded} top-level exec(s) considered`);
481
+ if (typeof onPoll === 'function') await onPoll({ sessionId, containerId, counts });
480
482
  }
481
483
  } catch (error) {
482
484
  log(`[raytace][gvisor] ${sessionId.slice(0, 12)}: failed to record evidence: ${error.message}`);
@@ -557,6 +557,12 @@ const server = createServer(async (req, res) => {
557
557
  // list keeps them.
558
558
  if (req.method === 'GET' && ['/raytace/traces', '/raytace/traces?scope=history', '/raytace/traces?scope=history&evidence=1'].includes(req.url)) {
559
559
  try {
560
+ if (gvisorForwarder) {
561
+ await Promise.race([gvisorForwarder.poll().catch(() => {}), new Promise((resolve) => setTimeout(resolve, 400))]);
562
+ for (const { sessionId } of gvisorForwarder.sandboxes.values()) {
563
+ await attributeLateProcesses(db, sessionId).catch(() => {});
564
+ }
565
+ }
560
566
  const cached = cachedTraces(req.url);
561
567
  const headers = { ...corsHeaders, etag: cached.etag, 'cache-control': 'no-cache', 'access-control-expose-headers': 'etag' };
562
568
  if (req.headers['if-none-match'] === cached.etag) { res.writeHead(304, headers); return res.end(); }
@@ -962,6 +968,7 @@ const gvisorForwarder = process.env.RAYTACE_GVISOR_FORWARDER === '0' ? null : st
962
968
  recordCapture: row => db.recordCaptureEvent(row),
963
969
  loadCheckpoint: (container,source) => db.captureCheckpoint(container,source),
964
970
  saveProgress: row => db.saveCaptureProgress(row),
971
+ onPoll: ({ sessionId, counts }) => { if (counts?.unattributed) return attributeLateProcesses(db, sessionId); },
965
972
  viewerBase: EVIDENCE_VIEWER,
966
973
  fetchImpl: fromViewer,
967
974
  ingest: (events, { sessionId }) => ingestExecutions(db, events, { sessionId }),
@@ -41,21 +41,48 @@ export async function ingestExecutions(db, events, { sessionId = null } = {}) {
41
41
  }
42
42
  const timestamps = events.map((e) => e.timestamp).filter(Number.isFinite);
43
43
  if (!sessionId || !timestamps.length) return matches;
44
+ // Exact marker joins bypass tight timestamp windows and can supersede weak
45
+ // window/text attributions; unmarked events only compete via text matching.
46
+ const markedEvents = events.filter((e) => Boolean(e.call_marker));
47
+ const unmarkedEvents = events.filter((e) => !e.call_marker);
48
+ const byExternalId = new Map();
49
+ if (markedEvents.length) {
50
+ const markerPool = db.markerCandidates
51
+ ? await db.markerCandidates({ sessionId, externalCallIds: markedEvents.map((e) => e.call_marker) })
52
+ : await db.candidatesInWindow(0, Number.MAX_SAFE_INTEGER, { sessionId });
53
+ for (const c of markerPool) byExternalId.set(c.external_call_id, c.call_id);
54
+ }
55
+ const claimedByMarker = new Set();
56
+ for (const event of markedEvents) {
57
+ const eventId = recorded.get(event.id)?.eventId;
58
+ const markedCall = byExternalId.get(event.call_marker);
59
+ if (!markedCall || !eventId) continue;
60
+ const method = claimedByMarker.has(markedCall) ? 'inherited' : 'marker';
61
+ claimedByMarker.add(markedCall);
62
+ await db.attribute({
63
+ toolCallId: markedCall, eventId, method,
64
+ confidence: method === 'marker' ? 'exact' : 'corroborated',
65
+ score: method === 'marker' ? 1 : null,
66
+ windowStartMs: null, windowEndMs: null,
67
+ });
68
+ matches.set(event.id, { call_id: markedCall, score: 1, basis: method === 'marker' ? 'marker' : 'inherited' });
69
+ }
70
+ if (!unmarkedEvents.length) return matches;
44
71
  // The pool reaches back as far as an open window may stay open, plus the
45
72
  // clock margin between the proxy and the sandbox.
46
- const margin = Math.max(0, ...events.map((e) => e.margin).filter(Number.isFinite));
47
- const candidates = await db.candidatesInWindow(Math.min(...timestamps) - OPEN_WINDOW_CAP_MS - margin, Math.max(...timestamps) + margin, { sessionId });
48
- const found = matchBatch(events, candidates.filter(runsCommands));
49
- const byExternalId = new Map(candidates.map((c) => [c.external_call_id, c.call_id]));
50
- for (const event of events) {
73
+ const margin = Math.max(0, ...unmarkedEvents.map((e) => e.margin).filter(Number.isFinite));
74
+ const unmarkedTimes = unmarkedEvents.map((e) => e.timestamp).filter(Number.isFinite);
75
+ const candidates = (await db.candidatesInWindow(Math.min(...unmarkedTimes) - OPEN_WINDOW_CAP_MS - margin, Math.max(...unmarkedTimes) + margin, { sessionId }))
76
+ .filter((c) => !claimedByMarker.has(c.call_id));
77
+ const found = matchBatch(unmarkedEvents, candidates.filter(runsCommands));
78
+ for (const event of unmarkedEvents) {
51
79
  const eventId = recorded.get(event.id)?.eventId;
52
- const markedCall = event.call_marker ? byExternalId.get(event.call_marker) : null;
53
- const match = markedCall ? { call_id: markedCall, score: 1, basis: 'marker' } : found.get(event.id);
80
+ const match = found.get(event.id);
54
81
  if (!match || !eventId) continue; // no confident match: the process stays recorded, unattributed -- never a guess
55
82
  await db.attribute({ toolCallId: match.call_id, eventId, method: match.basis === 'id' ? 'marker' : match.basis,
56
83
  // A marker join is exact; a text match that gVisor itself observed is
57
84
  // corroborated. Recorded at capture, never promoted later.
58
- confidence: markedCall ? 'exact' : 'corroborated', score: match.score,
85
+ confidence: 'corroborated', score: match.score,
59
86
  windowStartMs: match.window_start ?? null, windowEndMs: match.window_end ?? null });
60
87
  matches.set(event.id, match);
61
88
  }
@@ -68,16 +95,23 @@ export async function ingestExecutions(db, events, { sessionId = null } = {}) {
68
95
  * call is only recorded once the answer is complete, so the gVisor forwarder
69
96
  * has usually seen the process before the call it belongs to exists. Once
70
97
  * the call is recorded, the same rules apply as at exec time: the call id the
71
- * process carries (checked against this session's own calls), else a process
72
- * started by one already tied to a call inherits it, else the text match.
98
+ * process carries (checked against this session's own calls — superseding any
99
+ * earlier weak text match), else a process started by one already tied to a
100
+ * call inherits it, else the text match.
73
101
  */
74
102
  export async function attributeLateProcesses(db, sessionId, log = console.log) {
75
103
  const now = Date.now();
76
- const candidates = await db.candidatesInWindow(now - 24 * 3_600_000, now + 60_000, { sessionId });
77
- if (!candidates.length) return;
104
+ const sinceWindow = now - 24 * 3_600_000;
105
+ const candidates = await db.candidatesInWindow(sinceWindow, now + 60_000, { sessionId });
106
+ const markerPool = db.markerCandidates
107
+ ? await db.markerCandidates({ sessionId, sinceMs: sinceWindow })
108
+ : candidates;
109
+ if (!candidates.length && !markerPool.length) return 0;
78
110
  const margin = 2_000;
79
- const processes = await db.unattributedProcesses({ sessionId, sinceMs: Math.min(...candidates.map((c) => c.window_start)) - margin });
80
- const byExternalId = new Map(candidates.map((c) => [c.external_call_id, c]));
111
+ const earliest = Math.min(...[...candidates, ...markerPool].map((c) => c.window_start).filter(Number.isFinite));
112
+ if (!Number.isFinite(earliest)) return 0;
113
+ const processes = await db.unattributedProcesses({ sessionId, sinceMs: earliest - margin });
114
+ const byExternalId = new Map(markerPool.map((c) => [c.external_call_id, c]));
81
115
  const claimed = new Set();
82
116
  const callOfProcess = new Map(); // process id -> call id, for children within this pass
83
117
  const unmatched = [];
@@ -96,7 +130,11 @@ export async function attributeLateProcesses(db, sessionId, log = console.log) {
96
130
  await db.attribute({ toolCallId: call, eventId: proc.event_id, method, confidence: method === 'marker' ? 'exact' : 'corroborated', score: method === 'marker' ? 1 : null });
97
131
  callOfProcess.set(proc.process_id, call);
98
132
  tied += 1;
99
- } else if (command && Number.isFinite(proc.first_seen_ms)) unmatched.push({ id: proc.event_id, command, timestamp: proc.first_seen_ms, margin, process_id: proc.process_id });
133
+ } else if (!marker && command && Number.isFinite(proc.first_seen_ms)) {
134
+ // Never text-match a process carrying an unresolved RAYTRACE_CALL_ID:
135
+ // its own call has not been ingested yet, so leave it unattributed.
136
+ unmatched.push({ id: proc.event_id, command, timestamp: proc.first_seen_ms, margin, process_id: proc.process_id });
137
+ }
100
138
  }
101
139
  const found = matchBatch(unmatched, candidates.filter((c) => !claimed.has(c.call_id) && runsCommands(c)));
102
140
  for (const exec of unmatched) {
@@ -107,4 +145,5 @@ export async function attributeLateProcesses(db, sessionId, log = console.log) {
107
145
  tied += 1;
108
146
  }
109
147
  if (tied) log(`[raytace][claude-code] ${sessionId.slice(0, 12)}: tied ${tied} sandbox process(es) to calls recorded after they ran`);
148
+ return tied;
110
149
  }
@@ -0,0 +1,238 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { mkdtempSync, rmSync } from 'node:fs';
4
+ import { join } from 'node:path';
5
+ import { tmpdir } from 'node:os';
6
+ import { openEvidenceStore } from './evidence-store.mjs';
7
+ import { ingestExecutions, attributeLateProcesses } from './runtime-attribution.mjs';
8
+ import { commandMarker, toExecutionEvent } from './gvisor-forwarder.mjs';
9
+ import { readTraces } from './trace-view.mjs';
10
+
11
+ const CONTAINER = 'a'.repeat(64);
12
+ const SESSION = 'rtp-' + '1'.repeat(32);
13
+ const NS = (ms) => String(BigInt(ms) * 1_000_000n);
14
+
15
+ function withStore(fn) {
16
+ const dir = mkdtempSync(join(tmpdir(), 'raytace-attr-'));
17
+ const store = openEvidenceStore(join(dir, 'evidence.db'));
18
+ return Promise.resolve()
19
+ .then(() => fn(store))
20
+ .finally(() => { store.close(); rmSync(dir, { recursive: true, force: true }); });
21
+ }
22
+
23
+ function recordCall(store, { spanId, callId, name = 'Bash', args = {}, startedMs = Date.now(), prompt = 'run task' }) {
24
+ store.recordExchange({
25
+ event_type: 'model.exchange',
26
+ session_id: SESSION,
27
+ session_started_at: new Date(startedMs).toISOString(),
28
+ trace_id: `trace-${spanId}`,
29
+ span_id: spanId,
30
+ timestamp: new Date(startedMs).toISOString(),
31
+ completed_at: new Date(startedMs + 500).toISOString(),
32
+ provider: 'claude-code',
33
+ route: '/claude-code/v1/messages',
34
+ method: 'POST',
35
+ request: { payload: { model: 'claude-sonnet-4', input: [{ type: 'message', role: 'user', content: [{ type: 'input_text', text: prompt }] }] } },
36
+ response: { status: 200, payload: { status: 'completed', output: [{ type: 'function_call', call_id: callId, name, arguments: JSON.stringify(args) }] } },
37
+ });
38
+ }
39
+
40
+ function execEvent(eventId, pid, ppid, argv, ms, extra = {}) {
41
+ return {
42
+ event_id: eventId,
43
+ kind: 'exec_succeeded',
44
+ pid,
45
+ ppid,
46
+ argv,
47
+ container_id: CONTAINER,
48
+ process_start_ns: NS(ms),
49
+ timestamp_ns: NS(ms),
50
+ cwd: '/workspace',
51
+ ...extra,
52
+ };
53
+ }
54
+
55
+ test('commandMarker recognizes both single- and double-quoted export wrappers (#152)', () => {
56
+ assert.equal(commandMarker("eval 'export RAYTRACE_CALL_ID=toolu_01abc\ncurl https://example.com'"), 'toolu_01abc');
57
+ assert.equal(commandMarker('eval "export RAYTRACE_CALL_ID=toolu_02def; ls"'), 'toolu_02def');
58
+ });
59
+
60
+ test('weak text match is superseded when a later process arrives with RAYTRACE_CALL_ID (#152)', () => withStore(async (store) => {
61
+ const t0 = Date.now() - 5_000;
62
+ recordCall(store, { spanId: 'span-1', callId: 'toolu_weak_1', args: { command: 'curl -sS https://example.com' }, startedMs: t0 });
63
+
64
+ // Simulate an earlier weak window/text attribution (e.g. a stray child process).
65
+ const stray = store.recordProcessStart({
66
+ containerId: CONTAINER, projectId: SESSION,
67
+ raw: execEvent(1, 200, 10, ['tail', '-3'], t0 + 100), startedMs: t0 + 100,
68
+ });
69
+ const [cand] = store.candidatesInWindow(0, Number.MAX_SAFE_INTEGER, { sessionId: SESSION });
70
+ store.attribute({ toolCallId: cand.call_id, eventId: stray.eventId, method: 'window', confidence: 'corroborated', score: 0.85 });
71
+ assert.equal(store.divergence(['span-1'])[0].match_basis, 'window');
72
+
73
+ // Later, the real wrapping bash with RAYTRACE_CALL_ID and its curl child arrive.
74
+ const bashRaw = execEvent(2, 300, 10, ['/bin/bash', '-c', "eval 'export RAYTRACE_CALL_ID=toolu_weak_1\ncurl -sS https://example.com'"], t0 + 200);
75
+ const curlRaw = execEvent(3, 301, 300, ['curl', '-sS', 'https://example.com'], t0 + 250, { markers: { RAYTRACE_CALL_ID: 'toolu_weak_1' } });
76
+ store.recordProcessStart({ containerId: CONTAINER, projectId: SESSION, raw: bashRaw, startedMs: t0 + 200 });
77
+ store.recordProcessStart({ containerId: CONTAINER, projectId: SESSION, raw: curlRaw, startedMs: t0 + 250 });
78
+
79
+ await attributeLateProcesses(store, SESSION, () => {});
80
+ const [row] = store.divergence(['span-1']);
81
+ assert.equal(row.match_basis, 'id');
82
+ assert.equal(row.tier, 'mediated');
83
+ assert.equal(row.kernel_confirmed, 1);
84
+ assert.deepEqual(row.argv, bashRaw.argv);
85
+ assert.equal(row.descendant_count, 1);
86
+ const descendants = store.descendants(['span-1']);
87
+ assert.deepEqual(descendants[0].argv, ['curl', '-sS', 'https://example.com']);
88
+ }));
89
+
90
+ test('marked process whose call is not recorded yet never steals an earlier call by text (#152)', () => withStore(async (store) => {
91
+ const t0 = Date.now() - 5_000;
92
+ recordCall(store, { spanId: 'span-a', callId: 'toolu_call_A', args: { command: 'curl -sS https://example.com' }, startedMs: t0 });
93
+
94
+ // Process carries RAYTRACE_CALL_ID=toolu_call_B (call B not stored yet), same command text as call A.
95
+ const markedExec = toExecutionEvent(execEvent(10, 400, 10, ['curl', '-sS', 'https://example.com'], t0 + 300, { markers: { RAYTRACE_CALL_ID: 'toolu_call_B' } }));
96
+ const matches = await ingestExecutions(store, [markedExec], { sessionId: SESSION });
97
+ assert.equal(matches.size, 0, 'marked process must not fall back to text-matching another call');
98
+ assert.equal(store.divergence(['span-a'])[0].outcome, 'not_executed');
99
+
100
+ // Once call B arrives, late attribution joins it cleanly to call B.
101
+ recordCall(store, { spanId: 'span-b', callId: 'toolu_call_B', args: { command: 'curl -sS https://example.com' }, startedMs: t0 + 250 });
102
+ await attributeLateProcesses(store, SESSION, () => {});
103
+ assert.equal(store.divergence(['span-a'])[0].outcome, 'not_executed');
104
+ assert.equal(store.divergence(['span-b'])[0].match_basis, 'id');
105
+ assert.equal(store.divergence(['span-b'])[0].tier, 'mediated');
106
+ }));
107
+
108
+ test('process seen before tool-call row exists joins on trace reconciliation without a second transcript (#151)', () => withStore(async (store) => {
109
+ const t0 = Date.now() - 5_000;
110
+ // 1. gVisor observes bash + curl BEFORE the transcript exchange is stored.
111
+ const bashExec = toExecutionEvent(execEvent(20, 500, 10, ['/bin/bash', '-c', "source /home/node/.claude/shell-snapshots/s.sh && eval 'export RAYTRACE_CALL_ID=toolu_curl_1\ncurl -sS https://example.com'"], t0));
112
+ const curlExec = toExecutionEvent(execEvent(21, 501, 500, ['curl', '-sS', 'https://example.com'], t0 + 50, { markers: { RAYTRACE_CALL_ID: 'toolu_curl_1' } }));
113
+ await ingestExecutions(store, [bashExec, curlExec], { sessionId: SESSION });
114
+
115
+ // 2. Transcript arrives later with the single Bash call (no second session).
116
+ recordCall(store, { spanId: 'span-curl', callId: 'toolu_curl_1', args: { command: 'curl -sS https://example.com' }, startedMs: t0 + 100 });
117
+
118
+ // 3. Traces read triggers attributeLateProcesses before readTraces (no second transcript).
119
+ const tied = await attributeLateProcesses(store, SESSION, () => {});
120
+ assert.equal(tied, 2);
121
+ const [trace] = await readTraces(store, { includeHistory: true });
122
+ const [call] = trace.callVerifications;
123
+ assert.equal(call.call_id, 'toolu_curl_1');
124
+ assert.equal(call.verified, true);
125
+ assert.equal(call.kernel_confirmed, true);
126
+ assert.equal(call.tier, 'mediated');
127
+ assert.equal(call.match_basis, 'id');
128
+ assert.equal(call.descendant_count, 1);
129
+ assert.deepEqual(call.descendants[0].argv, ['curl', '-sS', 'https://example.com']);
130
+ }));
131
+
132
+ test('ingestExecutions matches RAYTRACE_CALL_ID even when transcript timestamp exceeds tight window margin (#151)', () => withStore(async (store) => {
133
+ const t0 = Date.now() - 10_000;
134
+ // Transcript exchange timestamp is 10s after the VM exec timestamp (past default 2s margin).
135
+ recordCall(store, { spanId: 'span-skew', callId: 'toolu_skew_1', args: { command: 'curl https://example.com' }, startedMs: t0 + 10_000 });
136
+ const bashExec = toExecutionEvent(execEvent(30, 600, 10, ['/bin/bash', '-c', "eval 'export RAYTRACE_CALL_ID=toolu_skew_1\ncurl https://example.com'"], t0));
137
+ const matches = await ingestExecutions(store, [bashExec], { sessionId: SESSION });
138
+ assert.equal(matches.size, 1);
139
+ assert.equal(store.divergence(['span-skew'])[0].match_basis, 'id');
140
+ assert.equal(store.divergence(['span-skew'])[0].tier, 'mediated');
141
+ }));
142
+
143
+ test('isolated Edit (no Bash) is verified=true from file fact without kernel_confirmed from /bin/true, and Read is in_agent (#150)', () => withStore(async (store) => {
144
+ // Hook announce process must still be dropped by toExecutionEvent.
145
+ const announce = toExecutionEvent({
146
+ event_id: 40, kind: 'exec_succeeded', pid: 742, ppid: 741,
147
+ executable: '/bin/true', argv: ['/bin/true', 'raytrace-tool', 'begin', 'Edit', '/workspace/slugify.py'],
148
+ markers: { RAYTRACE_CALL_ID: 'toolu_edit_1' }, container_id: CONTAINER, timestamp_ns: NS(Date.now()),
149
+ });
150
+ assert.equal(announce, null, '/bin/true raytrace-tool announce must never become a process attribution');
151
+
152
+ const t0 = Date.now() - 3_000;
153
+ store.recordExchange({
154
+ event_type: 'model.exchange',
155
+ session_id: SESSION,
156
+ session_started_at: new Date(t0).toISOString(),
157
+ trace_id: 'trace-edit',
158
+ span_id: 'span-edit',
159
+ timestamp: new Date(t0).toISOString(),
160
+ completed_at: new Date(t0 + 400).toISOString(),
161
+ provider: 'claude-code',
162
+ route: '/claude-code/v1/messages',
163
+ method: 'POST',
164
+ request: { payload: { model: 'claude-sonnet-4', input: [{ type: 'message', role: 'user', content: [{ type: 'input_text', text: 'Edit slugify.py' }] }] } },
165
+ response: {
166
+ status: 200,
167
+ payload: {
168
+ status: 'completed',
169
+ output: [
170
+ { type: 'function_call', call_id: 'toolu_read_1', name: 'Read', arguments: JSON.stringify({ file_path: '/workspace/slugify.py' }) },
171
+ { type: 'function_call', call_id: 'toolu_edit_1', name: 'Edit', arguments: JSON.stringify({ file_path: '/workspace/slugify.py', old_string: 'a', new_string: 'b' }) },
172
+ ],
173
+ },
174
+ },
175
+ });
176
+
177
+ // Simulate hosted db reader returning the host-observed file fact from sandbox_facts.
178
+ const dbWithFacts = {
179
+ ...store,
180
+ activityFactsForCalls: async (callIds) => new Map(
181
+ callIds.includes('toolu_edit_1')
182
+ ? [['toolu_edit_1', [{ kind: 'file', subject: 'slugify.py', effect: 'changed', call_from: 'tool_report', pid: 741, process: 'claude.exe' }]]]
183
+ : [],
184
+ ),
185
+ };
186
+
187
+ const [trace] = await readTraces(dbWithFacts, { includeHistory: true });
188
+ const readCall = trace.callVerifications.find((c) => c.call_id === 'toolu_read_1');
189
+ const editCall = trace.callVerifications.find((c) => c.call_id === 'toolu_edit_1');
190
+
191
+ assert.equal(editCall.verified, true);
192
+ assert.equal(editCall.file_confirmed, true);
193
+ assert.equal(editCall.kernel_confirmed, false);
194
+ assert.equal(editCall.source, 'file_fact');
195
+ assert.equal(editCall.match_basis, 'tool_report');
196
+ assert.equal(editCall.tier, 'corroborated');
197
+
198
+ assert.equal(readCall.verified, false);
199
+ assert.equal(readCall.kernel_confirmed, false);
200
+ assert.equal(readCall.file_confirmed, false);
201
+ assert.equal(readCall.status, 'in_agent', 'Read without a file fact stays in_agent, not a missing command');
202
+
203
+ // When engine.py emits a confirmed read fact for an announced Read (#156), Read becomes verified=true without kernel_confirmed.
204
+ const dbWithReadFact = {
205
+ ...store,
206
+ activityFactsForCalls: async (callIds) => new Map([
207
+ ...(callIds.includes('toolu_read_1') ? [['toolu_read_1', [{ kind: 'file', subject: 'slugify.py', effect: 'read', call_from: 'tool_report', pid: 741, process: 'claude.exe' }]]] : []),
208
+ ...(callIds.includes('toolu_edit_1') ? [['toolu_edit_1', [{ kind: 'file', subject: 'slugify.py', effect: 'changed', call_from: 'tool_report', pid: 741, process: 'claude.exe' }]]] : []),
209
+ ]),
210
+ };
211
+ const [traceWithRead] = await readTraces(dbWithReadFact, { includeHistory: true });
212
+ const verifiedRead = traceWithRead.callVerifications.find((c) => c.call_id === 'toolu_read_1');
213
+ assert.equal(verifiedRead.verified, true);
214
+ assert.equal(verifiedRead.file_confirmed, true);
215
+ assert.equal(verifiedRead.kernel_confirmed, false);
216
+ assert.equal(verifiedRead.source, 'file_fact');
217
+ assert.equal(verifiedRead.match_basis, 'tool_report');
218
+ }));
219
+
220
+ test('command call with an activity fact carrying call_id reports join_pending instead of not_executed (#151)', () => withStore(async (store) => {
221
+ const t0 = Date.now() - 2_000;
222
+ recordCall(store, { spanId: 'span-net', callId: 'toolu_net_1', args: { command: 'curl https://example.com' }, startedMs: t0 });
223
+ const dbWithFacts = {
224
+ ...store,
225
+ activityFactsForCalls: async (callIds) => new Map(
226
+ callIds.includes('toolu_net_1')
227
+ ? [['toolu_net_1', [{ kind: 'network', subject: 'example.com:443', effect: 'connect', call_from: null, pid: 800, process: 'curl' }]]]
228
+ : [],
229
+ ),
230
+ };
231
+ const [trace] = await readTraces(dbWithFacts, { includeHistory: true });
232
+ const [call] = trace.callVerifications;
233
+ assert.equal(call.verified, true);
234
+ assert.equal(call.status, 'join_pending');
235
+ assert.equal(call.kernel_confirmed, false);
236
+ assert.equal(call.source, 'activity_fact');
237
+ assert.equal(call.match_basis, 'id');
238
+ }));