@raytrace-cli/cli 0.4.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 (102) hide show
  1. package/README.md +132 -126
  2. package/bin/raytrace.mjs +41 -20
  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/commands.mjs +73 -4
  84. package/src/lima.mjs +135 -0
  85. package/src/local-sandbox.mjs +324 -0
  86. package/src/proxy-process.mjs +20 -1
  87. package/src/sandbox.mjs +24 -6
  88. package/worker/sandbox/Dockerfile +8 -0
  89. package/worker/sandbox/SYSCALL_CATALOG.md +197 -0
  90. package/worker/sandbox/claude-hook.mjs +331 -0
  91. package/worker/sandbox/collector.py +357 -0
  92. package/worker/sandbox/dns_forwarder.py +255 -0
  93. package/worker/sandbox/engine.py +940 -0
  94. package/worker/sandbox/file_scan.py +491 -0
  95. package/worker/sandbox/lima.yaml +29 -0
  96. package/worker/sandbox/network.py +90 -0
  97. package/worker/sandbox/projects.py +678 -0
  98. package/worker/sandbox/setup.py +159 -0
  99. package/worker/sandbox/syscall_catalog.sql +985 -0
  100. package/worker/sandbox/viewer.py +132 -0
  101. package/dist/dashboard/assets/index-BQ9_JxGq.js +0 -27
  102. package/dist/dashboard/assets/index-L5cUAvhE.css +0 -1
@@ -0,0 +1,185 @@
1
+ /**
2
+ * Correlates a command the sandbox actually ran (a gVisor exec) to the
3
+ * model's proposed tool call it fulfilled (an agent_tool_calls row captured
4
+ * from the response payload).
5
+ *
6
+ * Why this is needed at all: the process carries no call id -- the model's
7
+ * `call_id` never reaches the program Codex spawns -- so there is no shared
8
+ * key to join on. This module bridges them by content (does the executed
9
+ * command text match what the model proposed?) inside each call's causal
10
+ * window and, for ties, by chronological order.
11
+ *
12
+ * Correctness stance: a wrong "not correlated" is harmless (falls back to
13
+ * today's `not_executed` default). A wrong *positive* match — attributing a
14
+ * real execution to the wrong proposed call — is the failure mode to avoid,
15
+ * so matching only commits above a real similarity bar; ambiguous or weak
16
+ * cases return no match rather than guessing.
17
+ */
18
+
19
+ /** Recursively flatten any JSON value's string content into one lowercase
20
+ * string, so matching survives whatever shape a tool's arguments happen to
21
+ * be in ({command: "..."} vs {cmd: "..."} vs a bare string, etc). */
22
+ export function flattenText(value) {
23
+ if (value == null) return '';
24
+ if (typeof value === 'string') return value.toLowerCase();
25
+ if (Array.isArray(value)) return value.map(flattenText).join(' ');
26
+ if (typeof value === 'object') return Object.values(value).map(flattenText).join(' ');
27
+ return String(value).toLowerCase();
28
+ }
29
+
30
+ /** Longest common substring length between two strings — cheap, and unlike
31
+ * a token-set/Jaccard measure it rewards exact shared command text (which is
32
+ * the common case: Codex runs precisely what the model proposed) over
33
+ * coincidental word overlap. */
34
+ function longestCommonSubstringLength(a, b) {
35
+ if (!a || !b) return 0;
36
+ const [short, long] = a.length <= b.length ? [a, b] : [b, a];
37
+ let best = 0;
38
+ // Cap work on pathological inputs (huge stdout dumps embedded in args)
39
+ // rather than letting one bad row hang the batch.
40
+ const shortCapped = short.slice(0, 4000);
41
+ const longCapped = long.slice(0, 20000);
42
+ for (let i = 0; i < shortCapped.length; i++) {
43
+ for (let j = i + 1; j <= shortCapped.length; j++) {
44
+ const piece = shortCapped.slice(i, j);
45
+ if (piece.length <= best) continue;
46
+ if (longCapped.includes(piece)) best = piece.length;
47
+ else break; // longer pieces starting at i won't match either
48
+ }
49
+ }
50
+ return best;
51
+ }
52
+
53
+ // Codex wraps every command in its own shell invocation before running it
54
+ // (e.g. "/bin/zsh -lc <what the model actually asked for>") — that wrapper
55
+ // text never appears in the model's proposed arguments, so it must be
56
+ // stripped before comparing, or it dilutes even an exact match's score.
57
+ const SHELL_WRAPPER_PREFIX = /^\/bin\/(?:zsh|bash|sh)\s+-[a-z]+\s+/i;
58
+
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. */
68
+ export function similarity(executedCommand, candidateArgs) {
69
+ const command = String(executedCommand ?? '').toLowerCase().replace(SHELL_WRAPPER_PREFIX, '');
70
+ const candidateText = flattenText(candidateArgs);
71
+ if (!command || !candidateText) return 0;
72
+ return longestCommonSubstringLength(command, candidateText) / command.length;
73
+ }
74
+
75
+ const MATCH_THRESHOLD = 0.6; // below this, treat as "no confident match"
76
+ const DEFAULT_WINDOW_MS = 30_000; // how far a candidate's timestamp may drift from the execution's
77
+ // A causal window with no result yet stays open this long. Past that, a call
78
+ // that never ran must stop competing for every later look-alike command.
79
+ export const OPEN_WINDOW_CAP_MS = 10 * 60_000;
80
+ const DEFAULT_MARGIN_MS = 2_000; // clock uncertainty when the caller has not measured it
81
+
82
+ /** Whether an execution could have fulfilled this candidate, by time alone.
83
+ *
84
+ * A candidate that carries `window_start` has a *causal* window: the call
85
+ * cannot have run before the request that proposed it started, and it must
86
+ * have started before the agent sent its result back (`window_end`, null
87
+ * while no result has arrived). Those bounds come from the agent's own
88
+ * traffic, so a slow command still matches however late it runs, and a
89
+ * retried proposal cannot claim a run that happened before it existed.
90
+ * `margin` absorbs the uncertainty between the proxy's clock and the
91
+ * clock the execution was timestamped with.
92
+ *
93
+ * A candidate without one keeps a symmetric window around its timestamp. */
94
+ function inTimeWindow(candidate, exec, { windowMs, margin }) {
95
+ if (!Number.isFinite(candidate.window_start)) return Math.abs(candidate.timestamp - exec.timestamp) <= windowMs;
96
+ const end = Number.isFinite(candidate.window_end) ? candidate.window_end : candidate.window_start + OPEN_WINDOW_CAP_MS;
97
+ return exec.timestamp >= candidate.window_start - margin && exec.timestamp <= end + margin;
98
+ }
99
+
100
+ /**
101
+ * @param {{command: string, timestamp: number}} execEvent - parsed CommandExecution
102
+ * @param {Array<{call_id: string, timestamp: number, args: unknown}>} candidates
103
+ * - tool_calls rows in the surrounding time window, each already excluding
104
+ * call_ids matched earlier in this same batch (caller's responsibility —
105
+ * see matchBatch below, which handles that for a whole batch at once).
106
+ * @param {{windowMs?: number}} [options]
107
+ * @returns {{call_id: string, score: number, basis: 'id'|'text'|'order'} | null}
108
+ */
109
+ export function matchExecutionToCall(execEvent, candidates, { windowMs = DEFAULT_WINDOW_MS } = {}) {
110
+ const margin = Number.isFinite(execEvent.margin) ? execEvent.margin : DEFAULT_MARGIN_MS;
111
+ // Newer Codex builds run shell commands through a "unified_exec" path that
112
+ // skips minting its own exec-<uuid> and just reuses the model's own
113
+ // call_id as the CommandExecution's id directly. When that's the case
114
+ // there's no ambiguity to resolve at all — call_id is the tool_calls
115
+ // primary key, so a hit is correct no matter how much time passed between
116
+ // the call being proposed and actually running (a queued or long-delayed
117
+ // command shouldn't lose an otherwise-certain match just because it fell
118
+ // outside the window sized for disambiguating *fuzzy* text matches).
119
+ // Check the full candidate pool, unfiltered by the time window, first.
120
+ const exact = candidates.find((c) => c.call_id === execEvent.id);
121
+ if (exact) return { call_id: exact.call_id, score: 1, basis: 'id' };
122
+
123
+ // No exact id available (older Codex exec-<uuid> path) — fall back to
124
+ // content similarity, which DOES need a time window to stay safe: two
125
+ // near-identical commands run close together could otherwise be
126
+ // ambiguous, so this fallback only considers candidates that could have
127
+ // produced this execution. Text is still required inside a causal window:
128
+ // the agent runs its own helpers (git status, ...) while a call is pending.
129
+ const inWindow = candidates.filter((c) => inTimeWindow(c, execEvent, { windowMs, margin }));
130
+ if (!inWindow.length) return null;
131
+
132
+ // Ties: the causal window that opened most recently, then the closest
133
+ // timestamp. With causal windows a tie means two pending look-alike calls
134
+ // whose windows both cover this run; the newer one is the one the agent
135
+ // was acting on when it ran.
136
+ // Candidates without one keep closest-timestamp alone.
137
+ const newerWindow = (x, y) => Number.isFinite(x.window_start) && Number.isFinite(y.window_start) ? y.window_start - x.window_start : 0;
138
+ const scored = inWindow
139
+ .map((c) => ({ c, score: similarity(execEvent.command, c.args) }))
140
+ .filter((entry) => entry.score >= MATCH_THRESHOLD)
141
+ .sort((x, y) => y.score - x.score
142
+ || newerWindow(x.c, y.c)
143
+ || Math.abs(x.c.timestamp - execEvent.timestamp) - Math.abs(y.c.timestamp - execEvent.timestamp));
144
+
145
+ if (scored.length) {
146
+ const best = scored[0];
147
+ if (!Number.isFinite(best.c.window_start)) return { call_id: best.c.call_id, score: best.score, basis: 'text' };
148
+ // The bounds that justified the match travel with it, so the row can
149
+ // later show why this process was tied to this call.
150
+ return { call_id: best.c.call_id, score: best.score, basis: 'window',
151
+ window_start: best.c.window_start, window_end: Number.isFinite(best.c.window_end) ? best.c.window_end : null };
152
+ }
153
+
154
+ // No candidate's argument text matches well enough — this is deliberately
155
+ // conservative. We do NOT fall back to "closest timestamp, any content" for
156
+ // a single execution in isolation; that risks confidently mislabeling an
157
+ // unrelated call. Pure order-based fallback is only safe *within* a batch
158
+ // of genuinely tied (near-identical) candidates — see matchBatch.
159
+ return null;
160
+ }
161
+
162
+ /**
163
+ * Correlates a whole batch of parsed executions (chronological) against a
164
+ * shared candidate pool, so identical/duplicate commands in the same window
165
+ * pair up in the order they occurred rather than all claiming the same
166
+ * "best" candidate. Each candidate is consumed at most once.
167
+ *
168
+ * @param {Array<{id: string, command: string, timestamp: number}>} execEvents - chronological
169
+ * @param {Array<{call_id: string, timestamp: number, args: unknown}>} candidates
170
+ * @returns {Map<string, {call_id: string, score: number, basis: string}>} exec id -> match
171
+ */
172
+ export function matchBatch(execEvents, candidates, options = {}) {
173
+ const remaining = [...candidates];
174
+ const results = new Map();
175
+ const sortedExecs = [...execEvents].sort((a, b) => a.timestamp - b.timestamp);
176
+
177
+ for (const exec of sortedExecs) {
178
+ const match = matchExecutionToCall(exec, remaining, options);
179
+ if (!match) continue;
180
+ results.set(exec.id, match);
181
+ const claimedIndex = remaining.findIndex((c) => c.call_id === match.call_id);
182
+ if (claimedIndex !== -1) remaining.splice(claimedIndex, 1);
183
+ }
184
+ return results;
185
+ }
@@ -1,5 +1,5 @@
1
1
  import { createHash, randomUUID } from 'node:crypto';
2
- import { TOOL_RESULT_KINDS } from './tool-metadata.mjs';
2
+ import { TOOL_RESULT_KINDS, nativeFileOperation } from './tool-metadata.mjs';
3
3
 
4
4
  export const digest = (value) => createHash('sha256').update(JSON.stringify(value)).digest('hex');
5
5
  const callTypes = new Set(['function_call', 'custom_tool_call', 'tool_use']);
@@ -26,9 +26,12 @@ export function describeCall(argsRaw) {
26
26
  /** The command a tool call proposed, as close to verbatim as its arguments
27
27
  * allow, for showing next to the process that actually ran. Shell tools carry
28
28
  * it as `cmd`/`command` (a string, or an argv whose `bash -lc` wrapper never
29
- * appears in what the model meant); anything else, such as a patch, falls
30
- * back to describeCall's plain-English reading. */
31
- export function proposedCommand(argsRaw) {
29
+ * appears in what the model meant); a native file tool (pass its `name`)
30
+ * carries the file it worked on; anything else, such as a patch, falls back
31
+ * to describeCall's plain-English reading. */
32
+ export function proposedCommand(argsRaw, name) {
33
+ const native = name ? nativeFileOperation(name, argsRaw) : null;
34
+ if (native) return clip(native.text, 200);
32
35
  let args = argsRaw;
33
36
  if (typeof args === 'string') { try { args = JSON.parse(args); } catch { /* raw string args */ } }
34
37
  const value = args && typeof args === 'object' && !Array.isArray(args) ? (args.cmd ?? args.command ?? args.script) : args;
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Failure signatures: collapse repeat failures ("ENOENT /work/a/x.js",
3
+ * "ENOENT /work/b/x.js") into one cluster, Splunk `cluster`-style.
4
+ * Deliberately conservative (under-clusters): volatile parts only --
5
+ * absolute directory prefixes, hex/uuids, bare numbers, quoted temp
6
+ * names -- are normalized; the failing program, error name and file
7
+ * basename survive, so distinct failures stay distinct.
8
+ */
9
+ import { createHash } from 'node:crypto';
10
+
11
+ const ERRORISH = /error|failed|failure|exception|traceback|not found|no such|denied|enoent|eacces|eperm|econn|timeout|timed out|exit(?:ed)? (?:with )?code|panic|fatal|cannot|unable|invalid|syntaxerror|typeerror|referenceerror/i;
12
+
13
+ const RUNNER_HEADER = /^(wall time:|process exited with code|process running with session|chunk id:|output:$|exit code -?\d+$)/i;
14
+
15
+ function pickLine(text) {
16
+ const all = String(text ?? '').split('\n').map((line) => line.trim()).filter(Boolean);
17
+ // The runner's header ("Process exited with code 1") would cluster every
18
+ // failure of a tool together; the output below it is the real signature.
19
+ const lines = all.filter((line) => !RUNNER_HEADER.test(line));
20
+ const pool = lines.length ? lines : all;
21
+ if (!pool.length) return '';
22
+ return pool.find((line) => ERRORISH.test(line)) ?? pool[0];
23
+ }
24
+
25
+ export function normalizeErrorLine(text) {
26
+ let line = pickLine(text).toLowerCase();
27
+ line = line
28
+ .replace(/\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/gi, '<uuid>')
29
+ .replace(/\b0x[0-9a-f]+\b/gi, '<hex>')
30
+ .replace(/\b[0-9a-f]{16,}\b/gi, '<hex>')
31
+ // Absolute paths: keep only the basename (the file that mattered).
32
+ .replace(/(?:\/[\w.@+~-]+){2,}\/([\w.@+~-]+)/g, '<dir>/$1')
33
+ .replace(/\b\d{4}-\d{2}-\d{2}(?:[t ]\d{2}:\d{2}(?::\d{2})?(?:\.\d+)?z?)?\b/g, '<date>')
34
+ .replace(/\b\d+(?:\.\d+)?\s*(?:ms|s|sec|seconds|bytes|kb|mb|gb)\b/g, '<n>$1')
35
+ .replace(/:\d+(?::\d+)?\b/g, ':<n>') // file:line:col
36
+ .replace(/\bpid[= ]\d+\b/g, 'pid=<n>')
37
+ .replace(/\s+/g, ' ')
38
+ .trim()
39
+ .slice(0, 240);
40
+ return line;
41
+ }
42
+
43
+ /**
44
+ * The cluster for one failure. `signature` is stable across runs of the
45
+ * same failure; `label` is the human line shown for the cluster.
46
+ * Returns null when there is no error text to sign.
47
+ */
48
+ export function failureSignature({ errorText, exitCode = null, toolName = null } = {}) {
49
+ const label = normalizeErrorLine(errorText);
50
+ if (!label && exitCode == null) return null;
51
+ const shown = exitCode != null && !/exit/.test(label) ? `exit ${String(exitCode)} · ${label}`.slice(0, 240) : (label || `exit ${String(exitCode)}`);
52
+ const signature = createHash('sha256')
53
+ .update(JSON.stringify([toolName ?? '', exitCode ?? '', label]))
54
+ .digest('hex').slice(0, 16);
55
+ return { signature, label: shown };
56
+ }