@raytrace-cli/cli 0.5.0 → 0.7.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 (59) hide show
  1. package/README.md +54 -2
  2. package/bin/raytrace.mjs +81 -2
  3. package/dist/dashboard/assets/{index-jyV5iYHJ.js → index-Dc3LTk8b.js} +4 -4
  4. package/dist/dashboard/index.html +1 -1
  5. package/package.json +2 -1
  6. package/proxy/agent-intent-schema.test.mjs +142 -0
  7. package/proxy/call-assessment.test.mjs +167 -0
  8. package/proxy/capture.mjs +11 -4
  9. package/proxy/capture.test.mjs +49 -0
  10. package/proxy/claude-code-adapter.mjs +19 -0
  11. package/proxy/claude-code-hook.mjs +3 -1
  12. package/proxy/codex-config.mjs +5 -0
  13. package/proxy/codex.mjs +3 -2
  14. package/proxy/evidence-schema.test.mjs +233 -0
  15. package/proxy/evidence-store.mjs +91 -22
  16. package/proxy/evidence-store.test.mjs +304 -0
  17. package/proxy/exec-narrative.test.mjs +262 -0
  18. package/proxy/execution-correlation.test.mjs +146 -0
  19. package/proxy/execution-runner.test.mjs +38 -0
  20. package/proxy/experiment-engine.test.mjs +93 -0
  21. package/proxy/explanations.test.mjs +20 -0
  22. package/proxy/gvisor-forwarder.test.mjs +368 -0
  23. package/proxy/init-evidence-db.mjs +30 -0
  24. package/proxy/local-token.mjs +30 -0
  25. package/proxy/playground-recovery.test.mjs +130 -0
  26. package/proxy/playground.mjs +31 -3
  27. package/proxy/prompt-traces.test.mjs +32 -0
  28. package/proxy/providers.test.mjs +76 -0
  29. package/proxy/proxy.integration.test.mjs +135 -0
  30. package/proxy/raytace-proxy.mjs +58 -18
  31. package/proxy/request-metrics.test.mjs +19 -0
  32. package/proxy/request-policy.mjs +45 -0
  33. package/proxy/request-policy.test.mjs +47 -0
  34. package/proxy/sandbox-bridge.mjs +3 -0
  35. package/proxy/search.test.mjs +161 -0
  36. package/proxy/smoke.test.mjs +93 -0
  37. package/proxy/step-lab.test.mjs +38 -0
  38. package/proxy/summaries.test.mjs +69 -0
  39. package/proxy/tool-metadata.test.mjs +38 -0
  40. package/proxy/trace-view.mjs +50 -18
  41. package/proxy/trace-view.test.mjs +72 -0
  42. package/proxy/typesafe.test.mjs +39 -0
  43. package/src/api.mjs +57 -0
  44. package/src/auth.mjs +35 -1
  45. package/src/beta.mjs +96 -0
  46. package/src/claude-code.mjs +38 -1
  47. package/src/commands.mjs +69 -25
  48. package/src/config.mjs +16 -7
  49. package/src/export.mjs +200 -0
  50. package/src/lima.mjs +42 -1
  51. package/src/local-sandbox.mjs +19 -4
  52. package/src/paths.mjs +8 -8
  53. package/src/proxy-process.mjs +26 -3
  54. package/src/sandbox.mjs +73 -40
  55. package/src/upload.mjs +198 -0
  56. package/worker/sandbox/claude-hook.mjs +50 -17
  57. package/worker/sandbox/projects.py +3 -2
  58. package/worker/sandbox/transcript-delivery.test.mjs +153 -0
  59. package/worker/sandbox/viewer.py +21 -2
@@ -0,0 +1,146 @@
1
+ import { test } from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { similarity, matchExecutionToCall, matchBatch } from './execution-correlation.mjs';
4
+
5
+ test('similarity: identical command text scores 1.0 regardless of args shape', () => {
6
+ const command = "rg -n 'cost|duration' app/request-metrics.tsx; cat proxy/request-metrics.mjs";
7
+ assert.equal(similarity(command, { command }), 1);
8
+ assert.equal(similarity(command, { cmd: command }), 1); // shape-agnostic — different key name
9
+ assert.equal(similarity(command, command), 1); // bare string args
10
+ });
11
+
12
+ test('similarity: unrelated commands score low', () => {
13
+ const score = similarity('ls -la proxy/', { command: 'npm install --save-dev vitest' });
14
+ assert.ok(score < 0.3, `expected low similarity, got ${score}`);
15
+ });
16
+
17
+ test('matchExecutionToCall picks the real proposed call over an unrelated one in the same window', () => {
18
+ const exec = { id: 'exec-1', command: "cat package.json; cat app/request-metrics.tsx", timestamp: 1_000_000 };
19
+ const candidates = [
20
+ { call_id: 'call_unrelated', timestamp: 1_000_500, args: { command: 'git status --short' } },
21
+ { call_id: 'call_real', timestamp: 1_000_200, args: { command: 'cat package.json; cat app/request-metrics.tsx' } },
22
+ ];
23
+ const match = matchExecutionToCall(exec, candidates);
24
+ assert.equal(match.call_id, 'call_real');
25
+ assert.equal(match.basis, 'text');
26
+ });
27
+
28
+ test('matchExecutionToCall returns null when nothing in the window matches well', () => {
29
+ const exec = { id: 'exec-1', command: 'rm -rf node_modules', timestamp: 1_000_000 };
30
+ const candidates = [{ call_id: 'call_a', timestamp: 1_000_100, args: { command: 'ls -la' } }];
31
+ assert.equal(matchExecutionToCall(exec, candidates), null);
32
+ });
33
+
34
+ test('matchExecutionToCall short-circuits on an exact id match (newer unified_exec Codex builds reuse call_id as the exec id)', () => {
35
+ // No shared command text at all — if this matches, it can only be via the
36
+ // exact-id path, not the fuzzy similarity fallback.
37
+ const exec = { id: 'call_e04139dfcab54327affa0c75', command: 'ls -la proxy/', timestamp: 1_000_000 };
38
+ const candidates = [
39
+ { call_id: 'call_unrelated', timestamp: 1_000_050, args: { command: 'git status --short' } },
40
+ { call_id: 'call_e04139dfcab54327affa0c75', timestamp: 1_000_400, args: { command: 'totally different args text' } },
41
+ ];
42
+ const match = matchExecutionToCall(exec, candidates);
43
+ assert.equal(match.call_id, 'call_e04139dfcab54327affa0c75');
44
+ assert.equal(match.score, 1);
45
+ assert.equal(match.basis, 'id');
46
+ });
47
+
48
+ test('matchExecutionToCall prefers the exact id match over a higher-scoring text match on a different candidate', () => {
49
+ const exec = { id: 'call_abc', command: 'npm test', timestamp: 1_000_000 };
50
+ const candidates = [
51
+ { call_id: 'call_abc', timestamp: 1_000_300, args: { command: 'unrelated text' } },
52
+ { call_id: 'call_xyz', timestamp: 1_000_050, args: { command: 'npm test' } }, // would win on text score alone
53
+ ];
54
+ const match = matchExecutionToCall(exec, candidates);
55
+ assert.equal(match.call_id, 'call_abc');
56
+ assert.equal(match.basis, 'id');
57
+ });
58
+
59
+ test('matchExecutionToCall finds an exact id match even when it falls outside the time window (a queued/delayed command should not lose a certain match)', () => {
60
+ const exec = { id: 'call_1cf2b295fbd94c239a29b2ff', command: 'find ~/.codex -type f -exec grep -l qwen {} \\;', timestamp: 1_000_000 };
61
+ const candidates = [
62
+ { call_id: 'call_1cf2b295fbd94c239a29b2ff', timestamp: 1_000_000 - 31_560, args: { cmd: 'find ~/.codex -type f -exec grep -l qwen {} \\;' } },
63
+ ];
64
+ const match = matchExecutionToCall(exec, candidates, { windowMs: 30_000 });
65
+ assert.equal(match.call_id, 'call_1cf2b295fbd94c239a29b2ff');
66
+ assert.equal(match.score, 1);
67
+ assert.equal(match.basis, 'id');
68
+ });
69
+
70
+ test('matchExecutionToCall ignores candidates outside the time window', () => {
71
+ const exec = { id: 'exec-1', command: 'ls -la', timestamp: 1_000_000 };
72
+ const candidates = [{ call_id: 'call_far', timestamp: 1_000_000 + 60_000, args: { command: 'ls -la' } }];
73
+ assert.equal(matchExecutionToCall(exec, candidates, { windowMs: 30_000 }), null);
74
+ });
75
+
76
+ test('matchBatch resolves duplicate identical commands in chronological order, one candidate each', () => {
77
+ const execs = [
78
+ { id: 'exec-1', command: 'ls -la', timestamp: 1_000_000 },
79
+ { id: 'exec-2', command: 'ls -la', timestamp: 1_000_500 },
80
+ ];
81
+ const candidates = [
82
+ { call_id: 'call_first', timestamp: 999_900, args: { command: 'ls -la' } },
83
+ { call_id: 'call_second', timestamp: 1_000_400, args: { command: 'ls -la' } },
84
+ ];
85
+ const results = matchBatch(execs, candidates);
86
+ assert.equal(results.get('exec-1').call_id, 'call_first'); // earliest exec claims closest-in-time first
87
+ assert.equal(results.get('exec-2').call_id, 'call_second'); // second exec gets what's left, not a re-claim
88
+ });
89
+
90
+ test('matchBatch never assigns the same call_id to two executions', () => {
91
+ const execs = [
92
+ { id: 'exec-1', command: 'npm test', timestamp: 1_000_000 },
93
+ { id: 'exec-2', command: 'npm test', timestamp: 1_000_100 },
94
+ { id: 'exec-3', command: 'npm test', timestamp: 1_000_200 },
95
+ ];
96
+ const candidates = [{ call_id: 'call_only_one', timestamp: 1_000_050, args: { command: 'npm test' } }];
97
+ const results = matchBatch(execs, candidates);
98
+ assert.equal(results.size, 1); // only one candidate existed; the other two executions stay unmatched
99
+ });
100
+
101
+ // Causal windows: a sandbox call can only have run after the request that
102
+ // proposed it started, and before the agent sent its result back.
103
+ const RM = { command: 'rm notes.md' };
104
+ const causal = (call_id, window_start, window_end = null) => ({ call_id, timestamp: window_start, args: RM, window_start, window_end });
105
+
106
+ test('causal window: a retried proposal cannot claim a run from before it existed, and vice versa', () => {
107
+ // call_a proposed at 0, result sent at 5 s; call_b (the retry) proposed at 10 s, still pending.
108
+ const candidates = [causal('call_a', 0, 5_000), causal('call_b', 10_000)];
109
+ assert.deepEqual(matchExecutionToCall({ command: '/bin/bash -lc rm notes.md', timestamp: 12_000, margin: 250 }, candidates),
110
+ { call_id: 'call_b', score: 1, basis: 'window', window_start: 10_000, window_end: null });
111
+ assert.equal(matchExecutionToCall({ command: 'rm notes.md', timestamp: 3_000, margin: 250 }, candidates).call_id, 'call_a');
112
+ });
113
+
114
+ test('causal window: a slow command still matches 45 s after its proposal (the old +-30 s window missed it)', () => {
115
+ const exec = { command: 'rm notes.md', timestamp: 45_000, margin: 250 };
116
+ assert.equal(matchExecutionToCall(exec, [causal('call_a', 0)])?.call_id, 'call_a');
117
+ assert.equal(matchExecutionToCall(exec, [{ call_id: 'call_a', timestamp: 0, args: RM }]), null, 'legacy candidates keep the old window');
118
+ });
119
+
120
+ test('causal window: a run that starts after the result was sent is not that call', () => {
121
+ assert.equal(matchExecutionToCall({ command: 'rm notes.md', timestamp: 8_000, margin: 250 }, [causal('call_a', 0, 5_000)]), null);
122
+ // ...but clock margin still absorbs measured skew at the edges.
123
+ assert.equal(matchExecutionToCall({ command: 'rm notes.md', timestamp: 5_200, margin: 250 }, [causal('call_a', 0, 5_000)])?.call_id, 'call_a');
124
+ assert.equal(matchExecutionToCall({ command: 'rm notes.md', timestamp: -200, margin: 250 }, [causal('call_a', 0, 5_000)])?.call_id, 'call_a');
125
+ });
126
+
127
+ test('causal window: a call that never reported back stops competing after the open-window cap', () => {
128
+ assert.equal(matchExecutionToCall({ command: 'rm notes.md', timestamp: 11 * 60_000, margin: 250 }, [causal('call_a', 0)]), null);
129
+ });
130
+
131
+ test('causal window: text is still required inside the window (agent helpers run while a call is pending)', () => {
132
+ assert.equal(matchExecutionToCall({ command: 'git status --short', timestamp: 1_000, margin: 250 }, [causal('call_a', 0)]), null);
133
+ });
134
+
135
+ test('causal window: two pending look-alikes resolve to the most recently opened one', () => {
136
+ const candidates = [causal('call_old', 0), causal('call_new', 20_000)];
137
+ assert.equal(matchExecutionToCall({ command: 'rm notes.md', timestamp: 21_000, margin: 250 }, candidates).call_id, 'call_new');
138
+ });
139
+
140
+ test('causal window: a window match carries the bounds that justified it', () => {
141
+ assert.deepEqual(matchExecutionToCall({ command: 'rm notes.md', timestamp: 3_000, margin: 250 }, [causal('call_a', 0, 5_000)]),
142
+ { call_id: 'call_a', score: 1, basis: 'window', window_start: 0, window_end: 5_000 });
143
+ // A legacy text match carries none.
144
+ assert.deepEqual(matchExecutionToCall({ command: 'rm notes.md', timestamp: 3_000 }, [{ call_id: 'call_a', timestamp: 0, args: RM }]),
145
+ { call_id: 'call_a', score: 1, basis: 'text' });
146
+ });
@@ -0,0 +1,38 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { mkdtemp, mkdir, writeFile, readFile, rm, symlink } from 'node:fs/promises';
4
+ import { tmpdir } from 'node:os';
5
+ import { join } from 'node:path';
6
+ import { execFile } from 'node:child_process';
7
+ import { promisify } from 'node:util';
8
+ import { createServer } from 'node:http';
9
+ import { once } from 'node:events';
10
+ import { executeSequence, copyWorkspace } from './execution-runner.mjs';
11
+ import { providerConfig } from './providers.mjs';
12
+ const exec = promisify(execFile);
13
+
14
+ test('execution copies current files, isolates secrets, forwards the selected model and enforces the request cap', { timeout: 15000 }, async (t) => {
15
+ const root = await mkdtemp(join(tmpdir(), 'raytace-exec-'));
16
+ t.after(() => rm(root, { recursive: true, force: true }));
17
+ const source = join(root, 'source'); const bin = join(root, 'bin');
18
+ await mkdir(source); await mkdir(bin); await exec('git', ['init', '-q'], { cwd: source });
19
+ await writeFile(join(source, 'transaction.js'), 'original'); await writeFile(join(source, '.env'), 'SECRET=value');
20
+ await symlink(join(source, '.env'), join(source, 'secret-link'));
21
+ const copy = join(root, 'copy'); await mkdir(copy); await copyWorkspace(source, copy);
22
+ assert.equal(await readFile(join(copy, 'transaction.js'), 'utf8'), 'original');
23
+ await assert.rejects(readFile(join(copy, '.env'))); await assert.rejects(readFile(join(copy, 'secret-link')));
24
+ const seen = [];
25
+ const upstream = createServer(async (req, res) => { let body = ''; for await (const chunk of req) body += chunk; seen.push(JSON.parse(body)); res.writeHead(200, { 'content-type': 'application/json' }); res.end('{"status":"completed","output":[]}'); });
26
+ upstream.listen(0, '127.0.0.1'); await once(upstream, 'listening');
27
+ t.after(() => { upstream.closeAllConnections(); upstream.close(); });
28
+ // A fake Codex client exercises the actual gateway without running paid models.
29
+ await writeFile(join(bin, 'codex'), `#!${process.execPath}\nconst fs=require('node:fs'); const a=process.argv.slice(2); const base=a.find(x=>x.startsWith('model_providers.raytace_execution.base_url=')).split('=')[1].replaceAll('"',''); const cwd=a[a.indexOf('--cd')+1]; if(!a.includes('workspace-write')||!a.includes('never')||!a.includes('--ignore-user-config'))process.exit(3); fs.writeFileSync(cwd+'/transaction.js','edited copy'); let prompt='';process.stdin.on('data',x=>prompt+=x);process.stdin.on('end',async()=>{for(let i=0;i<3;i++){const r=await fetch(base+'/responses',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({model:'wrong',input:prompt})});await r.text();console.log(JSON.stringify({type:'item.completed',item:{type:'agent_message',text:'done'}}));} });`, { mode: 0o755 });
30
+ const oldPath = process.env.PATH; process.env.PATH = `${bin}:${oldPath}`;
31
+ t.after(() => { process.env.PATH = oldPath; });
32
+ const routing = providerConfig({ RAYTACE_PROVIDER: 'openrouter', OPENROUTER_API_KEY: 'test', RAYTACE_OPENROUTER_UPSTREAM: `http://127.0.0.1:${upstream.address().port}` });
33
+ const job = { id: 'test-run', model: routing.defaultModel, max_requests: 2, events: [] };
34
+ await executeSequence(job, { input: [{ role: 'user', content: 'fix transaction' }] }, routing, source, join(root, 'runs'), new AbortController().signal);
35
+ assert.equal(job.status, 'limited'); assert.equal(seen.length, 2); assert.equal(seen[0].model, routing.defaultModel);
36
+ assert.equal(await readFile(join(source, 'transaction.js'), 'utf8'), 'original');
37
+ assert.equal(await readFile(join(job.workspace, 'transaction.js'), 'utf8'), 'edited copy');
38
+ });
@@ -0,0 +1,93 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { createExperiment, evidenceFor, makeVariant, matchesTarget, outcome, replayEligibility, runExperiment, summarize, validateTarget, wilson } from './experiment-engine.mjs';
4
+
5
+ const response = (name = 'read_file', args = '{"path":"auth.ts"}') => ({ status: 'completed', output: [{ type: 'function_call', name, arguments: args }] });
6
+ const entry = () => ({ provider: 'openai', route: '/v1/responses', payload: { model: 'fixture-model', stream: true, reasoning: { effort: 'medium' }, tools: [{ type: 'function', name: 'read_file' }], input: [
7
+ { type: 'message', role: 'user', content: 'Search found auth.ts' },
8
+ { type: 'function_call', name: 'read_file', call_id: 'call-1', arguments: '{"path":"auth.ts"}' },
9
+ { type: 'function_call_output', call_id: 'call-1', output: 'session validator' },
10
+ { type: 'message', role: 'user', content: 'Fix the login bug.' },
11
+ ] }, response: response() });
12
+ const config = (overrides = {}) => ({ exchange_id: 'capture', evidence_id: 'capture:0', repetitions: 5, target: { type: 'original_action' }, ...overrides });
13
+
14
+ test('withholding output preserves call/result pairing and original request', () => {
15
+ const source = entry(); const before = structuredClone(source.payload);
16
+ const evidence = evidenceFor(source.payload, 'capture').find((item) => item.index === 2);
17
+ const changed = makeVariant(source.payload, evidence);
18
+ assert.equal(changed.input[2].output, ''); assert.equal(changed.input[2].call_id, 'call-1');
19
+ assert.equal(changed.input.length, 4); assert.equal(evidence.source_call.name, 'read_file');
20
+ assert.deepEqual(source.payload, before);
21
+ assert.equal(makeVariant(source.payload, evidenceFor(source.payload, 'capture')[0]).input.length, 3);
22
+ });
23
+
24
+ test('Wilson intervals are bounded and remain uncertain at zero/all successes', () => {
25
+ assert.equal(wilson(0,0), null);
26
+ assert.ok(wilson(0,20)[1] > .16 && wilson(0,20)[1] < .162);
27
+ assert.ok(wilson(20,20)[0] > .838 && wilson(20,20)[0] < .84);
28
+ assert.ok(wilson(16,20)[0] < .59 && wilson(16,20)[1] > .91);
29
+ });
30
+
31
+ test('16/20 vs 5/20 yields 55 percentage points and a positive difference interval', () => {
32
+ const trials = ['baseline','intervention'].flatMap((arm) => Array.from({length:20}, (_, i) => ({ arm, status:'succeeded', matches: i < (arm === 'baseline' ? 16 : 5), outcome: {key:'call',label:'read_file'} })));
33
+ trials.push({ arm:'baseline', status:'failed' });
34
+ const summary = summarize(trials);
35
+ assert.equal(summary.baseline.rate, .8); assert.equal(summary.intervention.rate, .25);
36
+ assert.equal(summary.baseline.failed, 1); assert.equal(summary.baseline.successful, 20);
37
+ assert.ok(Math.abs(summary.effect.difference - .55) < 1e-10);
38
+ assert.ok(summary.effect.interval[0] > 0);
39
+ assert.equal(summarize([]).effect, null);
40
+ });
41
+
42
+ test('same tool with different file arguments differs; canonical JSON key order does not', () => {
43
+ const recorded = outcome(response('read_file', '{"path":"auth.ts","start":1}'));
44
+ const target = validateTarget({type:'original_action'}, recorded);
45
+ assert.equal(matchesTarget(outcome(response('read_file','{"start":1,"path":"auth.ts"}')), target), true);
46
+ assert.equal(matchesTarget(outcome(response('read_file','{"path":"billing.ts"}')), target), false);
47
+ assert.equal(matchesTarget(outcome(response()), {type:'tool_contains',name:'read_file',contains:'auth.ts'}), true);
48
+ const answer = outcome({status:'completed',output:[{type:'message',content:[{type:'output_text',text:'The session is valid'}]}]});
49
+ assert.equal(matchesTarget(answer, {type:'answer_contains',contains:'SESSION'}), true);
50
+ assert.throws(() => outcome({status:'incomplete',output:[]}), /incomplete/);
51
+ assert.throws(() => outcome({status:'completed',output:[]}), /No observable/);
52
+ });
53
+
54
+ test('reject unsupported/stateful/hosted tool snapshots and invalid trial budgets', () => {
55
+ const source = entry();
56
+ assert.equal(replayEligibility(source), null);
57
+ assert.match(replayEligibility({...source, provider:'anthropic'}), /Responses/);
58
+ source.payload.previous_response_id = 'resp_old'; assert.match(replayEligibility(source), /server-side/); delete source.payload.previous_response_id;
59
+ source.payload.tools.push({type:'web_search'}); assert.match(replayEligibility(source), /server-executed/);
60
+ assert.throws(() => createExperiment(entry(), config({repetitions:21})), /2–20/);
61
+ assert.throws(() => createExperiment(entry(), config({evidence_id:'wrong:0'})), /exact request/);
62
+ });
63
+
64
+ test('repeated trials invoke both arms and never use the recorded response as a trial', async () => {
65
+ const source = entry(); const original = structuredClone(source.payload); const job = createExperiment(source, config());
66
+ let count = 0;
67
+ await runExperiment(job, source, { random: () => .2, invoke: async (payload) => {
68
+ count++; assert.equal(payload.stream,true); assert.deepEqual(payload.reasoning,{effort:'medium'});
69
+ return payload.input.some((item)=>item.content === 'Search found auth.ts') ? response() : response('search', '{}');
70
+ }});
71
+ assert.equal(count,10); assert.equal(job.status,'completed'); assert.equal(job.summary.baseline.hits,5);
72
+ assert.equal(job.summary.intervention.hits,0); assert.deepEqual(source.payload,original);
73
+ assert.notEqual(job.snapshot_hash,job.variant_hash);
74
+ });
75
+
76
+ test('cancellation and provider errors stop future paid requests and preserve partial counts', async () => {
77
+ const source = entry(); const job = createExperiment(source, config()); const controller = new AbortController();
78
+ await runExperiment(job,source,{signal:controller.signal,invoke:async()=>response(),onUpdate:async()=>{if(job.trials.length===1)controller.abort();}});
79
+ assert.equal(job.status,'cancelled'); assert.equal(job.trials.length,1);
80
+ const failed = createExperiment(source,config());
81
+ await runExperiment(failed,source,{random:()=>0,invoke:async()=>{throw new Error('provider failed');}});
82
+ assert.equal(failed.status,'failed'); assert.equal(failed.trials.length,1);
83
+ assert.equal(failed.summary.baseline.failed,1); assert.equal(failed.summary.baseline.rate,null);
84
+ });
85
+
86
+ test('proposedCommand shows the command a call proposed, without the shell wrapper', async () => {
87
+ const { proposedCommand } = await import('./experiment-engine.mjs');
88
+ assert.equal(proposedCommand('{"cmd":"rm notes.md","workdir":"/workspace"}'), 'rm notes.md');
89
+ assert.equal(proposedCommand({ command: ['bash', '-lc', 'npm test'] }), 'npm test');
90
+ assert.equal(proposedCommand({ command: ['/bin/zsh', '-lc', 'git status'] }), 'git status');
91
+ assert.equal(proposedCommand({ command: ['ls', '-la'] }), 'ls -la');
92
+ assert.equal(proposedCommand('*** Begin Patch\n*** Update File: src/app.ts\n*** End Patch'), 'edited src/app.ts');
93
+ });
@@ -0,0 +1,20 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { explanationRequest, parseExplanations } from './explanations.mjs';
4
+ const sources = [{ evidence_id: 'a', text: 'transaction.js defines returnPayment()' }];
5
+ const hypothesis = { evidence_id: 'a', title: 'The search identified the payment implementation', explanation: 'This earlier search result identifies a file relevant to the task.', excerpt: 'transaction.js defines returnPayment()' };
6
+ const response = (hypotheses) => ({ status: 'completed', output: [{ type: 'message', content: [{ text: JSON.stringify({ hypotheses }) }] }] });
7
+ test('explanations require valid source IDs and exact quotes and remove duplicate titles', () => {
8
+ const result = parseExplanations(response([hypothesis, hypothesis, { ...hypothesis, title: 'Invented', excerpt: 'not in source' }, { ...hypothesis, title: 'Wrong source', evidence_id: 'b' }]), sources);
9
+ assert.equal(result.hypotheses.length, 1);
10
+ assert.equal(result.reported_cost, null);
11
+ assert.deepEqual(parseExplanations(response([]), sources).hypotheses, []);
12
+ assert.throws(() => parseExplanations({ status: 'incomplete' }, sources), /incomplete/);
13
+ });
14
+ test('request is bounded and cache key changes with configured model', () => {
15
+ const step = { decision: { label: 'read transaction.js' }, hypotheses: [], evidence: Array.from({length: 30}, (_, i) => ({ id: String(i), kind: 'user', content: 'x'.repeat(10000) })) };
16
+ const a = explanationRequest(step, 'a/model'); const b = explanationRequest(step, 'b/model');
17
+ assert.notEqual(a.key, b.key);
18
+ assert.ok(a.sources.reduce((sum, item) => sum + item.text.length, 0) <= 16000);
19
+ assert.equal(a.payload.model, 'a/model'); assert.equal(a.payload.tools, undefined);
20
+ });