opencode-agent-orchestration-kit 1.0.29 → 1.0.31

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.
@@ -0,0 +1,1906 @@
1
+ import assert from "node:assert/strict";
2
+ import fs from "node:fs";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import { spawnSync } from "node:child_process";
6
+ import test from "node:test";
7
+ import { fileURLToPath } from "node:url";
8
+
9
+ import {
10
+ parseLiveArguments,
11
+ runLiveReplay,
12
+ runtimeConfig,
13
+ spawnProcessWithTimeout,
14
+ } from "./run-routing-live-replay.mjs";
15
+
16
+ const scriptDir = path.dirname(fileURLToPath(import.meta.url));
17
+ const root = path.dirname(scriptDir);
18
+ const corpus = path.join(
19
+ root,
20
+ "docs",
21
+ "ai",
22
+ "evolution",
23
+ "benchmarks",
24
+ "router-scenarios.jsonl",
25
+ );
26
+ const scenarios = fs.readFileSync(corpus, "utf8").trim().split("\n").map(JSON.parse);
27
+ const freeformScenario = scenarios.find((row) => row.id === "freeform-ambiguous-clarify");
28
+ const featureScenario = scenarios.find((row) => row.command_path === "/feature");
29
+
30
+ function makeHarnessSource() {
31
+ const source = fs.mkdtempSync(path.join(os.tmpdir(), "routing-live-source-"));
32
+ fs.mkdirSync(path.join(source, "agents"));
33
+ fs.mkdirSync(path.join(source, "commands"));
34
+ fs.mkdirSync(path.join(source, "skills", "safe"), { recursive: true });
35
+ fs.mkdirSync(
36
+ path.join(source, "docs", "ai", "evolution", "benchmarks"),
37
+ { recursive: true },
38
+ );
39
+ fs.writeFileSync(path.join(source, "AGENTS.md"), "# Safe fixture\n");
40
+ fs.writeFileSync(path.join(source, "agents", "lead.md"), "# Lead\n");
41
+ fs.writeFileSync(path.join(source, "commands", "feature.md"), "# Feature\n");
42
+ fs.writeFileSync(path.join(source, "skills", "safe", "SKILL.md"), "# Safe\n");
43
+ fs.writeFileSync(
44
+ path.join(source, "docs", "ai", "evolution", "benchmarks", "router-scenarios.jsonl"),
45
+ `${JSON.stringify(freeformScenario)}\n`,
46
+ );
47
+ fs.writeFileSync(path.join(source, "opencode.json"), '{"private":"must-not-be-read"}\n');
48
+ fs.writeFileSync(path.join(source, "opencode.jsonc"), '{"private":"must-not-be-read"}\n');
49
+ for (const excluded of [".git", "node_modules", ".opencode", "artifacts", "raw"]) {
50
+ fs.mkdirSync(path.join(source, excluded), { recursive: true });
51
+ fs.writeFileSync(path.join(source, excluded, "canary.txt"), "never-copy");
52
+ }
53
+ return source;
54
+ }
55
+
56
+ function rootLine(id = "root-real") {
57
+ return JSON.stringify({
58
+ type: "session.created",
59
+ properties: { info: { id, parentID: null, agent: "lead" } },
60
+ });
61
+ }
62
+
63
+ function childSessionLine({
64
+ id = "child-real",
65
+ parentID = "root-real",
66
+ agent = "developer",
67
+ } = {}) {
68
+ return JSON.stringify({
69
+ type: "session.created",
70
+ properties: { info: { id, parentID, agent } },
71
+ });
72
+ }
73
+
74
+ function stopLine(condition = "clarification-required") {
75
+ return JSON.stringify({
76
+ type: "stop.observed",
77
+ properties: { condition },
78
+ });
79
+ }
80
+
81
+ function coverageLine(channels = [
82
+ "skill_events",
83
+ "tool_events",
84
+ "review_events",
85
+ "stop_events",
86
+ ]) {
87
+ return JSON.stringify({
88
+ type: "capture.complete",
89
+ properties: { channels },
90
+ });
91
+ }
92
+
93
+ function makeTree(rootId = "root-real", children = []) {
94
+ return {
95
+ root_session_id: rootId,
96
+ root_session: {
97
+ session_id: rootId,
98
+ parent_session_id: null,
99
+ agent: "lead",
100
+ },
101
+ child_sessions: children,
102
+ };
103
+ }
104
+
105
+ function makeDeps(overrides = {}) {
106
+ const calls = {
107
+ spawn: [],
108
+ collect: [],
109
+ remove: [],
110
+ sourceSnapshots: [],
111
+ };
112
+ const deps = {
113
+ makeTempDir: async () => fs.mkdtempSync(path.join(os.tmpdir(), "routing-live-run-")),
114
+ spawnProcess: async (command, args, options) => {
115
+ calls.spawn.push({ command, args, options });
116
+ return {
117
+ exitCode: 0,
118
+ stdout: `${rootLine()}\n${stopLine()}\n`,
119
+ stderr: "",
120
+ timedOut: false,
121
+ cancelled: false,
122
+ };
123
+ },
124
+ collectExecutionTreeByRoot: async (dbPath, rootId) => {
125
+ calls.collect.push({ dbPath, rootId });
126
+ return makeTree(rootId);
127
+ },
128
+ readOpenCodeDbPath: async () => "/tmp/fake-opencode.db",
129
+ wait: async () => {},
130
+ removeTree: async (target) => {
131
+ calls.remove.push(target);
132
+ fs.rmSync(target, { recursive: true, force: true });
133
+ },
134
+ ...overrides,
135
+ };
136
+ return { deps, calls };
137
+ }
138
+
139
+ function validOptions(sourceRoot, scenario = freeformScenario) {
140
+ return {
141
+ scenarioId: scenario.id,
142
+ confirmLive: true,
143
+ timeoutMs: 5_000,
144
+ sourceRoot,
145
+ scenarios,
146
+ protectedRoots: [root],
147
+ };
148
+ }
149
+
150
+ function collectStrings(value) {
151
+ if (typeof value === "string") return [value];
152
+ if (Array.isArray(value)) return value.flatMap(collectStrings);
153
+ if (value && typeof value === "object") {
154
+ return Object.values(value).flatMap(collectStrings);
155
+ }
156
+ return [];
157
+ }
158
+
159
+ test("live argument parser accepts only the explicit portable interface", () => {
160
+ assert.deepEqual(
161
+ parseLiveArguments([
162
+ "--scenario",
163
+ freeformScenario.id,
164
+ "--confirm-live",
165
+ "--timeout-ms",
166
+ "1234",
167
+ "--retain-private-output",
168
+ "/tmp/private-live-output",
169
+ ]),
170
+ {
171
+ scenarioId: freeformScenario.id,
172
+ confirmLive: true,
173
+ timeoutMs: 1234,
174
+ retainPrivateOutput: "/tmp/private-live-output",
175
+ },
176
+ );
177
+ });
178
+
179
+ test("CLI validation exits 2 without reaching OpenCode", () => {
180
+ const script = path.join(scriptDir, "run-routing-live-replay.mjs");
181
+ const result = spawnSync(process.execPath, [
182
+ script,
183
+ "--scenario",
184
+ freeformScenario.id,
185
+ ], { cwd: root, encoding: "utf8" });
186
+ assert.equal(result.status, 2);
187
+ assert.match(result.stderr, /--confirm-live is required/);
188
+ assert.equal(result.stdout, "");
189
+ });
190
+
191
+ for (const args of [
192
+ [],
193
+ ["--scenario", freeformScenario.id],
194
+ ["--scenario", freeformScenario.id, "--confirm-live", "--unknown"],
195
+ ["--scenario", freeformScenario.id, "--confirm-live", "--timeout-ms", "0"],
196
+ ["--scenario", freeformScenario.id, "--confirm-live", "--timeout-ms", "-1"],
197
+ ["--scenario", freeformScenario.id, "--confirm-live", "--retain-private-output", "relative"],
198
+ ...["--model", "--provider", "--variant", "--auto", "--attach", "--password", "--username"]
199
+ .map((option) => ["--scenario", freeformScenario.id, "--confirm-live", option, "x"]),
200
+ ]) {
201
+ test(`live argument parser rejects ${args.join(" ") || "missing scenario"}`, () => {
202
+ assert.throws(() => parseLiveArguments(args), { name: "LiveReplayError" });
203
+ });
204
+ }
205
+
206
+ test("runLiveReplay rejects unknown scenarios before spawning", async () => {
207
+ const source = makeHarnessSource();
208
+ const { deps, calls } = makeDeps();
209
+ try {
210
+ const result = await runLiveReplay({
211
+ ...validOptions(source),
212
+ scenarioId: "unknown-scenario",
213
+ }, deps);
214
+ assert.equal(result.exitCode, 2);
215
+ assert.equal(calls.spawn.length, 0);
216
+ } finally {
217
+ fs.rmSync(source, { recursive: true, force: true });
218
+ }
219
+ });
220
+
221
+ test("runLiveReplay validates the closed corpus before temp materialization or spawn", async () => {
222
+ const source = makeHarnessSource();
223
+ let tempCalls = 0;
224
+ const { deps, calls } = makeDeps({
225
+ makeTempDir: async () => {
226
+ tempCalls += 1;
227
+ return fs.mkdtempSync(path.join(os.tmpdir(), "must-not-materialize-"));
228
+ },
229
+ });
230
+ const invalidScenario = {
231
+ ...freeformScenario,
232
+ unexpected_private_key: "/private/provider",
233
+ };
234
+ try {
235
+ const result = await runLiveReplay({
236
+ ...validOptions(source),
237
+ scenarios: [invalidScenario],
238
+ }, deps);
239
+ assert.equal(result.exitCode, 2);
240
+ assert.equal(result.error, "Live replay corpus is invalid.");
241
+ assert.equal(tempCalls, 0);
242
+ assert.equal(calls.spawn.length, 0);
243
+ assert.equal(JSON.stringify(result).includes("/private/"), false);
244
+ } finally {
245
+ fs.rmSync(source, { recursive: true, force: true });
246
+ }
247
+ });
248
+
249
+ test("runLiveReplay requires explicit live confirmation before spawning", async () => {
250
+ const source = makeHarnessSource();
251
+ const { deps, calls } = makeDeps();
252
+ try {
253
+ const result = await runLiveReplay({
254
+ ...validOptions(source),
255
+ confirmLive: false,
256
+ }, deps);
257
+ assert.equal(result.exitCode, 2);
258
+ assert.equal(calls.spawn.length, 0);
259
+ } finally {
260
+ fs.rmSync(source, { recursive: true, force: true });
261
+ }
262
+ });
263
+
264
+ test("freeform rejects a non-lead expected root before spawning", async () => {
265
+ const source = makeHarnessSource();
266
+ const scenario = {
267
+ ...freeformScenario,
268
+ expected_root_agent: "developer",
269
+ };
270
+ const { deps, calls } = makeDeps();
271
+ try {
272
+ const result = await runLiveReplay({
273
+ ...validOptions(source),
274
+ scenarios: [scenario],
275
+ }, deps);
276
+ assert.equal(result.exitCode, 2);
277
+ assert.equal(calls.spawn.length, 0);
278
+ } finally {
279
+ fs.rmSync(source, { recursive: true, force: true });
280
+ }
281
+ });
282
+
283
+ test("runLiveReplay rejects protected retain destinations before spawning", async () => {
284
+ const source = makeHarnessSource();
285
+ const { deps, calls } = makeDeps();
286
+ try {
287
+ const result = await runLiveReplay({
288
+ ...validOptions(source),
289
+ retainPrivateOutput: path.join(root, "private-output"),
290
+ }, deps);
291
+ assert.equal(result.exitCode, 2);
292
+ assert.equal(calls.spawn.length, 0);
293
+ } finally {
294
+ fs.rmSync(source, { recursive: true, force: true });
295
+ }
296
+ });
297
+
298
+ test("runLiveReplay rejects retention inside any Git worktree before spawning", async () => {
299
+ const source = makeHarnessSource();
300
+ const otherRepo = fs.mkdtempSync(path.join(os.tmpdir(), "routing-live-other-repo-"));
301
+ spawnSync("git", ["init", "--quiet"], { cwd: otherRepo });
302
+ const { deps, calls } = makeDeps();
303
+ try {
304
+ const result = await runLiveReplay({
305
+ ...validOptions(source),
306
+ retainPrivateOutput: path.join(otherRepo, "private-output"),
307
+ }, deps);
308
+ assert.equal(result.exitCode, 2);
309
+ assert.equal(calls.spawn.length, 0);
310
+ } finally {
311
+ fs.rmSync(source, { recursive: true, force: true });
312
+ fs.rmSync(otherRepo, { recursive: true, force: true });
313
+ }
314
+ });
315
+
316
+ test("runLiveReplay rejects a non-empty retention directory before spawning", async () => {
317
+ const source = makeHarnessSource();
318
+ const destination = fs.realpathSync(
319
+ fs.mkdtempSync(path.join(os.tmpdir(), "routing-live-nonempty-retain-")),
320
+ );
321
+ fs.writeFileSync(path.join(destination, "existing"), "do not overwrite");
322
+ const { deps, calls } = makeDeps();
323
+ try {
324
+ const result = await runLiveReplay({
325
+ ...validOptions(source),
326
+ retainPrivateOutput: destination,
327
+ }, deps);
328
+ assert.equal(result.exitCode, 2);
329
+ assert.equal(calls.spawn.length, 0);
330
+ } finally {
331
+ fs.rmSync(source, { recursive: true, force: true });
332
+ fs.rmSync(destination, { recursive: true, force: true });
333
+ }
334
+ });
335
+
336
+ test("live adapter materializes a clean disposable repository and never copies private config", async () => {
337
+ const source = makeHarnessSource();
338
+ const sourceBefore = fs.readdirSync(source).sort();
339
+ let inspectedTemp;
340
+ const { deps, calls } = makeDeps({
341
+ spawnProcess: async (command, args, options) => {
342
+ calls.spawn.push({ command, args, options });
343
+ inspectedTemp = options.cwd;
344
+ assert.ok(inspectedTemp.startsWith(`${fs.realpathSync(os.tmpdir())}${path.sep}`));
345
+ assert.deepEqual(
346
+ JSON.parse(fs.readFileSync(path.join(inspectedTemp, "opencode.json"), "utf8")),
347
+ runtimeConfig,
348
+ );
349
+ assert.equal(fs.existsSync(path.join(inspectedTemp, "opencode.jsonc")), false);
350
+ assert.equal(
351
+ fs.existsSync(path.join(
352
+ inspectedTemp,
353
+ "docs",
354
+ "ai",
355
+ "evolution",
356
+ "benchmarks",
357
+ "router-scenarios.jsonl",
358
+ )),
359
+ true,
360
+ );
361
+ for (const excluded of ["node_modules", ".opencode", "artifacts", "raw"]) {
362
+ assert.equal(fs.existsSync(path.join(inspectedTemp, excluded)), false);
363
+ }
364
+ assert.ok(fs.existsSync(path.join(inspectedTemp, ".git")));
365
+ return {
366
+ exitCode: 0,
367
+ stdout: `${rootLine()}\n${stopLine()}\n${coverageLine()}\n`,
368
+ stderr: "",
369
+ timedOut: false,
370
+ cancelled: false,
371
+ };
372
+ },
373
+ });
374
+ try {
375
+ const result = await runLiveReplay(validOptions(source), deps);
376
+ assert.equal(result.exitCode, 0);
377
+ assert.equal(calls.remove.length, 1);
378
+ assert.equal(fs.existsSync(inspectedTemp), false);
379
+ assert.deepEqual(fs.readdirSync(source).sort(), sourceBefore);
380
+ } finally {
381
+ fs.rmSync(source, { recursive: true, force: true });
382
+ }
383
+ });
384
+
385
+ test("live adapter rejects symlinks in the portable source", async () => {
386
+ const source = makeHarnessSource();
387
+ fs.symlinkSync("/tmp", path.join(source, "agents", "unsafe-link"));
388
+ const { deps, calls } = makeDeps();
389
+ try {
390
+ const result = await runLiveReplay(validOptions(source), deps);
391
+ assert.equal(result.exitCode, 2);
392
+ assert.equal(calls.spawn.length, 0);
393
+ assert.equal(calls.remove.length, 1);
394
+ } finally {
395
+ fs.rmSync(source, { recursive: true, force: true });
396
+ }
397
+ });
398
+
399
+ test("live adapter rejects a symlink in an intermediate corpus path before spawning", async () => {
400
+ const source = makeHarnessSource();
401
+ const external = fs.mkdtempSync(path.join(os.tmpdir(), "routing-live-external-docs-"));
402
+ fs.mkdirSync(
403
+ path.join(external, "ai", "evolution", "benchmarks"),
404
+ { recursive: true },
405
+ );
406
+ fs.writeFileSync(
407
+ path.join(external, "ai", "evolution", "benchmarks", "router-scenarios.jsonl"),
408
+ `${JSON.stringify(freeformScenario)}\n`,
409
+ );
410
+ fs.rmSync(path.join(source, "docs"), { recursive: true });
411
+ fs.symlinkSync(external, path.join(source, "docs"));
412
+ const { deps, calls } = makeDeps();
413
+ try {
414
+ const result = await runLiveReplay(validOptions(source), deps);
415
+ assert.equal(result.exitCode, 2);
416
+ assert.equal(calls.spawn.length, 0);
417
+ assert.equal(calls.remove.length, 1);
418
+ } finally {
419
+ fs.rmSync(source, { recursive: true, force: true });
420
+ fs.rmSync(external, { recursive: true, force: true });
421
+ }
422
+ });
423
+
424
+ test("live adapter rejects a missing portable corpus before spawning", async () => {
425
+ const source = makeHarnessSource();
426
+ fs.rmSync(path.join(
427
+ source,
428
+ "docs",
429
+ "ai",
430
+ "evolution",
431
+ "benchmarks",
432
+ "router-scenarios.jsonl",
433
+ ));
434
+ const { deps, calls } = makeDeps();
435
+ try {
436
+ const result = await runLiveReplay(validOptions(source), deps);
437
+ assert.equal(result.exitCode, 2);
438
+ assert.equal(calls.spawn.length, 0);
439
+ assert.equal(calls.remove.length, 1);
440
+ } finally {
441
+ fs.rmSync(source, { recursive: true, force: true });
442
+ }
443
+ });
444
+
445
+ test("live adapter rejects a raw-capture symlink created during the run", async () => {
446
+ const source = makeHarnessSource();
447
+ const outside = fs.mkdtempSync(path.join(os.tmpdir(), "routing-live-outside-"));
448
+ const { deps } = makeDeps({
449
+ spawnProcess: async (command, args, options) => {
450
+ fs.rmSync(path.join(options.cwd, ".opencode-live"), { recursive: true, force: true });
451
+ fs.symlinkSync(outside, path.join(options.cwd, ".opencode-live"));
452
+ return {
453
+ exitCode: 0,
454
+ stdout: `${rootLine()}\n`,
455
+ stderr: "must stay contained",
456
+ timedOut: false,
457
+ cancelled: false,
458
+ };
459
+ },
460
+ });
461
+ try {
462
+ const result = await runLiveReplay(validOptions(source), deps);
463
+ assert.equal(result.exitCode, 2);
464
+ assert.equal(result.report, undefined);
465
+ assert.deepEqual(fs.readdirSync(outside), []);
466
+ } finally {
467
+ fs.rmSync(source, { recursive: true, force: true });
468
+ fs.rmSync(outside, { recursive: true, force: true });
469
+ }
470
+ });
471
+
472
+ test("raw files exist as regular mode-0600 files before spawn and a swap cannot overwrite a target", async () => {
473
+ const source = makeHarnessSource();
474
+ const outside = fs.mkdtempSync(path.join(os.tmpdir(), "routing-live-raw-file-target-"));
475
+ const target = path.join(outside, "target.txt");
476
+ fs.writeFileSync(target, "untouched");
477
+ let observedSecureFile = false;
478
+ const { deps } = makeDeps({
479
+ spawnProcess: async (command, args, options) => {
480
+ const stdoutPath = path.join(options.cwd, ".opencode-live", "stdout.jsonl");
481
+ const initial = fs.lstatSync(stdoutPath);
482
+ assert.equal(initial.isFile(), true);
483
+ assert.equal(initial.mode & 0o777, 0o600);
484
+ observedSecureFile = true;
485
+ fs.unlinkSync(stdoutPath);
486
+ fs.symlinkSync(target, stdoutPath);
487
+ options.onStdoutChunk(Buffer.from(`${rootLine()}\n`));
488
+ return {
489
+ exitCode: 0,
490
+ timedOut: false,
491
+ cancelled: false,
492
+ };
493
+ },
494
+ });
495
+ try {
496
+ const result = await runLiveReplay(validOptions(source), deps);
497
+ assert.equal(result.exitCode, 2);
498
+ assert.equal(observedSecureFile, true);
499
+ assert.equal(fs.readFileSync(target, "utf8"), "untouched");
500
+ } finally {
501
+ fs.rmSync(source, { recursive: true, force: true });
502
+ fs.rmSync(outside, { recursive: true, force: true });
503
+ }
504
+ });
505
+
506
+ test("unvalidated non-empty temp candidates are neither used nor deleted", async () => {
507
+ const source = makeHarnessSource();
508
+ const unsafe = fs.mkdtempSync(path.join(os.tmpdir(), "routing-live-unsafe-existing-"));
509
+ const sentinel = path.join(unsafe, "keep-me");
510
+ fs.writeFileSync(sentinel, "user data");
511
+ const { deps, calls } = makeDeps({
512
+ makeTempDir: async () => unsafe,
513
+ });
514
+ try {
515
+ const result = await runLiveReplay(validOptions(source), deps);
516
+ assert.equal(result.exitCode, 2);
517
+ assert.equal(calls.spawn.length, 0);
518
+ assert.equal(calls.remove.length, 0);
519
+ assert.equal(fs.readFileSync(sentinel, "utf8"), "user data");
520
+ } finally {
521
+ fs.rmSync(source, { recursive: true, force: true });
522
+ fs.rmSync(unsafe, { recursive: true, force: true });
523
+ }
524
+ });
525
+
526
+ test("freeform command uses exact argv and verifies lead before launch", async () => {
527
+ const source = makeHarnessSource();
528
+ const { deps, calls } = makeDeps();
529
+ try {
530
+ await runLiveReplay(validOptions(source), deps);
531
+ const call = calls.spawn[0];
532
+ assert.equal(call.command, "opencode");
533
+ assert.deepEqual(call.args, [
534
+ "run",
535
+ "--format",
536
+ "json",
537
+ "--thinking",
538
+ "--dir",
539
+ call.options.cwd,
540
+ freeformScenario.prompt,
541
+ ]);
542
+ assert.equal(call.options.shell, false);
543
+ } finally {
544
+ fs.rmSync(source, { recursive: true, force: true });
545
+ }
546
+ });
547
+
548
+ test("slash command uses exact portable argv", async () => {
549
+ const source = makeHarnessSource();
550
+ const { deps, calls } = makeDeps({
551
+ collectExecutionTreeByRoot: async (dbPath, rootId) => {
552
+ calls.collect.push({ dbPath, rootId });
553
+ return makeTree(rootId, [
554
+ {
555
+ session_id: "child",
556
+ parent_session_id: rootId,
557
+ agent: "researcher",
558
+ },
559
+ ]);
560
+ },
561
+ });
562
+ try {
563
+ await runLiveReplay(validOptions(source, featureScenario), deps);
564
+ const call = calls.spawn[0];
565
+ assert.deepEqual(call.args, [
566
+ "run",
567
+ "--format",
568
+ "json",
569
+ "--thinking",
570
+ "--command",
571
+ "feature",
572
+ "--dir",
573
+ call.options.cwd,
574
+ featureScenario.prompt,
575
+ ]);
576
+ const allArgs = call.args.join(" ");
577
+ for (const forbidden of ["--model", "--provider", "--variant", "--auto", "password", "username"]) {
578
+ assert.equal(allArgs.includes(forbidden), false);
579
+ }
580
+ } finally {
581
+ fs.rmSync(source, { recursive: true, force: true });
582
+ }
583
+ });
584
+
585
+ test("explicit root ID is the only ID passed to the exact-tree collector", async () => {
586
+ const source = makeHarnessSource();
587
+ const { deps, calls } = makeDeps();
588
+ try {
589
+ await runLiveReplay(validOptions(source), deps);
590
+ assert.ok(calls.collect.length >= 1);
591
+ assert.deepEqual(new Set(calls.collect.map((call) => call.rootId)), new Set(["root-real"]));
592
+ } finally {
593
+ fs.rmSync(source, { recursive: true, force: true });
594
+ }
595
+ });
596
+
597
+ test("explicit root evidence outranks generic child session IDs", async () => {
598
+ const source = makeHarnessSource();
599
+ const { deps, calls } = makeDeps({
600
+ spawnProcess: async () => ({
601
+ exitCode: 0,
602
+ stdout: [
603
+ rootLine("root-explicit"),
604
+ JSON.stringify({
605
+ type: "thinking",
606
+ sessionID: "child-generic",
607
+ properties: { text: "discard" },
608
+ }),
609
+ stopLine(),
610
+ ].join("\n"),
611
+ stderr: "",
612
+ timedOut: false,
613
+ cancelled: false,
614
+ }),
615
+ });
616
+ try {
617
+ const result = await runLiveReplay(validOptions(source), deps);
618
+ assert.ok(result.report);
619
+ assert.deepEqual(
620
+ new Set(calls.collect.map((call) => call.rootId)),
621
+ new Set(["root-explicit"]),
622
+ );
623
+ } finally {
624
+ fs.rmSync(source, { recursive: true, force: true });
625
+ }
626
+ });
627
+
628
+ test("stdout child absent from the exact tree makes the approved freeform replay inconclusive", async () => {
629
+ const source = makeHarnessSource();
630
+ const { deps, calls } = makeDeps({
631
+ spawnProcess: async () => ({
632
+ exitCode: 0,
633
+ stdout: [
634
+ rootLine(),
635
+ childSessionLine(),
636
+ stopLine(),
637
+ coverageLine(),
638
+ ].join("\n"),
639
+ stderr: "",
640
+ timedOut: false,
641
+ cancelled: false,
642
+ }),
643
+ });
644
+ try {
645
+ const result = await runLiveReplay(validOptions(source), deps);
646
+ assert.equal(result.exitCode, 3);
647
+ assert.equal(result.report.status, "inconclusive");
648
+ assert.equal(result.observation.observation_coverage.session_events, "partial");
649
+ assert.ok(result.observation.events.some(
650
+ (event) => event.type === "run_error" && event.code === "capture-incomplete",
651
+ ));
652
+ assert.deepEqual(result.report.scenario_results[0].observed_agents, ["lead"]);
653
+ assert.equal(
654
+ result.observation.events.some((event) => event.session_id === "child-real"),
655
+ false,
656
+ );
657
+ assert.deepEqual(
658
+ new Set(calls.collect.map((call) => call.rootId)),
659
+ new Set(["root-real"]),
660
+ );
661
+ } finally {
662
+ fs.rmSync(source, { recursive: true, force: true });
663
+ }
664
+ });
665
+
666
+ for (const scopedCase of [
667
+ {
668
+ name: "session completion",
669
+ event: {
670
+ type: "session.completed",
671
+ properties: { sessionID: "unknown-child", agent: "developer" },
672
+ },
673
+ },
674
+ {
675
+ name: "skill selection",
676
+ event: {
677
+ type: "skill.selected",
678
+ properties: {
679
+ sessionID: "unknown-child",
680
+ agent: "developer",
681
+ skill: "source-driven-development",
682
+ },
683
+ },
684
+ },
685
+ {
686
+ name: "tool completion",
687
+ event: {
688
+ type: "tool.completed",
689
+ properties: {
690
+ sessionID: "unknown-child",
691
+ agent: "developer",
692
+ tool: "read",
693
+ mutation: "read",
694
+ },
695
+ },
696
+ },
697
+ {
698
+ name: "review completion",
699
+ event: {
700
+ type: "review.completed",
701
+ properties: {
702
+ sessionID: "unknown-child",
703
+ agent: "reviewer",
704
+ verdict: "approved",
705
+ },
706
+ },
707
+ },
708
+ {
709
+ name: "stop",
710
+ event: {
711
+ type: "stop.observed",
712
+ properties: {
713
+ sessionID: "unknown-child",
714
+ condition: "clarification-required",
715
+ },
716
+ },
717
+ },
718
+ ]) {
719
+ test(`session-scoped ${scopedCase.name} outside the exact tree degrades session coverage`, async () => {
720
+ const source = makeHarnessSource();
721
+ const { deps, calls } = makeDeps({
722
+ spawnProcess: async () => ({
723
+ exitCode: 0,
724
+ stdout: [
725
+ rootLine(),
726
+ JSON.stringify(scopedCase.event),
727
+ stopLine(),
728
+ coverageLine(),
729
+ ].join("\n"),
730
+ stderr: "",
731
+ timedOut: false,
732
+ cancelled: false,
733
+ }),
734
+ });
735
+ try {
736
+ const result = await runLiveReplay(validOptions(source), deps);
737
+ assert.equal(result.exitCode, 3);
738
+ assert.equal(result.observation.observation_coverage.session_events, "partial");
739
+ assert.ok(result.observation.events.some(
740
+ (event) => event.type === "run_error" && event.code === "capture-incomplete",
741
+ ));
742
+ assert.deepEqual(result.report.scenario_results[0].observed_agents, ["lead"]);
743
+ const scopedEvents = result.observation.events.filter(
744
+ (event) => Object.hasOwn(event, "session_id"),
745
+ );
746
+ assert.ok(scopedEvents.every((event) => event.session_id === "session-1"));
747
+ assert.deepEqual(
748
+ new Set(calls.collect.map((call) => call.rootId)),
749
+ new Set(["root-real"]),
750
+ );
751
+ } finally {
752
+ fs.rmSync(source, { recursive: true, force: true });
753
+ }
754
+ });
755
+ }
756
+
757
+ for (const ignoredType of [
758
+ "thinking",
759
+ "step_start",
760
+ "step_finish",
761
+ "message.part.updated",
762
+ "text",
763
+ ]) {
764
+ test(`ignored session-scoped ${ignoredType} outside the exact tree degrades session coverage`, async () => {
765
+ const source = makeHarnessSource();
766
+ const sensitive = `discard-${ignoredType}-private`;
767
+ const { deps, calls } = makeDeps({
768
+ spawnProcess: async () => ({
769
+ exitCode: 0,
770
+ stdout: [
771
+ rootLine(),
772
+ JSON.stringify({
773
+ type: ignoredType,
774
+ sessionID: "unknown-child",
775
+ properties: { text: sensitive, args: sensitive },
776
+ }),
777
+ stopLine(),
778
+ coverageLine(),
779
+ ].join("\n"),
780
+ stderr: "",
781
+ timedOut: false,
782
+ cancelled: false,
783
+ }),
784
+ });
785
+ try {
786
+ const result = await runLiveReplay(validOptions(source), deps);
787
+ assert.equal(result.exitCode, 3);
788
+ assert.equal(result.report.status, "inconclusive");
789
+ assert.equal(result.observation.observation_coverage.session_events, "partial");
790
+ assert.ok(result.observation.events.some(
791
+ (event) => event.type === "run_error" && event.code === "capture-incomplete",
792
+ ));
793
+ assert.equal(JSON.stringify(result.observation).includes(sensitive), false);
794
+ assert.deepEqual(
795
+ new Set(calls.collect.map((call) => call.rootId)),
796
+ new Set(["root-real"]),
797
+ );
798
+ } finally {
799
+ fs.rmSync(source, { recursive: true, force: true });
800
+ }
801
+ });
802
+ }
803
+
804
+ test("known child thinking is discarded without competing with the explicit root", async () => {
805
+ const source = makeHarnessSource();
806
+ const sensitive = "discard-known-child-private";
807
+ const collectedRootIds = [];
808
+ const scenario = {
809
+ ...freeformScenario,
810
+ forbidden_agents: [],
811
+ maximum_delegation_budget: 1,
812
+ };
813
+ const { deps } = makeDeps({
814
+ spawnProcess: async () => ({
815
+ exitCode: 0,
816
+ stdout: [
817
+ rootLine("root-explicit"),
818
+ JSON.stringify({
819
+ type: "thinking",
820
+ sessionID: "child-known",
821
+ properties: { text: sensitive, args: sensitive },
822
+ }),
823
+ stopLine(),
824
+ coverageLine(),
825
+ ].join("\n"),
826
+ stderr: "",
827
+ timedOut: false,
828
+ cancelled: false,
829
+ }),
830
+ collectExecutionTreeByRoot: async (_dbPath, rootId) => {
831
+ collectedRootIds.push(rootId);
832
+ return makeTree("root-explicit", [{
833
+ session_id: "child-known",
834
+ parent_session_id: "root-explicit",
835
+ agent: "developer",
836
+ }]);
837
+ },
838
+ });
839
+ try {
840
+ const result = await runLiveReplay({
841
+ ...validOptions(source),
842
+ scenarios: [scenario],
843
+ }, deps);
844
+ assert.equal(result.observation.observation_coverage.session_events, "complete");
845
+ assert.equal(result.observation.events.some(
846
+ (event) => event.type === "run_error" && event.code === "capture-incomplete",
847
+ ), false);
848
+ assert.equal(JSON.stringify(result.observation).includes(sensitive), false);
849
+ assert.deepEqual(
850
+ new Set(collectedRootIds),
851
+ new Set(["root-explicit"]),
852
+ );
853
+ } finally {
854
+ fs.rmSync(source, { recursive: true, force: true });
855
+ }
856
+ });
857
+
858
+ for (const contradiction of [
859
+ {
860
+ name: "root agent",
861
+ stdout: [
862
+ JSON.stringify({
863
+ type: "session.created",
864
+ properties: {
865
+ info: { id: "root-real", parentID: null, agent: "developer" },
866
+ },
867
+ }),
868
+ stopLine(),
869
+ coverageLine(),
870
+ ].join("\n"),
871
+ tree: makeTree(),
872
+ expectedAgents: ["lead"],
873
+ },
874
+ {
875
+ name: "child parent",
876
+ stdout: [
877
+ rootLine(),
878
+ childSessionLine({ parentID: "other-parent" }),
879
+ stopLine(),
880
+ coverageLine(),
881
+ ].join("\n"),
882
+ tree: makeTree("root-real", [{
883
+ session_id: "child-real",
884
+ parent_session_id: "root-real",
885
+ agent: "developer",
886
+ }]),
887
+ expectedAgents: ["lead", "developer"],
888
+ },
889
+ {
890
+ name: "child agent",
891
+ stdout: [
892
+ rootLine(),
893
+ childSessionLine({ agent: "reviewer" }),
894
+ stopLine(),
895
+ coverageLine(),
896
+ ].join("\n"),
897
+ tree: makeTree("root-real", [{
898
+ session_id: "child-real",
899
+ parent_session_id: "root-real",
900
+ agent: "developer",
901
+ }]),
902
+ expectedAgents: ["lead", "developer"],
903
+ },
904
+ ]) {
905
+ test(`stdout/tree contradiction in ${contradiction.name} becomes capture-incomplete`, async () => {
906
+ const source = makeHarnessSource();
907
+ const scenario = {
908
+ ...freeformScenario,
909
+ forbidden_agents: [],
910
+ maximum_delegation_budget: 1,
911
+ };
912
+ const { deps } = makeDeps({
913
+ spawnProcess: async () => ({
914
+ exitCode: 0,
915
+ stdout: contradiction.stdout,
916
+ stderr: "",
917
+ timedOut: false,
918
+ cancelled: false,
919
+ }),
920
+ collectExecutionTreeByRoot: async () => contradiction.tree,
921
+ });
922
+ try {
923
+ const result = await runLiveReplay({
924
+ ...validOptions(source),
925
+ scenarios: [scenario],
926
+ }, deps);
927
+ assert.equal(result.exitCode, 3);
928
+ assert.equal(result.observation.observation_coverage.session_events, "partial");
929
+ assert.ok(result.observation.events.some(
930
+ (event) => event.type === "run_error" && event.code === "capture-incomplete",
931
+ ));
932
+ assert.deepEqual(
933
+ result.report.scenario_results[0].observed_agents,
934
+ contradiction.expectedAgents,
935
+ );
936
+ } finally {
937
+ fs.rmSync(source, { recursive: true, force: true });
938
+ }
939
+ });
940
+ }
941
+
942
+ test("exact-root collection retries boundedly until the requested tree stabilizes", async () => {
943
+ const source = makeHarnessSource();
944
+ let attempts = 0;
945
+ const waits = [];
946
+ const { deps, calls } = makeDeps({
947
+ collectExecutionTreeByRoot: async (dbPath, rootId) => {
948
+ calls.collect.push({ dbPath, rootId });
949
+ attempts += 1;
950
+ return attempts === 1 ? null : makeTree(rootId);
951
+ },
952
+ wait: async (milliseconds) => waits.push(milliseconds),
953
+ });
954
+ try {
955
+ const result = await runLiveReplay(validOptions(source), deps);
956
+ assert.ok(result.report);
957
+ assert.ok(attempts >= 2);
958
+ assert.ok(attempts <= 6);
959
+ assert.ok(waits.every((value) => value > 0 && value <= 1_000));
960
+ assert.deepEqual(new Set(calls.collect.map((call) => call.rootId)), new Set(["root-real"]));
961
+ } finally {
962
+ fs.rmSync(source, { recursive: true, force: true });
963
+ }
964
+ });
965
+
966
+ test("an execution tree that never stabilizes remains capture-incomplete", async () => {
967
+ const source = makeHarnessSource();
968
+ let attempts = 0;
969
+ const { deps } = makeDeps({
970
+ collectExecutionTreeByRoot: async (dbPath, rootId) => {
971
+ attempts += 1;
972
+ return makeTree(rootId, Array.from({ length: attempts }, (_, index) => ({
973
+ session_id: `child-${index}`,
974
+ parent_session_id: rootId,
975
+ agent: "developer",
976
+ })));
977
+ },
978
+ });
979
+ try {
980
+ const result = await runLiveReplay(validOptions(source), deps);
981
+ assert.equal(attempts, 6);
982
+ assert.ok(result.observation.events.some(
983
+ (event) => event.type === "run_error" && event.code === "capture-incomplete",
984
+ ));
985
+ } finally {
986
+ fs.rmSync(source, { recursive: true, force: true });
987
+ }
988
+ });
989
+
990
+ test("collector runtime failure becomes capture-incomplete instead of leaking infrastructure data", async () => {
991
+ const source = makeHarnessSource();
992
+ const { deps } = makeDeps({
993
+ collectExecutionTreeByRoot: async () => {
994
+ throw new Error("/private/opencode.db unavailable");
995
+ },
996
+ });
997
+ try {
998
+ const result = await runLiveReplay(validOptions(source), deps);
999
+ assert.equal(result.exitCode, 3);
1000
+ assert.ok(result.observation.events.some(
1001
+ (event) => event.type === "run_error" && event.code === "capture-incomplete",
1002
+ ));
1003
+ assert.equal(JSON.stringify(result.report).includes("/private/"), false);
1004
+ } finally {
1005
+ fs.rmSync(source, { recursive: true, force: true });
1006
+ }
1007
+ });
1008
+
1009
+ test("a successful tree does not claim non-session channel completeness by itself", async () => {
1010
+ const source = makeHarnessSource();
1011
+ const { deps } = makeDeps();
1012
+ try {
1013
+ const result = await runLiveReplay(validOptions(source), deps);
1014
+ assert.equal(result.exitCode, 3);
1015
+ assert.equal(result.observation.observation_coverage.session_events, "complete");
1016
+ for (const channel of ["skill_events", "tool_events", "review_events", "stop_events"]) {
1017
+ assert.equal(result.observation.observation_coverage[channel], "partial");
1018
+ }
1019
+ } finally {
1020
+ fs.rmSync(source, { recursive: true, force: true });
1021
+ }
1022
+ });
1023
+
1024
+ test("missing explicit root becomes root-session-unresolved without collection fallback", async () => {
1025
+ const source = makeHarnessSource();
1026
+ const { deps, calls } = makeDeps({
1027
+ spawnProcess: async () => ({
1028
+ exitCode: 0,
1029
+ stdout: `${stopLine()}\n`,
1030
+ stderr: "",
1031
+ timedOut: false,
1032
+ cancelled: false,
1033
+ }),
1034
+ });
1035
+ try {
1036
+ const result = await runLiveReplay(validOptions(source), deps);
1037
+ assert.equal(result.exitCode, 3);
1038
+ assert.equal(calls.collect.length, 0);
1039
+ assert.ok(result.observation.events.some(
1040
+ (event) => event.type === "run_error" && event.code === "root-session-unresolved",
1041
+ ));
1042
+ assert.deepEqual(result.report.scenario_results[0].observed_agents, ["unknown-agent"]);
1043
+ } finally {
1044
+ fs.rmSync(source, { recursive: true, force: true });
1045
+ }
1046
+ });
1047
+
1048
+ test("conflicting explicit roots become capture-incomplete", async () => {
1049
+ const source = makeHarnessSource();
1050
+ const { deps, calls } = makeDeps({
1051
+ spawnProcess: async () => ({
1052
+ exitCode: 0,
1053
+ stdout: `${rootLine("root-one")}\n${rootLine("root-two")}\n`,
1054
+ stderr: "",
1055
+ timedOut: false,
1056
+ cancelled: false,
1057
+ }),
1058
+ });
1059
+ try {
1060
+ const result = await runLiveReplay(validOptions(source), deps);
1061
+ assert.equal(result.exitCode, 3);
1062
+ assert.equal(calls.collect.length, 0);
1063
+ assert.ok(result.observation.events.some(
1064
+ (event) => event.type === "run_error" && event.code === "capture-incomplete",
1065
+ ));
1066
+ } finally {
1067
+ fs.rmSync(source, { recursive: true, force: true });
1068
+ }
1069
+ });
1070
+
1071
+ test("normalization keeps only canonical evidence and degrades unknown channels", async () => {
1072
+ const source = makeHarnessSource();
1073
+ const sensitive = "/private/model reasoning secret";
1074
+ const raw = [
1075
+ rootLine(),
1076
+ JSON.stringify({
1077
+ type: "tool.completed",
1078
+ properties: {
1079
+ sessionID: "root-real",
1080
+ agent: "lead",
1081
+ tool: "read",
1082
+ mutation: "read",
1083
+ arguments: sensitive,
1084
+ },
1085
+ }),
1086
+ JSON.stringify({
1087
+ type: "review.completed",
1088
+ properties: {
1089
+ sessionID: "review-real",
1090
+ agent: "reviewer",
1091
+ verdict: "approved",
1092
+ thinking: sensitive,
1093
+ },
1094
+ }),
1095
+ stopLine(),
1096
+ JSON.stringify({ type: "future.unknown", properties: { private: sensitive } }),
1097
+ ].join("\n");
1098
+ const { deps } = makeDeps({
1099
+ spawnProcess: async () => ({
1100
+ exitCode: 0,
1101
+ stdout: `${raw}\n`,
1102
+ stderr: sensitive,
1103
+ timedOut: false,
1104
+ cancelled: false,
1105
+ }),
1106
+ collectExecutionTreeByRoot: async (dbPath, rootId) => makeTree(rootId, [
1107
+ {
1108
+ session_id: "review-real",
1109
+ parent_session_id: rootId,
1110
+ agent: "reviewer",
1111
+ },
1112
+ ]),
1113
+ });
1114
+ try {
1115
+ const result = await runLiveReplay(validOptions(source), deps);
1116
+ const reportText = JSON.stringify(result.report);
1117
+ assert.equal(reportText.includes(sensitive), false);
1118
+ assert.equal(reportText.includes("arguments"), false);
1119
+ assert.equal(reportText.includes("thinking"), false);
1120
+ assert.ok(result.report.scenario_results[0].limitations.some(
1121
+ (row) => row.code === "unknown-live-event",
1122
+ ));
1123
+ for (const channel of ["skill_events", "tool_events", "review_events", "stop_events"]) {
1124
+ assert.equal(result.observation.observation_coverage[channel], "partial");
1125
+ }
1126
+ assert.equal(result.observation.observation_coverage.session_events, "complete");
1127
+ } finally {
1128
+ fs.rmSync(source, { recursive: true, force: true });
1129
+ }
1130
+ });
1131
+
1132
+ test("classified unknown tool events degrade only tool coverage", async () => {
1133
+ const source = makeHarnessSource();
1134
+ const raw = [
1135
+ rootLine(),
1136
+ stopLine(),
1137
+ coverageLine(),
1138
+ JSON.stringify({ type: "tool.future", properties: { arguments: "private" } }),
1139
+ ].join("\n");
1140
+ const { deps } = makeDeps({
1141
+ spawnProcess: async () => ({
1142
+ exitCode: 0,
1143
+ stdout: `${raw}\n`,
1144
+ stderr: "",
1145
+ timedOut: false,
1146
+ cancelled: false,
1147
+ }),
1148
+ });
1149
+ try {
1150
+ const result = await runLiveReplay(validOptions(source), deps);
1151
+ assert.equal(result.observation.observation_coverage.tool_events, "partial");
1152
+ for (const channel of ["skill_events", "review_events", "stop_events"]) {
1153
+ assert.equal(result.observation.observation_coverage[channel], "complete");
1154
+ }
1155
+ } finally {
1156
+ fs.rmSync(source, { recursive: true, force: true });
1157
+ }
1158
+ });
1159
+
1160
+ test("malformed supported tool evidence is omitted and degrades instead of crashing evaluation", async () => {
1161
+ const source = makeHarnessSource();
1162
+ const raw = [
1163
+ rootLine(),
1164
+ JSON.stringify({
1165
+ type: "tool.completed",
1166
+ properties: {
1167
+ sessionID: "root-real",
1168
+ mutation: "read",
1169
+ arguments: "/private/secret",
1170
+ },
1171
+ }),
1172
+ stopLine(),
1173
+ ].join("\n");
1174
+ const { deps } = makeDeps({
1175
+ spawnProcess: async () => ({
1176
+ exitCode: 0,
1177
+ stdout: `${raw}\n`,
1178
+ stderr: "",
1179
+ timedOut: false,
1180
+ cancelled: false,
1181
+ }),
1182
+ });
1183
+ try {
1184
+ const result = await runLiveReplay(validOptions(source), deps);
1185
+ assert.equal(result.exitCode, 3);
1186
+ assert.ok(result.report);
1187
+ assert.equal(
1188
+ result.observation.events.some((event) => event.type === "tool_call_completed"),
1189
+ false,
1190
+ );
1191
+ assert.equal(result.observation.observation_coverage.tool_events, "partial");
1192
+ assert.equal(JSON.stringify(result.report).includes("/private/"), false);
1193
+ } finally {
1194
+ fs.rmSync(source, { recursive: true, force: true });
1195
+ }
1196
+ });
1197
+
1198
+ test("incomplete exact-tree rows keep session coverage partial", async () => {
1199
+ const source = makeHarnessSource();
1200
+ const scenario = {
1201
+ ...freeformScenario,
1202
+ maximum_delegation_budget: 1,
1203
+ };
1204
+ const { deps } = makeDeps({
1205
+ collectExecutionTreeByRoot: async (dbPath, rootId) => makeTree(rootId, [
1206
+ {
1207
+ session_id: "child-without-agent",
1208
+ parent_session_id: rootId,
1209
+ agent: null,
1210
+ },
1211
+ ]),
1212
+ });
1213
+ try {
1214
+ const result = await runLiveReplay({
1215
+ ...validOptions(source),
1216
+ scenarios: [scenario],
1217
+ }, deps);
1218
+ assert.equal(result.exitCode, 3);
1219
+ assert.equal(result.observation.observation_coverage.session_events, "partial");
1220
+ assert.ok(result.observation.events.some(
1221
+ (event) => event.type === "run_error" && event.code === "capture-incomplete",
1222
+ ));
1223
+ } finally {
1224
+ fs.rmSync(source, { recursive: true, force: true });
1225
+ }
1226
+ });
1227
+
1228
+ for (const treeCase of [
1229
+ {
1230
+ name: "root with non-null parent",
1231
+ tree(rootId) {
1232
+ return {
1233
+ root_session_id: rootId,
1234
+ root_session: {
1235
+ session_id: rootId,
1236
+ parent_session_id: "external-parent",
1237
+ agent: "lead",
1238
+ },
1239
+ child_sessions: [],
1240
+ };
1241
+ },
1242
+ expectedAgents: ["unknown-agent"],
1243
+ },
1244
+ {
1245
+ name: "disconnected orphan child",
1246
+ tree(rootId) {
1247
+ return makeTree(rootId, [{
1248
+ session_id: "orphan-real",
1249
+ parent_session_id: "missing-real",
1250
+ agent: "developer",
1251
+ }]);
1252
+ },
1253
+ expectedAgents: ["lead"],
1254
+ },
1255
+ {
1256
+ name: "duplicate session IDs",
1257
+ tree(rootId) {
1258
+ return makeTree(rootId, [
1259
+ {
1260
+ session_id: "duplicate-real",
1261
+ parent_session_id: rootId,
1262
+ agent: "developer",
1263
+ },
1264
+ {
1265
+ session_id: "duplicate-real",
1266
+ parent_session_id: rootId,
1267
+ agent: "reviewer",
1268
+ },
1269
+ ]);
1270
+ },
1271
+ expectedAgents: ["lead"],
1272
+ },
1273
+ ]) {
1274
+ test(`malformed exact tree ${treeCase.name} becomes a valid capture-incomplete report`, async () => {
1275
+ const source = makeHarnessSource();
1276
+ const scenario = {
1277
+ ...freeformScenario,
1278
+ forbidden_agents: [],
1279
+ maximum_delegation_budget: 3,
1280
+ };
1281
+ const { deps } = makeDeps({
1282
+ collectExecutionTreeByRoot: async (dbPath, rootId) => treeCase.tree(rootId),
1283
+ });
1284
+ try {
1285
+ const result = await runLiveReplay({
1286
+ ...validOptions(source),
1287
+ scenarios: [scenario],
1288
+ }, deps);
1289
+ assert.equal(result.exitCode, 3);
1290
+ assert.ok(result.report);
1291
+ assert.equal(result.observation.observation_coverage.session_events, "partial");
1292
+ assert.ok(result.observation.events.some(
1293
+ (event) => event.type === "run_error" && event.code === "capture-incomplete",
1294
+ ));
1295
+ assert.deepEqual(result.report.scenario_results[0].observed_agents, treeCase.expectedAgents);
1296
+ const starts = result.observation.events.filter(
1297
+ (event) => event.type === "session_started",
1298
+ );
1299
+ assert.equal(new Set(starts.map((event) => event.session_id)).size, starts.length);
1300
+ assert.equal(starts.some((event) => event.parent_session_id === undefined), false);
1301
+ } finally {
1302
+ fs.rmSync(source, { recursive: true, force: true });
1303
+ }
1304
+ });
1305
+ }
1306
+
1307
+ test("exact tree children and explicit completion events normalize without real IDs", async () => {
1308
+ const source = makeHarnessSource();
1309
+ const developerScenario = scenarios.find((row) => row.id === "freeform-tiny-direct-fix");
1310
+ const raw = [
1311
+ rootLine(),
1312
+ JSON.stringify({
1313
+ type: "session.completed",
1314
+ properties: { sessionID: "child-real", agent: "developer" },
1315
+ }),
1316
+ stopLine("task-completed"),
1317
+ coverageLine(),
1318
+ ].join("\n");
1319
+ const { deps } = makeDeps({
1320
+ spawnProcess: async () => ({
1321
+ exitCode: 0,
1322
+ stdout: `${raw}\n`,
1323
+ stderr: "",
1324
+ timedOut: false,
1325
+ cancelled: false,
1326
+ }),
1327
+ collectExecutionTreeByRoot: async (dbPath, rootId) => makeTree(rootId, [
1328
+ {
1329
+ session_id: "child-real",
1330
+ parent_session_id: rootId,
1331
+ agent: "developer",
1332
+ },
1333
+ ]),
1334
+ });
1335
+ try {
1336
+ const result = await runLiveReplay(validOptions(source, developerScenario), deps);
1337
+ assert.ok(result.observation.events.some(
1338
+ (event) => event.type === "session_completed"
1339
+ && event.session_id === "session-2"
1340
+ && event.agent === "developer",
1341
+ ));
1342
+ assert.equal(JSON.stringify(result.report).includes("child-real"), false);
1343
+ } finally {
1344
+ fs.rmSync(source, { recursive: true, force: true });
1345
+ }
1346
+ });
1347
+
1348
+ test("exact-tree sessions are normalized in parent-before-child order", async () => {
1349
+ const source = makeHarnessSource();
1350
+ const { deps } = makeDeps({
1351
+ collectExecutionTreeByRoot: async (dbPath, rootId) => makeTree(rootId, [
1352
+ {
1353
+ session_id: "grandchild-real",
1354
+ parent_session_id: "child-real",
1355
+ agent: "reviewer",
1356
+ },
1357
+ {
1358
+ session_id: "child-real",
1359
+ parent_session_id: rootId,
1360
+ agent: "developer",
1361
+ },
1362
+ ]),
1363
+ });
1364
+ try {
1365
+ const result = await runLiveReplay(validOptions(source), deps);
1366
+ const starts = result.observation.events.filter((event) => event.type === "session_started");
1367
+ assert.deepEqual(
1368
+ starts.map((event) => [event.session_id, event.parent_session_id]),
1369
+ [
1370
+ ["session-1", null],
1371
+ ["session-2", "session-1"],
1372
+ ["session-3", "session-2"],
1373
+ ],
1374
+ );
1375
+ } finally {
1376
+ fs.rmSync(source, { recursive: true, force: true });
1377
+ }
1378
+ });
1379
+
1380
+ test("explicit portable run errors are normalized without raw details", async () => {
1381
+ const source = makeHarnessSource();
1382
+ const { deps } = makeDeps({
1383
+ spawnProcess: async () => ({
1384
+ exitCode: 0,
1385
+ stdout: [
1386
+ rootLine(),
1387
+ JSON.stringify({
1388
+ type: "run.error",
1389
+ properties: {
1390
+ code: "cancelled",
1391
+ message: "/private/model failure",
1392
+ },
1393
+ }),
1394
+ ].join("\n"),
1395
+ stderr: "",
1396
+ timedOut: false,
1397
+ cancelled: false,
1398
+ }),
1399
+ });
1400
+ try {
1401
+ const result = await runLiveReplay(validOptions(source), deps);
1402
+ assert.ok(result.observation.events.some(
1403
+ (event) => event.type === "run_error" && event.code === "cancelled",
1404
+ ));
1405
+ assert.equal(JSON.stringify(result.report).includes("/private/"), false);
1406
+ } finally {
1407
+ fs.rmSync(source, { recursive: true, force: true });
1408
+ }
1409
+ });
1410
+
1411
+ test("tracked changes after the run produce git_snapshot changed and observable exit 1", async () => {
1412
+ const source = makeHarnessSource();
1413
+ const { deps, calls } = makeDeps({
1414
+ spawnProcess: async (command, args, options) => {
1415
+ calls.spawn.push({ command, args, options });
1416
+ fs.appendFileSync(path.join(options.cwd, "AGENTS.md"), "mutation\n");
1417
+ return {
1418
+ exitCode: 0,
1419
+ stdout: `${rootLine()}\n${stopLine()}\n${coverageLine()}\n`,
1420
+ stderr: "",
1421
+ timedOut: false,
1422
+ cancelled: false,
1423
+ };
1424
+ },
1425
+ });
1426
+ try {
1427
+ const result = await runLiveReplay(validOptions(source), deps);
1428
+ assert.equal(result.observation.git_snapshot, "changed");
1429
+ assert.equal(result.exitCode, 1);
1430
+ } finally {
1431
+ fs.rmSync(source, { recursive: true, force: true });
1432
+ }
1433
+ });
1434
+
1435
+ test("nested .opencode-live mutations are not hidden from the Git snapshot", async () => {
1436
+ const source = makeHarnessSource();
1437
+ const { deps } = makeDeps({
1438
+ spawnProcess: async (command, args, options) => {
1439
+ const nested = path.join(options.cwd, "agents", ".opencode-live");
1440
+ fs.mkdirSync(nested, { recursive: true });
1441
+ fs.writeFileSync(path.join(nested, "mutation.txt"), "observable mutation\n");
1442
+ return {
1443
+ exitCode: 0,
1444
+ stdout: `${rootLine()}\n${stopLine()}\n${coverageLine()}\n`,
1445
+ stderr: "",
1446
+ timedOut: false,
1447
+ cancelled: false,
1448
+ };
1449
+ },
1450
+ });
1451
+ try {
1452
+ const result = await runLiveReplay(validOptions(source), deps);
1453
+ assert.equal(result.observation.git_snapshot, "changed");
1454
+ assert.equal(result.exitCode, 1);
1455
+ } finally {
1456
+ fs.rmSync(source, { recursive: true, force: true });
1457
+ }
1458
+ });
1459
+
1460
+ test("raw capture files use mode 0600 before cleanup", async () => {
1461
+ const source = makeHarnessSource();
1462
+ let inspected = false;
1463
+ const { deps } = makeDeps({
1464
+ removeTree: async (target) => {
1465
+ for (const name of ["stdout.jsonl", "stderr.log"]) {
1466
+ assert.equal(
1467
+ fs.statSync(path.join(target, ".opencode-live", name)).mode & 0o777,
1468
+ 0o600,
1469
+ );
1470
+ }
1471
+ inspected = true;
1472
+ fs.rmSync(target, { recursive: true, force: true });
1473
+ },
1474
+ });
1475
+ try {
1476
+ await runLiveReplay(validOptions(source), deps);
1477
+ assert.equal(inspected, true);
1478
+ } finally {
1479
+ fs.rmSync(source, { recursive: true, force: true });
1480
+ }
1481
+ });
1482
+
1483
+ test("spawn infrastructure errors exit 2 and still clean the temp repository", async () => {
1484
+ const source = makeHarnessSource();
1485
+ const { deps, calls } = makeDeps({
1486
+ spawnProcess: async () => {
1487
+ throw new Error("/private/executable missing");
1488
+ },
1489
+ });
1490
+ try {
1491
+ const result = await runLiveReplay(validOptions(source), deps);
1492
+ assert.equal(result.exitCode, 2);
1493
+ assert.equal(result.report, undefined);
1494
+ assert.equal(calls.remove.length, 1);
1495
+ } finally {
1496
+ fs.rmSync(source, { recursive: true, force: true });
1497
+ }
1498
+ });
1499
+
1500
+ test("timeout and cancellation become portable run errors", async () => {
1501
+ for (const resultShape of [
1502
+ { timedOut: true, cancelled: false, expected: "timeout" },
1503
+ { timedOut: false, cancelled: true, expected: "cancelled" },
1504
+ ]) {
1505
+ const source = makeHarnessSource();
1506
+ const { deps } = makeDeps({
1507
+ spawnProcess: async () => ({
1508
+ exitCode: null,
1509
+ stdout: `${rootLine()}\n`,
1510
+ stderr: "/private/error",
1511
+ timedOut: resultShape.timedOut,
1512
+ cancelled: resultShape.cancelled,
1513
+ }),
1514
+ });
1515
+ try {
1516
+ const result = await runLiveReplay(validOptions(source), deps);
1517
+ assert.equal(result.exitCode, 3);
1518
+ assert.ok(result.observation.events.some(
1519
+ (event) => event.type === "run_error" && event.code === resultShape.expected,
1520
+ ));
1521
+ assert.equal(JSON.stringify(result.report).includes("/private/"), false);
1522
+ } finally {
1523
+ fs.rmSync(source, { recursive: true, force: true });
1524
+ }
1525
+ }
1526
+ });
1527
+
1528
+ test("default process control closes inherited descendant pipes at an absolute timeout", {
1529
+ skip: process.platform === "win32",
1530
+ timeout: 5_000,
1531
+ }, async () => {
1532
+ const started = Date.now();
1533
+ const result = await spawnProcessWithTimeout(
1534
+ process.execPath,
1535
+ [
1536
+ "-e",
1537
+ [
1538
+ "const { spawn } = require('node:child_process');",
1539
+ "spawn(process.execPath, ['-e', 'setTimeout(() => {}, 3000)'],",
1540
+ " { stdio: ['ignore', 'inherit', 'inherit'] });",
1541
+ "process.on('SIGTERM', () => {});",
1542
+ "setInterval(() => {}, 1000);",
1543
+ ].join(" "),
1544
+ ],
1545
+ {
1546
+ cwd: root,
1547
+ timeoutMs: 100,
1548
+ killGraceMs: 50,
1549
+ absoluteGraceMs: 50,
1550
+ },
1551
+ );
1552
+ assert.equal(result.timedOut, true);
1553
+ assert.equal(result.exitCode, null);
1554
+ assert.ok(Date.now() - started >= 100);
1555
+ assert.ok(Date.now() - started < 1_000);
1556
+ });
1557
+
1558
+ test("stream callback failure terminates the process group before rejecting", {
1559
+ skip: process.platform === "win32",
1560
+ timeout: 5_000,
1561
+ }, async () => {
1562
+ const temp = fs.mkdtempSync(path.join(os.tmpdir(), "routing-live-stream-error-"));
1563
+ const marker = path.join(temp, "late-marker");
1564
+ const started = Date.now();
1565
+ try {
1566
+ await assert.rejects(
1567
+ spawnProcessWithTimeout(
1568
+ process.execPath,
1569
+ [
1570
+ "-e",
1571
+ [
1572
+ "const fs = require('node:fs');",
1573
+ `const marker = ${JSON.stringify(marker)};`,
1574
+ "process.stdout.write('trigger');",
1575
+ "setTimeout(() => fs.writeFileSync(marker, 'should-not-run'), 400);",
1576
+ "setInterval(() => {}, 1000);",
1577
+ ].join(" "),
1578
+ ],
1579
+ {
1580
+ cwd: root,
1581
+ timeoutMs: 2_000,
1582
+ killGraceMs: 50,
1583
+ absoluteGraceMs: 50,
1584
+ onStdoutChunk: () => {
1585
+ throw new Error("capture write failed");
1586
+ },
1587
+ },
1588
+ ),
1589
+ /capture write failed/,
1590
+ );
1591
+ assert.ok(Date.now() - started < 1_000);
1592
+ await new Promise((resolve) => setTimeout(resolve, 450));
1593
+ assert.equal(fs.existsSync(marker), false);
1594
+ } finally {
1595
+ fs.rmSync(temp, { recursive: true, force: true });
1596
+ }
1597
+ });
1598
+
1599
+ test("timeout still kills TERM-resistant descendants after the parent closes", {
1600
+ skip: process.platform === "win32",
1601
+ timeout: 5_000,
1602
+ }, async () => {
1603
+ const temp = fs.mkdtempSync(path.join(os.tmpdir(), "routing-live-descendant-"));
1604
+ const marker = path.join(temp, "descendant-survived");
1605
+ const started = Date.now();
1606
+ try {
1607
+ const result = await spawnProcessWithTimeout(
1608
+ process.execPath,
1609
+ [
1610
+ "-e",
1611
+ [
1612
+ "const { spawn } = require('node:child_process');",
1613
+ `const marker = ${JSON.stringify(marker)};`,
1614
+ "spawn(process.execPath, ['-e',",
1615
+ " `const fs=require('node:fs');",
1616
+ " process.on('SIGTERM',()=>{});",
1617
+ " setTimeout(()=>{fs.writeFileSync(${JSON.stringify(marker)},'bad');process.exit(0)},400);",
1618
+ " setInterval(()=>{},1000);`],",
1619
+ " { stdio: 'ignore' });",
1620
+ "setInterval(() => {}, 1000);",
1621
+ ].join(" "),
1622
+ ],
1623
+ {
1624
+ cwd: root,
1625
+ timeoutMs: 100,
1626
+ killGraceMs: 50,
1627
+ absoluteGraceMs: 50,
1628
+ },
1629
+ );
1630
+ assert.equal(result.timedOut, true);
1631
+ assert.ok(Date.now() - started < 1_000);
1632
+ await new Promise((resolve) => setTimeout(resolve, 500));
1633
+ assert.equal(fs.existsSync(marker), false);
1634
+ } finally {
1635
+ fs.rmSync(temp, { recursive: true, force: true });
1636
+ }
1637
+ });
1638
+
1639
+ test("streaming capture preserves fragmented UTF-8 without accumulating process output", async () => {
1640
+ const source = makeHarnessSource();
1641
+ const line = `${rootLine()}\n${JSON.stringify({
1642
+ type: "thinking",
1643
+ sessionID: "root-real",
1644
+ properties: { text: "emoji-😀-discarded" },
1645
+ })}\n${stopLine()}\n`;
1646
+ const bytes = Buffer.from(line);
1647
+ const emojiOffset = bytes.indexOf(Buffer.from("😀"));
1648
+ const { deps, calls } = makeDeps({
1649
+ spawnProcess: async (command, args, options) => {
1650
+ calls.spawn.push({ command, args, options });
1651
+ for (const chunk of [
1652
+ bytes.subarray(0, emojiOffset + 1),
1653
+ bytes.subarray(emojiOffset + 1, emojiOffset + 3),
1654
+ bytes.subarray(emojiOffset + 3),
1655
+ ]) {
1656
+ options.onStdoutChunk(chunk);
1657
+ }
1658
+ options.onStderrChunk(Buffer.from("fragmented stderr"));
1659
+ return { exitCode: 0, timedOut: false, cancelled: false };
1660
+ },
1661
+ });
1662
+ try {
1663
+ const result = await runLiveReplay(validOptions(source), deps);
1664
+ assert.ok(result.report);
1665
+ assert.deepEqual(
1666
+ new Set(calls.collect.map((call) => call.rootId)),
1667
+ new Set(["root-real"]),
1668
+ );
1669
+ assert.equal(JSON.stringify(result.report).includes("😀"), false);
1670
+ } finally {
1671
+ fs.rmSync(source, { recursive: true, force: true });
1672
+ }
1673
+ });
1674
+
1675
+ test("bounded stdout capture reports capture-incomplete while retained raw stays complete", async () => {
1676
+ const source = makeHarnessSource();
1677
+ const destination = path.join(
1678
+ fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "routing-live-bounded-"))),
1679
+ "retained",
1680
+ );
1681
+ const raw = `${rootLine()}\n${"x".repeat(4_096)}\n${stopLine()}\n`;
1682
+ const { deps } = makeDeps({
1683
+ spawnProcess: async (command, args, options) => {
1684
+ for (let offset = 0; offset < raw.length; offset += 37) {
1685
+ options.onStdoutChunk(Buffer.from(raw.slice(offset, offset + 37)));
1686
+ }
1687
+ return { exitCode: 0, timedOut: false, cancelled: false };
1688
+ },
1689
+ });
1690
+ try {
1691
+ const result = await runLiveReplay({
1692
+ ...validOptions(source),
1693
+ captureLimitBytes: Buffer.byteLength(`${rootLine()}\n`) + 8,
1694
+ retainPrivateOutput: destination,
1695
+ writeStderr: () => {},
1696
+ }, deps);
1697
+ assert.equal(result.exitCode, 3);
1698
+ assert.ok(result.observation.events.some(
1699
+ (event) => event.type === "run_error" && event.code === "capture-incomplete",
1700
+ ));
1701
+ assert.equal(
1702
+ fs.readFileSync(path.join(destination, "stdout.jsonl"), "utf8"),
1703
+ raw,
1704
+ );
1705
+ } finally {
1706
+ fs.rmSync(source, { recursive: true, force: true });
1707
+ fs.rmSync(path.dirname(destination), { recursive: true, force: true });
1708
+ }
1709
+ });
1710
+
1711
+ test("positive private retention copies only raw stdout and stderr after the run", async () => {
1712
+ const source = makeHarnessSource();
1713
+ const destination = path.join(
1714
+ fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "routing-live-retain-parent-"))),
1715
+ "retained",
1716
+ );
1717
+ let spawnFinished = false;
1718
+ const { deps, calls } = makeDeps({
1719
+ spawnProcess: async () => {
1720
+ spawnFinished = true;
1721
+ return {
1722
+ exitCode: 0,
1723
+ stdout: `${rootLine()}\n${stopLine()}\n`,
1724
+ stderr: "private stderr",
1725
+ timedOut: false,
1726
+ cancelled: false,
1727
+ };
1728
+ },
1729
+ });
1730
+ const warnings = [];
1731
+ try {
1732
+ const result = await runLiveReplay({
1733
+ ...validOptions(source),
1734
+ retainPrivateOutput: destination,
1735
+ writeStderr: (text) => warnings.push(text),
1736
+ }, deps);
1737
+ assert.equal(spawnFinished, true, result.error);
1738
+ assert.ok(fs.existsSync(destination));
1739
+ assert.equal(fs.statSync(destination).mode & 0o777, 0o700);
1740
+ assert.deepEqual(fs.readdirSync(destination).sort(), ["stderr.log", "stdout.jsonl"]);
1741
+ for (const file of fs.readdirSync(destination)) {
1742
+ assert.equal(fs.statSync(path.join(destination, file)).mode & 0o777, 0o600);
1743
+ }
1744
+ assert.equal(
1745
+ warnings.join(""),
1746
+ "Warning: retained live replay output may contain sensitive prompts, paths, model/provider metadata, or reasoning.\n",
1747
+ );
1748
+ assert.equal(JSON.stringify(result.report).includes(destination), false);
1749
+ assert.equal(calls.remove.length, 1);
1750
+ assert.equal(fs.existsSync(calls.remove[0]), false);
1751
+ } finally {
1752
+ fs.rmSync(source, { recursive: true, force: true });
1753
+ fs.rmSync(path.dirname(destination), { recursive: true, force: true });
1754
+ }
1755
+ });
1756
+
1757
+ test("retention is revalidated after the live run to close symlink races", async () => {
1758
+ const source = makeHarnessSource();
1759
+ const parent = fs.realpathSync(
1760
+ fs.mkdtempSync(path.join(os.tmpdir(), "routing-live-retain-race-")),
1761
+ );
1762
+ const destination = path.join(parent, "retained");
1763
+ const outside = fs.mkdtempSync(path.join(os.tmpdir(), "routing-live-retain-outside-"));
1764
+ const { deps } = makeDeps({
1765
+ spawnProcess: async () => {
1766
+ fs.symlinkSync(outside, destination);
1767
+ return {
1768
+ exitCode: 0,
1769
+ stdout: `${rootLine()}\n${stopLine()}\n`,
1770
+ stderr: "private",
1771
+ timedOut: false,
1772
+ cancelled: false,
1773
+ };
1774
+ },
1775
+ });
1776
+ try {
1777
+ const result = await runLiveReplay({
1778
+ ...validOptions(source),
1779
+ retainPrivateOutput: destination,
1780
+ }, deps);
1781
+ assert.equal(result.exitCode, 2);
1782
+ assert.ok(result.report);
1783
+ assert.deepEqual(fs.readdirSync(outside), []);
1784
+ assert.equal(JSON.stringify(result.report).includes(outside), false);
1785
+ } finally {
1786
+ fs.rmSync(source, { recursive: true, force: true });
1787
+ fs.rmSync(parent, { recursive: true, force: true });
1788
+ fs.rmSync(outside, { recursive: true, force: true });
1789
+ }
1790
+ });
1791
+
1792
+ test("retention never follows a destination file symlink", async () => {
1793
+ const source = makeHarnessSource();
1794
+ const destination = fs.realpathSync(
1795
+ fs.mkdtempSync(path.join(os.tmpdir(), "routing-live-retain-file-race-")),
1796
+ );
1797
+ const outside = fs.mkdtempSync(path.join(os.tmpdir(), "routing-live-retain-file-target-"));
1798
+ const target = path.join(outside, "target.txt");
1799
+ fs.writeFileSync(target, "untouched");
1800
+ const { deps } = makeDeps({
1801
+ spawnProcess: async () => {
1802
+ fs.symlinkSync(target, path.join(destination, "stdout.jsonl"));
1803
+ return {
1804
+ exitCode: 0,
1805
+ stdout: `${rootLine()}\n${stopLine()}\n`,
1806
+ stderr: "private",
1807
+ timedOut: false,
1808
+ cancelled: false,
1809
+ };
1810
+ },
1811
+ });
1812
+ try {
1813
+ const result = await runLiveReplay({
1814
+ ...validOptions(source),
1815
+ retainPrivateOutput: destination,
1816
+ }, deps);
1817
+ assert.equal(result.exitCode, 2);
1818
+ assert.ok(result.report);
1819
+ assert.equal(fs.readFileSync(target, "utf8"), "untouched");
1820
+ } finally {
1821
+ fs.rmSync(source, { recursive: true, force: true });
1822
+ fs.rmSync(destination, { recursive: true, force: true });
1823
+ fs.rmSync(outside, { recursive: true, force: true });
1824
+ }
1825
+ });
1826
+
1827
+ test("retention never reopens a substituted regular raw file by pathname", async () => {
1828
+ const source = makeHarnessSource();
1829
+ const destination = path.join(
1830
+ fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "routing-live-raw-identity-"))),
1831
+ "retained",
1832
+ );
1833
+ const captured = `${rootLine()}\n${stopLine()}\n`;
1834
+ const { deps } = makeDeps({
1835
+ spawnProcess: async (command, args, options) => {
1836
+ options.onStdoutChunk(Buffer.from(captured));
1837
+ const stdoutPath = path.join(options.cwd, ".opencode-live", "stdout.jsonl");
1838
+ fs.unlinkSync(stdoutPath);
1839
+ fs.writeFileSync(stdoutPath, "substitute-regular-file");
1840
+ return { exitCode: 0, timedOut: false, cancelled: false };
1841
+ },
1842
+ });
1843
+ try {
1844
+ const result = await runLiveReplay({
1845
+ ...validOptions(source),
1846
+ retainPrivateOutput: destination,
1847
+ writeStderr: () => {},
1848
+ }, deps);
1849
+ assert.equal(result.exitCode, 2);
1850
+ const retainedStdout = path.join(destination, "stdout.jsonl");
1851
+ if (fs.existsSync(retainedStdout)) {
1852
+ assert.notEqual(fs.readFileSync(retainedStdout, "utf8"), "substitute-regular-file");
1853
+ }
1854
+ } finally {
1855
+ fs.rmSync(source, { recursive: true, force: true });
1856
+ fs.rmSync(path.dirname(destination), { recursive: true, force: true });
1857
+ }
1858
+ });
1859
+
1860
+ test("cleanup failure preserves a sanitized report and forces operational exit 2", async () => {
1861
+ const source = makeHarnessSource();
1862
+ const { deps } = makeDeps({
1863
+ removeTree: async () => {
1864
+ throw new Error("/private/temp cleanup failed");
1865
+ },
1866
+ });
1867
+ try {
1868
+ const result = await runLiveReplay(validOptions(source), deps);
1869
+ assert.equal(result.exitCode, 2);
1870
+ assert.equal(result.report.operational_status, "cleanup-failed");
1871
+ assert.ok(result.report.scenario_results[0].limitations.some(
1872
+ (row) => row.code === "cleanup-failed",
1873
+ ));
1874
+ assert.equal(JSON.stringify(result.report).includes("/private/"), false);
1875
+ } finally {
1876
+ fs.rmSync(source, { recursive: true, force: true });
1877
+ }
1878
+ });
1879
+
1880
+ test("invalid injected executable proves tests do not launch a real OpenCode process", async () => {
1881
+ const source = makeHarnessSource();
1882
+ const { deps, calls } = makeDeps({
1883
+ spawnProcess: async (command, args, options) => {
1884
+ calls.spawn.push({ command, args, options });
1885
+ assert.equal(command, "definitely-not-a-real-opencode-executable");
1886
+ return {
1887
+ exitCode: 0,
1888
+ stdout: `${rootLine()}\n${stopLine()}\n`,
1889
+ stderr: "",
1890
+ timedOut: false,
1891
+ cancelled: false,
1892
+ };
1893
+ },
1894
+ });
1895
+ try {
1896
+ const result = await runLiveReplay({
1897
+ ...validOptions(source),
1898
+ executable: "definitely-not-a-real-opencode-executable",
1899
+ }, deps);
1900
+ assert.equal(result.report.mode, "live");
1901
+ assert.equal(calls.spawn.length, 1);
1902
+ assert.equal(collectStrings(result.report).some((value) => value.includes("real-opencode")), false);
1903
+ } finally {
1904
+ fs.rmSync(source, { recursive: true, force: true });
1905
+ }
1906
+ });